Compare commits

..
50 Commits
Author SHA1 Message Date
yunyingk f2595bb275 Merge pull request #66 from yunyingk/codex/unify-unknown-command-exit-codes
🧪 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
Unify unknown command and subcommand exit code classification
2026-09-11 10:06:12 +08:00
gitea 0534651e0a Refine runner test for domain unknown subcommands 2026-09-11 10:05:19 +08:00
gitea 225321f34a Unify unknown command and subcommand exit code classification 2026-09-11 10:02:50 +08:00
yunyingk bda8b82157 Merge pull request #65 from yunyingk/codex/release-v0.10.14
Release v0.10.14
2026-09-11 09:45:43 +08:00
gitea 0e1f744c53 Release v0.10.14: unify staging capability coverage 2026-09-11 09:44:38 +08:00
yunyingk 6df9c817d4 Merge pull request #64 from yunyingk/codex/simulation-approval-definitions
Add simulation approval definition lookup
2026-09-11 01:57:08 +08:00
gitea 2a82017e50 Add simulation approval definition lookup 2026-09-11 01:55:56 +08:00
yunyingk bffd3998a3 Merge pull request #63 from yunyingk/codex/insight-default-range
Default insight stats to current month
2026-09-11 01:53:18 +08:00
gitea 41e31774ee Default insight stats to current month 2026-09-11 01:52:02 +08:00
yunyingk 83c11b7588 Merge pull request #62 from yunyingk/codex/financial-data-query
Add financial data list queries
2026-09-11 01:49:34 +08:00
gitea b94d6d11d5 Add financial data list queries 2026-09-11 01:47:47 +08:00
yunyingk a9f5e2d3ef Merge pull request #61 from yunyingk/codex/insight-stats
Add insight stats query
2026-09-11 01:43:35 +08:00
gitea a946cf45c9 Add insight stats query 2026-09-11 01:42:41 +08:00
yunyingk d3c9302c14 Merge pull request #60 from yunyingk/codex/contacts-read-api
Add read-only contacts directory APIs
2026-09-11 01:38:31 +08:00
gitea 17a31042a1 Add read-only contacts directory APIs 2026-09-11 01:37:10 +08:00
yunyingk 42403130e0 Add universal mutation preview mode
Merge reviewed fix for #46 after rebasing onto main.
2026-09-11 01:19:48 +08:00
gitea 690ee604f1 Merge main into mutation preview 2026-09-11 01:18:41 +08:00
yunyingk 5eb7c87e8d Standardize semantic CLI error handling
Merge reviewed fixes for #43 and #44 after CI validation.
2026-09-11 01:15:40 +08:00
gitea 370435bef9 Merge main into semantic CLI errors 2026-09-11 01:13:47 +08:00
yunyingk 8623f1ab64 Add non-blocking simulation status checks
Merge reviewed fix for #45.
2026-09-11 01:09:48 +08:00
yunyingk 5912d22ce4 Apply approval rule pushes incrementally
Merge reviewed fix for #50.
2026-09-11 01:08:59 +08:00
yunyingk 9f559ad94e Document draft and published rule code spaces
Merge reviewed fix for #51.
2026-09-11 01:08:43 +08:00
yunyingk fa72a53d61 Clarify knowledge document creation constraints
Merge reviewed fixes for #49 and #52.
2026-09-11 01:08:31 +08:00
yunyingk eac331922c Fix HTTP error response body reporting
Merge reviewed fix for #48.
2026-09-11 01:06:33 +08:00
gitea 5242df2392 Update semantic exit code test 2026-09-11 01:05:25 +08:00
gitea 138a4a9498 Add universal mutation preview mode 2026-09-11 00:45:27 +08:00
gitea 7bf40dd726 Standardize semantic CLI error handling 2026-09-11 00:28:09 +08:00
gitea 995b9fa81e Add non-blocking simulation status checks 2026-09-11 00:15:35 +08:00
gitea 1910faa8ea Apply approval rule pushes incrementally 2026-09-11 00:10:10 +08:00
gitea 73c0b24b48 Document draft and published rule code spaces 2026-09-11 00:06:16 +08:00
gitea cc7da4f421 Clarify knowledge document creation constraints 2026-09-11 00:04:06 +08:00
gitea 64692fecba Fix HTTP error response body reporting 2026-09-10 23:58:28 +08:00
yunyingk 0b10a70924 Merge pull request #47 from yunyingk/codex/custom-http-headers
Add per-enterprise custom HTTP headers and cookies
2026-09-10 17:17:44 +08:00
gitea bb8b5edec6 Add per-enterprise custom HTTP headers and cookies
Some Seal tenants sit behind a gateway that only forwards requests
carrying its own session cookie. Corp configs can now set
seal.headers/seal.cookies, which the client merges into every request;
cookies are rendered into one Cookie header and the session bearer
token still wins over any configured Authorization.

corps add-seal accepts both fields and applies them when verifying the
tenant, so a gated enterprise can be registered in one step.
2026-09-10 16:25:11 +08:00
yunyingk fc06434813 Merge pull request #42 from yunyingk/codex/material-pack-file-policy
Add configurable material pack attachment file policy
2026-09-08 15:17:18 +08:00
gitea 799cdd1b17 Refine material pack policy recovery guidance 2026-09-08 15:10:39 +08:00
gitea 79c9420e4e Add material pack attachment file policy 2026-09-08 14:54:51 +08:00
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
66 changed files with 5530 additions and 1039 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.7",
"version": "0.10.14",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+90
View File
@@ -5,6 +5,96 @@ 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).
## [Unreleased]
## [0.10.14] - 2026-09-11
### Added
- **Material Pack Webhook Attachment File Policy**:
- Added per-Webhook minimum file size (default 500 bytes), optional maximum file size, and configurable file-extension whitelist.
- Added unified configuration fields for creating and updating Webhook policies.
- Enforced the policy before attachment upload and document push, with detailed validation errors and no partial push on failure.
- Added default support for common PDF, Office, text, email, and image formats.
- **Unified CLI coverage for staging frontend capabilities**:
- Added read-only contacts queries for department trees, department details, department users, and last synchronization time.
- Added `analytics insight` for risk-tag statistics with date-range filtering and current-month defaults.
- Added paginated `data expenses` and `data invoices` queries with frontend-compatible filters.
- Added `simulation approval-definitions` to discover Feishu approval codes before creating a test batch.
### Fixed & Enhanced
- Added non-blocking simulation status checks and `simulation create --no-wait`.
- Added semantic CLI exit codes and actionable next-command guidance.
- Added universal `--dry-run` previews for supported configuration and destructive operations.
- Changed approval-rule pushes to apply incrementally while preserving existing rule IDs.
- Preserved HTTP error response bodies for actionable upstream diagnostics.
- Documented draft versus published rule code spaces and knowledge-document creation constraints.
## [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
+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.
+235 -190
View File
@@ -1,102 +1,97 @@
import{createRequire as HD0}from"node:module";var qD0=Object.create;var{getPrototypeOf:UD0,defineProperty:CO,getOwnPropertyNames:YD0}=Object;var JD0=Object.prototype.hasOwnProperty;function QD0($){return this[$]}var KD0,zD0,RY=($,I,q)=>{var U=$!=null&&typeof $==="object";if(U){var Y=I?KD0??=new WeakMap:zD0??=new WeakMap,J=Y.get($);if(J)return J}q=$!=null?qD0(UD0($)):{};let Q=I||!$||!$.__esModule?CO(q,"default",{value:$,enumerable:!0}):q;for(let K of YD0($))if(!JD0.call(Q,K))CO(Q,K,{get:QD0.bind($,K),enumerable:!0});if(U)Y.set($,Q);return Q};var L=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);var wD0=($)=>$;function GD0($,I){this[$]=wD0.bind(null,I)}var d8=($,I)=>{for(var q in I)CO($,q,{get:I[q],enumerable:!0,configurable:!0,set:GD0.bind(I,q)})};var o=HD0(import.meta.url);var vJ=L((nf)=>{Object.defineProperty(nf,"__esModule",{value:!0});nf.regexpCode=nf.getEsmExportName=nf.getProperty=nf.safeStringify=nf.stringify=nf.strConcat=nf.addCodeArg=nf.str=nf._=nf.nil=nf._Code=nf.Name=nf.IDENTIFIER=nf._CodeOrName=void 0;class _G{}nf._CodeOrName=_G;nf.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pI extends _G{constructor($){super();if(!nf.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}}}nf.Name=pI;class y$ extends _G{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,q)=>`${I}${q}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((I,q)=>{if(q instanceof pI)I[q.str]=(I[q.str]||0)+1;return I},{})}}nf._Code=y$;nf.nil=new y$("");function kf($,...I){let q=[$[0]],U=0;while(U<I.length)cg(q,I[U]),q.push($[++U]);return new y$(q)}nf._=kf;var pg=new y$("+");function ff($,...I){let q=[BJ($[0])],U=0;while(U<I.length)q.push(pg),cg(q,I[U]),q.push(pg,BJ($[++U]));return _F0(q),new y$(q)}nf.str=ff;function cg($,I){if(I instanceof y$)$.push(...I._items);else if(I instanceof pI)$.push(I);else $.push(yF0(I))}nf.addCodeArg=cg;function _F0($){let I=1;while(I<$.length-1){if($[I]===pg){let q=hF0($[I-1],$[I+1]);if(q!==void 0){$.splice(I-1,3,q);continue}$[I++]="+"}I++}}function hF0($,I){if(I==='""')return $;if($==='""')return I;if(typeof $=="string"){if(I instanceof pI||$[$.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 pI))return`"${$}${I.slice(1)}`;return}function SF0($,I){return I.emptyStr()?$:$.emptyStr()?I:ff`${$}${I}`}nf.strConcat=SF0;function yF0($){return typeof $=="number"||typeof $=="boolean"||$===null?$:BJ(Array.isArray($)?$.join(","):$)}function uF0($){return new y$(BJ($))}nf.stringify=uF0;function BJ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}nf.safeStringify=BJ;function xF0($){return typeof $=="string"&&nf.IDENTIFIER.test($)?new y$(`.${$}`):kf`[${$}]`}nf.getProperty=xF0;function kF0($){if(typeof $=="string"&&nf.IDENTIFIER.test($))return new y$(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}nf.getEsmExportName=kF0;function fF0($){return new y$($.toString())}nf.regexpCode=fF0});var og=L((df)=>{Object.defineProperty(df,"__esModule",{value:!0});df.ValueScope=df.ValueScopeName=df.Scope=df.varKinds=df.UsedValueState=void 0;var u6=vJ();class pf extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var SG;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(SG||(df.UsedValueState=SG={}));df.varKinds={const:new u6.Name("const"),let:new u6.Name("let"),var:new u6.Name("var")};class lg{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return $ instanceof u6.Name?$:this.name($)}name($){return new u6.Name(this._newName($))}_newName($){let I=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){var I,q;if(((q=(I=this._parent)===null||I===void 0?void 0:I._prefixes)===null||q===void 0?void 0:q.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}df.Scope=lg;class mg extends u6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:q}){this.value=$,this.scopePath=u6._`.${new u6.Name(I)}[${q}]`}}df.ValueScopeName=mg;var sF0=u6._`\n`;class cf extends lg{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?sF0:u6.nil}}get(){return this._scope}name($){return new mg($,this._newName($))}value($,I){var q;if(I.ref===void 0)throw Error("CodeGen: ref must be passed in value");let U=this.toName($),{prefix:Y}=U,J=(q=I.key)!==null&&q!==void 0?q:I.ref,Q=this._values[Y];if(Q){let w=Q.get(J);if(Line truncated
`:""},this._extScope=$,this._scope=new u$.Scope({parent:$}),this._nodes=[new ef]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,I){let q=this._extScope.value($,I);return(this._values[q.prefix]||(this._values[q.prefix]=new Set)).add(q),q}getScopeValue($,I){return this._extScope.getValue($,I)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,I,q,U){let Y=this._scope.toName(I);if(q!==void 0&&U)this._constants[Y.str]=q;return this._leafNode(new mf($,Y,q)),Y}const($,I,q){return this._def(u$.varKinds.const,$,I,q)}let($,I,q){return this._def(u$.varKinds.let,$,I,q)}var($,I,q){return this._def(u$.varKinds.var,$,I,q)}assign($,I,q){return this._leafNode(new ag($,I,q))}add($,I){return this._leafNode(new of($,x6.operators.ADD,I))}code($){if(typeof $=="function")$();else if($!==Y1.nil)this._leafNode(new sf($));return this}object(...$){let I=["{"];for(let[q,U]of $){if(I.length>1)I.push(",");if(I.push(q),q!==U||this.opts.es5)I.push(":"),(0,Y1.addCodeArg)(I,U)}return I.push("}"),new Y1._Code(I)}if($,I,q){if(this._blockNode(new t8($)),I&&q)this.code(I).else().code(q).endIf();else if(I)this.code(I).endIf();else if(q)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new t8($))}else(){return this._elseNode(new RJ)}endIf(){return this._endBlockNode(t8,RJ)}_for($,I){if(this._blockNode($),I)this.code(I).endFor();return this}for($,I){return this._for(new $n($),I)}forRange($,I,q,U,Y=this.opts.es5?u$.varKinds.var:u$.varKinds.let){let J=this._scope.toName($);return this._for(new In(Y,J,I,q),()=>U(J))}forOf($,I,q,U=u$.varKinds.const){let Y=this._scope.toName($);if(this.opts.es5){let J=I instanceof Y1.Name?I:this.var("_arr",I);return this.forRange("_i",0,Y1._`${J}.length`,(Q)=>{this.var(Y,Y1._`${J}[${Q}]`),q(Y)})}return this._for(new rg("of",U,Y,I),()=>q(Y))}forIn($,I,q,U=this.opts.es5?u$.varKinds.var:u$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,Y1._`Object.keys(${I})`,q);let Y=this._scope.toName($);return this._for(new rg("in",U,Y,I),()=>q(Y))}endFor(){return this._endBlockNode(cI)}label($){return this._leafNode(new rf($))}break($){return this._leafNode(new tf($))}return($){let I=new uG;if(this._blockNode(I),this.code($),I.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(uG)}try($,I,q){if(!I&&!q)throw Error('CodeGen: "try" without "catch" and "finally"');let U=new qn;if(this._blockNode(U),this.code($),I){let Y=this.name("e");this._currNode=U.catch=new xG(Y),I(Y)}if(q)this._currNode=U.finally=new kG,this.code(q);return this._endBlockNode(xG,kG)}throw($){return this._leafNode(new af($))}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 q=this._nodes.length-I;if(q<0||$!==void 0&&q!==$)throw Error(`CodeGen: wrong number of nodes: ${q} vs ${$} expected`);return this._nodes.length=I,this}func($,I=Y1.nil,q,U){if(this._blockNode(new yG($,I,q)),U)this.code(U).endFunc();return this}endFunc(){return this._endBlockNode(yG)}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 q=this._currNode;if(q instanceof $||I&&q 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 t8))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]=$}}x6.CodeGen=Un;function B7($,I){for(let q in I)$[q]=($[q]||0)+(I[q]||0);return $}function fG($,I){return I instanceof Y1._CodeOrName?B7($,I.names):$}function dI($,I,q){if($ instanceof Y1.Name)return U($);if(!Y($))return $;return new Y1._Code($._items.reduce((J,Q)=>{if(Q instanceof Y1.Name)Q=U(Q);if(Q instanceof Y1._Code)J.push(...Q._items);else J.push(Q);return J},[]));function U(J){let Q=q[J.str];if(Q===void 0||I[J.str]!==1)return J;return delete I[J.str],Q}function Y(J){return J instanceof Y1._Code&&J._items.some((Q)=>Q instanceof Y1.Name&&I[Q.str]===1&&q[Q.str]!==void 0)}}function qM0($,I){for(let q in I)$[q]=($[q]||0)-(I[q]||0)}function Yn($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:Y1._`!${tg($)}`}x6.not=Yn;var UM0=Jn(x6.operators.AND);function YM0(...$){return $.reduce(UM0)}x6.and=YM0;var JM0=Jn(x6.operators.OR);function QM0(...$){return $.reduce(JM0)}x6.or=QM0;function Jn($){return(I,q)=>I===Y1.nil?q:q===Y1.nil?I:Y1._`${tg(I)} ${$} ${tg(q)}`}function tg($){return $ instanceof Y1.Name?$:Y1._`(${Line truncated
|| (${Q} == "string" && ${Y} && ${Y} == +${Y})`).assign(K,l0._`+${Y}`);return;case"integer":U.elseIf(l0._`${Q} === "boolean" || ${Y} === null
|| (${Q} === "string" && ${Y} && ${Y} == +${Y} && !(${Y} % 1))`).assign(K,l0._`+${Y}`);return;case"boolean":U.elseIf(l0._`${Y} === "false" || ${Y} === 0 || ${Y} === null`).assign(K,!1).elseIf(l0._`${Y} === "true" || ${Y} === 1`).assign(K,!0);return;case"null":U.elseIf(l0._`${Y} === "" || ${Y} === 0 || ${Y} === false`),U.assign(K,null);return;case"array":U.elseIf(l0._`${Q} === "string" || ${Q} === "number"
|| ${Q} === "boolean" || ${Y} === null`).assign(K,l0._`[${Y}]`)}}}function NA0({gen:$,parentData:I,parentDataProperty:q},U){$.if(l0._`${I} !== undefined`,()=>$.assign(l0._`${I}[${q}]`,U))}function YP($,I,q,U=lI.Correct){let Y=U===lI.Correct?l0.operators.EQ:l0.operators.NEQ,J;switch($){case"null":return l0._`${I} ${Y} null`;case"array":J=l0._`Array.isArray(${I})`;break;case"object":J=l0._`${I} && typeof ${I} == "object" && !Array.isArray(${I})`;break;case"integer":J=Q(l0._`!(${I} % 1) && !isNaN(${I})`);break;case"number":J=Q();break;default:return l0._`typeof ${I} ${Y} ${$}`}return U===lI.Correct?J:(0,l0.not)(J);function Q(K=l0.nil){return(0,l0.and)(l0._`typeof ${I} == "number"`,K,q?l0._`isFinite(${I})`:l0.nil)}}yn.checkDataType=YP;function JP($,I,q,U){if($.length===1)return YP($[0],I,q,U);let Y,J=(0,_n.toHash)($);if(J.array&&J.object){let Q=l0._`typeof ${I} != "object"`;Y=J.null?Q:l0._`!${I} || ${Q}`,delete J.null,delete J.array,delete J.object}else Y=l0.nil;if(J.number)delete J.integer;for(let Q in J)Y=(0,l0.and)(Y,YP(Q,I,q,U));return Y}yn.checkDataTypes=JP;var FA0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:I})=>typeof $=="string"?l0._`{type: ${$}}`:l0._`{type: ${I}}`};function QP($){let I=MA0($);(0,ZA0.reportError)(I,FA0)}yn.reportTypeError=QP;function MA0($){let{gen:I,data:q,schema:U}=$,Y=(0,_n.schemaRefOrVal)($,U,"type");return{gen:I,keyword:"type",data:q,schema:U.type,schemaCode:Y,schemaValue:Y,parentSchema:U,params:{},it:$}}});var nn=L((kn)=>{Object.defineProperty(kn,"__esModule",{value:!0});kn.assignDefaults=void 0;var mI=o0(),BA0=w1();function vA0($,I){let{properties:q,items:U}=$.schema;if(I==="object"&&q)for(let Y in q)xn($,Y,q[Y].default);else if(I==="array"&&Array.isArray(U))U.forEach((Y,J)=>xn($,J,Y.default))}kn.assignDefaults=vA0;function xn($,I,q){let{gen:U,compositeRule:Y,data:J,opts:Q}=$;if(q===void 0)return;let K=mI._`${J}${(0,mI.getProperty)(I)}`;if(Y){(0,BA0.checkStrictMode)($,`default is ignored for: ${K}`);return}let z=mI._`${K} === undefined`;if(Q.useDefaults==="empty")z=mI._`${z} || ${K} === null || ${K} === ""`;U.if(z,mI._`${K} = ${(0,mI.stringify)(q)}`)}});var D$=L((cn)=>{Object.defineProperty(cn,"__esModule",{value:!0});cn.validateUnion=cn.validateArray=cn.usePattern=cn.callValidateCode=cn.schemaProperties=cn.allSchemaProperties=cn.noPropertyInData=cn.propertyInData=cn.isOwnProperty=cn.hasPropFunc=cn.reportMissingProp=cn.checkMissingProp=cn.checkReportMissingProp=void 0;var l1=o0(),KP=w1(),K9=a8(),RA0=w1();function CA0($,I){let{gen:q,data:U,it:Y}=$;q.if(wP(q,U,I,Y.opts.ownProperties),()=>{$.setParams({missingProperty:l1._`${I}`},!0),$.error()})}cn.checkReportMissingProp=CA0;function _A0({gen:$,data:I,it:{opts:q}},U,Y){return(0,l1.or)(...U.map((J)=>(0,l1.and)(wP($,I,J,q.ownProperties),l1._`${Y} = ${J}`)))}cn.checkMissingProp=_A0;function hA0($,I){$.setParams({missingProperty:I},!0),$.error()}cn.reportMissingProp=hA0;function bn($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:l1._`Object.prototype.hasOwnProperty`})}cn.hasPropFunc=bn;function zP($,I,q){return l1._`${bn($)}.call(${I}, ${q})`}cn.isOwnProperty=zP;function SA0($,I,q,U){let Y=l1._`${I}${(0,l1.getProperty)(q)} !== undefined`;return U?l1._`${Y} && ${zP($,I,q)}`:Y}cn.propertyInData=SA0;function wP($,I,q,U){let Y=l1._`${I}${(0,l1.getProperty)(q)} === undefined`;return U?(0,l1.or)(Y,(0,l1.not)(zP($,I,q))):Y}cn.noPropertyInData=wP;function pn($){return $?Object.keys($).filter((I)=>I!=="__proto__"):[]}cn.allSchemaProperties=pn;function yA0($,I){return pn(I).filter((q)=>!(0,KP.alwaysValidSchema)($,I[q]))}cn.schemaProperties=yA0;function uA0({schemaCode:$,data:I,it:{gen:q,topSchemaRef:U,schemaPath:Y,errorPath:J},it:Q},K,z,w){let G=w?l1._`${$}, ${I}, ${U}${Y}`:I,H=[[K9.default.instancePath,(0,l1.strConcat)(K9.default.instancePath,J)],[K9.default.parentData,Q.parentData],[K9.default.parentDataProperty,Q.parentDataProperty],[K9.default.rootData,K9.default.rootData]];if(Q.opts.dynamicRef)H.push([K9.default.dynamicAnchors,K9.default.dynamicAnchors]);let W=l1._`${G}, ${q.object(...H)}`;return z!==l1.nil?l1._`${K}.call(${z}, ${W})`:l1._`${K}(${W})`}cn.callValidateCode=uA0;var xA0=l1._`new RegExp`;function kA0({gen:$,it:{opts:I}},q){let U=I.unicodeRegExp?"u":"",{regExp:Y}=I.code,J=Y(q,U);return $.scopeValue("pattern",{key:J.toString(),ref:J,code:l1._`${Y.code==="new RegExp"?xA0:(0,RA0.useFunc)($,Y)}(${q}, ${U})`})}cn.usePattern=kA0;function fA0($){let{gen:I,data:q,keyword:U,it:Y}=$,J=I.name("valid");if(Y.allErrors){let K=I.let("valid",!0);return Q(()=>I.assign(K,!1)),K}return I.var(J,!0),Q(()=>I.break()),J;function Q(K){let z=I.const("len",l1._`${q}.length`);I.forRange("i",0,z,(w)=>{$.subschema({keyword:U,dataProp:w,dataPropType:KP.Type.Num},J),I.if((0,l1.not)(J),K)})}}cn.validateArray=fA0;function nA0($){let{gen:I,schema:q,keyword:U,it:Y}=$;if(!Array.isArray(q))throw Error("ajv implementation error");if(q.some((z)=>(0,KP.alwaysValidSchema)(Y,z))&&!Y.opts.unevaluated)return;le Line truncated
missingProperty: ${U},
import{createRequire as YL0}from"node:module";var oz0=Object.create;var{getPrototypeOf:rz0,defineProperty:uD,getOwnPropertyNames:tz0}=Object;var az0=Object.prototype.hasOwnProperty;function sz0($){return this[$]}var ez0,$L0,XI=($,I,U)=>{var Y=$!=null&&typeof $==="object";if(Y){var J=I?ez0??=new WeakMap:$L0??=new WeakMap,Q=J.get($);if(Q)return Q}U=$!=null?oz0(rz0($)):{};let K=I||!$||!$.__esModule?uD(U,"default",{value:$,enumerable:!0}):U;for(let q of tz0($))if(!az0.call(K,q))uD(K,q,{get:sz0.bind($,q),enumerable:!0});if(Y)J.set($,K);return K};var O=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);var IL0=($)=>$;function UL0($,I){this[$]=IL0.bind(null,I)}var o8=($,I)=>{for(var U in I)uD($,U,{get:I[U],enumerable:!0,configurable:!0,set:UL0.bind(I,U)})};var r=YL0(import.meta.url);var gQ=O((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 _W{}rf._CodeOrName=_W;rf.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class sI extends _W{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=sI;class b$ extends _W{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 sI)I[U.str]=(I[U.str]||0)+1;return I},{})}}rf._Code=b$;rf.nil=new b$("");function lf($,...I){let U=[$[0]],Y=0;while(Y<I.length)aP(U,I[Y]),U.push($[++Y]);return new b$(U)}rf._=lf;var tP=new b$("+");function of($,...I){let U=[SQ($[0])],Y=0;while(Y<I.length)U.push(tP),aP(U,I[Y]),U.push(tP,SQ($[++Y]));return TN0(U),new b$(U)}rf.str=of;function aP($,I){if(I instanceof b$)$.push(...I._items);else if(I instanceof sI)$.push(I);else $.push(vN0(I))}rf.addCodeArg=aP;function TN0($){let I=1;while(I<$.length-1){if($[I]===tP){let U=EN0($[I-1],$[I+1]);if(U!==void 0){$.splice(I-1,3,U);continue}$[I++]="+"}I++}}function EN0($,I){if(I==='""')return $;if($==='""')return I;if(typeof $=="string"){if(I instanceof sI||$[$.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 sI))return`"${$}${I.slice(1)}`;return}function BN0($,I){return I.emptyStr()?$:$.emptyStr()?I:of`${$}${I}`}rf.strConcat=BN0;function vN0($){return typeof $=="number"||typeof $=="boolean"||$===null?$:SQ(Array.isArray($)?$.join(","):$)}function RN0($){return new b$(SQ($))}rf.stringify=RN0;function SQ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}rf.safeStringify=SQ;function CN0($){return typeof $=="string"&&rf.IDENTIFIER.test($)?new b$(`.${$}`):lf`[${$}]`}rf.getProperty=CN0;function jN0($){if(typeof $=="string"&&rf.IDENTIFIER.test($))return new b$(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}rf.getEsmExportName=jN0;function _N0($){return new b$($.toString())}rf.regexpCode=_N0});var IT=O((ef)=>{Object.defineProperty(ef,"__esModule",{value:!0});ef.ValueScope=ef.ValueScopeName=ef.Scope=ef.varKinds=ef.UsedValueState=void 0;var u6=gQ();class af extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var gW;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(gW||(ef.UsedValueState=gW={}));ef.varKinds={const:new u6.Name("const"),let:new u6.Name("let"),var:new u6.Name("var")};class eP{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return $ instanceof u6.Name?$:this.name($)}name($){return new u6.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}}}ef.Scope=eP;class $T extends u6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:U}){this.value=$,this.scopePath=u6._`.${new u6.Name(I)}[${U}]`}}ef.ValueScopeName=$T;var cN0=u6._`\n`;class sf extends eP{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?cN0:u6.nil}}get(){return this._scope}name($){return new $T($,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 i$.Scope({parent:$}),this._nodes=[new qb]}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 Ib($,J,U)),J}const($,I,U){return this._def(i$.varKinds.const,$,I,U)}let($,I,U){return this._def(i$.varKinds.let,$,I,U)}var($,I,U){return this._def(i$.varKinds.var,$,I,U)}assign($,I,U){return this._leafNode(new JT($,I,U))}add($,I){return this._leafNode(new Ub($,f6.operators.ADD,I))}code($){if(typeof $=="function")$();else if($!==q1.nil)this._leafNode(new Kb($));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,q1.addCodeArg)(I,Y)}return I.push("}"),new q1._Code(I)}if($,I,U){if(this._blockNode(new e8($)),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 e8($))}else(){return this._elseNode(new yQ)}endIf(){return this._endBlockNode(e8,yQ)}_for($,I){if(this._blockNode($),I)this.code(I).endFor();return this}for($,I){return this._for(new Gb($),I)}forRange($,I,U,Y,J=this.opts.es5?i$.varKinds.var:i$.varKinds.let){let Q=this._scope.toName($);return this._for(new Hb(J,Q,I,U),()=>Y(Q))}forOf($,I,U,Y=i$.varKinds.const){let J=this._scope.toName($);if(this.opts.es5){let Q=I instanceof q1.Name?I:this.var("_arr",I);return this.forRange("_i",0,q1._`${Q}.length`,(K)=>{this.var(J,q1._`${Q}[${K}]`),U(J)})}return this._for(new UT("of",Y,J,I),()=>U(J))}forIn($,I,U,Y=this.opts.es5?i$.varKinds.var:i$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,q1._`Object.keys(${I})`,U);let J=this._scope.toName($);return this._for(new UT("in",Y,J,I),()=>U(J))}endFor(){return this._endBlockNode(eI)}label($){return this._leafNode(new Yb($))}break($){return this._leafNode(new Jb($))}return($){let I=new hW;if(this._blockNode(I),this.code($),I.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(hW)}try($,I,U){if(!I&&!U)throw Error('CodeGen: "try" without "catch" and "finally"');let Y=new Wb;if(this._blockNode(Y),this.code($),I){let J=this.name("e");this._currNode=Y.catch=new xW(J),I(J)}if(U)this._currNode=Y.finally=new kW,this.code(U);return this._endBlockNode(xW,kW)}throw($){return this._leafNode(new Qb($))}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=q1.nil,U,Y){if(this._blockNode(new yW($,I,U)),Y)this.code(Y).endFunc();return this}endFunc(){return this._endBlockNode(yW)}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 e8))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]=$}}f6.CodeGen=Vb;function j7($,I){for(let U in I)$[U]=($[U]||0)+(I[U]||0);return $}function uW($,I){return I instanceof q1._CodeOrName?j7($,I.names):$}function $U($,I,U){if($ instanceof q1.Name)return Y($);if(!J($))return $;return new q1._Code($._items.reduce((Q,K)=>{if(K instanceof q1.Name)K=Y(K);if(K instanceof q1._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 q1._Code&&Q._items.some((K)=>K instanceof q1.Name&&I[K.str]===1&&U[K.str]!==void 0)}}function oN0($,I){for(let U in I)$[U]=($[U]||0)-(I[U]||0)}function wb($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:q1._`!${YT($)}`}f6.not=wb;var rN0=Zb(f6.operators.AND);function tN0(...$){return $.reduce(rN0)}f6.and=tN0;var aN0=Zb(f6.operators.OR);function sN0(...$){return $.reduce(aN0)}f6.or=sN0;function Zb($){return(I,U)=>I===q1.nil?U:U===q1.nil?I:q1._`${YT(I)} ${$} ${YT(U)}`}function YT($){return $ instanceof q1.Name?$:q1._`(${Line truncated
|| (${K} == "string" && ${J} && ${J} == +${J})`).assign(q,t0._`+${J}`);return;case"integer":Y.elseIf(t0._`${K} === "boolean" || ${J} === null
|| (${K} === "string" && ${J} && ${J} == +${J} && !(${J} % 1))`).assign(q,t0._`+${J}`);return;case"boolean":Y.elseIf(t0._`${J} === "false" || ${J} === 0 || ${J} === null`).assign(q,!1).elseIf(t0._`${J} === "true" || ${J} === 1`).assign(q,!0);return;case"null":Y.elseIf(t0._`${J} === "" || ${J} === 0 || ${J} === false`),Y.assign(q,null);return;case"array":Y.elseIf(t0._`${K} === "string" || ${K} === "number"
|| ${K} === "boolean" || ${J} === null`).assign(q,t0._`[${J}]`)}}}function VA0({gen:$,parentData:I,parentDataProperty:U},Y){$.if(t0._`${I} !== undefined`,()=>$.assign(t0._`${I}[${U}]`,Y))}function VT($,I,U,Y=IU.Correct){let J=Y===IU.Correct?t0.operators.EQ:t0.operators.NEQ,Q;switch($){case"null":return t0._`${I} ${J} null`;case"array":Q=t0._`Array.isArray(${I})`;break;case"object":Q=t0._`${I} && typeof ${I} == "object" && !Array.isArray(${I})`;break;case"integer":Q=K(t0._`!(${I} % 1) && !isNaN(${I})`);break;case"number":Q=K();break;default:return t0._`typeof ${I} ${J} ${$}`}return Y===IU.Correct?Q:(0,t0.not)(Q);function K(q=t0.nil){return(0,t0.and)(t0._`typeof ${I} == "number"`,q,U?t0._`isFinite(${I})`:t0.nil)}}pb.checkDataType=VT;function wT($,I,U,Y){if($.length===1)return VT($[0],I,U,Y);let J,Q=(0,bb.toHash)($);if(Q.array&&Q.object){let K=t0._`typeof ${I} != "object"`;J=Q.null?K:t0._`!${I} || ${K}`,delete Q.null,delete Q.array,delete Q.object}else J=t0.nil;if(Q.number)delete Q.integer;for(let K in Q)J=(0,t0.and)(J,VT(K,I,U,Y));return J}pb.checkDataTypes=wT;var wA0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:I})=>typeof $=="string"?t0._`{type: ${$}}`:t0._`{type: ${I}}`};function ZT($){let I=ZA0($);(0,KA0.reportError)(I,wA0)}pb.reportTypeError=ZT;function ZA0($){let{gen:I,data:U,schema:Y}=$,J=(0,bb.schemaRefOrVal)($,Y,"type");return{gen:I,keyword:"type",data:U,schema:Y.type,schemaCode:J,schemaValue:J,parentSchema:Y,params:{},it:$}}});var ob=O((mb)=>{Object.defineProperty(mb,"__esModule",{value:!0});mb.assignDefaults=void 0;var UU=s0(),NA0=w1();function MA0($,I){let{properties:U,items:Y}=$.schema;if(I==="object"&&U)for(let J in U)db($,J,U[J].default);else if(I==="array"&&Array.isArray(Y))Y.forEach((J,Q)=>db($,Q,J.default))}mb.assignDefaults=MA0;function db($,I,U){let{gen:Y,compositeRule:J,data:Q,opts:K}=$;if(U===void 0)return;let q=UU._`${Q}${(0,UU.getProperty)(I)}`;if(J){(0,NA0.checkStrictMode)($,`default is ignored for: ${q}`);return}let G=UU._`${q} === undefined`;if(K.useDefaults==="empty")G=UU._`${G} || ${q} === null || ${q} === ""`;Y.if(G,UU._`${q} = ${(0,UU.stringify)(U)}`)}});var O$=O((ab)=>{Object.defineProperty(ab,"__esModule",{value:!0});ab.validateUnion=ab.validateArray=ab.usePattern=ab.callValidateCode=ab.schemaProperties=ab.allSchemaProperties=ab.noPropertyInData=ab.propertyInData=ab.isOwnProperty=ab.hasPropFunc=ab.reportMissingProp=ab.checkMissingProp=ab.checkReportMissingProp=void 0;var l1=s0(),XT=w1(),W9=$5(),AA0=w1();function PA0($,I){let{gen:U,data:Y,it:J}=$;U.if(LT(U,Y,I,J.opts.ownProperties),()=>{$.setParams({missingProperty:l1._`${I}`},!0),$.error()})}ab.checkReportMissingProp=PA0;function TA0({gen:$,data:I,it:{opts:U}},Y,J){return(0,l1.or)(...Y.map((Q)=>(0,l1.and)(LT($,I,Q,U.ownProperties),l1._`${J} = ${Q}`)))}ab.checkMissingProp=TA0;function EA0($,I){$.setParams({missingProperty:I},!0),$.error()}ab.reportMissingProp=EA0;function rb($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:l1._`Object.prototype.hasOwnProperty`})}ab.hasPropFunc=rb;function zT($,I,U){return l1._`${rb($)}.call(${I}, ${U})`}ab.isOwnProperty=zT;function BA0($,I,U,Y){let J=l1._`${I}${(0,l1.getProperty)(U)} !== undefined`;return Y?l1._`${J} && ${zT($,I,U)}`:J}ab.propertyInData=BA0;function LT($,I,U,Y){let J=l1._`${I}${(0,l1.getProperty)(U)} === undefined`;return Y?(0,l1.or)(J,(0,l1.not)(zT($,I,U))):J}ab.noPropertyInData=LT;function tb($){return $?Object.keys($).filter((I)=>I!=="__proto__"):[]}ab.allSchemaProperties=tb;function vA0($,I){return tb(I).filter((U)=>!(0,XT.alwaysValidSchema)($,I[U]))}ab.schemaProperties=vA0;function RA0({schemaCode:$,data:I,it:{gen:U,topSchemaRef:Y,schemaPath:J,errorPath:Q},it:K},q,G,H){let W=H?l1._`${$}, ${I}, ${Y}${J}`:I,V=[[W9.default.instancePath,(0,l1.strConcat)(W9.default.instancePath,Q)],[W9.default.parentData,K.parentData],[W9.default.parentDataProperty,K.parentDataProperty],[W9.default.rootData,W9.default.rootData]];if(K.opts.dynamicRef)V.push([W9.default.dynamicAnchors,W9.default.dynamicAnchors]);let w=l1._`${W}, ${U.object(...V)}`;return G!==l1.nil?l1._`${q}.call(${G}, ${w})`:l1._`${q}(${w})`}ab.callValidateCode=RA0;var CA0=l1._`new RegExp`;function jA0({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:l1._`${J.code==="new RegExp"?CA0:(0,AA0.useFunc)($,J)}(${U}, ${Y})`})}ab.usePattern=jA0;function _A0($){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",l1._`${U}.length`);I.forRange("i",0,G,(H)=>{$.subschema({keyword:Y,dataProp:H,dataPropType:XT.Type.Num},Q),I.if((0,l1.not)(Q),q)})}}ab.validateArray=_A0;function SA0($){let{gen:I,schema:U,keyword:Y,it:J}=$;if(!Array.isArray(U))throw Error("ajv implementation error");if(U.some((G)=>(0,XT.alwaysValidSchema)(J,G))&&!J.opts.unevaluated)return;le Line truncated
missingProperty: ${Y},
depsCount: ${I},
deps: ${q}}`};var JE0={keyword:"dependencies",type:"object",schemaType:"object",error:Kp.error,code($){let[I,q]=QE0($);Jp($,I),Qp($,q)}};function QE0({schema:$}){let I={},q={};for(let U in $){if(U==="__proto__")continue;let Y=Array.isArray($[U])?I:q;Y[U]=$[U]}return[I,q]}function Jp($,I=$.schema){let{gen:q,data:U,it:Y}=$;if(Object.keys(I).length===0)return;let J=q.let("missing");for(let Q in I){let K=I[Q];if(K.length===0)continue;let z=(0,oJ.propertyInData)(q,U,Q,Y.opts.ownProperties);if($.setParams({property:Q,depsCount:K.length,deps:K.join(", ")}),Y.allErrors)q.if(z,()=>{for(let w of K)(0,oJ.checkReportMissingProp)($,w)});else q.if(_P._`${z} && (${(0,oJ.checkMissingProp)($,K,J)})`),(0,oJ.reportMissingProp)($,J),q.else()}}Kp.validatePropertyDeps=Jp;function Qp($,I=$.schema){let{gen:q,data:U,keyword:Y,it:J}=$,Q=q.name("valid");for(let K in I){if((0,YE0.alwaysValidSchema)(J,I[K]))continue;q.if((0,oJ.propertyInData)(q,U,K,J.opts.ownProperties),()=>{let z=$.subschema({keyword:Y,schemaProp:K},Q);$.mergeValidEvaluated(z,Q)},()=>q.var(Q,!0)),$.ok(Q)}}Kp.validateSchemaDeps=Qp;Kp.default=JE0});var Wp=L((Vp)=>{Object.defineProperty(Vp,"__esModule",{value:!0});var Hp=o0(),wE0=w1(),GE0={message:"property name must be valid",params:({params:$})=>Hp._`{propertyName: ${$.propertyName}}`},HE0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:GE0,code($){let{gen:I,schema:q,data:U,it:Y}=$;if((0,wE0.alwaysValidSchema)(Y,q))return;let J=I.name("valid");I.forIn("key",U,(Q)=>{$.setParams({propertyName:Q}),$.subschema({keyword:"propertyNames",data:Q,dataTypes:["string"],propertyName:Q,compositeRule:!0},J),I.if((0,Hp.not)(J),()=>{if($.error(!0),!Y.allErrors)I.break()})}),$.ok(J)}};Vp.default=HE0});var hP=L((Zp)=>{Object.defineProperty(Zp,"__esModule",{value:!0});var KH=D$(),f$=o0(),WE0=a8(),zH=w1(),ZE0={message:"must NOT have additional properties",params:({params:$})=>f$._`{additionalProperty: ${$.additionalProperty}}`},XE0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ZE0,code($){let{gen:I,schema:q,parentSchema:U,data:Y,errsCount:J,it:Q}=$;if(!J)throw Error("ajv implementation error");let{allErrors:K,opts:z}=Q;if(Q.props=!0,z.removeAdditional!=="all"&&(0,zH.alwaysValidSchema)(Q,q))return;let w=(0,KH.allSchemaProperties)(U.properties),G=(0,KH.allSchemaProperties)(U.patternProperties);H(),$.ok(f$._`${J} === ${WE0.default.errors}`);function H(){I.forIn("key",Y,(O)=>{if(!w.length&&!G.length)X(O);else I.if(W(O),()=>X(O))})}function W(O){let N;if(w.length>8){let T=(0,zH.schemaRefOrVal)(Q,U.properties,"properties");N=(0,KH.isOwnProperty)(I,T,O)}else if(w.length)N=(0,f$.or)(...w.map((T)=>f$._`${O} === ${T}`));else N=f$.nil;if(G.length)N=(0,f$.or)(N,...G.map((T)=>f$._`${(0,KH.usePattern)($,T)}.test(${O})`));return(0,f$.not)(N)}function V(O){I.code(f$._`delete ${Y}[${O}]`)}function X(O){if(z.removeAdditional==="all"||z.removeAdditional&&q===!1){V(O);return}if(q===!1){if($.setParams({additionalProperty:O}),$.error(),!K)I.break();return}if(typeof q=="object"&&!(0,zH.alwaysValidSchema)(Q,q)){let N=I.name("valid");if(z.removeAdditional==="failing")D(O,N,!1),I.if((0,f$.not)(N),()=>{$.reset(),V(O)});else if(D(O,N),!K)I.if((0,f$.not)(N),()=>I.break())}}function D(O,N,T){let P={keyword:"additionalProperties",dataProp:O,dataPropType:zH.Type.Str};if(T===!1)Object.assign(P,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(P,N)}}};Zp.default=XE0});var Lp=L((Op)=>{Object.defineProperty(Op,"__esModule",{value:!0});var OE0=uJ(),Xp=D$(),SP=w1(),Dp=hP(),LE0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:q,parentSchema:U,data:Y,it:J}=$;if(J.opts.removeAdditional==="all"&&U.additionalProperties===void 0)Dp.default.code(new OE0.KeywordCxt(J,Dp.default,"additionalProperties"));let Q=(0,Xp.allSchemaProperties)(q);for(let H of Q)J.definedProperties.add(H);if(J.opts.unevaluated&&Q.length&&J.props!==!0)J.props=SP.mergeEvaluated.props(I,(0,SP.toHash)(Q),J.props);let K=Q.filter((H)=>!(0,SP.alwaysValidSchema)(J,q[H]));if(K.length===0)return;let z=I.name("valid");for(let H of K){if(w(H))G(H);else{if(I.if((0,Xp.propertyInData)(I,Y,H,J.opts.ownProperties)),G(H),!J.allErrors)I.else().var(z,!0);I.endIf()}$.it.definedProperties.add(H),$.ok(z)}function w(H){return J.opts.useDefaults&&!J.compositeRule&&q[H].default!==void 0}function G(H){$.subschema({keyword:"properties",schemaProp:H,dataProp:H},z)}}};Op.default=LE0});var gp=L((Ap)=>{Object.defineProperty(Ap,"__esModule",{value:!0});var Np=D$(),wH=o0(),Fp=w1(),Mp=w1(),FE0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:q,data:U,parentSchema:Y,it:J}=$,{opts:Q}=J,K=(0,Np.allSchemaProperties)(q),z=K.filter((D)=>(0,Fp.alwaysValidSchema)(J,q[D]));if(K.length===0||z.length===K.length&&(!J.opts.unevaluated||J.props===!0))return;let w=Q.strictSchema&&!Q.allowMatchingProperties&&Y.properties,G=I.name("valid");if(J.props!==!0&&!(J.props instanceo Line 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 Rm=L(($_0)=>{var Tj=Y5().Buffer;$_0._dbcs=Q5;var t4=-1,vm=-2,F$=-10,j6=-1000,Aq=Array(256),DQ=-1;for(XQ=0;XQ<256;XQ++)Aq[XQ]=t4;var XQ;function Q5($,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 q=$.table();this.decodeTables=[],this.decodeTables[0]=Aq.slice(0),this.decodeTableSeq=[];for(var U=0;U<q.length;U++)this._addDecodeChunk(q[U]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var Y=this.decodeTables.length;this.decodeTables.push(Aq.slice(0));var J=this.decodeTables.length;this.decodeTables.push(Aq.slice(0));var Q=this.decodeTables[0];for(var U=129;U<=254;U++){var K=this.decodeTables[j6-Q[U]];for(var z=48;z<=57;z++){if(K[z]===t4)K[z]=j6-Y;else if(K[z]>j6)throw Error("gb18030 decode tables conflict at byte 2");var w=this.decodeTables[j6-K[z]];for(var G=129;G<=254;G++){if(w[G]===t4)w[G]=j6-J;else if(w[G]===j6-J)continue;else if(w[G]>j6)throw Error("gb18030 decode tables conflict at byte 3");var H=this.decodeTables[j6-w[G]];for(var W=48;W<=57;W++)if(H[W]===t4)H[W]=vm}}}}this.defaultCharUnicode=I.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var V={};if($.encodeSkipVals)for(var U=0;U<$.encodeSkipVals.length;U++){var X=$.encodeSkipVals[U];if(typeof X==="number")V[X]=!0;else for(var z=X.from;z<=X.to;z++)V[z]=!0}if(this._fillEncodeTable(0,0,V),$.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===t4)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===t4)this.defCharSB=63}Q5.prototype.encoder=UV;Q5.prototype.decoder=jj;Q5.prototype._getDecodeTrieNode=function($){var I=[];for(;$>0;$>>>=8)I.push($&255);if(I.length==0)I.push(0);var q=this.decodeTables[0];for(var U=I.length-1;U>0;U--){var Y=q[I[U]];if(Y==t4)q[I[U]]=j6-this.decodeTables.length,this.decodeTables.push(q=Aq.slice(0));else if(Y<=j6)q=this.decodeTables[j6-Y];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return q};Q5.prototype._addDecodeChunk=function($){var I=parseInt($[0],16),q=this._getDecodeTrieNode(I);I=I&255;for(var U=1;U<$.length;U++){var Y=$[U];if(typeof Y==="string")for(var J=0;J<Y.length;){var Q=Y.charCodeAt(J++);if(Q>=55296&&Q<56320){var K=Y.charCodeAt(J++);if(K>=56320&&K<57344)q[I++]=65536+(Q-55296)*1024+(K-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(Q>4080&&Q<=4095){var z=4095-Q+2,w=[];for(var G=0;G<z;G++)w.push(Y.charCodeAt(J++));q[I++]=F$-this.decodeTableSeq.length,this.decodeTableSeq.push(w)}else q[I++]=Q}else if(typeof Y==="number"){var H=q[I-1]+1;for(var J=0;J<Y;J++)q[I++]=H++}else throw Error("Incorrect type '"+typeof Y+"' given in "+this.encodingName+" at chunk "+$[0])}if(I>255)throw Error("Incorrect chunk in "+this.encodinLine truncated
\x00`,p+=p1(n,2),p+=K.magic,p+=p1(O,2),p+=p1(N,2),p+=p1(h.crc32,4),p+=p1(h.compressedSize,4),p+=p1(h.uncompressedSize,4),p+=p1(w.length,2),p+=p1(T.length,2);var C=UW.LOCAL_FILE_HEADER+p+w+T,f=UW.CENTRAL_FILE_HEADER+p1(t,2)+p+p1(W.length,2)+"\x00\x00\x00\x00"+p1(S,4)+p1(U,4)+w+T+W;return{fileRecord:C,dirRecord:f}},Qf0=function($,I,q,U,Y){var J="",Q=cq.transformTo("string",Y(U));return J=UW.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+p1($,2)+p1($,2)+p1(I,4)+p1(q,4)+p1(Q.length,2)+Q,J},Kf0=function($){var I="";return I=UW.DATA_DESCRIPTOR+p1($.crc32,4)+p1($.compressedSize,4)+p1($.uncompressedSize,4),I};function m$($,I,q,U){dq.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=I,this.zipPlatform=q,this.encodeFileName=U,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}cq.inherits(m$,dq);m$.prototype.push=function($){var I=$.meta.percent||0,q=this.entriesCount,U=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,dq.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:q?(I+100*(q-U-1))/q:100}})};m$.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var I=this.streamFiles&&!$.file.dir;if(I){var q=js($,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:q.fileRecord,meta:{percent:0}})}else this.accumulate=!0};m$.prototype.closedSource=function($){this.accumulate=!1;var I=this.streamFiles&&!$.file.dir,q=js($,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(q.dirRecord),I)this.push({data:Kf0($),meta:{percent:100}});else{this.push({data:q.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};m$.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 q=this.bytesWritten-$,U=Qf0(this.dirRecords.length,q,$,this.zipComment,this.encodeFileName);this.push({data:U,meta:{percent:100}})};m$.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};m$.prototype.registerPrevious=function($){this._sources.push($);var I=this;return $.on("data",function(q){I.processChunk(q)}),$.on("end",function(){if(I.closedSource(I.previous.streamInfo),I._sources.length)I.prepareNextSource();else I.end()}),$.on("error",function(q){I.error(q)}),this};m$.prototype.resume=function(){if(!dq.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};m$.prototype.error=function($){var I=this._sources;if(!dq.prototype.error.call(this,$))return!1;for(var q=0;q<I.length;q++)try{I[q].error($)}catch(U){}return!0};m$.prototype.lock=function(){dq.prototype.lock.call(this);var $=this._sources;for(var I=0;I<$.length;I++)$[I].lock()};Es.exports=m$});var vs=L((Hf0)=>{var zf0=ZB(),wf0=Bs(),Gf0=function($,I){var q=$||I,U=zf0[q];if(!U)throw Error(q+" is not a valid compression method !");return U};Hf0.generateWorker=function($,I,q){var U=new wf0(I.streamFiles,q,I.platform,I.encodeFileName),Y=0;try{$.forEach(function(J,Q){Y++;var K=Gf0(Q.options.compression,I.compression),z=Q.options.compressionOptions||I.compressionOptions||{},w=Q.dir,G=Q.date;Q._compressWorker(K,z).withStreamInfo("file",{name:J,dir:w,date:G,comment:Q.comment||"",unixPermissions:Q.unixPermissions,dosPermissions:Q.dosPermissions}).pipe(U)}),U.entriesCount=Y}catch(J){U.error(J)}return U}});var Cs=L((ug1,Rs)=>{var Wf0=z4(),YW=I$();function q2($,I){YW.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(I)}Wf0.inherits(q2,YW);q2.prototype._bindStream=function($){var I=this;this._stream=$,$.pause(),$.on("data",function(q){I.push({data:q,meta:{percent:0}})}).on("error",function(q){if(I.isPaused)this.generatedError=q;else I.error(q)}).on("end",function(){if(I.isPaused)I._upstreamEnded=!0;else I.end()})};q2.prototype.pause=function(){if(!YW.prototype.pause.call(this))return!1;return this._stream.pause(),!0};q2.prototype.resume=function(){if(!YW.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};Rs.exports=q2});var bs=L((xg1,ns)=>{var Zf0=Sq(),U2=z4(),ys=I$(),Xf0=FE(),us=ME(),_s=fV(),Df0=ht(),Of0=vs(),hs=yQ(),Lf0=Cs(),xs=function($,I,q){var U=U2.getTypeOf(I),Y,J=U2.extend(q||{},us);if(J.date=J.date||new Date,J.compression!==null)J.compression=J.compression.toUpperCase();if(typeof J.unixPermissions==="string")J.unixPermissions=parseInt(J.unixPermissions,8);if(J.unixPermissions&&J.unixPermissions&16384)J.dir=!0;if(J.dosPermissions&&J.dosPermissions&16)J.dir=!0;if(J. Line truncated
`)}openNode($,I){let q=this.tos,U=this._xml;if(q&&this.open)U.push(">");this._stack.push($),U.push("<"),U.push($),sB(U,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)C00(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");sB(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(R00.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,q){if(this.openNode($,I),q!==void 0)this.writeText(q);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("")}}eB.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};_00.exports=eB});var $v=L((wi0)=>{var h00=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function zi0($){if(typeof $==="string")return $;if(h00)return h00.decode($);return $.toString()}wi0.bufferToString=zi0});var k00=L((y00)=>{Object.defineProperty(y00,"__esModule",{value:!0});y00.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;y00.S=` \r
`;y00.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";y00.NAME_CHAR="-"+y00.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";y00.CHAR_RE=new RegExp("^["+y00.CHAR+"]$","u");y00.S_RE=new RegExp("^["+y00.S+"]+$","u");y00.NAME_START_CHAR_RE=new RegExp("^["+y00.NAME_START_CHAR+"]$","u");y00.NAME_CHAR_RE=new RegExp("^["+y00.NAME_CHAR+"]$","u");y00.NAME_RE=new RegExp("^["+y00.NAME_START_CHAR+"]["+y00.NAME_CHAR+"]*$","u");y00.NMTOKEN_RE=new RegExp("^["+y00.NAME_CHAR+"]+$","u");var Iv=9,qv=10,Uv=13,Yv=32;y00.S_LIST=[Yv,qv,Uv,Iv];function Hi0($){return $>=Yv&&$<=55295||$===qv||$===Uv||$===Iv||$>=57344&&$<=65533||$>=65536&&$<=1114111}y00.isChar=Hi0;function Vi0($){return $===Yv||$===qv||$===Uv||$===Iv}y00.isS=Vi0;function S00($){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}y00.isNameStartChar=S00;function Wi0($){return S00($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}y00.isNameChar=Wi0});var o00=L((c00)=>{Object.defineProperty(c00,"__esModule",{value:!0});c00.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";c00.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";c00.S=` \r
`;c00.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";c00.NAME_CHAR="-"+c00.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";c00.CHAR_RE=new RegExp("^["+c00.CHAR+"]$","u");c00.RESTRICTED_CHAR_RE=new RegExp("^["+c00.RESTRICTED_CHAR+"]$","u");c00.S_RE=new RegExp("^["+c00.S+"]+$","u");c00.NAME_START_CHAR_RE=new RegExp("^["+c00.NAME_START_CHAR+"]$","u");c00.NAME_CHAR_RE=new RegExp("^["+c00.NAME_CHAR+"]$","u");c00.NAME_RE=new RegExp("^["+c00.NAME_START_CHAR+"]["+c00.NAME_CHAR+"]*$","u");c00.NMTOKEN_RE=new RegExp("^["+c00.NAME_CHAR+"]+$","u");var f00=9,n00=10,b00=13,i00=32;c00.S_LIST=[i00,n00,b00,f00];function Ti0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}c00.isChar=Ti0;function ji0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}c00.isRestrictedChar=ji0;function Ei0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}c00.isCharAndNotRestricted=Ei0;function Bi0($){return $===i00||$===n00||$===b00||$===f00}c00.isS=Bi0;function p00($){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}c00.isNameStartChar=p00;function vi0($){return p00($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}c00.isNameChar=vi0});var a00=L((t00)=>{Object.defineProperty(t00,"__esModule",{value:!0});t00.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";t00.NC_NAME_CHAR="-"+t00.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";t00.NC_NAME_START_CHAR_RE=new RegExp("^["+t00.NC_NAME_START_CHAR+"]$","u");t00.NC_NAME_CHAR_RE=new RegExp("^["+t00.NC_NAME_CHAR+"]$","u");t00.NC_NAME_RE=new RegExp("^["+t00.NC_NAME_START_CHAR+"]["+t00.NC_NAME_CHAR+"]*$","u");function r00($){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}t00.isNCNameStartChar=r00;function ci0($){return r00($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}t00.isNCNameChar=ci0});var N10=L((L10)=>{Object.defineProperty(L10,"__esModule",{value:!0});var qU=k00(),ti0=o00(),Lv=a00(),p6=qU.isS,ai0=qU.isChar,D2=qU.isNameStartChar,s00=qU.isNameChar,V10=qU.S_LIST,si0=qU.NAME_RE,ei0=ti0.isChar,$p0=Lv.isNCNameStartChar,Ip0=Lv.isNCNameChar,qp0=Lv.NC_NAME_RE,hW="http://www.w3.org/XML/1998/namespace",IU="http://www.w3.org/2000/xmlns/",Up0={__proto__:null,xml:hW,xmlns:IU},Yp0={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},U4=-1,v8=-2,e00=0,Jp0=1,Qv=2,Qp0=3,sq=4,Kp0=5,zp0=6,wp0=7,Kv=8,Gp0=9,Hp0=10,Vp0=11,Wp0=12,B6=13,BW=14,zv=15,Zp0=16,wv=17,Xp0=18,Dp0=19,Gv=20,Op0=21,Lp0=22,Np0=23,$10=24,Hv=25,vW=26,I10=27,Fp0=28,Mp0=29,q10=30,Ap0=31,gp0=32,Q3=33,Pp0=34,Vv=35,O2=36,Wv=37,Tp0=38,U10=39,Y10=40,jp0=41,J10=42,Ep0=43,Bp0=44,Zv=9,r$=10,Xv=13,Q10=32,K10=33,W10=34,L2=38,Z10=39,RW=45,CW=47,vp0=59,C9=60,eq=61,_4=62,$6=63,X10=91,$U=93,z10=133,w10=8232,_W=($)=>$===W10||$===Z10,D10=[W10,Z10],Rp0=[...D10,X10,_4],Cp0=[...D10,C9,$U],_p0=[eq,$6,...V10],hp0=[...V10,_4,L2,C9];function Ov($,I,q){switch(I){case"xml":if(q!==hW)$.fail(`xml prefix must be bound to ${hW}.`);break;case"xmlns":if(q!==IU)$.fail(`xmlns prefix must be bound to ${IU}.`);break;default:}switch(q){case IU:$.fail(I===""?`the default namespace may not be set to ${q}.`:`may not assign a prefix (even "xmlns") to the URI ${IU}.`);break;case hW:switch(I){case"xml":break;case"":$.fail(`the default namespace may not be set to ${q}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function Sp0($,I){for(let q of Object.keys(I))Ov($,q,I[q])}var yp0=($)=>qp0.test($),up0=($)=>si0.test($),K3=0,G10=1,Dv=2;L10.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var H10={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 O10{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=$p0,this.nameCheck=Ip0,this.isName=yp0,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},Up0);let q=this.opt.additionalNamesp Line truncated
`,I=this.i}}captureToChar($){let{i:I}=this,{chunk:q}=this;while(!0){let U=this.getCode();switch(U){case v8:this.text+=`${q.slice(I,this.prevI)}
`,I=this.i,U=r$;break;case U4:return this.text+=q.slice(I),!1;default:}if(U===$)return this.text+=q.slice(I,this.prevI),!0}}captureNameChars(){let{chunk:$,i:I}=this;while(!0){let q=this.getCode();if(q===U4)return this.name+=$.slice(I),U4;if(!s00(q))return this.name+=$.slice(I,this.prevI),q===v8?r$:q}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===U4||!p6($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=ai0,this.getCode=this.getCode10;else this.isChar=ei0,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=Jp0}sBeginWhitespace(){let $=this.i,I=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(I){case C9:if(this.state=zv,this.text.length!==0)throw Error("no-empty text at start");break;case U4:break;default:this.unget(),this.state=B6,this.xmlDeclPossible=!1}}sDoctype(){var $;let I=this.captureTo(Rp0);switch(I){case _4:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=B6,this.doctype=!0;break}case U4:break;default:if(this.text+=String.fromCodePoint(I),I===X10)this.state=sq;else if(_W(I))this.state=Qp0,this.q=I}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=Qv}sDTD(){let $=this.captureTo(Cp0);if($===U4)return;if(this.text+=String.fromCodePoint($),$===$U)this.state=Qv;else if($===C9)this.state=zp0;else if(_W($))this.state=Kp0,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=sq,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case K10:this.state=wp0,this.openWakaBang="";break;case $6:this.state=Vp0;break;default:this.state=sq}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),I=this.openWakaBang+=$;if(this.text+=$,I!=="-")this.state=I==="--"?Kv:sq,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(RW))this.text+="-",this.state=Gp0}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===RW?Hp0:Kv}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===_4)this.state=sq;else this.fail("malformed comment."),this.state=Kv}sDTDPI(){if(this.captureToChar($6))this.text+="?",this.state=Wp0}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===_4)this.state=sq}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:I}=this;$:while(!0)switch(this.getCode()){case v8:this.entity+=`${I.slice($,this.prevI)}
`,$=this.i;break;case vp0:{let{entityReturnState:q}=this,U=this.entity+I.slice($,this.prevI);this.state=q;let Y;if(U==="")this.fail("empty entity name."),Y="&;";else Y=this.parseEntity(U),this.entity="";if(q!==B6||this.textHandler!==void 0)this.text+=Y;break $}case U4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(D2($))this.state=Pp0,this.unget(),this.xmlDeclPossible=!1;else switch($){case CW:this.state=Ep0,this.xmlDeclPossible=!1;break;case K10:this.state=Zp0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case $6:this.state=Np0;break;default:this.fail("disallowed character in tag name"),this.state=B6,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=Gv,this.openWakaBang="";break;case"--":this.state=wv,this.openWakaBang="";break;case"DOCTYPE":if(this.state=Qv,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(RW))this.state=Xp0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===RW)this.state=Dp0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=wv}sCommentEnded(){let $=this.getCodeNorm();if($!==_4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=wv;else this.state=B6}sCData(){if(this.captureToChar($U))this.state=Op0}sCDataEnding(){let $=this.getCodeNorm();if($===$U)this.state=Lp0;else this.text+=`]${String.fromCodePoint($)}`,this.state=Gv}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case _4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=B6;break}case $U:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=Gv}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=$10;else if($===$6||p6($))this.fail("processing instruction without a target."),this.state=$===$6?vW:Hv;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=$10}sPIRest(){let{chunk:$,i:I}=this;while(!0){let q=this.getCodeNorm();if(q===U4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(q)){this.piTarget+=$.slice(I,this.prevI);let U=q===$6;if(U||p6(q))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=U?Q3:I10}else this.state=U?vW:Hv;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(q);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===$6)this.state=vW;else if(!p6($))this.text=String.fromCodePoint($)}else if(this.captureToChar($6))this.state=vW}sPIEnding(){var $;let I=this.getCodeNorm();if(I===_4){let{piTarget:q}=this;if(q.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:q,body:this.text}),this.piTarget=this.text="",this.state=B6}else if(I===$6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=Hv;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===$6){this.state=Q3;return}if($!==U4)this.state=Fp0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(_p0);if($===$6){this.state=Q3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(p6($)||$===eq))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=$===eq?q10:Mp0}sXMLDeclEq(){let $=this.getCodeNorm();if($===$6){this.state=Q3,this.fail("XML declaration is incomplete.");return}if(p6($))return;if($!==eq)this.fail("value required.");this.state=q10}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===$6){this.state=Q3,this.fail("XML declaration is incomplete.");return}if(p6($))return;if(!_W($))this.fail("value must be quoted."),this.q=Q10;else this.q=$;this.state=Ap0}sXMLDeclValue(){let $=this.captureTo([this.q,$6]);if($===$6){this.state=Q3,this.text="",this.fail("XML declaration is incomplete.");return}if($===U4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let q=I;if(this.xmlDecl.version=q,!/^1\.[0-9]+$/.test(q))this.fail("ver Line truncated
`;$=this.i,I=K3;break;case U4:if(U!==void 0)this.text+=q.slice($);break $;default:I=K3}this.forbiddenState=I}handleTextOutsideRoot(){let{i:$}=this,{chunk:I,textHandler:q}=this,U=!1;$:while(!0){let Y=this.getCode();switch(Y){case C9:{if(this.state=zv,q!==void 0){let{text:J}=this,Q=I.slice($,this.prevI);if(J.length!==0)q(J+Q),this.text="";else if(Q.length!==0)q(Q)}break $}case L2:if(this.state=BW,this.entityReturnState=B6,q!==void 0)this.text+=I.slice($,this.prevI);U=!0;break $;case v8:if(q!==void 0)this.text+=`${I.slice($,this.prevI)}
`;$=this.i;break;case U4:if(q!==void 0)this.text+=I.slice($);break $;default:if(!p6(Y))U=!0}}if(!U)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 q;let{prefix:U,local:Y}=this.qname($),J={name:$,prefix:U,local:Y,value:I};if(this.attribList.push(J),(q=this.attributeHandler)===null||q===void 0||q.call(this,J),U==="xmlns"){let Q=I.trim();if(this.currentXMLVersion==="1.0"&&Q==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[Y]=Q,Ov(this,Y,Q)}else if($==="xmlns"){let Q=I.trim();this.topNS[""]=Q,Ov(this,"",Q)}}pushAttribPlain($,I){var q;let U={name:$,value:I};this.attribList.push(U),(q=this.attributeHandler)===null||q===void 0||q.call(this,U)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:q}=this;while(q.length>0){let Y=q.pop();this.fail(`unclosed tag: ${Y.name}`)}if(this.state!==e00&&this.state!==B6)this.fail("unexpected end.");let{text:U}=this;if(U.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,U),this.text="";return this._closed=!0,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,q;let U=this.topNS[$];if(U!==void 0)return U;let{tags:Y}=this;for(let J=Y.length-1;J>=0;J--)if(U=Y[J].ns[$],U!==void 0)return U;if(U=this.ns[$],U!==void 0)return U;return(q=(I=this.opt).resolvePrefix)===null||q===void 0?void 0:q.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let q=$.slice(I+1),U=$.slice(0,I);if(U===""||q===""||q.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:U,local:q}}processAttribsNS(){var $;let{attribList:I}=this,q=this.tag;{let{prefix:J,local:Q}=this.qname(q.name);q.prefix=J,q.local=Q;let K=q.uri=($=this.resolve(J))!==null&&$!==void 0?$:"";if(J!==""){if(J==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(K==="")this.fail(`unbound namespace prefix: ${JSON.stringify(J)}.`),q.uri=J}}if(I.length===0)return;let{attributes:U}=q,Y=new Set;for(let J of I){let{name:Q,prefix:K,local:z}=J,w,G;if(K==="")w=Q==="xmlns"?IU:"",G=Q;else{if(w=this.resolve(K),w===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(K)}.`),w=K;G=`{${w}}${z}`}if(Y.has(G))this.fail(`duplicate attribute: ${G}.`);Y.add(G),J.uri=w,U[Q]=J}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:q,value:U}of $){if(I[q]!==void 0)this.fail(`duplicate attribute: ${q}.`);I[q]=U}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,q=this.tag;q.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,q),I.push(q),this.state=B6,this.name=""}openSelfClosingTag(){var $,I,q;this.processAttribs();let{tags:U}=this,Y=this.tag;if(Y.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,Y),(I=this.closeTagHandler)===null||I===void 0||I.call(this,Y),(this.tag=(q=U[U.length-1])!==null&&q!==void 0?q:null)===null)this.closedRoot=!0;this.state=B6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=B6,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let q=this.closeTagHandler,U=$.length;while(U-- >0){let Y=this.tag=$.pop();if(this.topNS=Y.ns,q===null||q===void 0||q(Y),Y.name===I)break;this.fail("unexpected close tag.")}if(U===0)this.closedRoot=!0;else if(U<0)this.fail(`unmatched closing tag: ${I}.`),this.text+=`</${I}>`}parseEntity($){if($[0]!=="#"){let q=this.ENTITIES[$];if(q!==void 0)return q;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)}}L10.SaxesParser=O10});var N2=L((FP1,F10)=>{var{SaxesParser:fp0}=N10(),{PassThrough:np0}=W6(),{bufferToString:bp0}=$v();F10.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new np0);let I=new fp0,q;I.on("error",(Y)=>{q=Y});let U=[];I.on("opentag",(Y)=>U.push({eventType:"opentag",value:Y})),I.on("text",(Y)=>U.push({eventType:"text",value:Y})),I.on("closetag",(Y)=>U.push({eventType:"closetag",value:Y}));for await(let Y of $){if(I.write(bp0(Y)),q)throw q;yield U,U=[]}}});var Z0=L((MP1,M10)=>{var ip0=N2(),pp0=e4();class UU{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof UU)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let I of $)for(let{eventType:q,value:U}of I)if(q==="opentag")this.parseOpen(U);else if(q==="text")this.parseText(U);else if(q==="closetag"){if(!this.parseClose(U.name))return thLine 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}`}}a90.FormatterOptions=t90});var VZ=L((lj1,q70)=>{var er0="[object AsyncFunction]",$t0="[object Function]",It0="[object GeneratorFunction]",qt0="[object Null]",Ut0="[object Proxy]",Yt0="[object Undefined]",Jt0=typeof global=="object"&&global&&global.Object===Object&&global,Qt0=typeof self=="object"&&self&&self.Object===Object&&self,Kt0=Jt0||Qt0||Function("return this")(),$70=Object.prototype,zt0=$70.hasOwnProperty,I70=$70.toString,e90=Kt0.Symbol,Z3=e90?e90.toStringTag:void 0;function wt0($){if($==null)return $===void 0?Yt0:qt0;return Z3&&Z3 in Object($)?Gt0($):Ht0($)}function Gt0($){var I=zt0.call($,Z3),q=$[Z3];try{$[Z3]=void 0;var U=!0}catch(J){}var Y=I70.call($);if(U)if(I)$[Z3]=q;else delete $[Z3];return Y}function Ht0($){return I70.call($)}function Vt0($){if(!Wt0($))return!1;var I=wt0($);return I==$t0||I==It0||I==er0||I==Ut0}function Wt0($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}q70.exports=Vt0});var x70=L((WZ,WU)=>{var Zt0=200,bR="__lodash_hash_undefined__",MZ=1,Z70=2,X70=9007199254740991,ZZ="[object Arguments]",SR="[object Array]",Xt0="[object AsyncFunction]",D70="[object Boolean]",O70="[object Date]",L70="[object Error]",N70="[object Function]",Dt0="[object GeneratorFunction]",XZ="[object Map]",F70="[object Number]",Ot0="[object Null]",VU="[object Object]",U70="[object Promise]",Lt0="[object Proxy]",M70="[object RegExp]",DZ="[object Set]",A70="[object String]",Nt0="[object Symbol]",Ft0="[object Undefined]",yR="[object WeakMap]",g70="[object ArrayBuffer]",OZ="[object DataView]",Mt0="[object Float32Array]",At0="[object Float64Array]",gt0="[object Int8Array]",Pt0="[object Int16Array]",Tt0="[object Int32Array]",jt0="[object Uint8Array]",Et0="[object Uint8ClampedArray]",Bt0="[object Uint16Array]",vt0="[object Uint32Array]",Rt0=/[\\^$.*+?()[\]{}|]/g,Ct0=/^\[object .+?Constructor\]$/,_t0=/^(?:0|[1-9]\d*)$/,o1={};o1[Mt0]=o1[At0]=o1[gt0]=o1[Pt0]=o1[Tt0]=o1[jt0]=o1[Et0]=o1[Bt0]=o1[vt0]=!0;o1[ZZ]=o1[SR]=o1[g70]=o1[D70]=o1[OZ]=o1[O70]=o1[L70]=o1[N70]=o1[XZ]=o1[F70]=o1[VU]=o1[M70]=o1[DZ]=o1[A70]=o1[yR]=!1;var P70=typeof global=="object"&&global&&global.Object===Object&&global,ht0=typeof self=="object"&&self&&self.Object===Object&&self,F5=P70||ht0||Function("return this")(),T70=typeof WZ=="object"&&WZ&&!WZ.nodeType&&WZ,Y70=T70&&typeof WU=="object"&&WU&&!WU.nodeType&&WU,j70=Y70&&Y70.exports===T70,CR=j70&&P70.process,J70=function(){try{return CR&&CR.binding&&CR.binding("util")}catch($){}}(),Q70=J70&&J70.isTypedArray;function St0($,I){var q=-1,U=$==null?0:$.length,Y=0,J=[];while(++q<U){var Q=$[q];if(I(Q,q,$))J[Y++]=Q}return J}function yt0($,I){var q=-1,U=I.length,Y=$.length;while(++q<U)$[Y+q]=I[q];return $}function ut0($,I){var q=-1,U=$==null?0:$.length;while(++q<U)if(I($[q],q,$))return!0;return!1}function xt0($,I){var q=-1,U=Array($);while(++q<$)U[q]=I(q);return U}function kt0($){return function(I){return $(I)}}function ft0($,I){return $.has(I)}function nt0($,I){return $==null?void 0:$[I]}function bt0($){var I=-1,q=Array($.size);return $.forEach(function(U,Y){q[++I]=[Y,U]}),q}function it0($,I){return function(q){return $(I(q))}}function pt0($){var I=-1,q=Array($.size);return $.forEach(function(U){q[++I]=U}),q}var ct0=Array.prototype,dt0=Function.prototype,AZ=Object.prototype,_R=F5["__core-js_shared__"],E70=dt0.toString,C8=AZ.hasOwnProperty,K70=function(){var $=/[^.]+$/.exec(_R&&_R.keys&&_R.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),B70=AZ.toString,lt0=RegExp("^"+E70.call(C8).replace(Rt0,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),z70=j70?F5.Buffer:void 0,LZ=F5.Symbol,w70=F5.Uint8Array,v70=AZ.propertyIsEnumerable,mt0=ct0.splice,X3=LZ?LZ.toStringTag:void 0,G70=Object.getOwnPropertySymbols,ot0=z70?z70.isBuffer:void 0,rt0=it0(Object.keys,Object),uR=ZU(F5,"DataView"),j2=ZU(F5,"Map"),xR=ZU(F5,"Promise"),kR=ZU(F5,"Set"),fR=ZU(F5,"WeakMap"),E2=ZU(Object,"create"),tt0=L3(uR),at0=L3(j2),st0=L3(xR),et0=L3(kR),$a0=L3(fR),H70=LZ?LZ.prototype:void 0,hR=H70?H70.valueOf:void 0;function D3($){var I=-1,q=$==null?0:$.length;this.clear();while(++I<q){var U=$[I];this.set(U[0],U[1])}}function Ia0(){this.__data__=E2?E2(null):{},this.size=0}function qa0($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function Ua0($){var I=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(I)}set headers($){this._headers=$}shouldQuote($,I){let q=I?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(ws0.default(q))return q;if(Array.isArray(q))return q[$];if(this._headers!==null)return q[this._headers[$]];return!1}format($,I,q){let U=`${Gs0.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:Y}=this;if(Y.quote!==""){if(U.indexOf(Y.quote)!==-1)return this.quoteField(U.replace(this.REPLACE_REGEXP,Y.escapedQuote))}if(U.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(I,q))return this.quoteField(U);return U}quoteField($){let{quote:I}=this.formatterOptions;return`${I}${$}${I}`}}XU.FieldFormatter=l70});var lR=L((m70)=>{Object.defineProperty(m70,"__esModule",{value:!0});m70.isSyncTransform=void 0;m70.isSyncTransform=($)=>$.length===1});var t70=L((DU)=>{var r70=DU&&DU.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(DU,"__esModule",{value:!0});DU.RowFormatter=void 0;var Vs0=r70(VZ()),Ws0=r70(x70()),Zs0=dR(),Xs0=lR();class N3{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new Zs0.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(N3.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(Xs0.isSyncTransform($))return(I,q)=>{let U=null;try{U=$(I)}catch(Y){return q(Y)}return q(null,U)};return(I,q)=>{$(I,q)}}set rowTransform($){if(!Vs0.default($))throw TypeError("The transform should be a function");this._rowTransform=N3.createTransform($)}format($,I){this.callTransformer($,(q,U)=>{if(q)return I(q);if(!$)return I(null);let Y=[];if(U){let{shouldFormatColumns:J,headers:Q}=this.checkHeaders(U);if(this.shouldWriteHeaders&&Q&&!this.hasWrittenHeaders)Y.push(this.formatColumns(Q,!0)),this.hasWrittenHeaders=!0;if(J){let K=this.gatherColumns(U);Y.push(this.formatColumns(K,!1))}}return I(null,Y)})}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=N3.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!Ws0.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(N3.isRowHashArray($))return this.headers.map((I,q)=>{let U=$[q];if(U)return U[1];return""});if(N3.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((I,q)=>$[q])}callTransformer($,I){if(!this._rowTransform)return I(null,$);return this._rowTransform($,I)}formatColumns($,I){let q=$.map((Y,J)=>this.fieldFormatter.format(Y,J,I)).join(this.formatterOptions.delimiter),{rowCount:U}=this;if(this.rowCount+=1,U)return[this.formatterOptions.rowDelimiter,q].join("");return q}}DU.RowFormatter=N3});var a70=L((TZ)=>{Object.defineProperty(TZ,"__esModule",{value:!0});TZ.FieldFormatter=TZ.RowFormatter=void 0;var Ds0=t70();Object.defineProperty(TZ,"RowFormatter",{enumerable:!0,get:function(){return Ds0.RowFormatter}});var Os0=dR();Object.defineProperty(TZ,"FieldFormatter",{enumerable:!0,get:function(){return Os0.FieldFormatter}})});var mR=L((e70)=>{Object.defineProperty(e70,"__esModule",{value:!0});e70.CsvFormatterStream=void 0;var Ns0=o("stream"),Fs0=a70();class s70 extends Ns0.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new Fs0.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,I,q){let U=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(Y,J)=>{if(Y)return U=!0,q(Y);if(J)J.forEach((Q)=>{this.push(Buffer.from(Q,"utf8"))});return U=!0,q()})}catch(Y){if(U)throw Y;q(Y)}}_flush($){this.rowFormatter.finish((I,q)=>{if(I)return $(I);if(q)q.forEach((U)=>{this.push(Buffer.from(U,"utf8"))});return $()})}}e70.CsvFormatterStream=s70});var q30=L((O1)=>{var I30=O1&&O1.__createBinding||(Object.create?function($,I,q,U){if(U===void 0)U=q;Object.defineProperty($,U,{enumerable:!0,get:function(){return I[q]}})}:function($,I,q,U){if(U===void 0)U=q;$[U]=I[q]}),Ms0=O1&&O1.__setModuleDefault||(Object.create?function($,I){Ob Line truncated
deps: ${U}}`};var aB0={keyword:"dependencies",type:"object",schemaType:"object",error:zp.error,code($){let[I,U]=sB0($);Zp($,I),Xp($,U)}};function sB0({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 Zp($,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,sQ.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,sQ.checkReportMissingProp)($,H)});else U.if(fT._`${G} && (${(0,sQ.checkMissingProp)($,q,Q)})`),(0,sQ.reportMissingProp)($,Q),U.else()}}zp.validatePropertyDeps=Zp;function Xp($,I=$.schema){let{gen:U,data:Y,keyword:J,it:Q}=$,K=U.name("valid");for(let q in I){if((0,tB0.alwaysValidSchema)(Q,I[q]))continue;U.if((0,sQ.propertyInData)(U,Y,q,Q.opts.ownProperties),()=>{let G=$.subschema({keyword:J,schemaProp:q},K);$.mergeValidEvaluated(G,K)},()=>U.var(K,!0)),$.ok(K)}}zp.validateSchemaDeps=Xp;zp.default=aB0});var Mp=O((Np)=>{Object.defineProperty(Np,"__esModule",{value:!0});var Fp=s0(),Iv0=w1(),Uv0={message:"property name must be valid",params:({params:$})=>Fp._`{propertyName: ${$.propertyName}}`},Yv0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Uv0,code($){let{gen:I,schema:U,data:Y,it:J}=$;if((0,Iv0.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,Fp.not)(Q),()=>{if($.error(!0),!J.allErrors)I.break()})}),$.ok(Q)}};Np.default=Yv0});var bT=O((Ap)=>{Object.defineProperty(Ap,"__esModule",{value:!0});var KV=O$(),c$=s0(),Qv0=$5(),qV=w1(),Kv0={message:"must NOT have additional properties",params:({params:$})=>c$._`{additionalProperty: ${$.additionalProperty}}`},qv0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Kv0,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,qV.alwaysValidSchema)(K,U))return;let H=(0,KV.allSchemaProperties)(Y.properties),W=(0,KV.allSchemaProperties)(Y.patternProperties);V(),$.ok(c$._`${Q} === ${Qv0.default.errors}`);function V(){I.forIn("key",J,(D)=>{if(!H.length&&!W.length)z(D);else I.if(w(D),()=>z(D))})}function w(D){let F;if(H.length>8){let E=(0,qV.schemaRefOrVal)(K,Y.properties,"properties");F=(0,KV.isOwnProperty)(I,E,D)}else if(H.length)F=(0,c$.or)(...H.map((E)=>c$._`${D} === ${E}`));else F=c$.nil;if(W.length)F=(0,c$.or)(F,...W.map((E)=>c$._`${(0,KV.usePattern)($,E)}.test(${D})`));return(0,c$.not)(F)}function Z(D){I.code(c$._`delete ${J}[${D}]`)}function z(D){if(G.removeAdditional==="all"||G.removeAdditional&&U===!1){Z(D);return}if(U===!1){if($.setParams({additionalProperty:D}),$.error(),!q)I.break();return}if(typeof U=="object"&&!(0,qV.alwaysValidSchema)(K,U)){let F=I.name("valid");if(G.removeAdditional==="failing")L(D,F,!1),I.if((0,c$.not)(F),()=>{$.reset(),Z(D)});else if(L(D,F),!q)I.if((0,c$.not)(F),()=>I.break())}}function L(D,F,E){let T={keyword:"additionalProperties",dataProp:D,dataPropType:qV.Type.Str};if(E===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(T,F)}}};Ap.default=qv0});var Bp=O((Ep)=>{Object.defineProperty(Ep,"__esModule",{value:!0});var Hv0=bQ(),Pp=O$(),iT=w1(),Tp=bT(),Wv0={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)Tp.default.code(new Hv0.KeywordCxt(Q,Tp.default,"additionalProperties"));let K=(0,Pp.allSchemaProperties)(U);for(let V of K)Q.definedProperties.add(V);if(Q.opts.unevaluated&&K.length&&Q.props!==!0)Q.props=iT.mergeEvaluated.props(I,(0,iT.toHash)(K),Q.props);let q=K.filter((V)=>!(0,iT.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,Pp.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)}}};Ep.default=Wv0});var _p=O((jp)=>{Object.defineProperty(jp,"__esModule",{value:!0});var vp=O$(),GV=s0(),Rp=w1(),Cp=w1(),wv0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,data:Y,parentSchema:J,it:Q}=$,{opts:K}=Q,q=(0,vp.allSchemaProperties)(U),G=q.filter((L)=>(0,Rp.alwaysValidSchema)(Q,U[L]));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`,n+=c1(b,2),n+=q.magic,n+=c1(D,2),n+=c1(F,2),n+=c1(g.crc32,4),n+=c1(g.compressedSize,4),n+=c1(g.uncompressedSize,4),n+=c1(H.length,2),n+=c1(E.length,2);var S=kw.LOCAL_FILE_HEADER+n+H+E,f=kw.CENTRAL_FILE_HEADER+c1(p,2)+n+c1(w.length,2)+"\x00\x00\x00\x00"+c1(C,4)+c1(Y,4)+H+E+w;return{fileRecord:S,dirRecord:f}},bx0=function($,I,U,Y,J){var Q="",K=iU.transformTo("string",J(Y));return Q=kw.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+c1($,2)+c1($,2)+c1(I,4)+c1(U,4)+c1(K.length,2)+K,Q},ix0=function($){var I="";return I=kw.DATA_DESCRIPTOR+c1($.crc32,4)+c1($.compressedSize,4)+c1($.uncompressedSize,4),I};function a$($,I,U,Y){nU.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=[]}iU.inherits(a$,nU);a$.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,nU.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:U?(I+100*(U-Y-1))/U:100}})};a$.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var I=this.streamFiles&&!$.file.dir;if(I){var U=Ba($,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:U.fileRecord,meta:{percent:0}})}else this.accumulate=!0};a$.prototype.closedSource=function($){this.accumulate=!1;var I=this.streamFiles&&!$.file.dir,U=Ba($,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(U.dirRecord),I)this.push({data:ix0($),meta:{percent:100}});else{this.push({data:U.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};a$.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=bx0(this.dirRecords.length,U,$,this.zipComment,this.encodeFileName);this.push({data:Y,meta:{percent:100}})};a$.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};a$.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};a$.prototype.resume=function(){if(!nU.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};a$.prototype.error=function($){var I=this._sources;if(!nU.prototype.error.call(this,$))return!1;for(var U=0;U<I.length;U++)try{I[U].error($)}catch(Y){}return!0};a$.prototype.lock=function(){nU.prototype.lock.call(this);var $=this._sources;for(var I=0;I<$.length;I++)$[I].lock()};va.exports=a$});var Ca=O((dx0)=>{var nx0=Av(),px0=Ra(),cx0=function($,I){var U=$||I,Y=nx0[U];if(!Y)throw Error(U+" is not a valid compression method !");return Y};dx0.generateWorker=function($,I,U){var Y=new px0(I.streamFiles,U,I.platform,I.encodeFileName),J=0;try{$.forEach(function(Q,K){J++;var q=cx0(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 _a=O((bA1,ja)=>{var lx0=H4(),uw=Y$();function s2($,I){uw.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(I)}lx0.inherits(s2,uw);s2.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()})};s2.prototype.pause=function(){if(!uw.prototype.pause.call(this))return!1;return this._stream.pause(),!0};s2.prototype.resume=function(){if(!uw.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};ja.exports=s2});var ia=O((iA1,ba)=>{var ox0=_U(),e2=H4(),ha=Y$(),rx0=RB(),xa=CB(),Sa=Fw(),tx0=gr(),ax0=Ca(),ga=_2(),sx0=_a(),ka=function($,I,U){var Y=e2.getTypeOf(I),J,Q=e2.extend(U||{},xa);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($),KR(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)_e(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");KR(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(je.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("")}}qR.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};Se.exports=qR});var GR=O((pf0)=>{var ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function nf0($){if(typeof $==="string")return $;if(ge)return ge.decode($);return $.toString()}pf0.bufferToString=nf0});var ue=O((he)=>{Object.defineProperty(he,"__esModule",{value:!0});he.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;he.S=` \r
`;he.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";he.NAME_CHAR="-"+he.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";he.CHAR_RE=new RegExp("^["+he.CHAR+"]$","u");he.S_RE=new RegExp("^["+he.S+"]+$","u");he.NAME_START_CHAR_RE=new RegExp("^["+he.NAME_START_CHAR+"]$","u");he.NAME_CHAR_RE=new RegExp("^["+he.NAME_CHAR+"]$","u");he.NAME_RE=new RegExp("^["+he.NAME_START_CHAR+"]["+he.NAME_CHAR+"]*$","u");he.NMTOKEN_RE=new RegExp("^["+he.NAME_CHAR+"]+$","u");var HR=9,WR=10,VR=13,wR=32;he.S_LIST=[wR,WR,VR,HR];function df0($){return $>=wR&&$<=55295||$===WR||$===VR||$===HR||$>=57344&&$<=65533||$>=65536&&$<=1114111}he.isChar=df0;function mf0($){return $===wR||$===WR||$===VR||$===HR}he.isS=mf0;function ye($){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}he.isNameStartChar=ye;function lf0($){return ye($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}he.isNameChar=lf0});var oe=O((ce)=>{Object.defineProperty(ce,"__esModule",{value:!0});ce.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";ce.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";ce.S=` \r
`;ce.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";ce.NAME_CHAR="-"+ce.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";ce.CHAR_RE=new RegExp("^["+ce.CHAR+"]$","u");ce.RESTRICTED_CHAR_RE=new RegExp("^["+ce.RESTRICTED_CHAR+"]$","u");ce.S_RE=new RegExp("^["+ce.S+"]+$","u");ce.NAME_START_CHAR_RE=new RegExp("^["+ce.NAME_START_CHAR+"]$","u");ce.NAME_CHAR_RE=new RegExp("^["+ce.NAME_CHAR+"]$","u");ce.NAME_RE=new RegExp("^["+ce.NAME_START_CHAR+"]["+ce.NAME_CHAR+"]*$","u");ce.NMTOKEN_RE=new RegExp("^["+ce.NAME_CHAR+"]+$","u");var fe=9,be=10,ie=13,ne=32;ce.S_LIST=[ne,be,ie,fe];function Qb0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}ce.isChar=Qb0;function Kb0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}ce.isRestrictedChar=Kb0;function qb0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}ce.isCharAndNotRestricted=qb0;function Gb0($){return $===ne||$===be||$===ie||$===fe}ce.isS=Gb0;function pe($){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}ce.isNameStartChar=pe;function Hb0($){return pe($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}ce.isNameChar=Hb0});var ae=O((te)=>{Object.defineProperty(te,"__esModule",{value:!0});te.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";te.NC_NAME_CHAR="-"+te.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";te.NC_NAME_START_CHAR_RE=new RegExp("^["+te.NC_NAME_START_CHAR+"]$","u");te.NC_NAME_CHAR_RE=new RegExp("^["+te.NC_NAME_CHAR+"]$","u");te.NC_NAME_RE=new RegExp("^["+te.NC_NAME_START_CHAR+"]["+te.NC_NAME_CHAR+"]*$","u");function re($){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}te.isNCNameStartChar=re;function Tb0($){return re($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}te.isNCNameChar=Tb0});var F00=O((O00)=>{Object.defineProperty(O00,"__esModule",{value:!0});var eU=ue(),jb0=oe(),BR=ae(),p6=eU.isS,_b0=eU.isChar,wK=eU.isNameStartChar,se=eU.isNameChar,w00=eU.S_LIST,Sb0=eU.NAME_RE,gb0=jb0.isChar,yb0=BR.isNCNameStartChar,hb0=BR.isNCNameChar,xb0=BR.NC_NAME_RE,ZZ="http://www.w3.org/XML/1998/namespace",sU="http://www.w3.org/2000/xmlns/",kb0={__proto__:null,xml:ZZ,xmlns:sU},ub0={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},Q4=-1,v8=-2,ee=0,fb0=1,XR=2,bb0=3,rU=4,ib0=5,nb0=6,pb0=7,zR=8,cb0=9,db0=10,mb0=11,lb0=12,C6=13,GZ=14,LR=15,ob0=16,DR=17,rb0=18,tb0=19,OR=20,ab0=21,sb0=22,eb0=23,$00=24,FR=25,HZ=26,I00=27,$i0=28,Ii0=29,U00=30,Ui0=31,Yi0=32,J3=33,Ji0=34,NR=35,ZK=36,MR=37,Qi0=38,Y00=39,J00=40,Ki0=41,Q00=42,qi0=43,Gi0=44,AR=9,e$=10,PR=13,K00=32,q00=33,Z00=34,XK=38,X00=39,WZ=45,VZ=47,Hi0=59,g9=60,tU=61,g4=62,I6=63,z00=91,aU=93,G00=133,H00=8232,wZ=($)=>$===Z00||$===X00,L00=[Z00,X00],Wi0=[...L00,z00,g4],Vi0=[...L00,g9,aU],wi0=[tU,I6,...w00],Zi0=[...w00,g4,XK,g9];function ER($,I,U){switch(I){case"xml":if(U!==ZZ)$.fail(`xml prefix must be bound to ${ZZ}.`);break;case"xmlns":if(U!==sU)$.fail(`xmlns prefix must be bound to ${sU}.`);break;default:}switch(U){case sU:$.fail(I===""?`the default namespace may not be set to ${U}.`:`may not assign a prefix (even "xmlns") to the URI ${sU}.`);break;case ZZ: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 Xi0($,I){for(let U of Object.keys(I))ER($,U,I[U])}var zi0=($)=>xb0.test($),Li0=($)=>Sb0.test($),Q3=0,W00=1,TR=2;O00.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var V00={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 D00{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=yb0,this.nameCheck=hb0,this.isName=zi0,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},kb0);let U=this.opt.additionalNamespaces;if(U!=null)Xi0(this,U),Object.assign(this.ns,U)}else this. Line truncated
`,I=this.i}}captureToChar($){let{i:I}=this,{chunk:U}=this;while(!0){let Y=this.getCode();switch(Y){case v8:this.text+=`${U.slice(I,this.prevI)}
`,I=this.i,Y=e$;break;case Q4: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===Q4)return this.name+=$.slice(I),Q4;if(!se(U))return this.name+=$.slice(I,this.prevI),U===v8?e$:U}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===Q4||!p6($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=_b0,this.getCode=this.getCode10;else this.isChar=gb0,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=fb0}sBeginWhitespace(){let $=this.i,I=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(I){case g9:if(this.state=LR,this.text.length!==0)throw Error("no-empty text at start");break;case Q4:break;default:this.unget(),this.state=C6,this.xmlDeclPossible=!1}}sDoctype(){var $;let I=this.captureTo(Wi0);switch(I){case g4:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=C6,this.doctype=!0;break}case Q4:break;default:if(this.text+=String.fromCodePoint(I),I===z00)this.state=rU;else if(wZ(I))this.state=bb0,this.q=I}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=XR}sDTD(){let $=this.captureTo(Vi0);if($===Q4)return;if(this.text+=String.fromCodePoint($),$===aU)this.state=XR;else if($===g9)this.state=nb0;else if(wZ($))this.state=ib0,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=rU,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case q00:this.state=pb0,this.openWakaBang="";break;case I6:this.state=mb0;break;default:this.state=rU}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),I=this.openWakaBang+=$;if(this.text+=$,I!=="-")this.state=I==="--"?zR:rU,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(WZ))this.text+="-",this.state=cb0}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===WZ?db0:zR}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===g4)this.state=rU;else this.fail("malformed comment."),this.state=zR}sDTDPI(){if(this.captureToChar(I6))this.text+="?",this.state=lb0}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===g4)this.state=rU}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:I}=this;$:while(!0)switch(this.getCode()){case v8:this.entity+=`${I.slice($,this.prevI)}
`,$=this.i;break;case Hi0:{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!==C6||this.textHandler!==void 0)this.text+=J;break $}case Q4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(wK($))this.state=Ji0,this.unget(),this.xmlDeclPossible=!1;else switch($){case VZ:this.state=qi0,this.xmlDeclPossible=!1;break;case q00:this.state=ob0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case I6:this.state=eb0;break;default:this.fail("disallowed character in tag name"),this.state=C6,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=OR,this.openWakaBang="";break;case"--":this.state=DR,this.openWakaBang="";break;case"DOCTYPE":if(this.state=XR,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(WZ))this.state=rb0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===WZ)this.state=tb0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=DR}sCommentEnded(){let $=this.getCodeNorm();if($!==g4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=DR;else this.state=C6}sCData(){if(this.captureToChar(aU))this.state=ab0}sCDataEnding(){let $=this.getCodeNorm();if($===aU)this.state=sb0;else this.text+=`]${String.fromCodePoint($)}`,this.state=OR}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case g4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=C6;break}case aU:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=OR}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=$00;else if($===I6||p6($))this.fail("processing instruction without a target."),this.state=$===I6?HZ:FR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=$00}sPIRest(){let{chunk:$,i:I}=this;while(!0){let U=this.getCodeNorm();if(U===Q4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(I,this.prevI);let Y=U===I6;if(Y||p6(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=Y?J3:I00}else this.state=Y?HZ:FR;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=HZ;else if(!p6($))this.text=String.fromCodePoint($)}else if(this.captureToChar(I6))this.state=HZ}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=C6}else if(I===I6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=FR;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===I6){this.state=J3;return}if($!==Q4)this.state=$i0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(wi0);if($===I6){this.state=J3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(p6($)||$===tU))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=$===tU?U00:Ii0}sXMLDeclEq(){let $=this.getCodeNorm();if($===I6){this.state=J3,this.fail("XML declaration is incomplete.");return}if(p6($))return;if($!==tU)this.fail("value required.");this.state=U00}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===I6){this.state=J3,this.fail("XML declaration is incomplete.");return}if(p6($))return;if(!wZ($))this.fail("value must be quoted."),this.q=K00;else this.q=$;this.state=Ui0}sXMLDeclValue(){let $=this.captureTo([this.q,I6]);if($===I6){this.state=J3,this.text="",this.fail("XML declaration is incomplete.");return}if($===Q4)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("ver Line truncated
`;$=this.i,I=Q3;break;case Q4:if(Y!==void 0)this.text+=U.slice($);break $;default:I=Q3}this.forbiddenState=I}handleTextOutsideRoot(){let{i:$}=this,{chunk:I,textHandler:U}=this,Y=!1;$:while(!0){let J=this.getCode();switch(J){case g9:{if(this.state=LR,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 XK:if(this.state=GZ,this.entityReturnState=C6,U!==void 0)this.text+=I.slice($,this.prevI);Y=!0;break $;case v8:if(U!==void 0)this.text+=`${I.slice($,this.prevI)}
`;$=this.i;break;case Q4:if(U!==void 0)this.text+=I.slice($);break $;default:if(!p6(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,ER(this,J,K)}else if($==="xmlns"){let K=I.trim();this.topNS[""]=K,ER(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!==ee&&this.state!==C6)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"?sU:"",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=C6,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=C6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=C6,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)}}O00.SaxesParser=D00});var zK=O((TP1,N00)=>{var{SaxesParser:Fi0}=F00(),{PassThrough:Ni0}=z6(),{bufferToString:Mi0}=GR();N00.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new Ni0);let I=new Fi0,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(Mi0(J)),U)throw U;yield Y,Y=[]}}});var z0=O((EP1,M00)=>{var Ai0=zK(),Pi0=$6();class $Y{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof $Y)$.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 thiLine 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}`}}a50.FormatterOptions=t50});var mZ=O((tE1,U90)=>{var gl0="[object AsyncFunction]",yl0="[object Function]",hl0="[object GeneratorFunction]",xl0="[object Null]",kl0="[object Proxy]",ul0="[object Undefined]",fl0=typeof global=="object"&&global&&global.Object===Object&&global,bl0=typeof self=="object"&&self&&self.Object===Object&&self,il0=fl0||bl0||Function("return this")(),$90=Object.prototype,nl0=$90.hasOwnProperty,I90=$90.toString,e50=il0.Symbol,w3=e50?e50.toStringTag:void 0;function pl0($){if($==null)return $===void 0?ul0:xl0;return w3&&w3 in Object($)?cl0($):dl0($)}function cl0($){var I=nl0.call($,w3),U=$[w3];try{$[w3]=void 0;var Y=!0}catch(Q){}var J=I90.call($);if(Y)if(I)$[w3]=U;else delete $[w3];return J}function dl0($){return I90.call($)}function ml0($){if(!ll0($))return!1;var I=pl0($);return I==yl0||I==hl0||I==gl0||I==kl0}function ll0($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}U90.exports=ml0});var k90=O((lZ,WY)=>{var ol0=200,rC="__lodash_hash_undefined__",IX=1,X90=2,z90=9007199254740991,oZ="[object Arguments]",nC="[object Array]",rl0="[object AsyncFunction]",L90="[object Boolean]",D90="[object Date]",O90="[object Error]",F90="[object Function]",tl0="[object GeneratorFunction]",rZ="[object Map]",N90="[object Number]",al0="[object Null]",HY="[object Object]",Y90="[object Promise]",sl0="[object Proxy]",M90="[object RegExp]",tZ="[object Set]",A90="[object String]",el0="[object Symbol]",$o0="[object Undefined]",pC="[object WeakMap]",P90="[object ArrayBuffer]",aZ="[object DataView]",Io0="[object Float32Array]",Uo0="[object Float64Array]",Yo0="[object Int8Array]",Jo0="[object Int16Array]",Qo0="[object Int32Array]",Ko0="[object Uint8Array]",qo0="[object Uint8ClampedArray]",Go0="[object Uint16Array]",Ho0="[object Uint32Array]",Wo0=/[\\^$.*+?()[\]{}|]/g,Vo0=/^\[object .+?Constructor\]$/,wo0=/^(?:0|[1-9]\d*)$/,r1={};r1[Io0]=r1[Uo0]=r1[Yo0]=r1[Jo0]=r1[Qo0]=r1[Ko0]=r1[qo0]=r1[Go0]=r1[Ho0]=!0;r1[oZ]=r1[nC]=r1[P90]=r1[L90]=r1[aZ]=r1[D90]=r1[O90]=r1[F90]=r1[rZ]=r1[N90]=r1[HY]=r1[M90]=r1[tZ]=r1[A90]=r1[pC]=!1;var T90=typeof global=="object"&&global&&global.Object===Object&&global,Zo0=typeof self=="object"&&self&&self.Object===Object&&self,F5=T90||Zo0||Function("return this")(),E90=typeof lZ=="object"&&lZ&&!lZ.nodeType&&lZ,J90=E90&&typeof WY=="object"&&WY&&!WY.nodeType&&WY,B90=J90&&J90.exports===E90,fC=B90&&T90.process,Q90=function(){try{return fC&&fC.binding&&fC.binding("util")}catch($){}}(),K90=Q90&&Q90.isTypedArray;function Xo0($,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 zo0($,I){var U=-1,Y=I.length,J=$.length;while(++U<Y)$[J+U]=I[U];return $}function Lo0($,I){var U=-1,Y=$==null?0:$.length;while(++U<Y)if(I($[U],U,$))return!0;return!1}function Do0($,I){var U=-1,Y=Array($);while(++U<$)Y[U]=I(U);return Y}function Oo0($){return function(I){return $(I)}}function Fo0($,I){return $.has(I)}function No0($,I){return $==null?void 0:$[I]}function Mo0($){var I=-1,U=Array($.size);return $.forEach(function(Y,J){U[++I]=[J,Y]}),U}function Ao0($,I){return function(U){return $(I(U))}}function Po0($){var I=-1,U=Array($.size);return $.forEach(function(Y){U[++I]=Y}),U}var To0=Array.prototype,Eo0=Function.prototype,UX=Object.prototype,bC=F5["__core-js_shared__"],v90=Eo0.toString,C8=UX.hasOwnProperty,q90=function(){var $=/[^.]+$/.exec(bC&&bC.keys&&bC.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),R90=UX.toString,Bo0=RegExp("^"+v90.call(C8).replace(Wo0,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),G90=B90?F5.Buffer:void 0,sZ=F5.Symbol,H90=F5.Uint8Array,C90=UX.propertyIsEnumerable,vo0=To0.splice,Z3=sZ?sZ.toStringTag:void 0,W90=Object.getOwnPropertySymbols,Ro0=G90?G90.isBuffer:void 0,Co0=Ao0(Object.keys,Object),cC=VY(F5,"DataView"),AK=VY(F5,"Map"),dC=VY(F5,"Promise"),mC=VY(F5,"Set"),lC=VY(F5,"WeakMap"),PK=VY(Object,"create"),jo0=L3(cC),_o0=L3(AK),So0=L3(dC),go0=L3(mC),yo0=L3(lC),V90=sZ?sZ.prototype:void 0,iC=V90?V90.valueOf:void 0;function X3($){var I=-1,U=$==null?0:$.length;this.clear();while(++I<U){var Y=$[I];this.set(Y[0],Y[1])}}function ho0(){this.__data__=PK?PK(null):{},this.size=0}function xo0($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function ko0($){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(pr0.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=`${cr0.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}`}}wY.FieldFormatter=m90});var $j=O((l90)=>{Object.defineProperty(l90,"__esModule",{value:!0});l90.isSyncTransform=void 0;l90.isSyncTransform=($)=>$.length===1});var t90=O((ZY)=>{var r90=ZY&&ZY.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(ZY,"__esModule",{value:!0});ZY.RowFormatter=void 0;var mr0=r90(mZ()),lr0=r90(k90()),or0=eC(),rr0=$j();class D3{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new or0.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(D3.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(rr0.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(!mr0.default($))throw TypeError("The transform should be a function");this._rowTransform=D3.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=D3.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!lr0.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(D3.isRowHashArray($))return this.headers.map((I,U)=>{let Y=$[U];if(Y)return Y[1];return""});if(D3.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}}ZY.RowFormatter=D3});var a90=O((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});QX.FieldFormatter=QX.RowFormatter=void 0;var tr0=t90();Object.defineProperty(QX,"RowFormatter",{enumerable:!0,get:function(){return tr0.RowFormatter}});var ar0=eC();Object.defineProperty(QX,"FieldFormatter",{enumerable:!0,get:function(){return ar0.FieldFormatter}})});var Ij=O((e90)=>{Object.defineProperty(e90,"__esModule",{value:!0});e90.CsvFormatterStream=void 0;var er0=r("stream"),$t0=a90();class s90 extends er0.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new $t0.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 $()})}}e90.CsvFormatterStream=s90});var U70=O((N1)=>{var I70=N1&&N1.__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]}),It0=N1&&N1.__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}}UI0.Token=qI0});var OC=L((KI0)=>{Object.defineProperty(KI0,"__esModule",{value:!0});KI0.Scanner=void 0;var JI0=i9(),v11=/((?:\r\n)|\n|\r)/;class QI0{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 q=I.exec($);if(q==null)return null;let U=q[1],Y=this.cursor+(q.index||0);return new JI0.Token({token:U,startCursor:Y,endCursor:Y+U.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:I}=this;if(I<=$)return null;return new JI0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=v11.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}}KI0.Scanner=QI0});var oZ=L((GI0)=>{Object.defineProperty(GI0,"__esModule",{value:!0});GI0.ColumnFormatter=void 0;class wI0{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}}GI0.ColumnFormatter=wI0});var LC=L((ZI0)=>{Object.defineProperty(ZI0,"__esModule",{value:!0});ZI0.NonQuotedColumnParser=void 0;var R11=oZ(),VI0=i9();class WI0{constructor($){this.parserOptions=$,this.columnFormatter=new R11.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:I}=this,q=[],U=$.nextCharacterToken;for(;U;U=$.nextCharacterToken){if(VI0.Token.isTokenDelimiter(U,I)||VI0.Token.isTokenRowDelimiter(U))break;q.push(U.token),$.advancePastToken(U)}return this.columnFormatter.format(q.join(""))}}ZI0.NonQuotedColumnParser=WI0});var NC=L((OI0)=>{Object.defineProperty(OI0,"__esModule",{value:!0});OI0.QuotedColumnParser=void 0;var C11=oZ(),EU=i9();class DI0{constructor($){this.parserOptions=$,this.columnFormatter=new C11.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let I=$.cursor,{foundClosingQuote:q,col:U}=this.gatherDataBetweenQuotes($);if(!q){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($),U}gatherDataBetweenQuotes($){let{parserOptions:I}=this,q=!1,U=!1,Y=[],J=$.nextCharacterToken;for(;!U&&J!==null;J=$.nextCharacterToken){let Q=EU.Token.isTokenQuote(J,I);if(!q&&Q)q=!0;else if(q)if(EU.Token.isTokenEscapeCharacter(J,I)){$.advancePastToken(J);let K=$.nextCharacterToken;if(K!==null&&(EU.Token.isTokenQuote(K,I)||EU.Token.isTokenEscapeCharacter(K,I)))Y.push(K.token),J=K;else if(Q)U=!0;else Y.push(J.token)}else if(Q)U=!0;else Y.push(J.token);$.advancePastToken(J)}return{col:this.columnFormatter.format(Y.join("")),foundClosingQuote:U}}checkForMalformedColumn($){let{parserOptions:I}=this,{nextNonSpaceToken:q}=$;if(q){let U=EU.Token.isTokenDelimiter(q,I),Y=EU.Token.isTokenRowDelimiter(q);if(!(U||Y)){let J=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${I.escapedDelimiter}' OR new line got: '${q.token}'. at '${J}`)}$.advanceToToken(q)}else if(!$.hasMoreData)$.advancePastLine()}}OI0.QuotedColumnParser=DI0});var AI0=L((FI0)=>{Object.defineProperty(FI0,"__esModule",{value:!0});FI0.ColumnParser=void 0;var _11=LC(),h11=NC(),S11=i9();class NI0{constructor($){this.parserOptions=$,this.quotedColumnParser=new h11.QuotedColumnParser($),this.nonQuotedColumnParser=new _11.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:I}=$;if(I!==null&&S11.Token.isTokenQuote(I,this.parserOptions))return $.advanceToToken(I),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}FI0.ColumnParser=NI0});var FC=L((BU)=>{Object.defineProperty(BU,"__esModule",{value:!0});BU.ColumnFormatter=BU.QuotedColumnParser=BU.NonQuotedColumnParser=BU.ColumnParser=void 0;var y11=AI0();Object.defineProperty(BU,"ColumnParser",{enumerable:!0,get:function(){return y11.ColumnParser}});var u11=LC();Object.defineProperty(BU,"NonQuotedColumnParser",{enumerable:!0,get:function(){return u11.NonQuotedColumnParser}});var x11=NC();Object.defineProperty(BU,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,k,k,V,U);let h=V.type==="*"?uC:V.type==="?"?fC:"\\"+V.type;Y=!0,U=U.slice(0,V.reStart)+h+"\\("+k}if(P(),J)U+="\\\\";let g=B41[U.charAt(0)];for(let k=K.length-1;k>-1;k--){let h=K[k],n=U.slice(0,h.reStart),S=U.slice(h.reStart,h.reEnd-8),t=U.slice(h.reEnd),p=U.slice(h.reEnd-8,h.reEnd)+t,C=n.split(")").length,f=n.split("(").length-C,b=t;for(let j=0;j<f;j++)b=b.replace(/\)[+*?]?/,"");t=b;let J0=t===""&&I!==xC?"(?:$|\\/)":"";U=n+S+t+J0+p}if(U!==""&&Y)U="(?=.)"+U;if(g)U=N()+U;if(I===xC)return[U,Y];if(q.nocase&&!Y)Y=$.toUpperCase()!==$.toLowerCase();if(!Y)return R41($);let B=q.nocase?"i":"";try{return Object.assign(new RegExp("^"+U+"$",B),{_glob:$,_src:U})}catch(k){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,q=I.noglobstar?uC:I.dot?j41:E41,U=I.nocase?"i":"",Y=$.map((J)=>{return J=J.map((Q)=>typeof Q==="string"?_41(Q):Q===v6?v6:Q._src).reduce((Q,K)=>{if(!(Q[Q.length-1]===v6&&K===v6))Q.push(K);return Q},[]),J.forEach((Q,K)=>{if(Q!==v6||J[K-1]===v6)return;if(K===0)if(J.length>1)J[K+1]="(?:\\/|"+q+"\\/)?"+J[K+1];else J[K]=q;else if(K===J.length-1)J[K-1]+="(?:\\/|"+q+")?";else J[K-1]+="(?:\\/|\\/"+q+"\\/)"+J[K+1],J[K+1]=v6}),J.filter((Q)=>Q!==v6).join("/")}).join("|");if(Y="^(?:"+Y+")$",this.negate)Y="^(?!"+Y+").*$";try{this.regexp=new RegExp(Y,U)}catch(J){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 q=this.options;if(kC.sep!=="/")$=$.split(kC.sep).join("/");$=$.split(Zq0),this.debug(this.pattern,"split",$);let U=this.set;this.debug(this.pattern,"set",U);let Y;for(let J=$.length-1;J>=0;J--)if(Y=$[J],Y)break;for(let J=0;J<U.length;J++){let Q=U[J],K=$;if(q.matchBase&&Q.length===1)K=[Y];if(this.matchOne(K,Q,I)){if(q.flipNegate)return!0;return!this.negate}}if(q.flipNegate)return!1;return this.negate}static defaults($){return Y$.defaults($).Minimatch}}Y$.Minimatch=y2});var Aq0=L((IB1,Mq0)=>{Mq0.exports=Fq0;var iC=o("fs"),{EventEmitter:S41}=o("events"),{Minimatch:bC}=Oq0(),{resolve:y41}=o("path");function u41($,I){return new Promise((q,U)=>{iC.readdir($,{withFileTypes:!0},(Y,J)=>{if(Y)switch(Y.code){case"ENOTDIR":if(I)U(Y);else q([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":q([]);break;case"ELOOP":default:U(Y);break}else q(J)})})}function Lq0($,I){return new Promise((q,U)=>{(I?iC.stat:iC.lstat)($,(J,Q)=>{if(J)switch(J.code){case"ENOENT":if(I)q(Lq0($,!1));else q(null);break;default:q(null);break}else q(Q)})})}async function*Nq0($,I,q,U,Y,J){let Q=await u41(I+$,J);for(let K of Q){let z=K.name;if(z===void 0)z=K,U=!0;let w=$+"/"+z,G=w.slice(1),H=I+"/"+G,W=null;if(U||q)W=await Lq0(H,q);if(!W&&K.name!==void 0)W=K;if(W===null)W={isDirectory:()=>!1};if(W.isDirectory()){if(!Y(G))yield{relative:G,absolute:H,stats:W},yield*Nq0(w,I,q,U,Y,!1)}else yield{relative:G,absolute:H,stats:W}}}async function*x41($,I,q,U){yield*Nq0("",$,I,q,U,!0)}function k41($){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 pC extends S41{constructor($,I,q){super();if(typeof I==="function")q=I,I=null;if(this.options=k41(I||{}),this.matchers=[],this.options.pattern){let U=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=U.map((Y)=>new bC(Y,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let U=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=U.map((Y)=>new bC(Y,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let U=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=U.map((Y)=>new bC(Y,{dot:!0}))}if(this.iterator=x41(y41($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,q)this._matches=[],this.on("match",(U)=>this._matches.push(this.options.absolute?U.absolute:U.relative)),this.on("error",(U)=>q(U)),this.on("end",()=>q(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((I)=>I.match($))}_fileMatches($,I){let q=$+(I?"/":"");return(this.matchers.length===0||this.matchers.some((U)=>U.match(q)))&&!this.ignoreMatchers.some((U)=>U.match(q))&&(!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 q=$.value.relative,U=$.value.absolute;if(this.options.mark&&I)q+="/",U+="/";if(this.options.stat)this.emit("match",{relative:q,absolute:U,stat:$.value.stats});else this.emit("match",{relative:q,ab Line truncated
`,R);R=$0===-1?A.length:$0}else if(i!==-1&&A[R]==="/"&&A[R+1]==="*"){let $0=A.indexOf("*/",R);if($0!==-1)R=$0+2,i=A.indexOf("*/",R);else E+=A[R],R++}else E+=A[R],R++;return E}function c8(A){let E=G$(A.toString()),R=E.match(w$);if(!R)R=E.match(_$);if(!R)throw Error(`could not parse args in autoInject
`}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}}Y30.Token=U30});var Ej=O((q30)=>{Object.defineProperty(q30,"__esModule",{value:!0});q30.Scanner=void 0;var Q30=c9(),He0=/((?:\r\n)|\n|\r)/;class K30{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 Q30.Token({token:Y,startCursor:J,endCursor:J+Y.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:I}=this;if(I<=$)return null;return new Q30.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=He0.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}}q30.Scanner=K30});var RX=O((W30)=>{Object.defineProperty(W30,"__esModule",{value:!0});W30.ColumnFormatter=void 0;class H30{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}}W30.ColumnFormatter=H30});var Bj=O((X30)=>{Object.defineProperty(X30,"__esModule",{value:!0});X30.NonQuotedColumnParser=void 0;var We0=RX(),w30=c9();class Z30{constructor($){this.parserOptions=$,this.columnFormatter=new We0.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:I}=this,U=[],Y=$.nextCharacterToken;for(;Y;Y=$.nextCharacterToken){if(w30.Token.isTokenDelimiter(Y,I)||w30.Token.isTokenRowDelimiter(Y))break;U.push(Y.token),$.advancePastToken(Y)}return this.columnFormatter.format(U.join(""))}}X30.NonQuotedColumnParser=Z30});var vj=O((D30)=>{Object.defineProperty(D30,"__esModule",{value:!0});D30.QuotedColumnParser=void 0;var Ve0=RX(),TY=c9();class L30{constructor($){this.parserOptions=$,this.columnFormatter=new Ve0.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=TY.Token.isTokenQuote(Q,I);if(!U&&K)U=!0;else if(U)if(TY.Token.isTokenEscapeCharacter(Q,I)){$.advancePastToken(Q);let q=$.nextCharacterToken;if(q!==null&&(TY.Token.isTokenQuote(q,I)||TY.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=TY.Token.isTokenDelimiter(U,I),J=TY.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()}}D30.QuotedColumnParser=L30});var A30=O((N30)=>{Object.defineProperty(N30,"__esModule",{value:!0});N30.ColumnParser=void 0;var we0=Bj(),Ze0=vj(),Xe0=c9();class F30{constructor($){this.parserOptions=$,this.quotedColumnParser=new Ze0.QuotedColumnParser($),this.nonQuotedColumnParser=new we0.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:I}=$;if(I!==null&&Xe0.Token.isTokenQuote(I,this.parserOptions))return $.advanceToToken(I),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}N30.ColumnParser=F30});var Rj=O((EY)=>{Object.defineProperty(EY,"__esModule",{value:!0});EY.ColumnFormatter=EY.QuotedColumnParser=EY.NonQuotedColumnParser=EY.ColumnParser=void 0;var ze0=A30();Object.defineProperty(EY,"ColumnParser",{enumerable:!0,get:function(){return ze0.ColumnParser}});var Le0=Bj();Object.defineProperty(EY,"NonQuotedColumnParser",{enumerable:!0,get:function(){return Le0.NonQuotedColumnParser}});var De0=vj();Object.defineProperty(EY,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,u,u,Z,Y);let g=Z.type==="*"?cj:Z.type==="?"?lj:"\\"+Z.type;J=!0,Y=Y.slice(0,Z.reStart)+g+"\\("+u}if(T(),Q)Y+="\\\\";let A=G01[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),p=Y.slice(g.reEnd),n=Y.slice(g.reEnd-8,g.reEnd)+p,S=b.split(")").length,f=b.split("(").length-S,i=p;for(let B=0;B<f;B++)i=i.replace(/\)[+*?]?/,"");p=i;let Y0=p===""&&I!==dj?"(?:$|\\/)":"";Y=b+C+p+Y0+n}if(Y!==""&&J)Y="(?=.)"+Y;if(A)Y=F()+Y;if(I===dj)return[Y,J];if(U.nocase&&!J)J=$.toUpperCase()!==$.toLowerCase();if(!J)return W01($);let R=U.nocase?"i":"";try{return Object.assign(new RegExp("^"+Y+"$",R),{_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?cj:I.dot?K01:q01,Y=I.nocase?"i":"",J=$.map((Q)=>{return Q=Q.map((K)=>typeof K==="string"?w01(K):K===j6?j6:K._src).reduce((K,q)=>{if(!(K[K.length-1]===j6&&q===j6))K.push(q);return K},[]),Q.forEach((K,q)=>{if(K!==j6||Q[q-1]===j6)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]=j6}),Q.filter((K)=>K!==j6).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(mj.sep!=="/")$=$.split(mj.sep).join("/");$=$.split(XI0),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 K$.defaults($).Minimatch}}K$.Minimatch=_K});var AI0=O((Qv1,MI0)=>{MI0.exports=NI0;var tj=r("fs"),{EventEmitter:X01}=r("events"),{Minimatch:rj}=DI0(),{resolve:z01}=r("path");function L01($,I){return new Promise((U,Y)=>{tj.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 OI0($,I){return new Promise((U,Y)=>{(I?tj.stat:tj.lstat)($,(Q,K)=>{if(Q)switch(Q.code){case"ENOENT":if(I)U(OI0($,!1));else U(null);break;default:U(null);break}else U(K)})})}async function*FI0($,I,U,Y,J,Q){let K=await L01(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,w=null;if(Y||U)w=await OI0(V,U);if(!w&&q.name!==void 0)w=q;if(w===null)w={isDirectory:()=>!1};if(w.isDirectory()){if(!J(W))yield{relative:W,absolute:V,stats:w},yield*FI0(H,I,U,Y,J,!1)}else yield{relative:W,absolute:V,stats:w}}}async function*D01($,I,U,Y){yield*FI0("",$,I,U,Y,!0)}function O01($){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 aj extends X01{constructor($,I,U){super();if(typeof I==="function")U=I,I=null;if(this.options=O01(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 rj(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 rj(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 rj(J,{dot:!0}))}if(this.iterator=D01(z01($||"."),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 v+=P[y],y++}else v+=P[y],y++;return v}function l8(P){let v=w$(P.toString()),y=v.match(V$);if(!y)y=v.match(k$);if(!y)throw Error(`could not parse args in autoInject
Source:
`+E);let[,i]=R;return i.replace(/\s/g,"").split(p8).map(($0)=>$0.replace(h$,"").trim())}function t6(A,E){var R={};return Object.keys(A).forEach((i)=>{var $0=A[i],q0,Q0=V($0),z0=!Q0&&$0.length===1||Q0&&$0.length===0;if(Array.isArray($0))q0=[...$0],$0=q0.pop(),R[i]=q0.concat(q0.length>0?V0:$0);else if(z0)R[i]=$0;else{if(q0=c8($0),$0.length===0&&!Q0&&q0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!Q0)q0.pop();R[i]=q0.concat(V0)}function V0(j0,U1){var W1=q0.map((K1)=>j0[K1]);W1.push(U1),O($0)(...W1)}}),v4(R,E)}class D7{constructor(){this.head=this.tail=null,this.length=0}removeLink(A){if(A.prev)A.prev.next=A.next;else this.head=A.next;if(A.next)A.next.prev=A.prev;else this.tail=A.prev;return A.prev=A.next=null,this.length-=1,A}empty(){while(this.head)this.shift();return this}insertAfter(A,E){if(E.prev=A,E.next=A.next,A.next)A.next.prev=E;else this.tail=E;A.next=E,this.length+=1}insertBefore(A,E){if(E.prev=A.prev,E.next=A,A.prev)A.prev.next=E;else this.head=E;A.prev=E,this.length+=1}unshift(A){if(this.head)this.insertBefore(this.head,A);else a6(this,A)}push(A){if(this.tail)this.insertAfter(this.tail,A);else a6(this,A)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var A=this.head;while(A)yield A.data,A=A.next}remove(A){var E=this.head;while(E){var{next:R}=E;if(A(E))this.removeLink(E);E=R}return this}}function a6(A,E){A.length=1,A.head=A.tail=E}function p5(A,E,R){if(E==null)E=1;else if(E===0)throw RangeError("Concurrency must not be zero");var i=O(A),$0=0,q0=[];let Q0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function z0(_0,P0){Q0[_0].push(P0)}function V0(_0,P0){let h0=(...z1)=>{j0(_0,h0),P0(...z1)};Q0[_0].push(h0)}function j0(_0,P0){if(!_0)return Object.keys(Q0).forEach((h0)=>Q0[h0]=[]);if(!P0)return Q0[_0]=[];Q0[_0]=Q0[_0].filter((h0)=>h0!==P0)}function U1(_0,...P0){Q0[_0].forEach((h0)=>h0(...P0))}var W1=!1;function K1(_0,P0,h0,z1){if(z1!=null&&typeof z1!=="function")throw Error("task callback must be a function");Z1.started=!0;var $4,x4;function V$(L7,...vY){if(L7)return h0?x4(L7):$4();if(vY.length<=1)return $4(vY[0]);$4(vY)}var JI=Z1._createTaskItem(_0,h0?V$:z1||V$);if(P0)Z1._tasks.unshift(JI);else Z1._tasks.push(JI);if(!W1)W1=!0,w(()=>{W1=!1,Z1.process()});if(h0||!z1)return new Promise((L7,vY)=>{$4=L7,x4=vY})}function H$(_0){return function(P0,...h0){$0-=1;for(var z1=0,$4=_0.length;z1<$4;z1++){var x4=_0[z1],V$=q0.indexOf(x4);if(V$===0)q0.shift();else if(V$>0)q0.splice(V$,1);if(x4.callback(P0,...h0),P0!=null)U1("error",P0,x4.data)}if($0<=Z1.concurrency-Z1.buffer)U1("unsaturated");if(Z1.idle())U1("drain");Z1.process()}}function YI(_0){if(_0.length===0&&Z1.idle())return w(()=>U1("drain")),!0;return!1}let O7=(_0)=>(P0)=>{if(!P0)return new Promise((h0,z1)=>{V0(_0,($4,x4)=>{if($4)return z1($4);h0(x4)})});j0(_0),z0(_0,P0)};var BY=!1,Z1={_tasks:new D7,_createTaskItem(_0,P0){return{data:_0,callback:P0}},*[Symbol.iterator](){yield*Z1._tasks[Symbol.iterator]()},concurrency:E,payload:R,buffer:E/4,started:!1,paused:!1,push(_0,P0){if(Array.isArray(_0)){if(YI(_0))return;return _0.map((h0)=>K1(h0,!1,!1,P0))}return K1(_0,!1,!1,P0)},pushAsync(_0,P0){if(Array.isArray(_0)){if(YI(_0))return;return _0.map((h0)=>K1(h0,!1,!0,P0))}return K1(_0,!1,!0,P0)},kill(){j0(),Z1._tasks.empty()},unshift(_0,P0){if(Array.isArray(_0)){if(YI(_0))return;return _0.map((h0)=>K1(h0,!0,!1,P0))}return K1(_0,!0,!1,P0)},unshiftAsync(_0,P0){if(Array.isArray(_0)){if(YI(_0))return;return _0.map((h0)=>K1(h0,!0,!0,P0))}return K1(_0,!0,!0,P0)},remove(_0){Z1._tasks.remove(_0)},process(){if(BY)return;BY=!0;while(!Z1.paused&&$0<Z1.concurrency&&Z1._tasks.length){var _0=[],P0=[],h0=Z1._tasks.length;if(Z1.payload)h0=Math.min(h0,Z1.payload);for(var z1=0;z1<h0;z1++){var $4=Z1._tasks.shift();_0.push($4),q0.push($4),P0.push($4.data)}if($0+=1,Z1._tasks.length===0)U1("empty");if($0===Z1.concurrency)U1("saturated");var x4=C(H$(_0));i(P0,x4)}BY=!1},length(){return Z1._tasks.length},running(){return $0},workersList(){return q0},idle(){return Z1._tasks.length+$0===0},pause(){Z1.paused=!0},resume(){if(Z1.paused===!1)return;Z1.paused=!1,w(Z1.process)}};return Object.defineProperties(Z1,{saturated:{writable:!1,value:O7("saturated")},unsaturated:{writable:!1,value:O7("unsaturated")},empty:{writable:!1,value:O7("empty")},drain:{writable:!1,value:O7("drain")},error:{writable:!1,value:O7("error")}}),Z1}function g0(A,E){return p5(A,1,E)}function r(A,E,R){return p5(A,E,R)}function F(A,E,R,i){i=k(i);var $0=O(R);return m0(A,(q0,Q0,z0)=>{$0(E,q0,(V0,j0)=>{E=j0,z0(V0)})},(q0)=>i(q0,E))}var M=N(F,4);function v(...A){var E=A.map(O);return function(...R){var i=this,$0=R[R.length-1];if(typeof $0=="function")R.pop();else $0=Y4();return M(E,R,(q0,Q0,z0)=>{Q0.apply(i,q0.concat((V0,...j0)=>{z0(V0,j0)}))},(q0,Q0)=>$0(q0,...Q0)),$0[C1]}}function y(...A){return v(...A.reverse())}function s(A,E,R,i){return P(b(E),A,R,i)}var c=N(s,4);function e( Line truncated
GFS4: `),console.error($)};if(!G4[q6]){if(cC=global[q6]||[],hq0(G4,cC),G4.close=function($){function I(q,U){return $.call(G4,q,function(Y){if(!Y)_q0();if(typeof U==="function")U.apply(this,arguments)})}return Object.defineProperty(I,YX,{value:$}),I}(G4.close),G4.closeSync=function($){function I(q){$.apply(G4,arguments),_q0()}return Object.defineProperty(I,YX,{value:$}),I}(G4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){g3(G4[q6]),o("assert").equal(G4[q6].length,0)})}var cC;if(!global[q6])hq0(global,G4[q6]);mC.exports=dC(m41(G4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!G4.__patched)mC.exports=dC(G4),G4.__patched=!0;function dC($){d41($),$.gracefulify=dC,$.createReadStream=B,$.createWriteStream=k;var I=$.readFile;$.readFile=q;function q(S,t,p){if(typeof t==="function")p=t,t=null;return C(S,t,p);function C(f,b,J0,j){return I(f,b,function(u){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))CU([C,[f,b,J0],u,j||Date.now(),Date.now()]);else if(typeof J0==="function")J0.apply(this,arguments)})}}var U=$.writeFile;$.writeFile=Y;function Y(S,t,p,C){if(typeof p==="function")C=p,p=null;return f(S,t,p,C);function f(b,J0,j,u,d){return U(b,J0,j,function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([f,[b,J0,j,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var J=$.appendFile;if(J)$.appendFile=Q;function Q(S,t,p,C){if(typeof p==="function")C=p,p=null;return f(S,t,p,C);function f(b,J0,j,u,d){return J(b,J0,j,function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([f,[b,J0,j,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var K=$.copyFile;if(K)$.copyFile=z;function z(S,t,p,C){if(typeof p==="function")C=p,p=0;return f(S,t,p,C);function f(b,J0,j,u,d){return K(b,J0,j,function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([f,[b,J0,j,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var w=$.readdir;$.readdir=H;var G=/^v[0-5]\./;function H(S,t,p){if(typeof t==="function")p=t,t=null;var C=G.test(process.version)?function(J0,j,u,d){return w(J0,f(J0,j,u,d))}:function(J0,j,u,d){return w(J0,j,f(J0,j,u,d))};return C(S,t,p);function f(b,J0,j,u){return function(d,a){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))CU([C,[b,J0,j],d,u||Date.now(),Date.now()]);else{if(a&&a.sort)a.sort();if(typeof j==="function")j.call(this,d,a)}}}}if(process.version.substr(0,4)==="v0.8"){var W=l41($);N=W.ReadStream,P=W.WriteStream}var V=$.ReadStream;if(V)N.prototype=Object.create(V.prototype),N.prototype.open=T;var X=$.WriteStream;if(X)P.prototype=Object.create(X.prototype),P.prototype.open=g;Object.defineProperty($,"ReadStream",{get:function(){return N},set:function(S){N=S},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return P},set:function(S){P=S},enumerable:!0,configurable:!0});var D=N;Object.defineProperty($,"FileReadStream",{get:function(){return D},set:function(S){D=S},enumerable:!0,configurable:!0});var O=P;Object.defineProperty($,"FileWriteStream",{get:function(){return O},set:function(S){O=S},enumerable:!0,configurable:!0});function N(S,t){if(this instanceof N)return V.apply(this,arguments),this;else return N.apply(Object.create(N.prototype),arguments)}function T(){var S=this;n(S.path,S.flags,S.mode,function(t,p){if(t){if(S.autoClose)S.destroy();S.emit("error",t)}else S.fd=p,S.emit("open",p),S.read()})}function P(S,t){if(this instanceof P)return X.apply(this,arguments),this;else return P.apply(Object.create(P.prototype),arguments)}function g(){var S=this;n(S.path,S.flags,S.mode,function(t,p){if(t)S.destroy(),S.emit("error",t);else S.fd=p,S.emit("open",p)})}function B(S,t){return new $.ReadStream(S,t)}function k(S,t){return new $.WriteStream(S,t)}var h=$.open;$.open=n;function n(S,t,p,C){if(typeof p==="function")C=p,p=null;return f(S,t,p,C);function f(b,J0,j,u,d){return h(b,J0,j,function(a,K0){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([f,[b,J0,j,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}return $}function CU($){g3("ENQUEUE",$[0].name,$[1]),G4[q6].push($),lC()}var UX;function _q0(){var $=Date.now();for(var I=0;I<G4[q6].length;++I)if(G4[q6][I].length>2)G4[q6][I][3]=$,G4[q6][I][4]=$;lC()}function lC(){if(clearTimeout(UX),UX=void 0,G4[q6].length===0)return;var $=G4[q6].shift(),I=$[0],q=$[1],U=$[2],Y=$[3],J=$[4];if(Y===void 0)g3("RETRY",I.name,q),I.apply(null,q);else if(Date.now()-Y>=60000){g3("TIMEOUT",I.name,q);var Q=q.pop();if(typeof Q==="function")Q.call(null,U)}else{var K=Date.now()-J,z=Math.max(J-Y,1),w=Math.min(z*1.2,100);if(K>=w)g3("RETRY",I.name,q),I.apply(null,q.concat([Y]));else G4[q6].push($)}if(UX===void 0)UX=setTimeout(lC,0)}});var yq0=L((QB1,oC)=>{function r41($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var Sq0=F4().Buffer,u2=o("util");function t41($,I,q){$.copy(I,q)}oC.exports=function(){function $(){r41(this,$),this.head=null,this.tail=null,th Line truncated
`+v);let[,c]=y;return c.replace(/\s/g,"").split(m8).map(($0)=>$0.replace(u$,"").trim())}function a6(P,v){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=l8($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(j0,K1){var D1=U0.map((W1)=>j0[W1]);D1.push(K1),D($0)(...D1)}}),j4(y,v)}class O7{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,v){if(v.prev=P,v.next=P.next,P.next)P.next.prev=v;else this.tail=v;P.next=v,this.length+=1}insertBefore(P,v){if(v.prev=P.prev,v.next=P,P.prev)P.prev.next=v;else this.head=v;P.prev=v,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 v=this.head;while(v){var{next:y}=v;if(P(v))this.removeLink(v);v=y}return this}}function s6(P,v){P.length=1,P.head=P.tail=v}function m5(P,v,y){if(v==null)v=1;else if(v===0)throw RangeError("Concurrency must not be zero");var c=D(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=(...V1)=>{j0(h0,x0),R0(...V1)};q0[h0].push(x0)}function j0(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 K1(h0,...R0){q0[h0].forEach((x0)=>x0(...R0))}var D1=!1;function W1(h0,R0,x0,V1){if(V1!=null&&typeof V1!=="function")throw Error("task callback must be a function");O1.started=!0;var U4,u4;function X$(N7,...yJ){if(N7)return x0?u4(N7):U4();if(yJ.length<=1)return U4(yJ[0]);U4(yJ)}var ZI=O1._createTaskItem(h0,x0?X$:V1||X$);if(R0)O1._tasks.unshift(ZI);else O1._tasks.push(ZI);if(!D1)D1=!0,H(()=>{D1=!1,O1.process()});if(x0||!V1)return new Promise((N7,yJ)=>{U4=N7,u4=yJ})}function Z$(h0){return function(R0,...x0){$0-=1;for(var V1=0,U4=h0.length;V1<U4;V1++){var u4=h0[V1],X$=U0.indexOf(u4);if(X$===0)U0.shift();else if(X$>0)U0.splice(X$,1);if(u4.callback(R0,...x0),R0!=null)K1("error",R0,u4.data)}if($0<=O1.concurrency-O1.buffer)K1("unsaturated");if(O1.idle())K1("drain");O1.process()}}function wI(h0){if(h0.length===0&&O1.idle())return H(()=>K1("drain")),!0;return!1}let F7=(h0)=>(R0)=>{if(!R0)return new Promise((x0,V1)=>{Z0(h0,(U4,u4)=>{if(U4)return V1(U4);x0(u4)})});j0(h0),G0(h0,R0)};var gJ=!1,O1={_tasks:new O7,_createTaskItem(h0,R0){return{data:h0,callback:R0}},*[Symbol.iterator](){yield*O1._tasks[Symbol.iterator]()},concurrency:v,payload:y,buffer:v/4,started:!1,paused:!1,push(h0,R0){if(Array.isArray(h0)){if(wI(h0))return;return h0.map((x0)=>W1(x0,!1,!1,R0))}return W1(h0,!1,!1,R0)},pushAsync(h0,R0){if(Array.isArray(h0)){if(wI(h0))return;return h0.map((x0)=>W1(x0,!1,!0,R0))}return W1(h0,!1,!0,R0)},kill(){j0(),O1._tasks.empty()},unshift(h0,R0){if(Array.isArray(h0)){if(wI(h0))return;return h0.map((x0)=>W1(x0,!0,!1,R0))}return W1(h0,!0,!1,R0)},unshiftAsync(h0,R0){if(Array.isArray(h0)){if(wI(h0))return;return h0.map((x0)=>W1(x0,!0,!0,R0))}return W1(h0,!0,!0,R0)},remove(h0){O1._tasks.remove(h0)},process(){if(gJ)return;gJ=!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 V1=0;V1<x0;V1++){var U4=O1._tasks.shift();h0.push(U4),U0.push(U4),R0.push(U4.data)}if($0+=1,O1._tasks.length===0)K1("empty");if($0===O1.concurrency)K1("saturated");var u4=S(Z$(h0));c(R0,u4)}gJ=!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:F7("saturated")},unsaturated:{writable:!1,value:F7("unsaturated")},empty:{writable:!1,value:F7("empty")},drain:{writable:!1,value:F7("drain")},error:{writable:!1,value:F7("error")}}),O1}function E0(P,v){return m5(P,1,v)}function a(P,v,y){return m5(P,v,y)}function N(P,v,y,c){c=u(c);var $0=D(y);return f0(P,(U0,q0,G0)=>{$0(v,U0,(Z0,j0)=>{v=j0,G0(Z0)})},(U0)=>c(U0,v))}var M=F(N,4);function j(...P){var v=P.map(D);return function(...y){var c=this,$0=y[y.length-1];if(typeof $0=="function")y.pop();else $0=K4();return M(v,y,(U0,q0,G0)=>{q0.apply(c,U0.concat((Z0,...j0)=>{G0(Z0,j0)}))},(U0,q0)=>$0(U0,...q0)),$0[m0]}}function x(...P){return j(...P.reverse())}function s(P,v,y,c){return T(i(v),P,y,c)}var m=F(s,4);function e( Line truncated
GFS4: `),console.error($)};if(!V4[Y6]){if(sj=global[Y6]||[],gI0(V4,sj),V4.close=function($){function I(U,Y){return $.call(V4,U,function(J){if(!J)SI0();if(typeof Y==="function")Y.apply(this,arguments)})}return Object.defineProperty(I,uX,{value:$}),I}(V4.close),V4.closeSync=function($){function I(U){$.apply(V4,arguments),SI0()}return Object.defineProperty(I,uX,{value:$}),I}(V4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){M3(V4[Y6]),r("assert").equal(V4[Y6].length,0)})}var sj;if(!global[Y6])gI0(global,V4[Y6]);I_.exports=ej(v01(V4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!V4.__patched)I_.exports=ej(V4),V4.__patched=!0;function ej($){E01($),$.gracefulify=ej,$.createReadStream=R,$.createWriteStream=u;var I=$.readFile;$.readFile=U;function U(C,p,n){if(typeof p==="function")n=p,p=null;return S(C,p,n);function S(f,i,Y0,B){return I(f,i,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))RY([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,p,n,S){if(typeof n==="function")S=n,n=null;return f(C,p,n,S);function f(i,Y0,B,k,d){return Y(i,Y0,B,function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))RY([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,p,n,S){if(typeof n==="function")S=n,n=null;return f(C,p,n,S);function f(i,Y0,B,k,d){return Q(i,Y0,B,function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))RY([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,p,n,S){if(typeof n==="function")S=n,n=0;return f(C,p,n,S);function f(i,Y0,B,k,d){return q(i,Y0,B,function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))RY([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,p,n){if(typeof p==="function")n=p,p=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,p,n);function f(i,Y0,B,k){return function(d,t){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))RY([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 w=B01($);F=w.ReadStream,T=w.WriteStream}var Z=$.ReadStream;if(Z)F.prototype=Object.create(Z.prototype),F.prototype.open=E;var z=$.WriteStream;if(z)T.prototype=Object.create(z.prototype),T.prototype.open=A;Object.defineProperty($,"ReadStream",{get:function(){return F},set:function(C){F=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return T},set:function(C){T=C},enumerable:!0,configurable:!0});var L=F;Object.defineProperty($,"FileReadStream",{get:function(){return L},set:function(C){L=C},enumerable:!0,configurable:!0});var D=T;Object.defineProperty($,"FileWriteStream",{get:function(){return D},set:function(C){D=C},enumerable:!0,configurable:!0});function F(C,p){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(p,n){if(p){if(C.autoClose)C.destroy();C.emit("error",p)}else C.fd=n,C.emit("open",n),C.read()})}function T(C,p){if(this instanceof T)return z.apply(this,arguments),this;else return T.apply(Object.create(T.prototype),arguments)}function A(){var C=this;b(C.path,C.flags,C.mode,function(p,n){if(p)C.destroy(),C.emit("error",p);else C.fd=n,C.emit("open",n)})}function R(C,p){return new $.ReadStream(C,p)}function u(C,p){return new $.WriteStream(C,p)}var g=$.open;$.open=b;function b(C,p,n,S){if(typeof n==="function")S=n,n=null;return f(C,p,n,S);function f(i,Y0,B,k,d){return g(i,Y0,B,function(t,K0){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))RY([f,[i,Y0,B,k],t,d||Date.now(),Date.now()]);else if(typeof k==="function")k.apply(this,arguments)})}}return $}function RY($){M3("ENQUEUE",$[0].name,$[1]),V4[Y6].push($),$_()}var kX;function SI0(){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]=$;$_()}function $_(){if(clearTimeout(kX),kX=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)M3("RETRY",I.name,U),I.apply(null,U);else if(Date.now()-J>=60000){M3("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)M3("RETRY",I.name,U),I.apply(null,U.concat([J]));else V4[Y6].push($)}if(kX===void 0)kX=setTimeout($_,0)}});var hI0=O((Wv1,U_)=>{function C01($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var yI0=M4().Buffer,SK=r("util");function j01($,I,U){$.copy(I,U)}U_.exports=function(){function $(){C01(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.
*/MU0.exports=function($,I){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var q=$.length;if(q<=1)return $;var U="";if(q>4&&$[3]==="\\"){var Y=$[2];if((Y==="?"||Y===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),U="//"}var J=$.split(/[/\\]+/);if(I!==!1&&J[J.length-1]==="")J.pop();return U+J.join("/")}});var Z_=L((LB1,BU0)=>{var gU0=9007199254740991,q$1="[object Arguments]",U$1="[object Function]",Y$1="[object GeneratorFunction]",J$1=/^(?:0|[1-9]\d*)$/;function PU0($,I,q){switch(q.length){case 0:return $.call(I);case 1:return $.call(I,q[0]);case 2:return $.call(I,q[0],q[1]);case 3:return $.call(I,q[0],q[1],q[2])}return $.apply(I,q)}function Q$1($,I){var q=-1,U=Array($);while(++q<$)U[q]=I(q);return U}var d2=Object.prototype,l2=d2.hasOwnProperty,TU0=d2.toString,K$1=d2.propertyIsEnumerable,AU0=Math.max;function z$1($,I){var q=L$1($)||O$1($)?Q$1($.length,String):[],U=q.length,Y=!!U;for(var J in $)if((I||l2.call($,J))&&!(Y&&(J=="length"||EU0(J,U))))q.push(J);return q}function w$1($,I,q,U){if($===void 0||H_($,d2[q])&&!l2.call(U,q))return I;return $}function G$1($,I,q){var U=$[I];if(!(l2.call($,I)&&H_(U,q))||q===void 0&&!(I in $))$[I]=q}function H$1($){if(!W_($))return D$1($);var I=X$1($),q=[];for(var U in $)if(!(U=="constructor"&&(I||!l2.call($,U))))q.push(U);return q}function jU0($,I){return I=AU0(I===void 0?$.length-1:I,0),function(){var q=arguments,U=-1,Y=AU0(q.length-I,0),J=Array(Y);while(++U<Y)J[U]=q[I+U];U=-1;var Q=Array(I+1);while(++U<I)Q[U]=q[U];return Q[I]=J,PU0($,this,Q)}}function V$1($,I,q,U){q||(q={});var Y=-1,J=I.length;while(++Y<J){var Q=I[Y],K=U?U(q[Q],$[Q],Q,q,$):void 0;G$1(q,Q,K===void 0?$[Q]:K)}return q}function W$1($){return jU0(function(I,q){var U=-1,Y=q.length,J=Y>1?q[Y-1]:void 0,Q=Y>2?q[2]:void 0;if(J=$.length>3&&typeof J=="function"?(Y--,J):void 0,Q&&Z$1(q[0],q[1],Q))J=Y<3?void 0:J,Y=1;I=Object(I);while(++U<Y){var K=q[U];if(K)$(I,K,U,J)}return I})}function EU0($,I){return I=I==null?gU0:I,!!I&&(typeof $=="number"||J$1.test($))&&($>-1&&$%1==0&&$<I)}function Z$1($,I,q){if(!W_(q))return!1;var U=typeof I;if(U=="number"?V_(q)&&EU0(I,q.length):U=="string"&&(I in q))return H_(q[I],$);return!1}function X$1($){var I=$&&$.constructor,q=typeof I=="function"&&I.prototype||d2;return $===q}function D$1($){var I=[];if($!=null)for(var q in Object($))I.push(q);return I}function H_($,I){return $===I||$!==$&&I!==I}function O$1($){return N$1($)&&l2.call($,"callee")&&(!K$1.call($,"callee")||TU0.call($)==q$1)}var L$1=Array.isArray;function V_($){return $!=null&&M$1($.length)&&!F$1($)}function N$1($){return A$1($)&&V_($)}function F$1($){var I=W_($)?TU0.call($):"";return I==U$1||I==Y$1}function M$1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=gU0}function W_($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function A$1($){return!!$&&typeof $=="object"}var g$1=W$1(function($,I,q,U){V$1(I,T$1(I),$,U)}),P$1=jU0(function($){return $.push(void 0,w$1),PU0(g$1,void 0,$)});function T$1($){return V_($)?z$1($,!0):H$1($)}BU0.exports=P$1});var RU0=L((NB1,X_)=>{function j$1($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var vU0=F4().Buffer,m2=o("util");function E$1($,I,q){$.copy(I,q)}X_.exports=function(){function $(){j$1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(q){var U={data:q,next:null};if(this.length>0)this.tail.next=U;else this.head=U;this.tail=U,++this.length},$.prototype.unshift=function(q){var U={data:q,next:this.head};if(this.length===0)this.tail=U;this.head=U,++this.length},$.prototype.shift=function(){if(this.length===0)return;var q=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,q},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(q){if(this.length===0)return"";var U=this.head,Y=""+U.data;while(U=U.next)Y+=q+U.data;return Y},$.prototype.concat=function(q){if(this.length===0)return vU0.alloc(0);var U=vU0.allocUnsafe(q>>>0),Y=this.head,J=0;while(Y)E$1(Y.data,U,J),J+=Y.data.length,Y=Y.next;return U},$}();if(m2&&m2.inspect&&m2.inspect.custom)X_.exports.prototype[m2.inspect.custom]=function(){var $=m2.inspect({length:this.length});return this.constructor.name+" "+$}});var D_=L((FB1,CU0)=>{var OX=N4();function B$1($,I){var q=this,U=this._readableState&&this._readableState.destroyed,Y=this._writableState&&this._writableState.destroyed;if(U||Y){if(I)I($);else if($){if(!this._writableState)OX.nextTick(LX,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,OX.nextTick(LX,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(J){if(!I&&J){if(!q._writableState)OX.nextTick(LX,q,J);else if(!q._writableState.errorEmitted)q._writableState.errorEmitted=!0,OX.nextTick(LX,q,J)}else if(I)I(J)}),this}function v$1(){if(this._readableState)this._readable Line truncated
%s`,B,B,T,U);var k=T.type==="*"?$h:T.type==="?"?e_:"\\"+T.type;Y=!0,U=U.slice(0,T.reStart)+k+"\\("+B}if(X(),J)U+="\\\\";var h=!1;switch(U.charAt(0)){case"[":case".":case"(":h=!0}for(var n=K.length-1;n>-1;n--){var S=K[n],t=U.slice(0,S.reStart),p=U.slice(S.reStart,S.reEnd-8),C=U.slice(S.reEnd-8,S.reEnd),f=U.slice(S.reEnd);C+=f;var b=t.split("(").length-1,J0=f;for(D=0;D<b;D++)J0=J0.replace(/\)[+*?]?/,"");f=J0;var j="";if(f===""&&I!==SX)j="$";var u=t+p+f+j+C;U=u}if(U!==""&&Y)U="(?=.)"+U;if(h)U=W+U;if(I===SX)return[U,Y];if(!Y)return o71($);var d=q.nocase?"i":"";try{var a=new RegExp("^"+U+"$",d)}catch(K0){return new RegExp("$.")}return a._glob=$,a._src=U,a}J$.makeRe=function($,I){return new T4($,I||{}).makeRe()};T4.prototype.makeRe=m71;function m71(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var I=this.options,q=I.noglobstar?$h:I.dot?f71:n71,U=I.nocase?"i":"",Y=$.map(function(J){return J.map(function(Q){return Q===C3?q:typeof Q==="string"?r71(Q):Q._src}).join("\\/")}).join("|");if(Y="^(?:"+Y+")$",this.negate)Y="^(?!"+Y+").*$";try{this.regexp=new RegExp(Y,U)}catch(J){this.regexp=!1}return this.regexp}J$.match=function($,I,q){q=q||{};var U=new T4(I,q);if($=$.filter(function(Y){return U.match(Y)}),U.options.nonull&&!$.length)$.push(I);return $};T4.prototype.match=function(I,q){if(typeof q>"u")q=this.partial;if(this.debug("match",I,this.pattern),this.comment)return!1;if(this.empty)return I==="";if(I==="/"&&q)return!0;var U=this.options;if(JK.sep!=="/")I=I.split(JK.sep).join("/");I=I.split(JJ0),this.debug(this.pattern,"split",I);var Y=this.set;this.debug(this.pattern,"set",Y);var J,Q;for(Q=I.length-1;Q>=0;Q--)if(J=I[Q],J)break;for(Q=0;Q<Y.length;Q++){var K=Y[Q],z=I;if(U.matchBase&&K.length===1)z=[J];var w=this.matchOne(z,K,q);if(w){if(U.flipNegate)return!0;return!this.negate}}if(U.flipNegate)return!1;return this.negate};T4.prototype.matchOne=function($,I,q){if(I.indexOf(C3)!==-1)return this._matchGlobstar($,I,q,0,0);return this._matchOne($,I,q,0,0)};T4.prototype._matchGlobstar=function($,I,q,U,Y){var J,Q=-1;for(J=Y;J<I.length;J++)if(I[J]===C3){Q=J;break}var K=-1;for(J=I.length-1;J>=0;J--)if(I[J]===C3){K=J;break}var z=I.slice(Y,Q),w=q?I.slice(Q+1):I.slice(Q+1,K),G=q?[]:I.slice(K+1);if(z.length){var H=$.slice(U,U+z.length);if(!this._matchOne(H,z,q,0,0))return!1;U+=z.length}var W=0;if(G.length){if(G.length+U>$.length)return!1;var V=$.length-G.length;if(this._matchOne($,G,q,V,0))W=G.length;else{if($[$.length-1]!==""||U+G.length===$.length)return!1;if(V--,!this._matchOne($,G,q,V,0))return!1;W=G.length+1}}if(!w.length){var X=!!W;for(J=U;J<$.length-W;J++){var D=String($[J]);if(X=!0,D==="."||D===".."||!this.options.dot&&D.charAt(0)===".")return!1}return q||X}var O=[[[],0]],N=O[0],T=0,P=[0];for(var g=0;g<w.length;g++){var B=w[g];if(B===C3)P.push(T),N=[[],0],O.push(N);else N[0].push(B),T++}var k=O.length-1,h=$.length-W;for(var n=0;n<O.length;n++)O[n][1]=h-(P[k--]+O[n][0].length);return!!this._matchGlobStarBodySections($,O,U,0,q,0,!!W)};T4.prototype._matchGlobStarBodySections=function($,I,q,U,Y,J,Q){var K=I[U];if(!K){for(var z=q;z<$.length;z++){Q=!0;var w=$[z];if(w==="."||w===".."||!this.options.dot&&w.charAt(0)===".")return!1}return Q}var G=K[0],H=K[1];while(q<=H){var W=this._matchOne($.slice(0,q+G.length),G,Y,q,0);if(W&&J<this.maxGlobstarRecursion){var V=this._matchGlobStarBodySections($,I,q+G.length,U+1,Y,J+1,Q);if(V!==!1)return V}var w=$[q];if(w==="."||w===".."||!this.options.dot&&w.charAt(0)===".")return!1;q++}return Y||null};T4.prototype._matchOne=function($,I,q,U,Y){var J,Q,K,z;for(J=U,Q=Y,K=$.length,z=I.length;J<K&&Q<z;J++,Q++){this.debug("matchOne loop");var w=I[Q],G=$[J];if(this.debug(I,w,G),w===!1||w===C3)return!1;var H;if(typeof w==="string")H=G===w,this.debug("string match",w,G,H);else H=G.match(w),this.debug("pattern match",w,G,H);if(!H)return!1}if(J===K&&Q===z)return!0;else if(J===K)return q;else if(Q===z)return J===K-1&&$[J]==="";throw Error("wtf?")};function o71($){return $.replace(/\\(.)/g,"$1")}function r71($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var kX=L((fB1,xX)=>{function zJ0($){return $.charAt(0)==="/"}function wJ0($){var I=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,q=I.exec($),U=q[1]||"",Y=Boolean(U&&U.charAt(1)!==":");return Boolean(q[2]||Y)}xX.exports=process.platform==="win32"?wJ0:zJ0;xX.exports.posix=zJ0;xX.exports.win32=wJ0});var qh=L((J31)=>{J31.setopts=I31;J31.ownProp=GJ0;J31.makeAbs=QK;J31.finish=q31;J31.mark=U31;J31.isIgnored=VJ0;J31.childrenIgnored=Y31;function GJ0($,I){return Object.prototype.hasOwnProperty.call($,I)}var t71=o("fs"),cU=o("path"),a71=uX(),HJ0=kX(),Ih=a71.Minimatch;function s71($,I){return $.localeCompare(I,"en")}function e71($,I){if($.ignore=I.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map($31)}function $31($){var I=null;if($.slice(-3)==="/**"){var q=$.replace(/(\/\*\*)+$/,"");I=new Ih(q,{dot:!0})}return{matcher Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new h4($,I).found}function h4($,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 h4))return new h4($,I);if(Z31(this,$,I),this.noprocess)return this;var q=this.minimatch.set.length;this.matches=Array(q);for(var U=0;U<q;U++)this._process(this.minimatch.set[U],U,!1);this._finish()}h4.prototype._finish=function(){if(ZJ0.ok(this instanceof h4),this.realpath){var $=this;this.matches.forEach(function(I,q){var U=$.matches[q]=Object.create(null);for(var Y in I)try{Y=$._makeAbs(Y);var J=W31.realpathSync(Y,$.realpathCache);U[J]=!0}catch(Q){if(Q.syscall==="stat")U[$._makeAbs(Y)]=!0;else throw Q}})}_3.finish(this)};h4.prototype._process=function($,I,q){ZJ0.ok(this instanceof h4);var U=0;while(typeof $[U]==="string")U++;var Y;switch(U){case $.length:this._processSimple($.join("/"),I);return;case 0:Y=null;break;default:Y=$.slice(0,U).join("/");break}var J=$.slice(U),Q;if(Y===null)Q=".";else if(fX(Y)||fX($.map(function(w){return typeof w==="string"?w:"[*]"}).join("/"))){if(!Y||!fX(Y))Y="/"+Y;Q=Y}else Q=Y;var K=this._makeAbs(Q);if(X31(this,Q))return;var z=J[0]===WJ0.GLOBSTAR;if(z)this._processGlobStar(Y,Q,K,J,I,q);else this._processReaddir(Y,Q,K,J,I,q)};h4.prototype._processReaddir=function($,I,q,U,Y,J){var Q=this._readdir(q,J);if(!Q)return;var K=U[0],z=!!this.minimatch.negate,w=K._glob,G=this.dot||w.charAt(0)===".",H=[];for(var W=0;W<Q.length;W++){var V=Q[W];if(V.charAt(0)!=="."||G){var X;if(z&&!$)X=!V.match(K);else X=V.match(K);if(X)H.push(V)}}var D=H.length;if(D===0)return;if(U.length===1&&!this.mark&&!this.stat){if(!this.matches[Y])this.matches[Y]=Object.create(null);for(var W=0;W<D;W++){var V=H[W];if($)if($.slice(-1)!=="/")V=$+"/"+V;else V=$+V;if(V.charAt(0)==="/"&&!this.nomount)V=Uh.join(this.root,V);this._emitMatch(Y,V)}return}U.shift();for(var W=0;W<D;W++){var V=H[W],O;if($)O=[$,V];else O=[V];this._process(O.concat(U),Y,J)}};h4.prototype._emitMatch=function($,I){if(D31(this,I))return;var q=this._makeAbs(I);if(this.mark)I=this._mark(I);if(this.absolute)I=q;if(this.matches[$][I])return;if(this.nodir){var U=this.cache[q];if(U==="DIR"||Array.isArray(U))return}if(this.matches[$][I]=!0,this.stat)this._stat(I)};h4.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var I,q,U;try{q=this.fs.lstatSync($)}catch(J){if(J.code==="ENOENT")return null}var Y=q&&q.isSymbolicLink();if(this.symlinks[$]=Y,!Y&&q&&!q.isDirectory())this.cache[$]="FILE";else I=this._readdir($,!1);return I};h4.prototype._readdir=function($,I){var q;if(I&&!Yh(this.symlinks,$))return this._readdirInGlobStar($);if(Yh(this.cache,$)){var U=this.cache[$];if(!U||U==="FILE")return null;if(Array.isArray(U))return U}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(Y){return this._readdirError($,Y),null}};h4.prototype._readdirEntries=function($,I){if(!this.mark&&!this.stat)for(var q=0;q<I.length;q++){var U=I[q];if($==="/")U=$+U;else U=$+"/"+U;this.cache[U]=!0}return this.cache[$]=I,I};h4.prototype._readdirError=function($,I){switch(I.code){case"ENOTSUP":case"ENOTDIR":var q=this._makeAbs($);if(this.cache[q]="FILE",q===this.cwdAbs){var U=Error(I.code+" invalid cwd "+this.cwd);throw U.path=this.cwd,U.code=I.code,U}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}};h4.prototype._processGlobStar=function($,I,q,U,Y,J){var Q=this._readdir(q,J);if(!Q)return;var K=U.slice(1),z=$?[$]:[],w=z.concat(K);this._process(w,Y,!1);var G=Q.length,H=this.symlinks[q];if(H&&J)return;for(var W=0;W<G;W++){var V=Q[W];if(V.charAt(0)==="."&&!this.dot)continue;var X=z.concat(Q[W],K);this._process(X,Y,!0);var D=z.concat(Q[W],U);this._process(D,Y,!0)}};h4.prototype._processSimple=function($,I){var q=this._stat($);if(!this.matches[I])this.matches[I]=Object.create(null);if(!q)return;if($&&fX($)&&!this.nomount){var U=/[\/\\]$/.test($);if($.charAt(0)==="/")$=Uh.join(this.root,$);else if($=Uh.resolve(this.root,$),U)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(I,$)};h4.prototype._stat=function($){var I=this._makeAbs($),q=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&Yh(this.cache,I)){var Q=this.cache[I];if(Array.isArray(Q))Q="DIR";if(!q||Q==="DIR")return Q;if(q&&Q==="FILE")return!1}var U,Y=this.statCache[I];if(!Y){var J;try{J=this.fs.lstatSync(I)}catch(K){if(K&&(K.code==="ENOENT"||K.code==="ENOTDIR"))return this.statCache[I]=!1,!1}if(J&&J.isSymbolicLink())try{Y=this.fs.statSync(I)}catch(K){Y=J}else Y=J}this.statCache[I]=Y;var Q=!0;if(Y)Q=Y.isDirectory()?"DIR":"FILE";if(this.cache[I]=this.cache[I]||Q,q&&Q==="FILE")return!1;return Q};h4.prototype._mark=function($){return _3.mark(this,$)};h4.prototype._makeAbs=function($){return _3.makeAbs(this,$)}});var Jh=L((dB1,NJ0)=>{NJ0.exports=LJ0;function LJ0($,I){if($&&I)return LJ0($)(I);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(U){q[U]=$[U]}),q;f Line truncated
`);if($.linkname)I+=xh(" linkpath="+$.linkname+`
`);var q=$.pax;if(q)for(var U in q)I+=xh(" "+U+"="+q[U]+`
`);return Buffer.from(I)};_I1.decodePax=function($){var I={};while($.length){var q=0;while(q<$.length&&$[q]!==32)q++;var U=parseInt($.slice(0,q).toString(),10);if(!U)return I;var Y=$.slice(q+1,U-1).toString(),J=Y.indexOf("=");if(J===-1)return I;I[Y.slice(0,J)]=Y.slice(J+1),$=$.slice(U)}return I};_I1.encode=function($){var I=MI1(512),q=$.name,U="";if($.typeflag===5&&q[q.length-1]!=="/")q+="/";if(Buffer.byteLength(q)!==q.length)return null;while(Buffer.byteLength(q)>100){var Y=q.indexOf("/");if(Y===-1)return null;U+=U?"/"+q.slice(0,Y):q.slice(0,Y),q=q.slice(Y+1)}if(Buffer.byteLength(q)>100||Buffer.byteLength(U)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(I.write(q),I.write(s9($.mode&EI1,6),100),I.write(s9($.uid,6),108),I.write(s9($.gid,6),116),I.write(s9($.size,11),124),I.write(s9($.mtime.getTime()/1000|0,11),136),I[156]=xQ0+RI1($.type),$.linkname)I.write($.linkname,157);if(kQ0.copy(I,VK),PI1.copy(I,kh),$.uname)I.write($.uname,265);if($.gname)I.write($.gname,297);if(I.write(s9($.devmajor||0,6),329),I.write(s9($.devminor||0,6),337),U)I.write(U,345);return I.write(s9(nQ0(I),6),148),I};_I1.decode=function($,I,q){var U=$[156]===0?0:$[156]-xQ0,Y=oU($,0,100,I),J=e9($,100,8),Q=e9($,108,8),K=e9($,116,8),z=e9($,124,12),w=e9($,136,12),G=vI1(U),H=$[157]===0?null:oU($,157,100,I),W=oU($,265,32),V=oU($,297,32),X=e9($,329,8),D=e9($,337,8),O=nQ0($);if(O===256)return null;if(O!==e9($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(kQ0.compare($,VK,VK+6)===0){if($[345])Y=oU($,345,155,I)+"/"+Y}else if(TI1.compare($,VK,VK+6)===0&&jI1.compare($,kh,kh+2)===0);else if(!q)throw Error("Invalid tar header: unknown format.");if(U===0&&Y&&Y[Y.length-1]==="/")U=5;return{name:Y,mode:J,uid:Q,gid:K,size:z,mtime:new Date(1000*w),type:G,linkname:H,uname:W,gname:V,devmajor:X,devminor:D}}});var mQ0=L((jv1,lQ0)=>{var iQ0=o("util"),kI1=uQ0(),WK=fh(),pQ0=W6().Writable,cQ0=W6().PassThrough,dQ0=function(){},bQ0=function($){return $&=511,$&&512-$},fI1=function($,I){var q=new lX($,I);return q.end(),q},nI1=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,$},lX=function($,I){this._parent=$,this.offset=I,cQ0.call(this,{autoDestroy:!1})};iQ0.inherits(lX,cQ0);lX.prototype.destroy=function($){this._parent.destroy($)};var R5=function($){if(!(this instanceof R5))return new R5($);pQ0.call(this,$),$=$||{},this._offset=0,this._buffer=kI1(),this._missing=0,this._partial=!1,this._onparse=dQ0,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,q=I._buffer,U=function(){I._continue()},Y=function(W){if(I._locked=!1,W)return I.destroy(W);if(!I._stream)U()},J=function(){I._stream=null;var W=bQ0(I._header.size);if(W)I._parse(W,Q);else I._parse(512,H);if(!I._locked)U()},Q=function(){I._buffer.consume(bQ0(I._header.size)),I._parse(512,H),U()},K=function(){var W=I._header.size;I._paxGlobal=WK.decodePax(q.slice(0,W)),q.consume(W),J()},z=function(){var W=I._header.size;if(I._pax=WK.decodePax(q.slice(0,W)),I._paxGlobal)I._pax=Object.assign({},I._paxGlobal,I._pax);q.consume(W),J()},w=function(){var W=I._header.size;this._gnuLongPath=WK.decodeLongPath(q.slice(0,W),$.filenameEncoding),q.consume(W),J()},G=function(){var W=I._header.size;this._gnuLongLinkPath=WK.decodeLongPath(q.slice(0,W),$.filenameEncoding),q.consume(W),J()},H=function(){var W=I._offset,V;try{V=I._header=WK.decode(q.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(X){I.emit("error",X)}if(q.consume(512),!V){I._parse(512,H),U();return}if(V.type==="gnu-long-path"){I._parse(V.size,w),U();return}if(V.type==="gnu-long-link-path"){I._parse(V.size,G),U();return}if(V.type==="pax-global-header"){I._parse(V.size,K),U();return}if(V.type==="pax-header"){I._parse(V.size,z),U();return}if(I._gnuLongPath)V.name=I._gnuLongPath,I._gnuLongPath=null;if(I._gnuLongLinkPath)V.linkname=I._gnuLongLinkPath,I._gnuLongLinkPath=null;if(I._pax)I._header=V=nI1(V,I._pax),I._pax=null;if(I._locked=!0,!V.size||V.type==="directory"){I._parse(512,H),I.emit("entry",V,fI1(I,W),Y);return}I._stream=new lX(I,W),I.emit("entry",V,I._stream,Y),I._parse(V.size,J),U()};this._onheader=H,this._parse(512,H)};iQ0.inherits(R5,pQ0);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=dQ0,this._overflow)this._write(this._overflow,void 0,$);else $()};R5.prototype._write=function($,I,q){if(this._destroyed)return;var U=this._stream,Y=this._buffer,J=this._missing;if($.length)this._partial=!0;if($.length<J){ 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="${Jq1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${$.Target}"/>`);return I}_writeClose(){this.stream.write("</Relationships>")}}N20.exports=L20});var T20=L((uv1,P20)=>{var M20=e4(),A20=y9(),Kq1=K4(),zq1=LR(),wq1=FR();class g20{constructor($,I,q){this.id=q.id,this.count=0,this._worksheet=$,this._workbook=q.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:A20.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let I={Type:A20.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 q=new zq1,U=new M20;q.render(U,$),this.commentsStream.write(U.xml);let Y=new wq1,J=new M20;Y.render(J,$,I),this.vmlStream.write(J.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=Kq1.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()}}P20.exports=g20});var C20=L((xv1,R20)=>{var Gq1=W4(),Hq1=y9(),ih=K4(),j20=uj(),E20=z5(),Vq1=aB(),B20=GV(),ph=VV(),Wq1=F20(),Zq1=T20(),Xq1=Sj(),f4=new Vq1,ch=_9(),Dq1=lv(),Oq1=mv(),Lq1=ov(),Nq1=iv(),Fq1=nv(),Mq1=pv(),Aq1=rv(),gq1=tv(),Pq1=av(),Tq1=sv(),jq1=ev(),Eq1=$R(),Bq1=JR(),vq1=qR(),Rq1=IR(),n4={dataValidations:new Dq1,sheetProperties:new Oq1,sheetFormatProperties:new Lq1,columns:new ch({tag:"cols",length:!1,childXform:new Nq1}),row:new Fq1,hyperlinks:new ch({tag:"hyperlinks",length:!1,childXform:new Mq1}),sheetViews:new ch({tag:"sheetViews",length:!1,childXform:new Aq1}),sheetProtection:new gq1,pageMargins:new Pq1,pageSeteup:new Tq1,autoFilter:new jq1,picture:new Eq1,conditionalFormattings:new Bq1,headerFooter:new vq1,rowBreaks:new Rq1};class v20{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 Wq1($),this._sheetCommentsWriter=new Zq1(this,this._sheetRelsWriter,$),this._dimensions=new E20,this._rowZero=1,this.committed=!1,this.dataValidations=new Xq1,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
*/MU0.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 A_=O((Av1,RU0)=>{var PU0=9007199254740991,x11="[object Arguments]",k11="[object Function]",u11="[object GeneratorFunction]",f11=/^(?:0|[1-9]\d*)$/;function TU0($,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 b11($,I){var U=-1,Y=Array($);while(++U<$)Y[U]=I(U);return Y}var iK=Object.prototype,nK=iK.hasOwnProperty,EU0=iK.toString,i11=iK.propertyIsEnumerable,AU0=Math.max;function n11($,I){var U=s11($)||a11($)?b11($.length,String):[],Y=U.length,J=!!Y;for(var Q in $)if((I||nK.call($,Q))&&!(J&&(Q=="length"||vU0(Q,Y))))U.push(Q);return U}function p11($,I,U,Y){if($===void 0||F_($,iK[U])&&!nK.call(Y,U))return I;return $}function c11($,I,U){var Y=$[I];if(!(nK.call($,I)&&F_(Y,U))||U===void 0&&!(I in $))$[I]=U}function d11($){if(!M_($))return t11($);var I=r11($),U=[];for(var Y in $)if(!(Y=="constructor"&&(I||!nK.call($,Y))))U.push(Y);return U}function BU0($,I){return I=AU0(I===void 0?$.length-1:I,0),function(){var U=arguments,Y=-1,J=AU0(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,TU0($,this,K)}}function m11($,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;c11(U,K,q===void 0?$[K]:q)}return U}function l11($){return BU0(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&&o11(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 vU0($,I){return I=I==null?PU0:I,!!I&&(typeof $=="number"||f11.test($))&&($>-1&&$%1==0&&$<I)}function o11($,I,U){if(!M_(U))return!1;var Y=typeof I;if(Y=="number"?N_(U)&&vU0(I,U.length):Y=="string"&&(I in U))return F_(U[I],$);return!1}function r11($){var I=$&&$.constructor,U=typeof I=="function"&&I.prototype||iK;return $===U}function t11($){var I=[];if($!=null)for(var U in Object($))I.push(U);return I}function F_($,I){return $===I||$!==$&&I!==I}function a11($){return e11($)&&nK.call($,"callee")&&(!i11.call($,"callee")||EU0.call($)==x11)}var s11=Array.isArray;function N_($){return $!=null&&I41($.length)&&!$41($)}function e11($){return U41($)&&N_($)}function $41($){var I=M_($)?EU0.call($):"";return I==k11||I==u11}function I41($){return typeof $=="number"&&$>-1&&$%1==0&&$<=PU0}function M_($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function U41($){return!!$&&typeof $=="object"}var Y41=l11(function($,I,U,Y){m11(I,Q41(I),$,Y)}),J41=BU0(function($){return $.push(void 0,p11),TU0(Y41,void 0,$)});function Q41($){return N_($)?n11($,!0):d11($)}RU0.exports=J41});var jU0=O((Pv1,P_)=>{function K41($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var CU0=M4().Buffer,pK=r("util");function q41($,I,U){$.copy(I,U)}P_.exports=function(){function $(){K41(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 CU0.alloc(0);var Y=CU0.allocUnsafe(U>>>0),J=this.head,Q=0;while(J)q41(J.data,Y,Q),Q+=J.data.length,J=J.next;return Y},$}();if(pK&&pK.inspect&&pK.inspect.custom)P_.exports.prototype[pK.inspect.custom]=function(){var $=pK.inspect({length:this.length});return this.constructor.name+" "+$}});var T_=O((Tv1,_U0)=>{var aX=N4();function G41($,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)aX.nextTick(sX,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,aX.nextTick(sX,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)aX.nextTick(sX,U,Q);else if(!U._writableState.errorEmitted)U._writableState.errorEmitted=!0,aX.nextTick(sX,U,Q)}else if(I)I(Q)}),this}function H41(){if(this._readableState)this._readable Line truncated
%s`,R,R,E,Y);var u=E.type==="*"?GS:E.type==="?"?qS:"\\"+E.type;J=!0,Y=Y.slice(0,E.reStart)+u+"\\("+R}if(z(),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],p=Y.slice(0,C.reStart),n=Y.slice(C.reStart,C.reEnd-8),S=Y.slice(C.reEnd-8,C.reEnd),f=Y.slice(C.reEnd);S+=f;var i=p.split("(").length-1,Y0=f;for(L=0;L<i;L++)Y0=Y0.replace(/\)[+*?]?/,"");f=Y0;var B="";if(f===""&&I!==Xz)B="$";var k=p+n+f+B+S;Y=k}if(Y!==""&&J)Y="(?=.)"+Y;if(g)Y=w+Y;if(I===Xz)return[Y,J];if(!J)return R51($);var d=U.nocase?"i":"";try{var t=new RegExp("^"+Y+"$",d)}catch(K0){return new RegExp("$.")}return t._glob=$,t._src=Y,t}q$.makeRe=function($,I){return new B4($,I||{}).makeRe()};B4.prototype.makeRe=v51;function v51(){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?GS:I.dot?F51:N51,Y=I.nocase?"i":"",J=$.map(function(Q){return Q.map(function(K){return K===C3?U:typeof K==="string"?C51(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}q$.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(Iq.sep!=="/")I=I.split(Iq.sep).join("/");I=I.split(QJ0),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(C3)!==-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]===C3){K=Q;break}var q=-1;for(Q=I.length-1;Q>=0;Q--)if(I[Q]===C3){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 w=0;if(W.length){if(W.length+Y>$.length)return!1;var Z=$.length-W.length;if(this._matchOne($,W,U,Z,0))w=W.length;else{if($[$.length-1]!==""||Y+W.length===$.length)return!1;if(Z--,!this._matchOne($,W,U,Z,0))return!1;w=W.length+1}}if(!H.length){var z=!!w;for(Q=Y;Q<$.length-w;Q++){var L=String($[Q]);if(z=!0,L==="."||L===".."||!this.options.dot&&L.charAt(0)===".")return!1}return U||z}var D=[[[],0]],F=D[0],E=0,T=[0];for(var A=0;A<H.length;A++){var R=H[A];if(R===C3)T.push(E),F=[[],0],D.push(F);else F[0].push(R),E++}var u=D.length-1,g=$.length-w;for(var b=0;b<D.length;b++)D[b][1]=g-(T[u--]+D[b][0].length);return!!this._matchGlobStarBodySections($,D,Y,0,U,0,!!w)};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 w=this._matchOne($.slice(0,U+W.length),W,J,U,0);if(w&&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===C3)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 R51($){return $.replace(/\\(.)/g,"$1")}function C51($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var Oz=O((pv1,Dz)=>{function GJ0($){return $.charAt(0)==="/"}function HJ0($){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)}Dz.exports=process.platform==="win32"?HJ0:GJ0;Dz.exports.posix=GJ0;Dz.exports.win32=HJ0});var WS=O((f51)=>{f51.setopts=h51;f51.ownProp=WJ0;f51.makeAbs=Uq;f51.finish=x51;f51.mark=k51;f51.isIgnored=wJ0;f51.childrenIgnored=u51;function WJ0($,I){return Object.prototype.hasOwnProperty.call($,I)}var j51=r("fs"),iY=r("path"),_51=Lz(),VJ0=Oz(),HS=_51.Minimatch;function S51($,I){return $.localeCompare(I,"en")}function g51($,I){if($.ignore=I.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(y51)}function y51($){var I=null;if($.slice(-3)==="/**"){var U=$.replace(/(\/\*\*)+$/,"");I=new HS(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(o51(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(XJ0.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=l51.realpathSync(J,$.realpathCache);Y[Q]=!0}catch(K){if(K.syscall==="stat")Y[$._makeAbs(J)]=!0;else throw K}})}j3.finish(this)};y4.prototype._process=function($,I,U){XJ0.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(Fz(J)||Fz($.map(function(H){return typeof H==="string"?H:"[*]"}).join("/"))){if(!J||!Fz(J))J="/"+J;K=J}else K=J;var q=this._makeAbs(K);if(r51(this,K))return;var G=Q[0]===ZJ0.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 w=0;w<K.length;w++){var Z=K[w];if(Z.charAt(0)!=="."||W){var z;if(G&&!$)z=!Z.match(q);else z=Z.match(q);if(z)V.push(Z)}}var L=V.length;if(L===0)return;if(Y.length===1&&!this.mark&&!this.stat){if(!this.matches[J])this.matches[J]=Object.create(null);for(var w=0;w<L;w++){var Z=V[w];if($)if($.slice(-1)!=="/")Z=$+"/"+Z;else Z=$+Z;if(Z.charAt(0)==="/"&&!this.nomount)Z=VS.join(this.root,Z);this._emitMatch(J,Z)}return}Y.shift();for(var w=0;w<L;w++){var Z=V[w],D;if($)D=[$,Z];else D=[Z];this._process(D.concat(Y),J,Q)}};y4.prototype._emitMatch=function($,I){if(t51(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&&!wS(this.symlinks,$))return this._readdirInGlobStar($);if(wS(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 w=0;w<W;w++){var Z=K[w];if(Z.charAt(0)==="."&&!this.dot)continue;var z=G.concat(K[w],q);this._process(z,J,!0);var L=G.concat(K[w],Y);this._process(L,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($&&Fz($)&&!this.nomount){var Y=/[\/\\]$/.test($);if($.charAt(0)==="/")$=VS.join(this.root,$);else if($=VS.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&&wS(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 j3.mark(this,$)};y4.prototype._makeAbs=function($){return j3.makeAbs(this,$)}});var ZS=O((rv1,FJ0)=>{FJ0.exports=OJ0;function OJ0($,I){if($&&I)return OJ0($)(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+=dS(" linkpath="+$.linkname+`
`);var U=$.pax;if(U)for(var Y in U)I+=dS(" "+Y+"="+U[Y]+`
`);return Buffer.from(I)};w71.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};w71.encode=function($){var I=I71(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($7($.mode&q71,6),100),I.write($7($.uid,6),108),I.write($7($.gid,6),116),I.write($7($.size,11),124),I.write($7($.mtime.getTime()/1000|0,11),136),I[156]=kQ0+W71($.type),$.linkname)I.write($.linkname,157);if(uQ0.copy(I,Gq),J71.copy(I,mS),$.uname)I.write($.uname,265);if($.gname)I.write($.gname,297);if(I.write($7($.devmajor||0,6),329),I.write($7($.devminor||0,6),337),Y)I.write(Y,345);return I.write($7(bQ0(I),6),148),I};w71.decode=function($,I,U){var Y=$[156]===0?0:$[156]-kQ0,J=dY($,0,100,I),Q=I7($,100,8),K=I7($,108,8),q=I7($,116,8),G=I7($,124,12),H=I7($,136,12),W=H71(Y),V=$[157]===0?null:dY($,157,100,I),w=dY($,265,32),Z=dY($,297,32),z=I7($,329,8),L=I7($,337,8),D=bQ0($);if(D===256)return null;if(D!==I7($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(uQ0.compare($,Gq,Gq+6)===0){if($[345])J=dY($,345,155,I)+"/"+J}else if(Q71.compare($,Gq,Gq+6)===0&&K71.compare($,mS,mS+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:w,gname:Z,devmajor:z,devminor:L}}});var lQ0=O((jR1,mQ0)=>{var nQ0=r("util"),O71=xQ0(),Hq=lS(),pQ0=z6().Writable,cQ0=z6().PassThrough,dQ0=function(){},iQ0=function($){return $&=511,$&&512-$},F71=function($,I){var U=new Bz($,I);return U.end(),U},N71=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,$},Bz=function($,I){this._parent=$,this.offset=I,cQ0.call(this,{autoDestroy:!1})};nQ0.inherits(Bz,cQ0);Bz.prototype.destroy=function($){this._parent.destroy($)};var C5=function($){if(!(this instanceof C5))return new C5($);pQ0.call(this,$),$=$||{},this._offset=0,this._buffer=O71(),this._missing=0,this._partial=!1,this._onparse=dQ0,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(w){if(I._locked=!1,w)return I.destroy(w);if(!I._stream)Y()},Q=function(){I._stream=null;var w=iQ0(I._header.size);if(w)I._parse(w,K);else I._parse(512,V);if(!I._locked)Y()},K=function(){I._buffer.consume(iQ0(I._header.size)),I._parse(512,V),Y()},q=function(){var w=I._header.size;I._paxGlobal=Hq.decodePax(U.slice(0,w)),U.consume(w),Q()},G=function(){var w=I._header.size;if(I._pax=Hq.decodePax(U.slice(0,w)),I._paxGlobal)I._pax=Object.assign({},I._paxGlobal,I._pax);U.consume(w),Q()},H=function(){var w=I._header.size;this._gnuLongPath=Hq.decodeLongPath(U.slice(0,w),$.filenameEncoding),U.consume(w),Q()},W=function(){var w=I._header.size;this._gnuLongLinkPath=Hq.decodeLongPath(U.slice(0,w),$.filenameEncoding),U.consume(w),Q()},V=function(){var w=I._offset,Z;try{Z=I._header=Hq.decode(U.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(z){I.emit("error",z)}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=N71(Z,I._pax),I._pax=null;if(I._locked=!0,!Z.size||Z.type==="directory"){I._parse(512,V),I.emit("entry",Z,F71(I,w),J);return}I._stream=new Bz(I,w),I.emit("entry",Z,I._stream,J),I._parse(Z.size,Q),Y()};this._onheader=V,this._parse(512,V)};nQ0.inherits(C5,pQ0);C5.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};C5.prototype._parse=function($,I){if(this._destroyed)return;if(this._offset+=$,this._missing=$,I===this._onheader)this._partial=!1;this._onparse=I};C5.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=dQ0,this._overflow)this._write(this._overflow,void 0,$);else $()};C5.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="${f71.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${$.Target}"/>`);return I}_writeClose(){this.stream.write("</Relationships>")}}F20.exports=O20});var E20=O((bR1,T20)=>{var M20=$6(),A20=k9(),i71=G4(),n71=BC(),p71=RC();class P20{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:A20.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let I={Type:A20.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 n71,Y=new M20;U.render(Y,$),this.commentsStream.write(Y.xml);let J=new p71,Q=new M20;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=i71.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()}}T20.exports=P20});var _20=O((iR1,j20)=>{var c71=Z4(),d71=k9(),tS=G4(),B20=cE(),v20=q5(),m71=QR(),R20=cV(),aS=mV(),l71=N20(),o71=E20(),r71=nE(),i4=new m71,sS=y9(),t71=$C(),a71=IC(),s71=UC(),e71=tR(),$31=oR(),I31=aR(),U31=YC(),Y31=JC(),J31=QC(),Q31=KC(),K31=qC(),q31=GC(),G31=ZC(),H31=WC(),W31=HC(),n4={dataValidations:new t71,sheetProperties:new a71,sheetFormatProperties:new s71,columns:new sS({tag:"cols",length:!1,childXform:new e71}),row:new $31,hyperlinks:new sS({tag:"hyperlinks",length:!1,childXform:new I31}),sheetViews:new sS({tag:"sheetViews",length:!1,childXform:new U31}),sheetProtection:new Y31,pageMargins:new J31,pageSeteup:new Q31,autoFilter:new K31,picture:new q31,conditionalFormattings:new G31,headerFooter:new H31,rowBreaks:new W31};class C20{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 l71($),this._sheetCommentsWriter=new o71(this,this._sheetRelsWriter,$),this._dimensions=new v20,this._rowZero=1,this.committed=!1,this.dataValidations=new r71,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
`)},zS=wS.getNativePromise();if(wS.isNode&&typeof MutationObserver>"u")GS=global.setImmediate,HS=process.nextTick,n3=wS.isRecentNode?function($){GS.call(global,$)}:function($){HS.call(process,$)};else if(typeof zS==="function"&&typeof zS.resolve==="function")VS=zS.resolve(),n3=function($){VS.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))n3=function(){var $=document.createElement("div"),I={attributes:!0},q=!1,U=document.createElement("div"),Y=new MutationObserver(function(){$.classList.toggle("foo"),q=!1});Y.observe(U,I);var J=function(){if(q)return;q=!0,U.classList.toggle("foo")};return function(K){var z=new MutationObserver(function(){z.disconnect(),K()});z.observe($,I),J()}}();else if(typeof setImmediate<"u")n3=function($){setImmediate($)};else if(typeof setTimeout<"u")n3=function($){setTimeout($,0)};else n3=MU1;var GS,HS,VS;GK0.exports=n3});var WK0=L((rv1,VK0)=>{function AU1($,I,q,U,Y){for(var J=0;J<Y;++J)q[J+U]=$[J+I],$[J+I]=void 0}function q7($){this._capacity=$,this._length=0,this._front=0}q7.prototype._willBeOverCapacity=function($){return this._capacity<$};q7.prototype._pushOne=function($){var I=this.length();this._checkCapacity(I+1);var q=this._front+I&this._capacity-1;this[q]=$,this._length=I+1};q7.prototype.push=function($,I,q){var U=this.length()+3;if(this._willBeOverCapacity(U)){this._pushOne($),this._pushOne(I),this._pushOne(q);return}var Y=this._front+U-3;this._checkCapacity(U);var J=this._capacity-1;this[Y+0&J]=$,this[Y+1&J]=I,this[Y+2&J]=q,this._length=U};q7.prototype.shift=function(){var $=this._front,I=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,I};q7.prototype.length=function(){return this._length};q7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};q7.prototype._resizeTo=function($){var I=this._capacity;this._capacity=$;var q=this._front,U=this._length,Y=q+U&I-1;AU1(this,0,this,I,Y)};VK0.exports=q7});var FK0=L((tv1,WS)=>{var LK0;try{throw Error()}catch($){LK0=$}var gU1=HK0(),ZK0=WK0(),NK0=n1();function b4(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new ZK0(16),this._normalQueue=new ZK0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=gU1}b4.prototype.setScheduler=function($){var I=this._schedule;return this._schedule=$,this._customScheduler=!0,I};b4.prototype.hasCustomScheduler=function(){return this._customScheduler};b4.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};b4.prototype.disableTrampolineIfNecessary=function(){if(NK0.hasDevTools)this._trampolineEnabled=!1};b4.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};b4.prototype.fatalError=function($,I){if(I)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};b4.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(q){throw Error(`No async scheduler available
`)},Lg=Dg.getNativePromise();if(Dg.isNode&&typeof MutationObserver>"u")Og=global.setImmediate,Fg=process.nextTick,u3=Dg.isRecentNode?function($){Og.call(global,$)}:function($){Fg.call(process,$)};else if(typeof Lg==="function"&&typeof Lg.resolve==="function")Ng=Lg.resolve(),u3=function($){Ng.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))u3=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")u3=function($){setImmediate($)};else if(typeof setTimeout<"u")u3=function($){setTimeout($,0)};else u3=II1;var Og,Fg,Ng;WK0.exports=u3});var ZK0=O((eR1,wK0)=>{function UI1($,I,U,Y,J){for(var Q=0;Q<J;++Q)U[Q+Y]=$[Q+I],$[Q+I]=void 0}function J7($){this._capacity=$,this._length=0,this._front=0}J7.prototype._willBeOverCapacity=function($){return this._capacity<$};J7.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};J7.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};J7.prototype.shift=function(){var $=this._front,I=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,I};J7.prototype.length=function(){return this._length};J7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};J7.prototype._resizeTo=function($){var I=this._capacity;this._capacity=$;var U=this._front,Y=this._length,J=U+Y&I-1;UI1(this,0,this,I,J)};wK0.exports=J7});var NK0=O(($C1,Mg)=>{var OK0;try{throw Error()}catch($){OK0=$}var YI1=VK0(),XK0=ZK0(),FK0=b1();function p4(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new XK0(16),this._normalQueue=new XK0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=YI1}p4.prototype.setScheduler=function($){var I=this._schedule;return this._schedule=$,this._customScheduler=!0,I};p4.prototype.hasCustomScheduler=function(){return this._customScheduler};p4.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};p4.prototype.disableTrampolineIfNecessary=function(){if(FK0.hasDevTools)this._trampolineEnabled=!1};p4.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};p4.prototype.fatalError=function($,I){if(I)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};p4.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 XK0($,I,q){this._lateQueue.push($,I,q),this._queueTick()}function DK0($,I,q){this._normalQueue.push($,I,q),this._queueTick()}function OK0($){this._normalQueue._pushOne($),this._queueTick()}if(!NK0.hasDevTools)b4.prototype.invokeLater=XK0,b4.prototype.invoke=DK0,b4.prototype.settlePromises=OK0;else b4.prototype.invokeLater=function($,I,q){if(this._trampolineEnabled)XK0.call(this,$,I,q);else this._schedule(function(){setTimeout(function(){$.call(I,q)},100)})},b4.prototype.invoke=function($,I,q){if(this._trampolineEnabled)DK0.call(this,$,I,q);else this._schedule(function(){$.call(I,q)})},b4.prototype.settlePromises=function($){if(this._trampolineEnabled)OK0.call(this,$);else this._schedule(function(){$._settlePromises()})};b4.prototype._drainQueue=function($){while($.length()>0){var I=$.shift();if(typeof I!=="function"){I._settlePromises();continue}var q=$.shift(),U=$.shift();I.call(q,U)}};b4.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};b4.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};b4.prototype._reset=function(){this._isTickUsed=!1};WS.exports=b4;WS.exports.firstLineError=LK0});var _5=L((av1,gK0)=>{var DS=f3(),PU1=DS.freeze,MK0=n1(),AK0=MK0.inherits,eU=MK0.notEnumerableProp;function $Y($,I){function q(U){if(!(this instanceof q))return new q(U);if(eU(this,"message",typeof U==="string"?U:I),eU(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return AK0(q,Error),q}var ZS,XS,TU1=$Y("Warning","warning"),jU1=$Y("CancellationError","cancellation error"),EU1=$Y("TimeoutError","timeout error"),NK=$Y("AggregateError","aggregate error");try{ZS=TypeError,XS=RangeError}catch($){ZS=$Y("TypeError","type error"),XS=$Y("RangeError","range error")}var ID="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(b3=0;b3<ID.length;++b3)if(typeof Array.prototype[ID[b3]]==="function")NK.prototype[ID[b3]]=Array.prototype[ID[b3]];var b3;DS.defineProperty(NK.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});NK.prototype.isOperational=!0;var qD=0;NK.prototype.toString=function(){var $=Array(qD*4+1).join(" "),I=`
`)}};function zK0($,I,U){this._lateQueue.push($,I,U),this._queueTick()}function LK0($,I,U){this._normalQueue.push($,I,U),this._queueTick()}function DK0($){this._normalQueue._pushOne($),this._queueTick()}if(!FK0.hasDevTools)p4.prototype.invokeLater=zK0,p4.prototype.invoke=LK0,p4.prototype.settlePromises=DK0;else p4.prototype.invokeLater=function($,I,U){if(this._trampolineEnabled)zK0.call(this,$,I,U);else this._schedule(function(){setTimeout(function(){$.call(I,U)},100)})},p4.prototype.invoke=function($,I,U){if(this._trampolineEnabled)LK0.call(this,$,I,U);else this._schedule(function(){$.call(I,U)})},p4.prototype.settlePromises=function($){if(this._trampolineEnabled)DK0.call(this,$);else this._schedule(function(){$._settlePromises()})};p4.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)}};p4.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};p4.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};p4.prototype._reset=function(){this._isTickUsed=!1};Mg.exports=p4;Mg.exports.firstLineError=OK0});var _5=O((IC1,PK0)=>{var Tg=k3(),JI1=Tg.freeze,MK0=b1(),AK0=MK0.inherits,tY=MK0.notEnumerableProp;function aY($,I){function U(Y){if(!(this instanceof U))return new U(Y);if(tY(this,"message",typeof Y==="string"?Y:I),tY(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return AK0(U,Error),U}var Ag,Pg,QI1=aY("Warning","warning"),KI1=aY("CancellationError","cancellation error"),qI1=aY("TimeoutError","timeout error"),zq=aY("AggregateError","aggregate error");try{Ag=TypeError,Pg=RangeError}catch($){Ag=aY("TypeError","type error"),Pg=aY("RangeError","range error")}var hz="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(f3=0;f3<hz.length;++f3)if(typeof Array.prototype[hz[f3]]==="function")zq.prototype[hz[f3]]=Array.prototype[hz[f3]];var f3;Tg.defineProperty(zq.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});zq.prototype.isOperational=!0;var xz=0;zq.prototype.toString=function(){var $=Array(xz*4+1).join(" "),I=`
`+$+`AggregateError of:
`;qD++,$=Array(qD*4+1).join(" ");for(var q=0;q<this.length;++q){var U=this[q]===this?"[Circular AggregateError]":this[q]+"",Y=U.split(`
`);for(var J=0;J<Y.length;++J)Y[J]=$+Y[J];U=Y.join(`
`),I+=U+`
`}return qD--,I};function LK($){if(!(this instanceof LK))return new LK($);if(eU(this,"name","OperationalError"),eU(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)eU(this,"message",$.message),eU(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}AK0(LK,Error);var i3=Error.__BluebirdErrorTypes__;if(!i3)i3=PU1({CancellationError:jU1,TimeoutError:EU1,OperationalError:LK,RejectionError:LK,AggregateError:NK}),DS.defineProperty(Error,"__BluebirdErrorTypes__",{value:i3,writable:!1,enumerable:!1,configurable:!1});gK0.exports={Error,TypeError:ZS,RangeError:XS,CancellationError:i3.CancellationError,OperationalError:i3.OperationalError,TimeoutError:i3.TimeoutError,AggregateError:i3.AggregateError,Warning:TU1}});var TK0=L((sv1,PK0)=>{PK0.exports=function($,I){var q=n1(),U=q.errorObj,Y=q.isObject;function J(H,W){if(Y(H)){if(H instanceof $)return H;var V=K(H);if(V===U){if(W)W._pushContext();var X=$.reject(V.e);if(W)W._popContext();return X}else if(typeof V==="function"){if(w(H)){var X=new $(I);return H._then(X._fulfill,X._reject,void 0,X,null),X}return G(H,V,W)}}return H}function Q(H){return H.then}function K(H){try{return Q(H)}catch(W){return U.e=W,U}}var z={}.hasOwnProperty;function w(H){try{return z.call(H,"_promise0")}catch(W){return!1}}function G(H,W,V){var X=new $(I),D=X;if(V)V._pushContext();if(X._captureStackTrace(),V)V._popContext();var O=!0,N=q.tryCatch(W).call(H,T,P);if(O=!1,X&&N===U)X._rejectCallback(N.e,!0,!0),X=null;function T(g){if(!X)return;X._resolveCallback(g),X=null}function P(g){if(!X)return;X._rejectCallback(g,O,!0),X=null}return D}return J}});var EK0=L((ev1,jK0)=>{jK0.exports=function($,I,q,U,Y){var J=n1(),Q=J.isArray;function K(w){switch(w){case-2:return[];case-3:return{}}}function z(w){var G=this._promise=new $(I);if(w instanceof $)G._propagateFrom(w,3);G._setOnCancel(this),this._values=w,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return J.inherits(z,Y),z.prototype.length=function(){return this._length},z.prototype.promise=function(){return this._promise},z.prototype._init=function w(G,H){var W=q(this._values,this._promise);if(W instanceof $){W=W._target();var V=W._bitField;if(this._values=W,(V&50397184)===0)return this._promise._setAsyncGuaranteed(),W._then(w,this._reject,void 0,this,H);else if((V&33554432)!==0)W=W._value();else if((V&16777216)!==0)return this._reject(W._reason());else return this._cancel()}if(W=J.asArray(W),W===null){var X=U("expecting an array or an iterable object but got "+J.classString(W)).reason();this._promise._rejectCallback(X,!1);return}if(W.length===0){if(H===-5)this._resolveEmptyArray();else this._resolve(K(H));return}this._iterate(W)},z.prototype._iterate=function(w){var G=this.getActualLength(w.length);this._length=G,this._values=this.shouldCopyValues()?Array(G):this._values;var H=this._promise,W=!1,V=null;for(var X=0;X<G;++X){var D=q(w[X],H);if(D instanceof $)D=D._target(),V=D._bitField;else V=null;if(W){if(V!==null)D.suppressUnhandledRejections()}else if(V!==null)if((V&50397184)===0)D._proxy(this,X),this._values[X]=D;else if((V&33554432)!==0)W=this._promiseFulfilled(D._value(),X);else if((V&16777216)!==0)W=this._promiseRejected(D._reason(),X);else W=this._promiseCancelled(X);else W=this._promiseFulfilled(D,X)}if(!W)H._setAsyncGuaranteed()},z.prototype._isResolved=function(){return this._values===null},z.prototype._resolve=function(w){this._values=null,this._promise._fulfill(w)},z.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},z.prototype._reject=function(w){this._values=null,this._promise._rejectCallback(w,!1)},z.prototype._promiseFulfilled=function(w,G){this._values[G]=w;var H=++this._totalResolved;if(H>=this._length)return this._resolve(this._values),!0;return!1},z.prototype._promiseCancelled=function(){return this._cancel(),!0},z.prototype._promiseRejected=function(w){return this._totalResolved++,this._reject(w),!0},z.prototype._resultCancelled=function(){if(this._isResolved())return;var w=this._values;if(this._cancel(),w instanceof $)w.cancel();else for(var G=0;G<w.length;++G)if(w[G]instanceof $)w[G].cancel()},z.prototype.shouldCopyValues=function(){return!0},z.prototype.getActualLength=function(w){return w},z}});var vK0=L(($R1,BK0)=>{BK0.exports=function($){var I=!1,q=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function U(){this._trace=new U.CapturedTrace(J())}U.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,q.push(this._trace)},U.prototype._popContext=function(){if(this._trace!==void 0){var Q=q.pop(),K=Q._promiseCreated;return Q._promiseCreated=null,K}return null};function Y(){if(I)return new U}function J(){var Q=q.length-1;if(Q>=0)return q[Q];return}return U.CapturedTrace=null,U.create=Y,U.deactivateLong Line truncated
`;xz++,$=Array(xz*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 xz--,I};function Xq($){if(!(this instanceof Xq))return new Xq($);if(tY(this,"name","OperationalError"),tY(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)tY(this,"message",$.message),tY(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}AK0(Xq,Error);var b3=Error.__BluebirdErrorTypes__;if(!b3)b3=JI1({CancellationError:KI1,TimeoutError:qI1,OperationalError:Xq,RejectionError:Xq,AggregateError:zq}),Tg.defineProperty(Error,"__BluebirdErrorTypes__",{value:b3,writable:!1,enumerable:!1,configurable:!1});PK0.exports={Error,TypeError:Ag,RangeError:Pg,CancellationError:b3.CancellationError,OperationalError:b3.OperationalError,TimeoutError:b3.TimeoutError,AggregateError:b3.AggregateError,Warning:QI1}});var EK0=O((UC1,TK0)=>{TK0.exports=function($,I){var U=b1(),Y=U.errorObj,J=U.isObject;function Q(V,w){if(J(V)){if(V instanceof $)return V;var Z=q(V);if(Z===Y){if(w)w._pushContext();var z=$.reject(Z.e);if(w)w._popContext();return z}else if(typeof Z==="function"){if(H(V)){var z=new $(I);return V._then(z._fulfill,z._reject,void 0,z,null),z}return W(V,Z,w)}}return V}function K(V){return V.then}function q(V){try{return K(V)}catch(w){return Y.e=w,Y}}var G={}.hasOwnProperty;function H(V){try{return G.call(V,"_promise0")}catch(w){return!1}}function W(V,w,Z){var z=new $(I),L=z;if(Z)Z._pushContext();if(z._captureStackTrace(),Z)Z._popContext();var D=!0,F=U.tryCatch(w).call(V,E,T);if(D=!1,z&&F===Y)z._rejectCallback(F.e,!0,!0),z=null;function E(A){if(!z)return;z._resolveCallback(A),z=null}function T(A){if(!z)return;z._rejectCallback(A,D,!0),z=null}return L}return Q}});var vK0=O((YC1,BK0)=>{BK0.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 w=U(this._values,this._promise);if(w instanceof $){w=w._target();var Z=w._bitField;if(this._values=w,(Z&50397184)===0)return this._promise._setAsyncGuaranteed(),w._then(H,this._reject,void 0,this,V);else if((Z&33554432)!==0)w=w._value();else if((Z&16777216)!==0)return this._reject(w._reason());else return this._cancel()}if(w=Q.asArray(w),w===null){var z=Y("expecting an array or an iterable object but got "+Q.classString(w)).reason();this._promise._rejectCallback(z,!1);return}if(w.length===0){if(V===-5)this._resolveEmptyArray();else this._resolve(q(V));return}this._iterate(w)},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,w=!1,Z=null;for(var z=0;z<W;++z){var L=U(H[z],V);if(L instanceof $)L=L._target(),Z=L._bitField;else Z=null;if(w){if(Z!==null)L.suppressUnhandledRejections()}else if(Z!==null)if((Z&50397184)===0)L._proxy(this,z),this._values[z]=L;else if((Z&33554432)!==0)w=this._promiseFulfilled(L._value(),z);else if((Z&16777216)!==0)w=this._promiseRejected(L._reason(),z);else w=this._promiseCancelled(z);else w=this._promiseFulfilled(L,z)}if(!w)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 CK0=O((JC1,RK0)=>{RK0.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(!g0.longStackTraces&&h$()){var r=$.prototype._captureStackTrace,F=$.prototype._attachExtraTrace;g0.longStackTraces=!0,g=function(){if(U.haveItemsQueued()&&!g0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
`);if(!E0.longStackTraces&&u$()){var a=$.prototype._captureStackTrace,N=$.prototype._attachExtraTrace;E0.longStackTraces=!0,A=function(){if(Y.haveItemsQueued()&&!E0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
See http://goo.gl/MqrFmX
`);$.prototype._captureStackTrace=r,$.prototype._attachExtraTrace=F,I.deactivateLongStackTraces(),U.enableTrampoline(),g0.longStackTraces=!1},$.prototype._captureStackTrace=K0,$.prototype._attachExtraTrace=G0,I.activateLongStackTraces(),U.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return g0.longStackTraces&&h$()};var B=function(){try{if(typeof CustomEvent==="function"){var r=new CustomEvent("CustomEvent");return J.global.dispatchEvent(r),function(F,M){var v=new CustomEvent(F.toLowerCase(),{detail:M,cancelable:!0});return!J.global.dispatchEvent(v)}}else if(typeof Event==="function"){var r=new Event("CustomEvent");return J.global.dispatchEvent(r),function(M,v){var y=new Event(M.toLowerCase(),{cancelable:!0});return y.detail=v,!J.global.dispatchEvent(y)}}else{var r=document.createEvent("CustomEvent");return r.initCustomEvent("testingtheevent",!1,!0,{}),J.global.dispatchEvent(r),function(M,v){var y=document.createEvent("CustomEvent");return y.initCustomEvent(M.toLowerCase(),!1,!0,v),!J.global.dispatchEvent(y)}}}catch(F){}return function(){return!1}}(),k=function(){if(J.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!J.global)return function(){return!1};return function(r){var F="on"+r.toLowerCase(),M=J.global[F];if(!M)return!1;return M.apply(J.global,[].slice.call(arguments,1)),!0}}}();function h(r,F){return{promise:F}}var n={promiseCreated:h,promiseFulfilled:h,promiseRejected:h,promiseResolved:h,promiseCancelled:h,promiseChained:function(r,F,M){return{promise:F,child:M}},warning:function(r,F){return{warning:F}},unhandledRejection:function(r,F,M){return{reason:F,promise:M}},rejectionHandled:h},S=function(r){var F=!1;try{F=k.apply(null,arguments)}catch(v){U.throwLater(v),F=!0}var M=!1;try{M=B(r,n[r].apply(null,arguments))}catch(v){U.throwLater(v),M=!0}return M||F};$.config=function(r){if(r=Object(r),"longStackTraces"in r){if(r.longStackTraces)$.longStackTraces();else if(!r.longStackTraces&&$.hasLongStackTraces())g()}if("warnings"in r){var F=r.warnings;if(g0.warnings=!!F,P=g0.warnings,J.isObject(F)){if("wForgottenReturn"in F)P=!!F.wForgottenReturn}}if("cancellation"in r&&r.cancellation&&!g0.cancellation){if(U.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=J0,$.prototype._propagateFrom=j,$.prototype._onCancel=f,$.prototype._setOnCancel=b,$.prototype._attachCancellationCallback=C,$.prototype._execute=p,d=j,g0.cancellation=!0}if("monitoring"in r){if(r.monitoring&&!g0.monitoring)g0.monitoring=!0,$.prototype._fireEvent=S;else if(!r.monitoring&&g0.monitoring)g0.monitoring=!1,$.prototype._fireEvent=t}return $};function t(){return!1}$.prototype._fireEvent=t,$.prototype._execute=function(r,F,M){try{r(F,M)}catch(v){return v}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(r){},$.prototype._attachCancellationCallback=function(r){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(r,F){};function p(r,F,M){var v=this;try{r(F,M,function(y){if(typeof y!=="function")throw TypeError("onCancel must be a function, got: "+J.toString(y));v._attachCancellationCallback(y)})}catch(y){return y}}function C(r){if(!this._isCancellable())return this;var F=this._onCancel();if(F!==void 0)if(J.isArray(F))F.push(r);else this._setOnCancel([F,r]);else this._setOnCancel(r)}function f(){return this._onCancelField}function b(r){this._onCancelField=r}function J0(){this._cancellationParent=void 0,this._onCancelField=void 0}function j(r,F){if((F&1)!==0){this._cancellationParent=r;var M=r._branchesRemainingToCancel;if(M===void 0)M=0;r._branchesRemainingToCancel=M+1}if((F&2)!==0&&r._isBound())this._setBoundTo(r._boundTo)}function u(r,F){if((F&2)!==0&&r._isBound())this._setBoundTo(r._boundTo)}var d=u;function a(){var r=this._boundTo;if(r!==void 0){if(r instanceof $)if(r.isFulfilled())return r.value();else return}return r}function K0(){this._trace=new a6(this._peekContext())}function G0(r,F){if(Q(r)){var M=this._trace;if(M!==void 0){if(F)M=M._parent}if(M!==void 0)M.attachExtraTrace(r);else if(!r.__stackCleaned__){var v=Y4(r);J.notEnumerableProp(r,"stack",v.message+`
`+v.stack.join(`
`)),J.notEnumerableProp(r,"__stackCleaned__",!0)}}}function M0(r,F,M,v,y){if(r===void 0&&F!==null&&P){if(y!==void 0&&y._returnedNonUndefined())return;if((v._bitField&65535)===0)return;if(M)M=M+" ";var s="",c="";if(F._trace){var e=F._trace.stack.split(`
`),U0=Q1(e);for(var w0=U0.length-1;w0>=0;--w0){var T0=U0[w0];if(!G.test(T0)){var x0=T0.match(H);if(x0)s="at "+x0[1]+":"+x0[2]+":"+x0[3]+" ";break}}if(U0.length>0){var y0=U0[0];for(var w0=0;w0<e.length;++w0)if(e[w0]===y0){if(w0>0)c=`
`+e[w0-1];break}}}var q1="a promise was created in a "+M+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+c;v._warn(q1,!0,F)}}function v0(r,F){var M=r+" is deprecated and will be removed in a future version.";if(F)M+=" Use "+F+" instead.";return v1(M)}function v1(r,F,M){if(!g0.warnings)return;var v=new Y(r),y;if(F)M._attachExtraTrace(v);else if(g0.longStackTraces&&(y=$._peekContext()))y.attachExtraTrace(v);else{var s=Y4(v);v.stack=s.message+`
`);$.prototype._captureStackTrace=a,$.prototype._attachExtraTrace=N,I.deactivateLongStackTraces(),Y.enableTrampoline(),E0.longStackTraces=!1},$.prototype._captureStackTrace=K0,$.prototype._attachExtraTrace=W0,I.activateLongStackTraces(),Y.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return E0.longStackTraces&&u$()};var R=function(){try{if(typeof CustomEvent==="function"){var a=new CustomEvent("CustomEvent");return Q.global.dispatchEvent(a),function(N,M){var j=new CustomEvent(N.toLowerCase(),{detail:M,cancelable:!0});return!Q.global.dispatchEvent(j)}}else if(typeof Event==="function"){var a=new Event("CustomEvent");return Q.global.dispatchEvent(a),function(M,j){var x=new Event(M.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(M,j){var x=document.createEvent("CustomEvent");return x.initCustomEvent(M.toLowerCase(),!1,!0,j),!Q.global.dispatchEvent(x)}}}catch(N){}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 N="on"+a.toLowerCase(),M=Q.global[N];if(!M)return!1;return M.apply(Q.global,[].slice.call(arguments,1)),!0}}}();function g(a,N){return{promise:N}}var b={promiseCreated:g,promiseFulfilled:g,promiseRejected:g,promiseResolved:g,promiseCancelled:g,promiseChained:function(a,N,M){return{promise:N,child:M}},warning:function(a,N){return{warning:N}},unhandledRejection:function(a,N,M){return{reason:N,promise:M}},rejectionHandled:g},C=function(a){var N=!1;try{N=u.apply(null,arguments)}catch(j){Y.throwLater(j),N=!0}var M=!1;try{M=R(a,b[a].apply(null,arguments))}catch(j){Y.throwLater(j),M=!0}return M||N};$.config=function(a){if(a=Object(a),"longStackTraces"in a){if(a.longStackTraces)$.longStackTraces();else if(!a.longStackTraces&&$.hasLongStackTraces())A()}if("warnings"in a){var N=a.warnings;if(E0.warnings=!!N,T=E0.warnings,Q.isObject(N)){if("wForgottenReturn"in N)T=!!N.wForgottenReturn}}if("cancellation"in a&&a.cancellation&&!E0.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=n,d=B,E0.cancellation=!0}if("monitoring"in a){if(a.monitoring&&!E0.monitoring)E0.monitoring=!0,$.prototype._fireEvent=C;else if(!a.monitoring&&E0.monitoring)E0.monitoring=!1,$.prototype._fireEvent=p}return $};function p(){return!1}$.prototype._fireEvent=p,$.prototype._execute=function(a,N,M){try{a(N,M)}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,N){};function n(a,N,M){var j=this;try{a(N,M,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 N=this._onCancel();if(N!==void 0)if(Q.isArray(N))N.push(a);else this._setOnCancel([N,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,N){if((N&1)!==0){this._cancellationParent=a;var M=a._branchesRemainingToCancel;if(M===void 0)M=0;a._branchesRemainingToCancel=M+1}if((N&2)!==0&&a._isBound())this._setBoundTo(a._boundTo)}function k(a,N){if((N&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,N){if(K(a)){var M=this._trace;if(M!==void 0){if(N)M=M._parent}if(M!==void 0)M.attachExtraTrace(a);else if(!a.__stackCleaned__){var j=K4(a);Q.notEnumerableProp(a,"stack",j.message+`
`+j.stack.join(`
`)),Q.notEnumerableProp(a,"__stackCleaned__",!0)}}}function A0(a,N,M,j,x){if(a===void 0&&N!==null&&T){if(x!==void 0&&x._returnedNonUndefined())return;if((j._bitField&65535)===0)return;if(M)M=M+" ";var s="",m="";if(N._trace){var e=N._trace.stack.split(`
`),J0=g0(e);for(var H0=J0.length-1;H0>=0;--H0){var C0=J0[H0];if(!W.test(C0)){var b0=C0.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 Q1="a promise was created in a "+M+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+m;j._warn(Q1,!0,N)}}function v0(a,N){var M=a+" is deprecated and will be removed in a future version.";if(N)M+=" Use "+N+" instead.";return L1(M)}function L1(a,N,M){if(!E0.warnings)return;var j=new J(a),x;if(N)M._attachExtraTrace(j);else if(E0.longStackTraces&&(x=$._peekContext()))x.attachExtraTrace(j);else{var s=K4(j);j.stack=s.message+`
`+s.stack.join(`
`)}if(!S("warning",v))v4(v,"",!0)}function m0(r,F){for(var M=0;M<F.length-1;++M)F[M].push("From previous event:"),F[M]=F[M].join(`
`);if(M<F.length)F[M]=F[M].join(`
`);return r+`
`+F.join(`
`)}function N1(r){for(var F=0;F<r.length;++F)if(r[F].length===0||F+1<r.length&&r[F][0]===r[F+1][0])r.splice(F,1),F--}function F1(r){var F=r[0];for(var M=1;M<r.length;++M){var v=r[M],y=F.length-1,s=F[y],c=-1;for(var e=v.length-1;e>=0;--e)if(v[e]===s){c=e;break}for(var e=c;e>=0;--e){var U0=v[e];if(F[y]===U0)F.pop(),y--;else break}F=v}}function Q1(r){var F=[];for(var M=0;M<r.length;++M){var v=r[M],y=v===" (No stack trace)"||W.test(v),s=y&&G$(v);if(y&&!s){if(X&&v.charAt(0)!==" ")v=" "+v;F.push(v)}}return F}function C1(r){var F=r.stack.replace(/\s+$/g,"").split(`
`);for(var M=0;M<F.length;++M){var v=F[M];if(v===" (No stack trace)"||W.test(v))break}if(M>0&&r.name!="SyntaxError")F=F.slice(M);return F}function Y4(r){var F=r.stack,M=r.toString();return F=typeof F==="string"&&F.length>0?C1(r):[" (No stack trace)"],{message:M,stack:r.name=="SyntaxError"?F:Q1(F)}}function v4(r,F,M){if(typeof console<"u"){var v;if(J.isObject(r)){var y=r.stack;v=F+V(y,r)}else v=F+String(r);if(typeof D==="function")D(v,M);else if(typeof console.log==="function"||typeof console.log==="object")console.log(v)}}function w$(r,F,M,v){var y=!1;try{if(typeof F==="function")if(y=!0,r==="rejectionHandled")F(v);else F(M,v)}catch(s){U.throwLater(s)}if(r==="unhandledRejection"){if(!S(r,M,v)&&!y)v4(M,"Unhandled rejection ")}else S(r,v)}function _$(r){var F;if(typeof r==="function")F="[function "+(r.name||"anonymous")+"]";else{F=r&&typeof r.toString==="function"?r.toString():J.toString(r);var M=/\[object [a-zA-Z0-9$_]+\]/;if(M.test(F))try{var v=JSON.stringify(r);F=v}catch(y){}if(F.length===0)F="(empty array)"}return"(<"+p8(F)+">, no stack trace)"}function p8(r){var F=41;if(r.length<F)return r;return r.substr(0,F-3)+"..."}function h$(){return typeof p5==="function"}var G$=function(){return!1},c8=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function t6(r){var F=r.match(c8);if(F)return{fileName:F[1],line:parseInt(F[2],10)}}function D7(r,F){if(!h$())return;var M=r.stack.split(`
`),v=F.stack.split(`
`),y=-1,s=-1,c,e;for(var U0=0;U0<M.length;++U0){var w0=t6(M[U0]);if(w0){c=w0.fileName,y=w0.line;break}}for(var U0=0;U0<v.length;++U0){var w0=t6(v[U0]);if(w0){e=w0.fileName,s=w0.line;break}}if(y<0||s<0||!c||!e||c!==e||y>=s)return;G$=function(T0){if(w.test(T0))return!0;var x0=t6(T0);if(x0){if(x0.fileName===c&&(y<=x0.line&&x0.line<=s))return!0}return!1}}function a6(r){this._parent=r,this._promisesCreated=0;var F=this._length=1+(r===void 0?0:r._length);if(p5(this,a6),F>32)this.uncycle()}J.inherits(a6,Error),I.CapturedTrace=a6,a6.prototype.uncycle=function(){var r=this._length;if(r<2)return;var F=[],M={};for(var v=0,y=this;y!==void 0;++v)F.push(y),y=y._parent;r=this._length=v;for(var v=r-1;v>=0;--v){var s=F[v].stack;if(M[s]===void 0)M[s]=v}for(var v=0;v<r;++v){var c=F[v].stack,e=M[c];if(e!==void 0&&e!==v){if(e>0)F[e-1]._parent=void 0,F[e-1]._length=1;F[v]._parent=void 0,F[v]._length=1;var U0=v>0?F[v-1]:this;if(e<r-1)U0._parent=F[e+1],U0._parent.uncycle(),U0._length=U0._parent._length+1;else U0._parent=void 0,U0._length=1;var w0=U0._length+1;for(var T0=v-2;T0>=0;--T0)F[T0]._length=w0,w0++;return}}},a6.prototype.attachExtraTrace=function(r){if(r.__stackCleaned__)return;this.uncycle();var F=Y4(r),M=F.message,v=[F.stack],y=this;while(y!==void 0)v.push(Q1(y.stack.split(`
`))),y=y._parent;F1(v),N1(v),J.notEnumerableProp(r,"stack",m0(M,v)),J.notEnumerableProp(r,"__stackCleaned__",!0)};var p5=function(){var F=/^\s*at\s*/,M=function(c,e){if(typeof c==="string")return c;if(e.name!==void 0&&e.message!==void 0)return e.toString();return _$(e)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,W=F,V=M;var v=Error.captureStackTrace;return G$=function(c){return w.test(c)},function(c,e){Error.stackTraceLimit+=6,v(c,e),Error.stackTraceLimit-=6}}var y=Error();if(typeof y.stack==="string"&&y.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return W=/@/,V=M,X=!0,function(e){e.stack=Error().stack};var s;try{throw Error()}catch(c){s="stack"in c}if(!("stack"in y)&&s&&typeof Error.stackTraceLimit==="number")return W=F,V=M,function(e){Error.stackTraceLimit+=6;try{throw Error()}catch(U0){e.stack=U0.stack}Error.stackTraceLimit-=6};return V=function(c,e){if(typeof c==="string")return c;if((typeof e==="object"||typeof e==="function")&&e.name!==void 0&&e.message!==void 0)return e.toString();return _$(e)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(D=function(r){console.warn(r)},J.isNode&&process.stderr.isTTY)D=function(r,F){var M=F?"\x1B[33m":"\x1B[31m";console.warn(M+r+`\x1B[0m
`)};else if(!J.isNode&&typeof Error().stack==="string")D=function(r,F){console.warn("%c"+r,F?"color: darkorange":"color: red")}}var g0={warnings:N,longStackTraces:!1,cancellation:!1,monitoring:!1};if(T)$.longStackTraces();return{longStackTraces:function(){return g0.longStackTraces},warnings:function(){return g0.warnings},cancellation:function(){return g0.cancellation},monitoring:function(){return g0.monitoring},propagateFromFunction:function(){return d},boundValueFunction:function(){return a},checkForgottenReturns:M0,setBounds:D7,warn:v1,deprecated:v0,CapturedTrace:a6,fireDomEvent:B,fireGlobalEvent:k}}});var hK0=L((qR1,_K0)=>{_K0.exports=function($,I){var q=n1(),U=$.CancellationError,Y=q.errorObj;function J(H,W,V){this.promise=H,this.type=W,this.handler=V,this.called=!1,this.cancelPromise=null}J.prototype.isFinallyHandler=function(){return this.type===0};function Q(H){this.finallyHandler=H}Q.prototype._resultCancelled=function(){K(this.finallyHandler)};function K(H,W){if(H.cancelPromise!=null){if(arguments.length>1)H.cancelPromise._reject(W);else H.cancelPromise._cancel();return H.cancelPromise=null,!0}return!1}function z(){return G.call(this,this.promise._target()._settledValue())}function w(H){if(K(this,H))return;return Y.e=H,Y}function G(H){var W=this.promise,V=this.handler;if(!this.called){this.called=!0;var X=this.isFinallyHandler()?V.call(W._boundValue()):V.call(W._boundValue(),H);if(X!==void 0){W._setReturnedNonUndefined();var D=I(X,W);if(D instanceof $){if(this.cancelPromise!=null){if(D._isCancelled()){var O=new U("late cancellation observer");return W._attachExtraTrace(O),Y.e=O,Y}else if(D.isPending())D._attachCancellationCallback(new Q(this))}return D._then(z,w,void 0,this,void 0)}}}if(W.isRejected())return K(this),Y.e=H,Y;else return K(this),H}return $.prototype._passThrough=function(H,W,V,X){if(typeof H!=="function")return this.then();return this._then(V,X,void 0,new J(this,W,H),void 0)},$.prototype.lastly=$.prototype.finally=function(H){return this._passThrough(H,0,G,G)},$.prototype.tap=function(H){return this._passThrough(H,1,G)},J}});var yK0=L((UR1,SK0)=>{SK0.exports=function($){var I=n1(),q=f3().keys,U=I.tryCatch,Y=I.errorObj;function J(Q,K,z){return function(w){var G=z._boundValue();$:for(var H=0;H<Q.length;++H){var W=Q[H];if(W===Error||W!=null&&W.prototype instanceof Error){if(w instanceof W)return U(K).call(G,w)}else if(typeof W==="function"){var V=U(W).call(G,w);if(V===Y)return V;else if(V)return U(K).call(G,w)}else if(I.isObject(w)){var X=q(W);for(var D=0;D<X.length;++D){var O=X[D];if(W[O]!=w[O])continue $}return U(K).call(G,w)}}return $}}return J}});var OS=L((YR1,kK0)=>{var uK0=n1(),BU1=uK0.maybeWrapAsError,vU1=_5(),RU1=vU1.OperationalError,xK0=f3();function CU1($){return $ instanceof Error&&xK0.getPrototypeOf($)===Error.prototype}var _U1=/^(?:name|message|stack|cause)$/;function hU1($){var I;if(CU1($)){I=new RU1($),I.name=$.name,I.message=$.message,I.stack=$.stack;var q=xK0.keys($);for(var U=0;U<q.length;++U){var Y=q[U];if(!_U1.test(Y))I[Y]=$[Y]}return I}return uK0.markAsOriginatingFromRejection($),$}function SU1($,I){return function(q,U){if($===null)return;if(q){var Y=hU1(BU1(q));$._attachExtraTrace(Y),$._reject(Y)}else if(!I)$._fulfill(U);else{var J=arguments.length,Q=Array(Math.max(J-1,0));for(var K=1;K<J;++K)Q[K-1]=arguments[K];$._fulfill(Q)}$=null}}kK0.exports=SU1});var nK0=L((JR1,fK0)=>{fK0.exports=function($,I,q,U,Y){var J=n1(),Q=J.tryCatch;$.method=function(K){if(typeof K!=="function")throw new $.TypeError("expecting a function but got "+J.classString(K));return function(){var z=new $(I);z._captureStackTrace(),z._pushContext();var w=Q(K).apply(this,arguments),G=z._popContext();return Y.checkForgottenReturns(w,G,"Promise.method",z),z._resolveFromSyncValue(w),z}},$.attempt=$.try=function(K){if(typeof K!=="function")return U("expecting a function but got "+J.classString(K));var z=new $(I);z._captureStackTrace(),z._pushContext();var w;if(arguments.length>1){Y.deprecated("calling Promise.try with more than 1 argument");var G=arguments[1],H=arguments[2];w=J.isArray(G)?Q(K).apply(H,G):Q(K).call(H,G)}else w=Q(K)();var W=z._popContext();return Y.checkForgottenReturns(w,W,"Promise.try",z),z._resolveFromSyncValue(w),z},$.prototype._resolveFromSyncValue=function(K){if(K===J.errorObj)this._rejectCallback(K.e,!1);else this._resolveCallback(K,!0)}}});var iK0=L((QR1,bK0)=>{bK0.exports=function($,I,q,U){var Y=!1,J=function(w,G){this._reject(G)},Q=function(w,G){G.promiseRejectionQueued=!0,G.bindingPromise._then(J,J,null,this,w)},K=function(w,G){if((this._bitField&50397184)===0)this._resolveCallback(G.target)},z=function(w,G){if(!G.promiseRejectionQueued)this._reject(w)};$.prototype.bind=function(w){if(!Y)Y=!0,$.prototype._propagateFrom=U.propagateFromFunction(),$.prototype._boundValue=U.boundValueFunction();var G=q(w),H=new $(I);H._propagateFrom(this,1);var W=this._target();if(H._setBoundTo(G),G instanceof $){var V={promiseRejectionQueued:!1,promise:H,target:W,bindingPromise:G};W._then(I,Q,voi Line truncated
`)}if(!C("warning",j))j4(j,"",!0)}function f0(a,N){for(var M=0;M<N.length-1;++M)N[M].push("From previous event:"),N[M]=N[M].join(`
`);if(M<N.length)N[M]=N[M].join(`
`);return a+`
`+N.join(`
`)}function H1(a){for(var N=0;N<a.length;++N)if(a[N].length===0||N+1<a.length&&a[N][0]===a[N+1][0])a.splice(N,1),N--}function F0(a){var N=a[0];for(var M=1;M<a.length;++M){var j=a[M],x=N.length-1,s=N[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(N[x]===J0)N.pop(),x--;else break}N=j}}function g0(a){var N=[];for(var M=0;M<a.length;++M){var j=a[M],x=j===" (No stack trace)"||w.test(j),s=x&&w$(j);if(x&&!s){if(z&&j.charAt(0)!==" ")j=" "+j;N.push(j)}}return N}function m0(a){var N=a.stack.replace(/\s+$/g,"").split(`
`);for(var M=0;M<N.length;++M){var j=N[M];if(j===" (No stack trace)"||w.test(j))break}if(M>0&&a.name!="SyntaxError")N=N.slice(M);return N}function K4(a){var N=a.stack,M=a.toString();return N=typeof N==="string"&&N.length>0?m0(a):[" (No stack trace)"],{message:M,stack:a.name=="SyntaxError"?N:g0(N)}}function j4(a,N,M){if(typeof console<"u"){var j;if(Q.isObject(a)){var x=a.stack;j=N+Z(x,a)}else j=N+String(a);if(typeof L==="function")L(j,M);else if(typeof console.log==="function"||typeof console.log==="object")console.log(j)}}function V$(a,N,M,j){var x=!1;try{if(typeof N==="function")if(x=!0,a==="rejectionHandled")N(j);else N(M,j)}catch(s){Y.throwLater(s)}if(a==="unhandledRejection"){if(!C(a,M,j)&&!x)j4(M,"Unhandled rejection ")}else C(a,j)}function k$(a){var N;if(typeof a==="function")N="[function "+(a.name||"anonymous")+"]";else{N=a&&typeof a.toString==="function"?a.toString():Q.toString(a);var M=/\[object [a-zA-Z0-9$_]+\]/;if(M.test(N))try{var j=JSON.stringify(a);N=j}catch(x){}if(N.length===0)N="(empty array)"}return"(<"+m8(N)+">, no stack trace)"}function m8(a){var N=41;if(a.length<N)return a;return a.substr(0,N-3)+"..."}function u$(){return typeof m5==="function"}var w$=function(){return!1},l8=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function a6(a){var N=a.match(l8);if(N)return{fileName:N[1],line:parseInt(N[2],10)}}function O7(a,N){if(!u$())return;var M=a.stack.split(`
`),j=N.stack.split(`
`),x=-1,s=-1,m,e;for(var J0=0;J0<M.length;++J0){var H0=a6(M[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;w$=function(C0){if(H.test(C0))return!0;var b0=a6(C0);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 N=this._length=1+(a===void 0?0:a._length);if(m5(this,s6),N>32)this.uncycle()}Q.inherits(s6,Error),I.CapturedTrace=s6,s6.prototype.uncycle=function(){var a=this._length;if(a<2)return;var N=[],M={};for(var j=0,x=this;x!==void 0;++j)N.push(x),x=x._parent;a=this._length=j;for(var j=a-1;j>=0;--j){var s=N[j].stack;if(M[s]===void 0)M[s]=j}for(var j=0;j<a;++j){var m=N[j].stack,e=M[m];if(e!==void 0&&e!==j){if(e>0)N[e-1]._parent=void 0,N[e-1]._length=1;N[j]._parent=void 0,N[j]._length=1;var J0=j>0?N[j-1]:this;if(e<a-1)J0._parent=N[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 C0=j-2;C0>=0;--C0)N[C0]._length=H0,H0++;return}}},s6.prototype.attachExtraTrace=function(a){if(a.__stackCleaned__)return;this.uncycle();var N=K4(a),M=N.message,j=[N.stack],x=this;while(x!==void 0)j.push(g0(x.stack.split(`
`))),x=x._parent;F0(j),H1(j),Q.notEnumerableProp(a,"stack",f0(M,j)),Q.notEnumerableProp(a,"__stackCleaned__",!0)};var m5=function(){var N=/^\s*at\s*/,M=function(m,e){if(typeof m==="string")return m;if(e.name!==void 0&&e.message!==void 0)return e.toString();return k$(e)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,w=N,Z=M;var j=Error.captureStackTrace;return w$=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 w=/@/,Z=M,z=!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 w=N,Z=M,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 k$(e)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(L=function(a){console.warn(a)},Q.isNode&&process.stderr.isTTY)L=function(a,N){var M=N?"\x1B[33m":"\x1B[31m";console.warn(M+a+`\x1B[0m
`)};else if(!Q.isNode&&typeof Error().stack==="string")L=function(a,N){console.warn("%c"+a,N?"color: darkorange":"color: red")}}var E0={warnings:F,longStackTraces:!1,cancellation:!1,monitoring:!1};if(E)$.longStackTraces();return{longStackTraces:function(){return E0.longStackTraces},warnings:function(){return E0.warnings},cancellation:function(){return E0.cancellation},monitoring:function(){return E0.monitoring},propagateFromFunction:function(){return d},boundValueFunction:function(){return t},checkForgottenReturns:A0,setBounds:O7,warn:L1,deprecated:v0,CapturedTrace:s6,fireDomEvent:R,fireGlobalEvent:u}}});var gK0=O((KC1,SK0)=>{SK0.exports=function($,I){var U=b1(),Y=$.CancellationError,J=U.errorObj;function Q(V,w,Z){this.promise=V,this.type=w,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,w){if(V.cancelPromise!=null){if(arguments.length>1)V.cancelPromise._reject(w);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 w=this.promise,Z=this.handler;if(!this.called){this.called=!0;var z=this.isFinallyHandler()?Z.call(w._boundValue()):Z.call(w._boundValue(),V);if(z!==void 0){w._setReturnedNonUndefined();var L=I(z,w);if(L instanceof $){if(this.cancelPromise!=null){if(L._isCancelled()){var D=new Y("late cancellation observer");return w._attachExtraTrace(D),J.e=D,J}else if(L.isPending())L._attachCancellationCallback(new K(this))}return L._then(G,H,void 0,this,void 0)}}}if(w.isRejected())return q(this),J.e=V,J;else return q(this),V}return $.prototype._passThrough=function(V,w,Z,z){if(typeof V!=="function")return this.then();return this._then(Z,z,void 0,new Q(this,w,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 hK0=O((qC1,yK0)=>{yK0.exports=function($){var I=b1(),U=k3().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 w=K[V];if(w===Error||w!=null&&w.prototype instanceof Error){if(H instanceof w)return Y(q).call(W,H)}else if(typeof w==="function"){var Z=Y(w).call(W,H);if(Z===J)return Z;else if(Z)return Y(q).call(W,H)}else if(I.isObject(H)){var z=U(w);for(var L=0;L<z.length;++L){var D=z[L];if(w[D]!=H[D])continue $}return Y(q).call(W,H)}}return $}}return Q}});var Eg=O((GC1,uK0)=>{var xK0=b1(),GI1=xK0.maybeWrapAsError,HI1=_5(),WI1=HI1.OperationalError,kK0=k3();function VI1($){return $ instanceof Error&&kK0.getPrototypeOf($)===Error.prototype}var wI1=/^(?:name|message|stack|cause)$/;function ZI1($){var I;if(VI1($)){I=new WI1($),I.name=$.name,I.message=$.message,I.stack=$.stack;var U=kK0.keys($);for(var Y=0;Y<U.length;++Y){var J=U[Y];if(!wI1.test(J))I[J]=$[J]}return I}return xK0.markAsOriginatingFromRejection($),$}function XI1($,I){return function(U,Y){if($===null)return;if(U){var J=ZI1(GI1(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}}uK0.exports=XI1});var bK0=O((HC1,fK0)=>{fK0.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 w=G._popContext();return J.checkForgottenReturns(H,w,"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 nK0=O((WC1,iK0)=>{iK0.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 w=this._target();if(V._setBoundTo(W),W instanceof $){var Z={promiseRejectionQueued:!1,promise:V,target:w,bindingPromise:W};w._then(I,K,voi Line truncated
See http://goo.gl/MqrFmX
`);return this._settledValue()},U=I.prototype.error=I.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
`);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()},Y=I.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},J=I.prototype.isRejected=function(){return(this._bitField&16777216)!==0},Q=I.prototype.isPending=function(){return(this._bitField&50397184)===0},K=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 Q.call(this._target())},$.prototype.isRejected=function(){return J.call(this._target())},$.prototype.isFulfilled=function(){return Y.call(this._target())},$.prototype.isResolved=function(){return K.call(this._target())},$.prototype.value=function(){return q.call(this._target())},$.prototype.reason=function(){var z=this._target();return z._unsetRejectionIsUnhandled(),U.call(z)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=I}});var tK0=L((GR1,rK0)=>{rK0.exports=function($,I,q,U,Y,J){var Q=n1(),K=Q.canEvaluate,z=Q.tryCatch,w=Q.errorObj,G;if(K){var H=function(T){return Function("value","holder",`
`);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 tK0=O((XC1,rK0)=>{rK0.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,T))},W=function(T){return Function("promise","holder",`
`.replace(/Index/g,E))},w=function(E){return Function("promise","holder",`
'use strict';
holder.pIndex = promise;
`.replace(/Index/g,T))},V=function(T){var P=Array(T);for(var g=0;g<P.length;++g)P[g]="this.p"+(g+1);var B=P.join(" = ")+" = null;",k=`var promise;
`+P.map(function(t){return`
promise = `+t+`;
`.replace(/Index/g,E))},Z=function(E){var T=Array(E);for(var A=0;A<T.length;++A)T[A]="this.p"+(A+1);var R=T.join(" = ")+" = null;",u=`var promise;
`+T.map(function(p){return`
promise = `+p+`;
if (promise instanceof Promise) {
promise.cancel();
}
`}).join(`
`),h=P.join(", "),n="Holder$"+T,S=`return function(tryCatch, errorObj, Promise, async) {
`),g=T.join(", "),b="Holder$"+E,C=`return function(tryCatch, errorObj, Promise, async) {
'use strict';
function [TheName](fn) {
[TheProperties]
@@ -134,7 +129,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof h4))r
return [TheName];
}(tryCatch, errorObj, Promise, async);
`;return S=S.replace(/\[TheName\]/g,n).replace(/\[TheTotal\]/g,T).replace(/\[ThePassedArguments\]/g,h).replace(/\[TheProperties\]/g,B).replace(/\[CancellationCode\]/g,k),Function("tryCatch","errorObj","Promise","async",S)(z,w,$,Y)},X=[],D=[],O=[];for(var N=0;N<8;++N)X.push(V(N+1)),D.push(H(N+1)),O.push(W(N+1));G=function(T){this._reject(T)}}$.join=function(){var T=arguments.length-1,P;if(T>0&&typeof arguments[T]==="function"){if(P=arguments[T],T<=8&&K){var b=new $(U);b._captureStackTrace();var g=X[T-1],B=new g(P),k=D;for(var h=0;h<T;++h){var n=q(arguments[h],b);if(n instanceof $){n=n._target();var S=n._bitField;if((S&50397184)===0)n._then(k[h],G,void 0,b,B),O[h](n,B),B.asyncNeeded=!1;else if((S&33554432)!==0)k[h].call(b,n._value(),B);else if((S&16777216)!==0)b._reject(n._reason());else b._cancel()}else k[h].call(b,n,B)}if(!b._isFateSealed()){if(B.asyncNeeded){var t=J();if(t!==null)B.fn=Q.domainBind(t,B.fn)}b._setAsyncGuaranteed(),b._setOnCancel(B)}return b}}var p=arguments.length,C=Array(p);for(var f=0;f<p;++f)C[f]=arguments[f];if(P)C.pop();var b=new I(C).promise();return P!==void 0?b.spread(P):b}}});var sK0=L((HR1,aK0)=>{aK0.exports=function($,I,q,U,Y,J){var Q=$._getDomain,K=n1(),z=K.tryCatch,w=K.errorObj,G=$._async;function H(V,X,D,O){this.constructor$(V),this._promise._captureStackTrace();var N=Q();this._callback=N===null?X:K.domainBind(N,X),this._preservedValues=O===Y?Array(this.length()):null,this._limit=D,this._inFlight=0,this._queue=[],G.invoke(this._asyncInit,this,void 0)}K.inherits(H,I),H.prototype._asyncInit=function(){this._init$(void 0,-2)},H.prototype._init=function(){},H.prototype._promiseFulfilled=function(V,X){var D=this._values,O=this.length(),N=this._preservedValues,T=this._limit;if(X<0){if(X=X*-1-1,D[X]=V,T>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(T>=1&&this._inFlight>=T)return D[X]=V,this._queue.push(X),!1;if(N!==null)N[X]=V;var P=this._promise,g=this._callback,B=P._boundValue();P._pushContext();var k=z(g).call(B,V,X,O),h=P._popContext();if(J.checkForgottenReturns(k,h,N!==null?"Promise.filter":"Promise.map",P),k===w)return this._reject(k.e),!0;var n=U(k,this._promise);if(n instanceof $){n=n._target();var S=n._bitField;if((S&50397184)===0){if(T>=1)this._inFlight++;return D[X]=n,n._proxy(this,(X+1)*-1),!1}else if((S&33554432)!==0)k=n._value();else if((S&16777216)!==0)return this._reject(n._reason()),!0;else return this._cancel(),!0}D[X]=k}var t=++this._totalResolved;if(t>=O){if(N!==null)this._filter(D,N);else this._resolve(D);return!0}return!1},H.prototype._drainQueue=function(){var V=this._queue,X=this._limit,D=this._values;while(V.length>0&&this._inFlight<X){if(this._isResolved())return;var O=V.pop();this._promiseFulfilled(D[O],O)}},H.prototype._filter=function(V,X){var D=X.length,O=Array(D),N=0;for(var T=0;T<D;++T)if(V[T])O[N++]=X[T];O.length=N,this._resolve(O)},H.prototype.preservedValues=function(){return this._preservedValues};function W(V,X,D,O){if(typeof X!=="function")return q("expecting a function but got "+K.classString(X));var N=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 "+K.classString(D.concurrency)));N=D.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+K.classString(D)));return N=typeof N==="number"&&isFinite(N)&&N>=1?N:0,new H(V,X,N,O).promise()}$.prototype.map=function(V,X){return W(this,V,X,null)},$.map=function(V,X,D,O){return W(V,X,D,O)}}});var $z0=L((VR1,eK0)=>{var LS=Object.create;if(LS)UD=LS(null),YD=LS(null),UD[" size"]=YD[" size"]=0;var UD,YD;eK0.exports=function($){var I=n1(),q=I.canEvaluate,U=I.isIdentifier,Y,J,Q=function(V){return Function("ensureMethod",`
`;return C=C.replace(/\[TheName\]/g,b).replace(/\[TheTotal\]/g,E).replace(/\[ThePassedArguments\]/g,g).replace(/\[TheProperties\]/g,R).replace(/\[CancellationCode\]/g,u),Function("tryCatch","errorObj","Promise","async",C)(G,H,$,J)},z=[],L=[],D=[];for(var F=0;F<8;++F)z.push(Z(F+1)),L.push(V(F+1)),D.push(w(F+1));W=function(E){this._reject(E)}}$.join=function(){var E=arguments.length-1,T;if(E>0&&typeof arguments[E]==="function"){if(T=arguments[E],E<=8&&q){var i=new $(Y);i._captureStackTrace();var A=z[E-1],R=new A(T),u=L;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,R),D[g](b,R),R.asyncNeeded=!1;else if((C&33554432)!==0)u[g].call(i,b._value(),R);else if((C&16777216)!==0)i._reject(b._reason());else i._cancel()}else u[g].call(i,b,R)}if(!i._isFateSealed()){if(R.asyncNeeded){var p=Q();if(p!==null)R.fn=K.domainBind(p,R.fn)}i._setAsyncGuaranteed(),i._setOnCancel(R)}return i}}var n=arguments.length,S=Array(n);for(var f=0;f<n;++f)S[f]=arguments[f];if(T)S.pop();var i=new I(S).promise();return T!==void 0?i.spread(T):i}}});var sK0=O((zC1,aK0)=>{aK0.exports=function($,I,U,Y,J,Q){var K=$._getDomain,q=b1(),G=q.tryCatch,H=q.errorObj,W=$._async;function V(Z,z,L,D){this.constructor$(Z),this._promise._captureStackTrace();var F=K();this._callback=F===null?z:q.domainBind(F,z),this._preservedValues=D===J?Array(this.length()):null,this._limit=L,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,z){var L=this._values,D=this.length(),F=this._preservedValues,E=this._limit;if(z<0){if(z=z*-1-1,L[z]=Z,E>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(E>=1&&this._inFlight>=E)return L[z]=Z,this._queue.push(z),!1;if(F!==null)F[z]=Z;var T=this._promise,A=this._callback,R=T._boundValue();T._pushContext();var u=G(A).call(R,Z,z,D),g=T._popContext();if(Q.checkForgottenReturns(u,g,F!==null?"Promise.filter":"Promise.map",T),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 L[z]=b,b._proxy(this,(z+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}L[z]=u}var p=++this._totalResolved;if(p>=D){if(F!==null)this._filter(L,F);else this._resolve(L);return!0}return!1},V.prototype._drainQueue=function(){var Z=this._queue,z=this._limit,L=this._values;while(Z.length>0&&this._inFlight<z){if(this._isResolved())return;var D=Z.pop();this._promiseFulfilled(L[D],D)}},V.prototype._filter=function(Z,z){var L=z.length,D=Array(L),F=0;for(var E=0;E<L;++E)if(Z[E])D[F++]=z[E];D.length=F,this._resolve(D)},V.prototype.preservedValues=function(){return this._preservedValues};function w(Z,z,L,D){if(typeof z!=="function")return U("expecting a function but got "+q.classString(z));var F=0;if(L!==void 0)if(typeof L==="object"&&L!==null){if(typeof L.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+q.classString(L.concurrency)));F=L.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+q.classString(L)));return F=typeof F==="number"&&isFinite(F)&&F>=1?F:0,new V(Z,z,F,D).promise()}$.prototype.map=function(Z,z){return w(this,Z,z,null)},$.map=function(Z,z,L,D){return w(Z,z,L,D)}}});var $q0=O((LC1,eK0)=>{var Bg=Object.create;if(Bg)kz=Bg(null),uz=Bg(null),kz[" size"]=uz[" size"]=0;var kz,uz;eK0.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;
@@ -148,29 +143,29 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof h4))r
return obj.methodName.apply(obj, this);
}
};
`.replace(/methodName/g,V))(w)},K=function(V){return Function("obj",`
`.replace(/methodName/g,Z))(H)},q=function(Z){return Function("obj",`
'use strict';
return obj.propertyName;
`.replace("propertyName",V))},z=function(V,X,D){var O=D[V];if(typeof O!=="function"){if(!U(V))return null;if(O=X(V),D[V]=O,D[" size"]++,D[" size"]>512){var N=Object.keys(D);for(var T=0;T<256;++T)delete D[N[T]];D[" size"]=N.length-256}}return O};Y=function(V){return z(V,Q,UD)},J=function(V){return z(V,K,YD)};function w(V,X){var D;if(V!=null)D=V[X];if(typeof D!=="function"){var O="Object "+I.classString(V)+" has no method '"+I.toString(X)+"'";throw new $.TypeError(O)}return D}function G(V){var X=this.pop(),D=w(V,X);return D.apply(V,this)}$.prototype.call=function(V){var X=arguments.length,D=Array(Math.max(X-1,0));for(var O=1;O<X;++O)D[O-1]=arguments[O];if(q){var N=Y(V);if(N!==null)return this._then(N,void 0,void 0,D,void 0)}return D.push(V),this._then(G,void 0,void 0,D,void 0)};function H(V){return V[this]}function W(V){var X=+this;if(X<0)X=Math.max(0,X+V.length);return V[X]}$.prototype.get=function(V){var X=typeof V==="number",D;if(!X)if(q){var O=J(V);D=O!==null?O:H}else D=H;else D=W;return this._then(D,void 0,void 0,V,void 0)}}});var qz0=L((WR1,Iz0)=>{Iz0.exports=function($,I,q,U,Y,J){var Q=n1(),K=_5().TypeError,z=n1().inherits,w=Q.errorObj,G=Q.tryCatch,H={};function W(P){setTimeout(function(){throw P},0)}function V(P){var g=q(P);if(g!==P&&typeof P._isDisposable==="function"&&typeof P._getDisposer==="function"&&P._isDisposable())g._setDisposable(P._getDisposer());return g}function X(P,g){var B=0,k=P.length,h=new $(Y);function n(){if(B>=k)return h._fulfill();var S=V(P[B++]);if(S instanceof $&&S._isDisposable()){try{S=q(S._getDisposer().tryDispose(g),P.promise)}catch(t){return W(t)}if(S instanceof $)return S._then(n,W,null,null,null)}n()}return n(),h}function D(P,g,B){this._data=P,this._promise=g,this._context=B}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 H},D.prototype.tryDispose=function(P){var g=this.resource(),B=this._context;if(B!==void 0)B._pushContext();var k=g!==H?this.doDispose(g,P):null;if(B!==void 0)B._popContext();return this._promise._unsetDisposable(),this._data=null,k},D.isDisposer=function(P){return P!=null&&typeof P.resource==="function"&&typeof P.tryDispose==="function"};function O(P,g,B){this.constructor$(P,g,B)}z(O,D),O.prototype.doDispose=function(P,g){var B=this.data();return B.call(P,P,g)};function N(P){if(D.isDisposer(P))return this.resources[this.index]._setDisposable(P),P.promise();return P}function T(P){this.length=P,this.promise=null,this[P-1]=null}T.prototype._resultCancelled=function(){var P=this.length;for(var g=0;g<P;++g){var B=this[g];if(B instanceof $)B.cancel()}},$.using=function(){var P=arguments.length;if(P<2)return I("you must pass at least 2 arguments to Promise.using");var g=arguments[P-1];if(typeof g!=="function")return I("expecting a function but got "+Q.classString(g));var B,k=!0;if(P===2&&Array.isArray(arguments[0]))B=arguments[0],P=B.length,k=!1;else B=arguments,P--;var h=new T(P);for(var n=0;n<P;++n){var S=B[n];if(D.isDisposer(S)){var t=S;S=S.promise(),S._setDisposable(t)}else{var p=q(S);if(p instanceof $)S=p._then(N,null,null,{resources:h,index:n},void 0)}h[n]=S}var C=Array(h.length);for(var n=0;n<C.length;++n)C[n]=$.resolve(h[n]).reflect();var f=$.all(C).then(function(J0){for(var j=0;j<J0.length;++j){var u=J0[j];if(u.isRejected())return w.e=u.error(),w;else if(!u.isFulfilled()){f.cancel();return}J0[j]=u.value()}b._pushContext(),g=G(g);var d=k?g.apply(void 0,J0):g(J0),a=b._popContext();return J.checkForgottenReturns(d,a,"Promise.using",b),d}),b=f.lastly(function(){var J0=new $.PromiseInspection(f);return X(h,J0)});return h.promise=b,b._setOnCancel(h),b},$.prototype._setDisposable=function(P){this._bitField=this._bitField|131072,this._disposer=P},$.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(P){if(typeof P==="function")return new O(P,this,U());throw new K}}});var Yz0=L((ZR1,Uz0)=>{Uz0.exports=function($,I,q){var U=n1(),Y=$.TimeoutError;function J(H){this.handle=H}J.prototype._resultCancelled=function(){clearTimeout(this.handle)};var Q=function(H){return K(+this).thenReturn(H)},K=$.delay=function(H,W){var V,X;if(W!==void 0){if(V=$.resolve(W)._then(Q,null,null,H,void 0),q.cancellation()&&W instanceof $)V._setOnCancel(W)}else{if(V=new $(I),X=setTimeout(function(){V._fulfill()},+H),q.cancellation())V._setOnCancel(new J(X));V._captureStackTrace()}return V._setAsyncGuaranteed(),V};$.prototype.delay=function(H){return K(H,this)};var z=function(H,W,V){var X;if(typeof W!=="string")if(W instanceof Error)X=W;else X=new Y("operation timed out");else X=new Y(W);if(U.markAsOriginatingFromRejection(X),H._attachExtraTrace(X),H._reject(X),V!=null)V.cancel()};function w(H){return clearTimeout(this.handle),H}f Line truncated
`.replace("propertyName",Z))},G=function(Z,z,L){var D=L[Z];if(typeof D!=="function"){if(!Y(Z))return null;if(D=z(Z),L[Z]=D,L[" size"]++,L[" size"]>512){var F=Object.keys(L);for(var E=0;E<256;++E)delete L[F[E]];L[" size"]=F.length-256}}return D};J=function(Z){return G(Z,K,kz)},Q=function(Z){return G(Z,q,uz)};function H(Z,z){var L;if(Z!=null)L=Z[z];if(typeof L!=="function"){var D="Object "+I.classString(Z)+" has no method '"+I.toString(z)+"'";throw new $.TypeError(D)}return L}function W(Z){var z=this.pop(),L=H(Z,z);return L.apply(Z,this)}$.prototype.call=function(Z){var z=arguments.length,L=Array(Math.max(z-1,0));for(var D=1;D<z;++D)L[D-1]=arguments[D];if(U){var F=J(Z);if(F!==null)return this._then(F,void 0,void 0,L,void 0)}return L.push(Z),this._then(W,void 0,void 0,L,void 0)};function V(Z){return Z[this]}function w(Z){var z=+this;if(z<0)z=Math.max(0,z+Z.length);return Z[z]}$.prototype.get=function(Z){var z=typeof Z==="number",L;if(!z)if(U){var D=Q(Z);L=D!==null?D:V}else L=V;else L=w;return this._then(L,void 0,void 0,Z,void 0)}}});var Uq0=O((DC1,Iq0)=>{Iq0.exports=function($,I,U,Y,J,Q){var K=b1(),q=_5().TypeError,G=b1().inherits,H=K.errorObj,W=K.tryCatch,V={};function w(T){setTimeout(function(){throw T},0)}function Z(T){var A=U(T);if(A!==T&&typeof T._isDisposable==="function"&&typeof T._getDisposer==="function"&&T._isDisposable())A._setDisposable(T._getDisposer());return A}function z(T,A){var R=0,u=T.length,g=new $(J);function b(){if(R>=u)return g._fulfill();var C=Z(T[R++]);if(C instanceof $&&C._isDisposable()){try{C=U(C._getDisposer().tryDispose(A),T.promise)}catch(p){return w(p)}if(C instanceof $)return C._then(b,w,null,null,null)}b()}return b(),g}function L(T,A,R){this._data=T,this._promise=A,this._context=R}L.prototype.data=function(){return this._data},L.prototype.promise=function(){return this._promise},L.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return V},L.prototype.tryDispose=function(T){var A=this.resource(),R=this._context;if(R!==void 0)R._pushContext();var u=A!==V?this.doDispose(A,T):null;if(R!==void 0)R._popContext();return this._promise._unsetDisposable(),this._data=null,u},L.isDisposer=function(T){return T!=null&&typeof T.resource==="function"&&typeof T.tryDispose==="function"};function D(T,A,R){this.constructor$(T,A,R)}G(D,L),D.prototype.doDispose=function(T,A){var R=this.data();return R.call(T,T,A)};function F(T){if(L.isDisposer(T))return this.resources[this.index]._setDisposable(T),T.promise();return T}function E(T){this.length=T,this.promise=null,this[T-1]=null}E.prototype._resultCancelled=function(){var T=this.length;for(var A=0;A<T;++A){var R=this[A];if(R instanceof $)R.cancel()}},$.using=function(){var T=arguments.length;if(T<2)return I("you must pass at least 2 arguments to Promise.using");var A=arguments[T-1];if(typeof A!=="function")return I("expecting a function but got "+K.classString(A));var R,u=!0;if(T===2&&Array.isArray(arguments[0]))R=arguments[0],T=R.length,u=!1;else R=arguments,T--;var g=new E(T);for(var b=0;b<T;++b){var C=R[b];if(L.isDisposer(C)){var p=C;C=C.promise(),C._setDisposable(p)}else{var n=U(C);if(n instanceof $)C=n._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(),A=W(A);var d=u?A.apply(void 0,Y0):A(Y0),t=i._popContext();return Q.checkForgottenReturns(d,t,"Promise.using",i),d}),i=f.lastly(function(){var Y0=new $.PromiseInspection(f);return z(g,Y0)});return g.promise=i,i._setOnCancel(g),i},$.prototype._setDisposable=function(T){this._bitField=this._bitField|131072,this._disposer=T},$.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(T){if(typeof T==="function")return new D(T,this,Y());throw new q}}});var Jq0=O((OC1,Yq0)=>{Yq0.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,w){var Z,z;if(w!==void 0){if(Z=$.resolve(w)._then(K,null,null,V,void 0),U.cancellation()&&w instanceof $)Z._setOnCancel(w)}else{if(Z=new $(I),z=setTimeout(function(){Z._fulfill()},+V),U.cancellation())Z._setOnCancel(new Q(z));Z._captureStackTrace()}return Z._setAsyncGuaranteed(),Z};$.prototype.delay=function(V){return q(V,this)};var G=function(V,w,Z){var z;if(typeof w!=="string")if(w instanceof Error)z=w;else z=new J("operation timed out");else z=new J(w);if(Y.markAsOriginatingFromRejection(z),V._attachExtraTrace(z),V._reject(z),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:
`.replace("%s",D)+`From coroutine:
`+this._stack.split(`
`).slice(1,-7).join(`
`)));return}}N=N._target();var T=N._bitField;if((T&50397184)===0)this._yieldedPromise=N,N._proxy(this,null);else if((T&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,N._value());else if((T&16777216)!==0)$._async.invoke(this._promiseRejected,this,N._reason());else this._promiseCancelled()}},$.coroutine=function(X,D){if(typeof X!=="function")throw new K(`generatorFunction must be a function
`)));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(z,L){if(typeof z!=="function")throw new q(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var O=Object(D).yieldHandler,N=V,T=Error().stack;return function(){var P=X.apply(this,arguments),g=new N(void 0,void 0,O,T),B=g.promise();return g._generator=P,g._promiseFulfilled(void 0),B}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new K("expecting a function but got "+z.classString(X));H.push(X)},$.spawn=function(X){if(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunction must be a function
`);var D=Object(L).yieldHandler,F=Z,E=Error().stack;return function(){var T=z.apply(this,arguments),A=new F(void 0,void 0,D,E),R=A.promise();return A._generator=T,A._promiseFulfilled(void 0),R}},$.coroutine.addYieldHandler=function(z){if(typeof z!=="function")throw new q("expecting a function but got "+G.classString(z));V.push(z)},$.spawn=function(z){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof z!=="function")return I(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var D=new V(X,this),O=D.promise();return D._run($.spawn),O}}});var zz0=L((DR1,Kz0)=>{Kz0.exports=function($){var I=n1(),q=$._async,U=I.tryCatch,Y=I.errorObj;function J(z,w){var G=this;if(!I.isArray(z))return Q.call(G,z,w);var H=U(w).apply(G._boundValue(),[null].concat(z));if(H===Y)q.throwLater(H.e)}function Q(z,w){var G=this,H=G._boundValue(),W=z===void 0?U(w).call(H,null):U(w).call(H,null,z);if(W===Y)q.throwLater(W.e)}function K(z,w){var G=this;if(!z){var H=Error(z+"");H.cause=z,z=H}var W=U(w).call(G._boundValue(),z);if(W===Y)q.throwLater(W.e)}$.prototype.asCallback=$.prototype.nodeify=function(z,w){if(typeof z=="function"){var G=Q;if(w!==void 0&&Object(w).spread)G=J;this._then(G,K,void 0,this,z)}return this}}});var Gz0=L((OR1,wz0)=>{wz0.exports=function($,I){var q={},U=n1(),Y=OS(),J=U.withAppended,Q=U.maybeWrapAsError,K=U.canEvaluate,z=_5().TypeError,w="Async",G={__isPromisified__:!0},H=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],W=new RegExp("^(?:"+H.join("|")+")$"),V=function(f){return U.isIdentifier(f)&&f.charAt(0)!=="_"&&f!=="constructor"};function X(f){return!W.test(f)}function D(f){try{return f.__isPromisified__===!0}catch(b){return!1}}function O(f,b,J0){var j=U.getDataPropertyOrDefault(f,b+J0,G);return j?D(j):!1}function N(f,b,J0){for(var j=0;j<f.length;j+=2){var u=f[j];if(J0.test(u)){var d=u.replace(J0,"");for(var a=0;a<f.length;a+=2)if(f[a]===d)throw new z(`Cannot promisify an API that has normal methods with '%s'-suffix
`);var L=new Z(z,this),D=L.promise();return L._run($.spawn),D}}});var Gq0=O((NC1,qq0)=>{qq0.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(),w=G===void 0?Y(H).call(V,null):Y(H).call(V,null,G);if(w===J)U.throwLater(w.e)}function q(G,H){var W=this;if(!G){var V=Error(G+"");V.cause=G,G=V}var w=Y(H).call(W._boundValue(),G);if(w===J)U.throwLater(w.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 Wq0=O((MC1,Hq0)=>{Hq0.exports=function($,I){var U={},Y=b1(),J=Eg(),Q=Y.withAppended,K=Y.maybeWrapAsError,q=Y.canEvaluate,G=_5().TypeError,H="Async",W={__isPromisified__:!0},V=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],w=new RegExp("^(?:"+V.join("|")+")$"),Z=function(f){return Y.isIdentifier(f)&&f.charAt(0)!=="_"&&f!=="constructor"};function z(f){return!w.test(f)}function L(f){try{return f.__isPromisified__===!0}catch(i){return!1}}function D(f,i,Y0){var B=Y.getDataPropertyOrDefault(f,i+Y0,W);return B?L(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",b))}}}function T(f,b,J0,j){var u=U.inheritedDataKeys(f),d=[];for(var a=0;a<u.length;++a){var K0=u[a],G0=f[K0],M0=j===V?!0:V(K0,G0,f);if(typeof G0==="function"&&!D(G0)&&!O(f,K0,b)&&j(K0,G0,f,M0))d.push(K0,G0)}return N(d,b,J0),d}var P=function(f){return f.replace(/([$])/,"\\$")},g,B=function(f){var b=[f],J0=Math.max(0,f-1-3);for(var j=f-1;j>=J0;--j)b.push(j);for(var j=f+1;j<=3;++j)b.push(j);return b},k=function(f){return U.filledRange(f,"_arg","")},h=function(f){return U.filledRange(Math.max(f,3),"_arg","")},n=function(f){if(typeof f.length==="number")return Math.max(Math.min(f.length,1024),0);return 0};g=function(f,b,J0,j,u,d){var a=Math.max(0,n(j)-1),K0=B(a),G0=typeof f==="string"||b===q;function M0(N1){var F1=k(N1).join(", "),Q1=N1>0?", ":"",C1;if(G0)C1=`ret = callback.call(this, {{args}}, nodeback); break;
`;else C1=b===void 0?`ret = callback({{args}}, nodeback); break;
`.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],A0=B===Z?!0:Z(K0,W0,f);if(typeof W0==="function"&&!L(W0)&&!D(f,K0,i)&&B(K0,W0,f,A0))d.push(K0,W0)}return F(d,i,Y0),d}var T=function(f){return f.replace(/([$])/,"\\$")},A,R=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};A=function(f,i,Y0,B,k,d){var t=Math.max(0,b(B)-1),K0=R(t),W0=typeof f==="string"||i===U;function A0(H1){var F0=u(H1).join(", "),g0=H1>0?", ":"",m0;if(W0)m0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else m0=i===void 0?`ret = callback({{args}}, nodeback); break;
`:`ret = callback.call(receiver, {{args}}, nodeback); break;
`;return C1.replace("{{args}}",F1).replace(", ",Q1)}function v0(){var N1="";for(var F1=0;F1<K0.length;++F1)N1+="case "+K0[F1]+":"+M0(K0[F1]);return N1+=`
`;return m0.replace("{{args}}",F0).replace(", ",g0)}function v0(){var H1="";for(var F0=0;F0<K0.length;++F0)H1+="case "+K0[F0]+":"+A0(K0[F0]);return H1+=`
default:
var args = new Array(len + 1);
var i = 0;
@@ -180,9 +175,9 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof h4))r
args[i] = nodeback;
[CodeForCall]
break;
`.replace("[CodeForCall]",G0?`ret = callback.apply(this, args);
`.replace("[CodeForCall]",W0?`ret = callback.apply(this, args);
`:`ret = callback.apply(receiver, args);
`),N1}var v1=typeof f==="string"?"this != null ? this['"+f+"'] : fn":"fn",m0=`'use strict';
`),H1}var L1=typeof f==="string"?"this != null ? this['"+f+"'] : fn":"fn",f0=`'use strict';
var ret = function (Parameters) {
'use strict';
var len = arguments.length;
@@ -202,25 +197,25 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof h4))r
};
notEnumerableProp(ret, '__isPromisified__', true);
return ret;
`.replace("[CodeForSwitchCase]",v0()).replace("[GetFunctionCode]",v1);return m0=m0.replace("Parameters",h(a)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",m0)($,j,b,J,Q,Y,U.tryCatch,U.errorObj,U.notEnumerableProp,I)};function S(f,b,J0,j,u,d){var a=function(){return this}(),K0=f;if(typeof K0==="string")f=j;function G0(){var M0=b;if(b===q)M0=this;var v0=new $(I);v0._captureStackTrace();var v1=typeof K0==="string"&&this!==a?this[K0]:f,m0=Y(v0,d);try{v1.apply(M0,J(arguments,m0))}catch(N1){v0._rejectCallback(Q(N1),!0,!0)}if(!v0._isFateSealed())v0._setAsyncGuaranteed();return v0}return U.notEnumerableProp(G0,"__isPromisified__",!0),G0}var t=K?g:S;function p(f,b,J0,j,u){var d=new RegExp(P(b)+"$"),a=T(f,b,d,J0);for(var K0=0,G0=a.length;K0<G0;K0+=2){var M0=a[K0],v0=a[K0+1],v1=M0+b;if(j===t)f[v1]=t(M0,q,M0,v0,b,u);else{var m0=j(v0,function(){return t(M0,q,M0,v0,b,u)});U.notEnumerableProp(m0,"__isPromisified__",!0),f[v1]=m0}}return U.toFastProperties(f),f}function C(f,b,J0){return t(f,b,void 0,f,null,J0)}$.promisify=function(f,b){if(typeof f!=="function")throw new z("expecting a function but got "+U.classString(f));if(D(f))return f;b=Object(b);var J0=b.context===void 0?q:b.context,j=!!b.multiArgs,u=C(f,J0,j);return U.copyDescriptors(f,u,X),u},$.promisifyAll=function(f,b){if(typeof f!=="function"&&typeof f!=="object")throw new z(`the target of promisifyAll must be an object or a function
`.replace("[CodeForSwitchCase]",v0()).replace("[GetFunctionCode]",L1);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 A0=i;if(i===U)A0=this;var v0=new $(I);v0._captureStackTrace();var L1=typeof K0==="string"&&this!==t?this[K0]:f,f0=J(v0,d);try{L1.apply(A0,Q(arguments,f0))}catch(H1){v0._rejectCallback(K(H1),!0,!0)}if(!v0._isFateSealed())v0._setAsyncGuaranteed();return v0}return Y.notEnumerableProp(W0,"__isPromisified__",!0),W0}var p=q?A:C;function n(f,i,Y0,B,k){var d=new RegExp(T(i)+"$"),t=E(f,i,d,Y0);for(var K0=0,W0=t.length;K0<W0;K0+=2){var A0=t[K0],v0=t[K0+1],L1=A0+i;if(B===p)f[L1]=p(A0,U,A0,v0,i,k);else{var f0=B(v0,function(){return p(A0,U,A0,v0,i,k)});Y.notEnumerableProp(f0,"__isPromisified__",!0),f[L1]=f0}}return Y.toFastProperties(f),f}function S(f,i,Y0){return p(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(L(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,z),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
`);b=Object(b);var J0=!!b.multiArgs,j=b.suffix;if(typeof j!=="string")j=w;var u=b.filter;if(typeof u!=="function")u=V;var d=b.promisifier;if(typeof d!=="function")d=t;if(!U.isIdentifier(j))throw RangeError(`suffix must be a valid identifier
`);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=p;if(!Y.isIdentifier(B))throw RangeError(`suffix must be a valid identifier
See http://goo.gl/MqrFmX
`);var a=U.inheritedDataKeys(f);for(var K0=0;K0<a.length;++K0){var G0=f[a[K0]];if(a[K0]!=="constructor"&&U.isClass(G0))p(G0.prototype,j,u,d,J0),p(G0,j,u,d,J0)}return p(f,j,u,d,J0)}}});var Vz0=L((LR1,Hz0)=>{Hz0.exports=function($,I,q,U){var Y=n1(),J=Y.isObject,Q=f3(),K;if(typeof Map==="function")K=Map;var z=function(){var W=0,V=0;function X(D,O){this[W]=D,this[W+V]=O,W++}return function(O){V=O.size,W=0;var N=Array(O.size*2);return O.forEach(X,N),N}}(),w=function(W){var V=new K,X=W.length/2|0;for(var D=0;D<X;++D){var O=W[X+D],N=W[D];V.set(O,N)}return V};function G(W){var V=!1,X;if(K!==void 0&&W instanceof K)X=z(W),V=!0;else{var D=Q.keys(W),O=D.length;X=Array(O*2);for(var N=0;N<O;++N){var T=D[N];X[N]=W[T],X[N+O]=T}}this.constructor$(X),this._isMap=V,this._init$(void 0,-3)}Y.inherits(G,I),G.prototype._init=function(){},G.prototype._promiseFulfilled=function(W,V){this._values[V]=W;var X=++this._totalResolved;if(X>=this._length){var D;if(this._isMap)D=w(this._values);else{D={};var O=this.length();for(var N=0,T=this.length();N<T;++N)D[this._values[N+O]]=this._values[N]}return this._resolve(D),!0}return!1},G.prototype.shouldCopyValues=function(){return!1},G.prototype.getActualLength=function(W){return W>>1};function H(W){var V,X=q(W);if(!J(X))return U(`cannot await properties of a non-object
`);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))n(W0.prototype,B,k,d,Y0),n(W0,B,k,d,Y0)}return n(f,B,k,d,Y0)}}});var wq0=O((AC1,Vq0)=>{Vq0.exports=function($,I,U,Y){var J=b1(),Q=J.isObject,K=k3(),q;if(typeof Map==="function")q=Map;var G=function(){var w=0,Z=0;function z(L,D){this[w]=L,this[w+Z]=D,w++}return function(D){Z=D.size,w=0;var F=Array(D.size*2);return D.forEach(z,F),F}}(),H=function(w){var Z=new q,z=w.length/2|0;for(var L=0;L<z;++L){var D=w[z+L],F=w[L];Z.set(D,F)}return Z};function W(w){var Z=!1,z;if(q!==void 0&&w instanceof q)z=G(w),Z=!0;else{var L=K.keys(w),D=L.length;z=Array(D*2);for(var F=0;F<D;++F){var E=L[F];z[F]=w[E],z[F+D]=E}}this.constructor$(z),this._isMap=Z,this._init$(void 0,-3)}J.inherits(W,I),W.prototype._init=function(){},W.prototype._promiseFulfilled=function(w,Z){this._values[Z]=w;var z=++this._totalResolved;if(z>=this._length){var L;if(this._isMap)L=H(this._values);else{L={};var D=this.length();for(var F=0,E=this.length();F<E;++F)L[this._values[F+D]]=this._values[F]}return this._resolve(L),!0}return!1},W.prototype.shouldCopyValues=function(){return!1},W.prototype.getActualLength=function(w){return w>>1};function V(w){var Z,z=U(w);if(!Q(z))return Y(`cannot await properties of a non-object
See http://goo.gl/MqrFmX
`);else if(X instanceof $)V=X._then($.props,void 0,void 0,void 0,void 0);else V=new G(X).promise();if(X instanceof $)V._propagateFrom(X,2);return V}$.prototype.props=function(){return H(this)},$.props=function(W){return H(W)}}});var Zz0=L((NR1,Wz0)=>{Wz0.exports=function($,I,q,U){var Y=n1(),J=function(K){return K.then(function(z){return Q(z,K)})};function Q(K,z){var w=q(K);if(w instanceof $)return J(w);else if(K=Y.asArray(K),K===null)return U("expecting an array or an iterable object but got "+Y.classString(K));var G=new $(I);if(z!==void 0)G._propagateFrom(z,3);var{_fulfill:H,_reject:W}=G;for(var V=0,X=K.length;V<X;++V){var D=K[V];if(D===void 0&&!(V in K))continue;$.cast(D)._then(H,W,void 0,G,null)}return G}$.race=function(K){return Q(K,void 0)},$.prototype.race=function(){return Q(this,void 0)}}});var Dz0=L((FR1,Xz0)=>{Xz0.exports=function($,I,q,U,Y,J){var Q=$._getDomain,K=n1(),z=K.tryCatch;function w(X,D,O,N){this.constructor$(X);var T=Q();if(this._fn=T===null?D:K.domainBind(T,D),O!==void 0)O=$.resolve(O),O._attachCancellationCallback(this);if(this._initialValue=O,this._currentCancellable=null,N===Y)this._eachValues=Array(this._length);else if(N===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}K.inherits(w,I),w.prototype._gotAccum=function(X){if(this._eachValues!==void 0&&this._eachValues!==null&&X!==Y)this._eachValues.push(X)},w.prototype._eachComplete=function(X){if(this._eachValues!==null)this._eachValues.push(X);return this._eachValues},w.prototype._init=function(){},w.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},w.prototype.shouldCopyValues=function(){return!1},w.prototype._resolve=function(X){this._promise._resolveCallback(X),this._values=null},w.prototype._resultCancelled=function(X){if(X===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()},w.prototype._iterate=function(X){this._values=X;var D,O,N=X.length;if(this._initialValue!==void 0)D=this._initialValue,O=0;else D=$.resolve(X[0]),O=1;if(this._currentCancellable=D,!D.isRejected())for(;O<N;++O){var T={accum:null,value:X[O],index:O,length:N,array:this};D=D._then(W,void 0,void 0,T,void 0)}if(this._eachValues!==void 0)D=D._then(this._eachComplete,void 0,void 0,this,void 0);D._then(G,G,void 0,D,this)},$.prototype.reduce=function(X,D){return H(this,X,D,null)},$.reduce=function(X,D,O,N){return H(X,D,O,N)};function G(X,D){if(this.isFulfilled())D._resolve(X);else D._reject(X)}function H(X,D,O,N){if(typeof D!=="function")return q("expecting a function but got "+K.classString(D));var T=new w(X,D,O,N);return T.promise()}function W(X){this.accum=X,this.array._gotAccum(X);var D=U(this.value,this.array._promise);if(D instanceof $)return this.array._currentCancellable=D,D._then(V,void 0,void 0,this,void 0);else return V.call(this,D)}function V(X){var D=this.array,O=D._promise,N=z(D._fn);O._pushContext();var T;if(D._eachValues!==void 0)T=N.call(O._boundValue(),X,this.index,this.length);else T=N.call(O._boundValue(),this.accum,X,this.index,this.length);if(T instanceof $)D._currentCancellable=T;var P=O._popContext();return J.checkForgottenReturns(T,P,D._eachValues!==void 0?"Promise.each":"Promise.reduce",O),T}}});var Lz0=L((MR1,Oz0)=>{Oz0.exports=function($,I,q){var U=$.PromiseInspection,Y=n1();function J(Q){this.constructor$(Q)}Y.inherits(J,I),J.prototype._promiseResolved=function(Q,K){this._values[Q]=K;var z=++this._totalResolved;if(z>=this._length)return this._resolve(this._values),!0;return!1},J.prototype._promiseFulfilled=function(Q,K){var z=new U;return z._bitField=33554432,z._settledValueField=Q,this._promiseResolved(K,z)},J.prototype._promiseRejected=function(Q,K){var z=new U;return z._bitField=16777216,z._settledValueField=Q,this._promiseResolved(K,z)},$.settle=function(Q){return q.deprecated(".settle()",".reflect()"),new J(Q).promise()},$.prototype.settle=function(){return $.settle(this)}}});var Fz0=L((AR1,Nz0)=>{Nz0.exports=function($,I,q){var U=n1(),Y=_5().RangeError,J=_5().AggregateError,Q=U.isArray,K={};function z(G){this.constructor$(G),this._howMany=0,this._unwrap=!1,this._initialized=!1}U.inherits(z,I),z.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var G=Q(this._values);if(!this._isResolved()&&G&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},z.prototype.init=function(){this._initialized=!0,this._init()},z.prototype.setUnwrap=function(){this._unwrap=!0},z.prototype.howMany=function(){return this._howMany},z.prototype.setHowMany=function(G){this._howMany=G},z.prototype._promiseFulfilled=function(G){if(this._addFulfilled(G),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
`);else if(z instanceof $)Z=z._then($.props,void 0,void 0,void 0,void 0);else Z=new W(z).promise();if(z instanceof $)Z._propagateFrom(z,2);return Z}$.prototype.props=function(){return V(this)},$.props=function(w){return V(w)}}});var Xq0=O((PC1,Zq0)=>{Zq0.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:w}=W;for(var Z=0,z=q.length;Z<z;++Z){var L=q[Z];if(L===void 0&&!(Z in q))continue;$.cast(L)._then(V,w,void 0,W,null)}return W}$.race=function(q){return K(q,void 0)},$.prototype.race=function(){return K(this,void 0)}}});var Lq0=O((TC1,zq0)=>{zq0.exports=function($,I,U,Y,J,Q){var K=$._getDomain,q=b1(),G=q.tryCatch;function H(z,L,D,F){this.constructor$(z);var E=K();if(this._fn=E===null?L:q.domainBind(E,L),D!==void 0)D=$.resolve(D),D._attachCancellationCallback(this);if(this._initialValue=D,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(z){if(this._eachValues!==void 0&&this._eachValues!==null&&z!==J)this._eachValues.push(z)},H.prototype._eachComplete=function(z){if(this._eachValues!==null)this._eachValues.push(z);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(z){this._promise._resolveCallback(z),this._values=null},H.prototype._resultCancelled=function(z){if(z===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(z){this._values=z;var L,D,F=z.length;if(this._initialValue!==void 0)L=this._initialValue,D=0;else L=$.resolve(z[0]),D=1;if(this._currentCancellable=L,!L.isRejected())for(;D<F;++D){var E={accum:null,value:z[D],index:D,length:F,array:this};L=L._then(w,void 0,void 0,E,void 0)}if(this._eachValues!==void 0)L=L._then(this._eachComplete,void 0,void 0,this,void 0);L._then(W,W,void 0,L,this)},$.prototype.reduce=function(z,L){return V(this,z,L,null)},$.reduce=function(z,L,D,F){return V(z,L,D,F)};function W(z,L){if(this.isFulfilled())L._resolve(z);else L._reject(z)}function V(z,L,D,F){if(typeof L!=="function")return U("expecting a function but got "+q.classString(L));var E=new H(z,L,D,F);return E.promise()}function w(z){this.accum=z,this.array._gotAccum(z);var L=Y(this.value,this.array._promise);if(L instanceof $)return this.array._currentCancellable=L,L._then(Z,void 0,void 0,this,void 0);else return Z.call(this,L)}function Z(z){var L=this.array,D=L._promise,F=G(L._fn);D._pushContext();var E;if(L._eachValues!==void 0)E=F.call(D._boundValue(),z,this.index,this.length);else E=F.call(D._boundValue(),this.accum,z,this.index,this.length);if(E instanceof $)L._currentCancellable=E;var T=D._popContext();return Q.checkForgottenReturns(E,T,L._eachValues!==void 0?"Promise.each":"Promise.reduce",D),E}}});var Oq0=O((EC1,Dq0)=>{Dq0.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 Nq0=O((BC1,Fq0)=>{Fq0.exports=function($,I,U){var Y=b1(),J=_5().RangeError,Q=_5().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 W=new z(G),V=W.promise();return W.setHowMany(H),W.init(),V}$.some=function(G,H){return w(G,H)},$.prototype.some=function(G){return w(this,G)},$._SomePromiseArray=z}});var Az0=L((gR1,Mz0)=>{Mz0.exports=function($,I){var q=$.map;$.prototype.filter=function(U,Y){return q(this,U,Y,I)},$.filter=function(U,Y,J){return q(U,Y,J,I)}}});var Pz0=L((PR1,gz0)=>{gz0.exports=function($,I){var{reduce:q,all:U}=$;function Y(){return U(this)}function J(Q,K){return q(Q,K,I,I)}$.prototype.each=function(Q){return q(this,Q,I,0)._then(Y,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(Q){return q(this,Q,I,I)},$.each=function(Q,K){return q(Q,K,I,0)._then(Y,void 0,void 0,Q,void 0)},$.mapSeries=J}});var jz0=L((TR1,Tz0)=>{Tz0.exports=function($){var I=$._SomePromiseArray;function q(U){var Y=new I(U),J=Y.promise();return Y.setHowMany(1),Y.setUnwrap(),Y.init(),J}$.any=function(U){return q(U)},$.prototype.any=function(){return q(this)}}});var Ez0=L((jR1,NS)=>{NS.exports=function(){var $=function(){return new H(`circular promise resolution chain
`);var w=new G(W),Z=w.promise();return w.setHowMany(V),w.init(),Z}$.some=function(W,V){return H(W,V)},$.prototype.some=function(W){return H(this,W)},$._SomePromiseArray=G}});var Aq0=O((vC1,Mq0)=>{Mq0.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 Tq0=O((RC1,Pq0)=>{Pq0.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 Bq0=O((CC1,Eq0)=>{Eq0.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 vq0=O((jC1,vg)=>{vg.exports=function(){var $=function(){return new V(`circular promise resolution chain
See http://goo.gl/MqrFmX
`)},I=function(){return new C.PromiseInspection(this._target())},q=function(j){return C.reject(new H(j))};function U(){}var Y={},J=n1(),Q;if(J.isNode)Q=function(){var j=process.domain;if(j===void 0)j=null;return j};else Q=function(){return null};J.notEnumerableProp(C,"_getDomain",Q);var K=f3(),z=FK0(),w=new z;K.defineProperty(C,"_async",{value:w});var G=_5(),H=C.TypeError=G.TypeError;C.RangeError=G.RangeError;var W=C.CancellationError=G.CancellationError;C.TimeoutError=G.TimeoutError,C.OperationalError=G.OperationalError,C.RejectionError=G.OperationalError,C.AggregateError=G.AggregateError;var V=function(){},X={},D={},O=TK0()(C,V),N=EK0()(C,V,O,q,U),T=vK0()(C),P=T.create,g=CK0()(C,T),B=g.CapturedTrace,k=hK0()(C,O),h=yK0()(D),n=OS(),S=J.errorObj,t=J.tryCatch;function p(j,u){if(typeof u!=="function")throw new H("expecting a function but got "+J.classString(u));if(j.constructor!==C)throw new H(`the promise constructor cannot be invoked directly
`)},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=k3(),G=NK0(),H=new G;q.defineProperty(S,"_async",{value:H});var W=_5(),V=S.TypeError=W.TypeError;S.RangeError=W.RangeError;var w=S.CancellationError=W.CancellationError;S.TimeoutError=W.TimeoutError,S.OperationalError=W.OperationalError,S.RejectionError=W.OperationalError,S.AggregateError=W.AggregateError;var Z=function(){},z={},L={},D=EK0()(S,Z),F=vK0()(S,Z,D,U,Y),E=CK0()(S),T=E.create,A=_K0()(S,E),R=A.CapturedTrace,u=gK0()(S,D),g=hK0()(L),b=Eg(),C=Q.errorObj,p=Q.tryCatch;function n(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 C(j){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,j!==V)p(this,j),this._resolveFromExecutor(j);this._promiseCreated(),this._fireEvent("promiseCreated",this)}C.prototype.toString=function(){return"[object Promise]"},C.prototype.caught=C.prototype.catch=function(j){var u=arguments.length;if(u>1){var d=Array(u-1),a=0,K0;for(K0=0;K0<u-1;++K0){var G0=arguments[K0];if(J.isObject(G0))d[a++]=G0;else return q("expecting an object but got A catch statement predicate "+J.classString(G0))}return d.length=a,j=arguments[K0],this.then(void 0,h(d,j,this))}return this.then(void 0,j)},C.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},C.prototype.then=function(j,u){if(g.warnings()&&arguments.length>0&&typeof j!=="function"&&typeof u!=="function"){var d=".then() only accepts functions but was passed: "+J.classString(j);if(arguments.length>1)d+=", "+J.classString(u);this._warn(d)}return this._then(j,u,void 0,void 0,void 0)},C.prototype.done=function(j,u){var d=this._then(j,u,void 0,void 0,void 0);d._setIsFinal()},C.prototype.spread=function(j){if(typeof j!=="function")return q("expecting a function but got "+J.classString(j));return this.all()._then(j,void 0,void 0,X,void 0)},C.prototype.toJSON=function(){var j={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())j.fulfillmentValue=this.value(),j.isFulfilled=!0;else if(this.isRejected())j.rejectionReason=this.reason(),j.isRejected=!0;return j},C.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new N(this).promise()},C.prototype.error=function(j){return this.caught(J.originatesFromRejection,j)},C.getNewLibraryCopy=NS.exports,C.is=function(j){return j instanceof C},C.fromNode=C.fromCallback=function(j){var u=new C(V);u._captureStackTrace();var d=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,a=t(j)(n(u,d));if(a===S)u._rejectCallback(a.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},C.all=function(j){return new N(j).promise()},C.cast=function(j){var u=O(j);if(!(u instanceof C))u=new C(V),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=j;return u},C.resolve=C.fulfilled=C.cast,C.reject=C.rejected=function(j){var u=new C(V);return u._captureStackTrace(),u._rejectCallback(j,!0),u},C.setScheduler=function(j){if(typeof j!=="function")throw new H("expecting a function but got "+J.classString(j));return w.setScheduler(j)},C.prototype._then=function(j,u,d,a,K0){var G0=K0!==void 0,M0=G0?K0:new C(V),v0=this._target(),v1=v0._bitField;if(!G0){if(M0._propagateFrom(this,3),M0._captureStackTrace(),a===void 0&&(this._bitField&2097152)!==0)if((v1&50397184)!==0)a=this._boundValue();else a=v0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,M0)}var m0=Q();if((v1&50397184)!==0){var N1,F1,Q1=v0._settlePromiseCtx;if((v1&33554432)!==0)F1=v0._rejectionHandler0,N1=j;else if((v1&16777216)!==0)F1=v0._fulfillmentHandler0,N1=u,v0._unsetRejectionIsUnhandled();else Q1=v0._settlePromiseLateCancellationObserver,F1=new W("late cancellation observer"),v0._attachExtraTrace(F1),N1=u;w.invoke(Q1,v0,{handler:m0===null?N1:typeof N1==="function"&&J.domainBind(m0,N1),promise:M0,receiver:a,value:F1})}else v0._addCallbacks(j,u,M0,a,m0);return M0},C.prototype._length=function(){return this._bitField&65535},C.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},C.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},C.prototype._setLength=function(j){this._bitField=this._bitField&-65536|j&65535},C.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},C.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},C.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},C.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},C.prototype._isFinal=function(){return(this._bitField&4194304)>0},C.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},C.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},C.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},C.prototype._setAsyncGuaranteed=function(){if(w.hasCustomScheduler())return;this._bitField=this._bitField|134217728},C.prototype._receiverAt=function(j){var u=j===0?this._receiver0:this[j*4-4+3];if(u===Y)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},C.prototype._promiseAt=function(j){return this[j*4-4+2]},C.prototype._fulfillmentHandlerAt=function(j){return this[j*4-4+0]},C.prototype._rejectionHandlerAt=function(j){return this[j*4-4+1]},C.prototype._boundValue=function(){},C.prototype._migrateCallback0=function(j){var{_bit Line truncated
`)}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)n(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(A.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,z,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=vg.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=p(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=D(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,A0=W0?K0:new S(Z),v0=this._target(),L1=v0._bitField;if(!W0){if(A0._propagateFrom(this,3),A0._captureStackTrace(),t===void 0&&(this._bitField&2097152)!==0)if((L1&50397184)!==0)t=this._boundValue();else t=v0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,A0)}var f0=K();if((L1&50397184)!==0){var H1,F0,g0=v0._settlePromiseCtx;if((L1&33554432)!==0)F0=v0._rejectionHandler0,H1=B;else if((L1&16777216)!==0)F0=v0._fulfillmentHandler0,H1=k,v0._unsetRejectionIsUnhandled();else g0=v0._settlePromiseLateCancellationObserver,F0=new w("late cancellation observer"),v0._attachExtraTrace(F0),H1=k;H.invoke(g0,v0,{handler:f0===null?H1:typeof H1==="function"&&Q.domainBind(f0,H1),promise:A0,receiver:t,value:F0})}else v0._addCallbacks(B,k,A0,t,f0);return A0},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
@@ -229,91 +224,101 @@ fstream_unc_path = %s
fstream_class = %s
fstream_stack =
%s
`,I||"UNKNOWN",U.stack,U.path,U.syscall,U.fstream_type,U.fstream_path,U.fstream_unc_path,U.fstream_class,U.fstream_stack.join(`
`));else q.emit("warn",U)};J7.prototype.info=function($,I){this.emit("info",$,I)};J7.prototype.error=function($,I,q){var U=QG0($,I,this);if(q)throw U;else this.emit("error",U)};function QG0($,I,q){if(!($ instanceof Error))$=Error($);if($.code=$.code||I,$.path=$.path||q.path,$.fstream_type=$.fstream_type||q.type,$.fstream_path=$.fstream_path||q.path,q._path!==q.path)$.fstream_unc_path=$.fstream_unc_path||q._path;if(q.linkpath)$.fstream_linkpath=$.fstream_linkpath||q.linkpath;return $.fstream_class=$.fstream_class||q.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(U){return U.replace(/^ {4}at /,"")}),$}});var iK=L((qC1,zG0)=>{zG0.exports=WQ1;function WQ1($){var I=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],q;if($.type&&I.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var U=0,Y=I.length;U<Y;U++){q=I[U];var J=$[q]||$["is"+q];if(typeof J==="function")J=J.call($);if(J)return $[q]=!0,$.type=q,q}return null}});var Jy=L((UC1,wG0)=>{wG0.exports=pK;var ZQ1=l6(),XQ1=n0(),Yy=o3();XQ1(pK,Yy);function pK($){var I=this;if(!(I instanceof pK))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Yy.call(I,$)}pK.prototype._stat=function($){var I=this;ZQ1.readlink(I._path,function(q,U){if(q)return I.error(q);I.linkpath=I.props.linkpath=U,I.emit("linkpath",U),Yy.prototype._stat.call(I,$)})};pK.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Ky=L((YC1,VG0)=>{VG0.exports=n8;var HG0=l6(),DQ1=n0(),cK=o("path"),Qy=o3(),GG0=o("assert").ok;DQ1(n8,Qy);function n8($){var I=this;if(!(I instanceof n8))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;Qy.call(this,$)}n8.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,HG0.readdir($._path,function(I,q){if(I)return $.error(I);if($.entries=q,$.emit("entries",q),$._paused)$.once("resume",U);else U();function U(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};n8.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=cK.resolve($._path,$.entries[$._index]);GG0(I!==$._path),GG0($.entries[$._index]),$._currentEntry=I,HG0[$.props.follow?"stat":"lstat"](I,function(q,U){if(q)return $.error(q);var Y=$._proxy||$;U.path=I,U.basename=cK.basename(I),U.dirname=cK.dirname(I);var J=$.getChildProps.call(Y,U);J.path=I,J.basename=cK.basename(I),J.dirname=cK.dirname(I);var Q=Qy(J,U);$._currentEntry=Q,Q.on("pause",function(w){if(!$._paused&&!Q._disowned)$.pause(w)}),Q.on("resume",function(w){if($._paused&&!Q._disowned)$.resume(w)}),Q.on("stat",function(w){if($.emit("_entryStat",Q,w),Q._aborted)return;if(Q._paused)Q.once("resume",function(){$.emit("entryStat",Q,w)});else $.emit("entryStat",Q,w)}),Q.on("ready",function w(){if($._paused)return Q.pause($),$.once("resume",w);if(Q.type==="Socket")$.emit("socket",Q);else $.emitEntry(Q)});var K=!1;Q.on("close",z),Q.on("disown",z);function z(){if(K)return;if(K=!0,$.emit("childEnd",Q),$.emit("entryEnd",Q),$._currentEntry=null,!$._paused)$._read()}Q.on("error",function(w){if(Q._swallowErrors)$.warn(w),Q.emit("end"),Q.emit("close");else $.emit("error",w)}),["child","childEnd","warn"].forEach(function(w){Q.on(w,$.emit.bind($,w))})})};n8.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};n8.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}};n8.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",$)};n8.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()};n8.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var zy=L((JC1,DG0)=>{DG0.exports=r3;var OQ1=l6(),LQ1=n0(),WG0=o3(),ZG0={EOF:!0},XG0={CLOSE:!0};LQ1(r3,WG0);function r3($){var I=this;if(!(I instanceof r3))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,WG0.call(I,$)}r3.prototype._getStream=function(){var $=this,I=$._stream=OQ1.createReadStream($._path,$.pro Line truncated
`,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)};q7.prototype.info=function($,I){this.emit("info",$,I)};q7.prototype.error=function($,I,U){var Y=KH0($,I,this);if(U)throw Y;else this.emit("error",Y)};function KH0($,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 uq=O((Kj1,GH0)=>{GH0.exports=lY1;function lY1($){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 Zy=O((qj1,HH0)=>{HH0.exports=fq;var oY1=m6(),rY1=p0(),wy=m3();rY1(fq,wy);function fq($){var I=this;if(!(I instanceof fq))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);wy.call(I,$)}fq.prototype._stat=function($){var I=this;oY1.readlink(I._path,function(U,Y){if(U)return I.error(U);I.linkpath=I.props.linkpath=Y,I.emit("linkpath",Y),wy.prototype._stat.call(I,$)})};fq.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var zy=O((Gj1,wH0)=>{wH0.exports=u8;var VH0=m6(),tY1=p0(),bq=r("path"),Xy=m3(),WH0=r("assert").ok;tY1(u8,Xy);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;Xy.call(this,$)}u8.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,VH0.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=bq.resolve($._path,$.entries[$._index]);WH0(I!==$._path),WH0($.entries[$._index]),$._currentEntry=I,VH0[$.props.follow?"stat":"lstat"](I,function(U,Y){if(U)return $.error(U);var J=$._proxy||$;Y.path=I,Y.basename=bq.basename(I),Y.dirname=bq.dirname(I);var Q=$.getChildProps.call(J,Y);Q.path=I,Q.basename=bq.basename(I),Q.dirname=bq.dirname(I);var K=Xy(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 Ly=O((Hj1,LH0)=>{LH0.exports=l3;var aY1=m6(),sY1=p0(),ZH0=m3(),XH0={EOF:!0},zH0={CLOSE:!0};sY1(l3,ZH0);function l3($){var I=this;if(!(I instanceof l3))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,ZH0.call(I,$)}l3.prototype._getStream=function(){var $=this,I=$._stream=aY1.createReadStream($._path,$.pro Line truncated
expect: `+$.props.size+`
actual: `+$._bytesEmitted)}),I.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(XG0),$._read();else $.emit("close")}),I.on("error",function(q){$.emit("error",q)}),$._read()};r3.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var I=$._buffer;for(var q=0,U=I.length;q<U;q++){var Y=I[q];if(Y===ZG0)$.emit("end");else if(Y===XG0)$.emit("close");else $.emit("data",Y);if($._paused){$._buffer=I.slice(q);return}}$._buffer.length=0}};r3.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._stream)I._stream.pause();I.emit("pause",$)};r3.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 NG0=L((QC1,LG0)=>{LG0.exports=RD;var NQ1=n0(),OG0=o3();NQ1(RD,OG0);function RD($){var I=this;if(!(I instanceof RD))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);OG0.call(I,$)}RD.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Gy=L((KC1,FG0)=>{FG0.exports=t3;var wy=o3(),FQ1=iK(),MQ1=n0(),AQ1=l6();MQ1(t3,wy);function t3($){var I=this;if(!(I instanceof t3))throw Error("ProxyReader must be called as constructor.");I.props=$,I._buffer=[],I.ready=!1,wy.call(I,$)}t3.prototype._stat=function(){var $=this,I=$.props,q=I.follow?"stat":"lstat";AQ1[q](I.path,function(U,Y){var J;if(U||!Y)J="File";else J=FQ1(Y);I[J]=!0,I.type=$.type=J,$._old=Y,$._addProxy(wy(I,Y))})};t3.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(U){$.on(U,I.emit.bind(I,U))}),I.emit("proxy",$),$.on("ready",function(){I.ready=!0,I.emit("ready")});var q=I._buffer;I._buffer.length=0,q.forEach(function(U){$[U[0]].apply($,U[1])})};t3.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};t3.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var o3=L((zC1,gG0)=>{gG0.exports=I8;var gQ1=l6(),PQ1=o("stream").Stream,TQ1=n0(),Hy=o("path"),Vy=iK(),CD=I8.hardLinks={},MG0=vD();TQ1(I8,MG0);var AG0=Jy();function I8($,I){var q=this;if(!(q instanceof I8))return new I8($,I);if(typeof $==="string")$={path:$};var U,Y;if($.type&&typeof $.type==="function")U=$.type,Y=U;else U=Vy($),Y=I8;if(I&&!U)U=Vy(I),$[U]=!0,$.type=U;switch(U){case"Directory":Y=Ky();break;case"Link":case"File":Y=zy();break;case"SymbolicLink":Y=AG0;break;case"Socket":Y=NG0();break;case null:Y=Gy();break}if(!(q instanceof Y))return new Y($);if(MG0.call(q),!$.path)q.error("Must provide a path",null,!0);if(q.readable=!0,q.writable=!1,q.type=U,q.props=$,q.depth=$.depth=$.depth||0,q.parent=$.parent||null,q.root=$.root||$.parent&&$.parent.root||q,q._path=q.path=Hy.resolve($.path),process.platform==="win32"){if(q.path=q._path=q.path.replace(/\?/g,"_"),q._path.length>=260)q._swallowErrors=!0,q._path="\\\\?\\"+q.path.replace(/\//g,"\\")}if(q.basename=$.basename=Hy.basename(q.path),q.dirname=$.dirname=Hy.dirname(q.path),$.parent=$.root=null,q.size=$.size,q.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=jQ1;q._stat(I)}function jQ1($,I){return $===I?0:$.toLowerCase()>I.toLowerCase()?1:$.toLowerCase()<I.toLowerCase()?-1:$>I?1:-1}I8.prototype._stat=function($){var I=this,q=I.props,U=q.follow?"stat":"lstat";if($)process.nextTick(Y.bind(null,null,$));else gQ1[U](I._path,Y);function Y(J,Q){if(J)return I.error(J);if(Object.keys(Q).forEach(function(V){q[V]=Q[V]}),I.size!==void 0&&q.size!==I.size)return I.error("incorrect size");I.size=q.size;var K=Vy(q),z=q.hardlinks!==!1;if(z&&K!=="Directory"&&q.nlink&&q.nlink>1){var w=q.dev+":"+q.ino;if(CD[w]===I._path||!CD[w])CD[w]=I._path;else K=I.type=I.props.type="Link",I.Link=I.props.Link=!0,I.linkpath=I.props.linkpath=CD[w],I._stat=I._read=AG0.prototype._read}if(I.type&&I.type!==K)I.error("Unexpected type: "+K);if(I.filter){var G=I._proxy||I;if(!I.filter.call(G,G,q)){if(!I._disowned)I.abort(),I.emit("end"),I.emit("close");return}}var H=["_stat","stat","ready"],W=0;(function V(){if(I._aborted){I.emit("end"),I.emit("close");return}if(I._paused&&I.type!=="Directory"){I.once("resume",V);return}var X=H[W++];if(!X)return I._read();I.emit(X,q),V()})()}};I8.prototype.pipe=function($){var I=this;if(typeof $.add==="function")I.on("entry",function(q){var U=$.add(q);if(U===!1)I.pause()});return PQ1.prototype.pipe.apply(this,arguments)};I8.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};I8.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};I8.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var Dy=L((wC1,CG0)=>{C Line truncated
actual: `+$._bytesEmitted)}),I.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(zH0),$._read();else $.emit("close")}),I.on("error",function(U){$.emit("error",U)}),$._read()};l3.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===XH0)$.emit("end");else if(J===zH0)$.emit("close");else $.emit("data",J);if($._paused){$._buffer=I.slice(U);return}}$._buffer.length=0}};l3.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._stream)I._stream.pause();I.emit("pause",$)};l3.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 FH0=O((Wj1,OH0)=>{OH0.exports=WL;var eY1=p0(),DH0=m3();eY1(WL,DH0);function WL($){var I=this;if(!(I instanceof WL))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);DH0.call(I,$)}WL.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Oy=O((Vj1,NH0)=>{NH0.exports=o3;var Dy=m3(),$J1=uq(),IJ1=p0(),UJ1=m6();IJ1(o3,Dy);function o3($){var I=this;if(!(I instanceof o3))throw Error("ProxyReader must be called as constructor.");I.props=$,I._buffer=[],I.ready=!1,Dy.call(I,$)}o3.prototype._stat=function(){var $=this,I=$.props,U=I.follow?"stat":"lstat";UJ1[U](I.path,function(Y,J){var Q;if(Y||!J)Q="File";else Q=$J1(J);I[Q]=!0,I.type=$.type=Q,$._old=J,$._addProxy(Dy(I,J))})};o3.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])})};o3.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};o3.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var m3=O((wj1,PH0)=>{PH0.exports=Q8;var YJ1=m6(),JJ1=r("stream").Stream,QJ1=p0(),Fy=r("path"),Ny=uq(),VL=Q8.hardLinks={},MH0=HL();QJ1(Q8,MH0);var AH0=Zy();function Q8($,I){var U=this;if(!(U instanceof Q8))return new Q8($,I);if(typeof $==="string")$={path:$};var Y,J;if($.type&&typeof $.type==="function")Y=$.type,J=Y;else Y=Ny($),J=Q8;if(I&&!Y)Y=Ny(I),$[Y]=!0,$.type=Y;switch(Y){case"Directory":J=zy();break;case"Link":case"File":J=Ly();break;case"SymbolicLink":J=AH0;break;case"Socket":J=FH0();break;case null:J=Oy();break}if(!(U instanceof J))return new J($);if(MH0.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=Fy.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=Fy.basename(U.path),U.dirname=$.dirname=Fy.dirname(U.path),$.parent=$.root=null,U.size=$.size,U.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=KJ1;U._stat(I)}function KJ1($,I){return $===I?0:$.toLowerCase()>I.toLowerCase()?1:$.toLowerCase()<I.toLowerCase()?-1:$>I?1:-1}Q8.prototype._stat=function($){var I=this,U=I.props,Y=U.follow?"stat":"lstat";if($)process.nextTick(J.bind(null,null,$));else YJ1[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=Ny(U),G=U.hardlinks!==!1;if(G&&q!=="Directory"&&U.nlink&&U.nlink>1){var H=U.dev+":"+U.ino;if(VL[H]===I._path||!VL[H])VL[H]=I._path;else q=I.type=I.props.type="Link",I.Link=I.props.Link=!0,I.linkpath=I.props.linkpath=VL[H],I._stat=I._read=AH0.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"],w=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 z=V[w++];if(!z)return I._read();I.emit(z,U),Z()})()}};Q8.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 JJ1.prototype.pipe.apply(this,arguments)};Q8.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};Q8.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};Q8.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var Ty=O((Zj1,_H0)=>{_ Line truncated
expect: `+$.size+`
actual: `+$._bytesWritten);iD.prototype._finish.call($)}});var Ey=L((EC1,FH0)=>{FH0.exports=G7;var jy=VY(),eQ1=iK(),$21=n0(),I21=nD(),q21=o("fs");$21(G7,jy);function G7($){var I=this;if(!(I instanceof G7))throw Error("ProxyWriter must be called as constructor.");I.props=$,I._needDrain=!1,jy.call(I,$)}G7.prototype._stat=function(){var $=this,I=$.props,q=I.follow?"stat":"lstat";q21[q](I.path,function(U,Y){var J;if(U||!Y)J="File";else J=eQ1(Y);I[J]=!0,I.type=$.type=J,$._old=Y,$._addProxy(jy(I,Y))})};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(U){$.on(U,I.emit.bind(I,U))}),I.emit("proxy",$);var q=I._buffer;if(q.forEach(function(U){$[U[0]].apply($,U[1])}),I._buffer.length=0,I._needsDrain)I.emit("drain")};G7.prototype.add=function($){if(I21($),!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 VY=L((BC1,vH0)=>{vH0.exports=C$;var R$=l6(),U21=n0(),Y21=Dy(),J21=My(),oK=o("path"),AH0=process.platform==="win32"?0:process.umask(),gH0=iK(),PH0=vD();U21(C$,PH0);C$.dirmode=parseInt("0777",8)&~AH0;C$.filemode=parseInt("0666",8)&~AH0;var Q21=gy(),K21=Py(),z21=Ty(),w21=Ey();function C$($,I){var q=this;if(typeof $==="string")$={path:$};var U=gH0($),Y=C$;switch(U){case"Directory":Y=Q21;break;case"File":Y=z21;break;case"Link":case"SymbolicLink":Y=K21;break;case null:default:Y=w21;break}if(!(q instanceof Y))return new Y($);if(PH0.call(q),!$.path)q.error("Must provide a path",null,!0);if(q.type=$.type,q.props=$,q.depth=$.depth||0,q.clobber=$.clobber===!1?$.clobber:!0,q.parent=$.parent||null,q.root=$.root||$.parent&&$.parent.root||q,q._path=q.path=oK.resolve($.path),process.platform==="win32"){if(q.path=q._path=q.path.replace(/\?/g,"_"),q._path.length>=260)q._swallowErrors=!0,q._path="\\\\?\\"+q.path.replace(/\//g,"\\")}if(q.basename=oK.basename($.path),q.dirname=oK.dirname($.path),q.linkpath=$.linkpath||null,$.parent=$.root=null,q.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);q.readable=!1,q.writable=!0,q._buffer=[],q.ready=!1,q.filter=typeof $.filter==="function"?$.filter:null,q._stat(I)}C$.prototype._create=function(){var $=this;R$[$.props.follow?"stat":"lstat"]($._path,function(I){if(I)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};C$.prototype._stat=function($){var I=this,q=I.props,U=q.follow?"stat":"lstat",Y=I._proxy||I;if($)J(null,$);else R$[U](I._path,J);function J(Q,K){if(I.filter&&!I.filter.call(Y,Y,K)){I._aborted=!0,I.emit("end"),I.emit("close");return}if(Q||!K)return By(I);I._old=K;var z=gH0(K);if(z!==I.type||I.type==="File"&&K.nlink>1)return Y21(I._path,function(w){if(w)return I.error(w);I._old=null,By(I)});By(I)}};function By($){J21(oK.dirname($._path),C$.dirmode,function(I,q){if(I)return $.error(I);return $._madeDir=q,$._create()})}function TH0($,I,q,U,Y){var J=I.mode,Q=I.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!R$[Q])return Y();if(typeof J!=="number")return Y();var K=q.mode&parseInt("0777",8);if(J=J&parseInt("0777",8),J===K)return Y();R$[Q](U,J,Y)}function jH0($,I,q,U,Y){if(process.platform==="win32")return Y();if(!process.getuid||process.getuid()!==0)return Y();if(typeof I.uid!=="number"&&typeof I.gid!=="number")return Y();if(q.uid===I.uid&&q.gid===I.gid)return Y();var J=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!R$[J])return Y();if(typeof I.uid!=="number")I.uid=q.uid;if(typeof I.gid!=="number")I.gid=q.gid;R$[J](U,I.uid,I.gid,Y)}function EH0($,I,q,U,Y){if(!R$.utimes||process.platform==="win32")return Y();var J=I.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(J==="lutimes"&&!R$[J])J="utimes";if(!R$[J])return Y();var{atime:Q,mtime:K}=q,z=I.atime,w=I.mtime;if(z===void 0)z=Q;if(w===void 0)w=K;if(!MH0(z))z=new Date(z);if(!MH0(w))z=new Date(w);if(z.getTime()===Q.getTime()&&w.getTime()===K.getTime())return Y();R$[J](U,z,w,Y)}C$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var I=0,q=null,U=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),J($._old);else{var Y=$.props.follow?"stat":"lstat";R$[Y]($._path,function(K,z){if(K)if(K.code==="ENOENT"&&($.type==="Link"||$.type==="SymbolicLink")&&process.platform==="win32"){$.ready=!0,$.emit("ready"),$.emit("end"),$.emit("close"),$.end=$._finish=function(){};return}else return $.error(K);J($._old=z)})}return;function J(K){I+=3,TH0($,$.props,K,$._path,Q("chmod")),jH0($,$.props,K,$._path,Q("chown")),EH0($,$.props,K,$._path,Q("utimes"))}function Q(K){return function(z){if(q)return;if(z)return z.fstream_finish_call=K,$.error(q=z);if(--I>0)return;if(U)return;if(U=!0,!$._madeDir)return w();else BH0($,$._path,w);function w(G){if(G)return G.fstream_finish_call="setupMadeDir",$.error(G);$.emit("end"),$.emit("close")}}}};function BH0($,I,q){var U=$._madeDir,Y=oK.dirname(I);G21($,Y,function(J){if(J)return q(J);if(Y===U)return q();BH0($,Y,q)})}function G21($,I,q){var U={};Object.keys($.props).forEach(function(K){if(U[K]=$.props[K],K==="mode"&&$.type!=="Directory")U[K]=U[K]|parseInt("0111",8)});var Y=3,J=null;R$.stat(I,function(K,z){if(K)return q(J=K);TH0($,U,z,I,Q),jH0($,U,z,I,Q),EH0($,U,z,I,Q)});function Q(K){if(J)return;if(K)return q(J=K);if(--Y===0)return q()}}C$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};C$.prototype.add=function(){this.error("Can't add to non-Directory type")};C$.prototype.write=function(){return!0};function H21($){return Object.prototype.toString.call($)}function MH0($){return typeof $==="object"&&H21($)==="[object Date]"}});var hy=L((V21)=>{V21.Abstract=vD();V21.Reader=o3();V21.Writer=VY();V21.File={Reader:zy(),Writer:Ty()};V21.Dir={Reader:Ky(),Writer:gy()};V21.Link={Reader:Jy(),Writer:Py()};V21.Proxy={Reader:Gy(),Writer:Ey()};V21.Reader.Dir=V21.DirReader=V21.Dir.Reader;V21.Reader.File=V21.FileReader=V21.File.Reader;V21.Reader.Link=V21.LinkReader=V21.Link.Reader;V21.Reader.Proxy=V21.ProxyReader=V21.Proxy.Reader;V21.Writer.Dir=V21.DirWriter=V21.Dir.Writer;V21.Writer.File=V21.FileWriter=V21.File.Writer;V21.Writer.Link=V21.LinkWriter=V21.Link.Writer;V21.Writer.Proxy=V21.ProxyWriter=V21.Proxy.Writer;V21.collect=nD()});var CH0=L((kC1,RH0)=>{RH0.exports=F21;var X21=FD(),D21=hy().Writer,Sy=o("path"),O21=o("stream"),L21=qy(),N21=U7();function F21($){$.path=Sy.resolve(Sy.normalize($.path));var I=new X21($),q=new O21.Writable({objectMode:!0});q._write=function(Y,J,Q){if(Y.type=="Directory")return Q();var K=Sy.join($.path,Y.path);if(K.indexOf($.path)!=0)return Q();let z=$.getWriter?$.getWriter({path:K}):D21({path:K});Y.pipe(z).on("error",Q).on("close",Q)};var U=L21(I,q);return I.once("crx-header",function(Y){U.crxHeader=Y}),I.pipe(q).on("finish",function(){U.emit("close")}),U.promise=function(){return new N21(function(Y,J){U.on("close",Y),U.on("error",J)})},U}});var _H0=L((fC1,pD)=>{var S4=function($){var I=1e7,q=7,U=9007199254740992,Y=W(U),J="0123456789abcdefghijklmnopqrstuvwxyz",Q=typeof BigInt==="function";function K(F,M,v,y){if(typeof F>"u")return K[0];if(typeof M<"u")return+M===10&&!v?g0(F):h$(F,M,v,y);return g0(F)}function z(F,M){this.value=F,this.sign=M,this.isSmall=!1}z.prototype=Object.create(K.prototype);function w(F){this.value=F,this.sign=F<0,this.isSmall=!0}w.prototype=Object.create(K.prototype);function G(F){th Line truncated
actual: `+$._bytesWritten);AL.prototype._finish.call($)}});var hy=O((_j1,NW0)=>{NW0.exports=w7;var yy=HJ(),gJ1=uq(),yJ1=p0(),hJ1=NL(),xJ1=r("fs");yJ1(w7,yy);function w7($){var I=this;if(!(I instanceof w7))throw Error("ProxyWriter must be called as constructor.");I.props=$,I._needDrain=!1,yy.call(I,$)}w7.prototype._stat=function(){var $=this,I=$.props,U=I.follow?"stat":"lstat";xJ1[U](I.path,function(Y,J){var Q;if(Y||!J)Q="File";else Q=gJ1(J);I[Q]=!0,I.type=$.type=Q,$._old=J,$._addProxy(yy(I,J))})};w7.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")};w7.prototype.add=function($){if(hJ1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};w7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};w7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var HJ=O((Sj1,CW0)=>{CW0.exports=S$;var _$=m6(),kJ1=p0(),uJ1=Ty(),fJ1=Cy(),cq=r("path"),AW0=process.platform==="win32"?0:process.umask(),PW0=uq(),TW0=HL();kJ1(S$,TW0);S$.dirmode=parseInt("0777",8)&~AW0;S$.filemode=parseInt("0666",8)&~AW0;var bJ1=_y(),iJ1=Sy(),nJ1=gy(),pJ1=hy();function S$($,I){var U=this;if(typeof $==="string")$={path:$};var Y=PW0($),J=S$;switch(Y){case"Directory":J=bJ1;break;case"File":J=nJ1;break;case"Link":case"SymbolicLink":J=iJ1;break;case null:default:J=pJ1;break}if(!(U instanceof J))return new J($);if(TW0.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=cq.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=cq.basename($.path),U.dirname=cq.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)}S$.prototype._create=function(){var $=this;_$[$.props.follow?"stat":"lstat"]($._path,function(I){if(I)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};S$.prototype._stat=function($){var I=this,U=I.props,Y=U.follow?"stat":"lstat",J=I._proxy||I;if($)Q(null,$);else _$[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 xy(I);I._old=q;var G=PW0(q);if(G!==I.type||I.type==="File"&&q.nlink>1)return uJ1(I._path,function(H){if(H)return I.error(H);I._old=null,xy(I)});xy(I)}};function xy($){fJ1(cq.dirname($._path),S$.dirmode,function(I,U){if(I)return $.error(I);return $._madeDir=U,$._create()})}function EW0($,I,U,Y,J){var Q=I.mode,K=I.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!_$[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();_$[K](Y,Q,J)}function BW0($,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(!_$[Q])return J();if(typeof I.uid!=="number")I.uid=U.uid;if(typeof I.gid!=="number")I.gid=U.gid;_$[Q](Y,I.uid,I.gid,J)}function vW0($,I,U,Y,J){if(!_$.utimes||process.platform==="win32")return J();var Q=I.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(Q==="lutimes"&&!_$[Q])Q="utimes";if(!_$[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(!MW0(G))G=new Date(G);if(!MW0(H))G=new Date(H);if(G.getTime()===K.getTime()&&H.getTime()===q.getTime())return J();_$[Q](Y,G,H,J)}S$.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]($._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,EW0($,$.props,q,$._path,K("chmod")),BW0($,$.props,q,$._path,K("chown")),vW0($,$.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 RW0($,$._path,H);function H(W){if(W)return W.fstream_finish_call="setupMadeDir",$.error(W);$.emit("end"),$.emit("close")}}}};function RW0($,I,U){var Y=$._madeDir,J=cq.dirname(I);cJ1($,J,function(Q){if(Q)return U(Q);if(J===Y)return U();RW0($,J,U)})}function cJ1($,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;_$.stat(I,function(q,G){if(q)return U(Q=q);EW0($,Y,G,I,K),BW0($,Y,G,I,K),vW0($,Y,G,I,K)});function K(q){if(Q)return;if(q)return U(Q=q);if(--J===0)return U()}}S$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};S$.prototype.add=function(){this.error("Can't add to non-Directory type")};S$.prototype.write=function(){return!0};function dJ1($){return Object.prototype.toString.call($)}function MW0($){return typeof $==="object"&&dJ1($)==="[object Date]"}});var iy=O((mJ1)=>{mJ1.Abstract=HL();mJ1.Reader=m3();mJ1.Writer=HJ();mJ1.File={Reader:Ly(),Writer:gy()};mJ1.Dir={Reader:zy(),Writer:_y()};mJ1.Link={Reader:Zy(),Writer:Sy()};mJ1.Proxy={Reader:Oy(),Writer:hy()};mJ1.Reader.Dir=mJ1.DirReader=mJ1.Dir.Reader;mJ1.Reader.File=mJ1.FileReader=mJ1.File.Reader;mJ1.Reader.Link=mJ1.LinkReader=mJ1.Link.Reader;mJ1.Reader.Proxy=mJ1.ProxyReader=mJ1.Proxy.Reader;mJ1.Writer.Dir=mJ1.DirWriter=mJ1.Dir.Writer;mJ1.Writer.File=mJ1.FileWriter=mJ1.File.Writer;mJ1.Writer.Link=mJ1.LinkWriter=mJ1.Link.Writer;mJ1.Writer.Proxy=mJ1.ProxyWriter=mJ1.Proxy.Writer;mJ1.collect=NL()});var _W0=O((nj1,jW0)=>{jW0.exports=$Q1;var rJ1=$L(),tJ1=iy().Writer,ny=r("path"),aJ1=r("stream"),sJ1=Wy(),eJ1=Q7();function $Q1($){$.path=ny.resolve(ny.normalize($.path));var I=new rJ1($),U=new aJ1.Writable({objectMode:!0});U._write=function(J,Q,K){if(J.type=="Directory")return K();var q=ny.join($.path,J.path);if(q.indexOf($.path)!=0)return K();let G=$.getWriter?$.getWriter({path:q}):tJ1({path:q});J.pipe(G).on("error",K).on("close",K)};var Y=sJ1(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 eJ1(function(J,Q){Y.on("close",J),Y.on("error",Q)})},Y}});var SW0=O((pj1,PL)=>{var h4=function($){var I=1e7,U=7,Y=9007199254740992,J=w(Y),Q="0123456789abcdefghijklmnopqrstuvwxyz",K=typeof BigInt==="function";function q(N,M,j,x){if(typeof N>"u")return q[0];if(typeof M<"u")return+M===10&&!j?E0(N):u$(N,M,j,x);return E0(N)}function G(N,M){this.value=N,this.sign=M,this.isSmall=!1}G.prototype=Object.create(q.prototype);function H(N){this.value=N,this.sign=N<0,this.isSmall=!0}H.prototype=Object.create(q.prototype);function W(N){th Line truncated
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/var u1=o("fs"),rD=o("os"),y4=o("path"),dH0=o("crypto"),b8={fs:u1.constants,os:rD.constants},rH0=/XXXXXX/,tH0=(b8.O_CREAT||b8.fs.O_CREAT)|(b8.O_EXCL||b8.fs.O_EXCL)|(b8.O_RDWR||b8.fs.O_RDWR),c21=rD.platform()==="win32",d21=b8.EBADF||b8.os.errno.EBADF,l21=b8.ENOENT||b8.os.errno.ENOENT,ZY=[],aH0=u1.rmdirSync.bind(u1),sH0=!1;function m21($,I){return u1.rm($,{recursive:!0},I)}function eH0($){return u1.rmSync($,{recursive:!0})}function fy($,I){let q=XY($,I),U=q[0],Y=q[1];UK1(U,function(J,Q){if(J)return Y(J);let K=Q.tries;(function z(){try{let w=IV0(Q);u1.stat(w,function(G){if(!G){if(K-- >0)return z();return Y(Error("Could not get a unique tmp filename, max tries reached "+w))}Y(null,w)})}catch(w){Y(w)}})()})}function ny($){let I=XY($),q=I[0],U=YK1(q),Y=U.tries;do{let J=IV0(U);try{u1.statSync(J)}catch(Q){return J}}while(Y-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function o21($,I){let q=XY($,I),U=q[0],Y=q[1];fy(U,function(Q,K){if(Q)return Y(Q);u1.open(K,tH0,U.mode||384,function(w,G){if(w)return Y(w);if(U.discardDescriptor)return u1.close(G,function(W){return Y(W,K,void 0,xy(K,-1,U,!1))});else{let H=U.discardDescriptor||U.detachDescriptor;Y(null,K,G,xy(K,H?-1:G,U,!1))}})})}function r21($){let I=XY($),q=I[0],U=q.discardDescriptor||q.detachDescriptor,Y=ny(q),J=u1.openSync(Y,tH0,q.mode||384);if(q.discardDescriptor)u1.closeSync(J),J=void 0;return{name:Y,fd:J,removeCallback:xy(Y,U?-1:J,q,!0)}}function t21($,I){let q=XY($,I),U=q[0],Y=q[1];fy(U,function(Q,K){if(Q)return Y(Q);u1.mkdir(K,U.mode||448,function(w){if(w)return Y(w);Y(null,K,$V0(K,U,!1))})})}function a21($){let I=XY($),q=I[0],U=ny(q);return u1.mkdirSync(U,q.mode||448),{name:U,removeCallback:$V0(U,q,!0)}}function s21($,I){let q=function(U){if(U&&!ky(U))return I(U);I()};if(0<=$[0])u1.close($[0],function(){u1.unlink($[1],q)});else u1.unlink($[1],q)}function e21($){let I=null;try{if(0<=$[0])u1.closeSync($[0])}catch(q){if(!JK1(q)&&!ky(q))throw q}finally{try{u1.unlinkSync($[1])}catch(q){if(!ky(q))I=q}}if(I!==null)throw I}function xy($,I,q,U){let Y=oD(e21,[I,$],U),J=oD(s21,[I,$],U,Y);if(!q.keep)ZY.unshift(Y);return U?Y:J}function $V0($,I,q){let U=I.unsafeCleanup?m21:u1.rmdir.bind(u1),Y=I.unsafeCleanup?eH0:aH0,J=oD(Y,$,q),Q=oD(U,$,q,J);if(!I.keep)ZY.unshift(J);return q?J:Q}function oD($,I,q,U){let Y=!1;return function J(Q){if(!Y){let K=U||J,z=ZY.indexOf(K);if(z>=0)ZY.splice(z,1);if(Y=!0,q||$===aH0||$===eH0)return $(I);else return $(I,Q||function(){})}}}function $K1(){if(!sH0)return;while(ZY.length)try{ZY[0]()}catch($){}}function lH0($){let I=[],q=null;try{q=dH0.randomBytes($)}catch(U){q=dH0.pseudoRandomBytes($)}for(let U=0;U<$;U++)I.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[q[U]%62]);return I.join("")}function o6($){return typeof $>"u"}function XY($,I){if(typeof $==="function")return[{},$];if(o6($))return[{},I];let q={};for(let U of Object.getOwnPropertyNames($))q[U]=$[U];return[q,I]}function IK1($,I,q){let U=y4.isAbsolute($)?$:y4.join(I,$);u1.stat(U,function(Y){if(Y)u1.realpath(y4.dirname(U),function(J,Q){if(J)return q(J);q(null,y4.join(Q,y4.basename(U)))});else u1.realpath(U,q)})}function qK1($,I){let q=y4.isAbsolute($)?$:y4.join(I,$);try{return u1.statSync(q),u1.realpathSync(q)}catch(U){let Y=u1.realpathSync(y4.dirname(q));return y4.join(Y,y4.basename(q))}}function IV0($){let I=$.tmpdir;if(!o6($.name))return y4.join(I,$.dir,$.name);if(!o6($.template))return y4.join(I,$.dir,$.template).replace(rH0,lH0(6));let q=[$.prefix?$.prefix:"tmp","-",process.pid,"-",lH0(12),$.postfix?"-"+$.postfix:""].join("");return y4.join(I,$.dir,q)}function uy($,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 qV0($){if(!o6($.name)){let I=$.name;if(y4.isAbsolute(I))throw Error(`name option must not contain an absolute path, found "${I}".`);let q=y4.basename(I);if(q===".."||q==="."||q!==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(rH0))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)?"":uy("prefix",$.prefix),$.postfix=o6($.postfix)?"":uy("postfix",$.postfix),$.template=o6($.template)?void 0:uy("template",$.template)}function mH0($,I,q,U){if(o6(I))return U(null);IK1(I,q,function(Y,J){if(Y)return U(Y);let Q=y4.relative(q,J);if(Q.startsWith("..")||y4.isAbsolute(Q))return U(Error(`${$} option must be relative to "${q}", found "${Q}".`));U(null,Q)})}function oH0($,I,q){if(o6(I))return;let U=qK1(I,q),Y=y4.relative(q,U);if(Y.startsWith("..")||y4.isAbsolute(Y))throw ELine truncated
`)}var wI=($)=>(I,q,U,Y)=>{let J=U?{...U,async:!1}:{async:!1},Q=I._zod.run({value:q,issues:[]},J);if(Q instanceof Promise)throw new U8;if(Q.issues.length){let K=new(Y?.Err??$)(Q.issues.map((z)=>M6(z,J,V4())));throw pz(K,Y?.callee),K}return Q.value},nY=wI(S6),GI=($)=>async(I,q,U,Y)=>{let J=U?{...U,async:!0}:{async:!0},Q=I._zod.run({value:q,issues:[]},J);if(Q instanceof Promise)Q=await Q;if(Q.issues.length){let K=new(Y?.Err??$)(Q.issues.map((z)=>M6(z,J,V4())));throw pz(K,Y?.callee),K}return Q.value},bY=GI(S6),HI=($)=>(I,q,U)=>{let Y=U?{...U,async:!1}:{async:!1},J=I._zod.run({value:q,issues:[]},Y);if(J instanceof Promise)throw new U8;return J.issues.length?{success:!1,error:new($??xY)(J.issues.map((Q)=>M6(Q,Y,V4())))}:{success:!0,data:J.value}},VI=HI(S6),WI=($)=>async(I,q,U)=>{let Y=U?{...U,async:!0}:{async:!0},J=I._zod.run({value:q,issues:[]},Y);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((Q)=>M6(Q,Y,V4())))}:{success:!0,data:J.value}},iY=WI(S6),cz=($)=>(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return wI($)(I,q,Y)},Nx=cz(S6),dz=($)=>(I,q,U)=>{return wI($)(I,q,U)},Fx=dz(S6),lz=($)=>async(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return GI($)(I,q,Y)},Mx=lz(S6),mz=($)=>async(I,q,U)=>{return GI($)(I,q,U)},Ax=mz(S6),oz=($)=>(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return HI($)(I,q,Y)},gx=oz(S6),rz=($)=>(I,q,U)=>{return HI($)(I,q,U)},Px=rz(S6),tz=($)=>async(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return WI($)(I,q,Y)},Tx=tz(S6),az=($)=>async(I,q,U)=>{return WI($)(I,q,U)},jx=az(S6);var s6={};d8(s6,{xid:()=>rO,uuid7:()=>bD0,uuid6:()=>nD0,uuid4:()=>fD0,uuid:()=>A7,uppercase:()=>FL,unicodeEmail:()=>Ex,undefined:()=>LL,ulid:()=>oO,time:()=>HL,string:()=>WL,sha512_hex:()=>zO0,sha512_base64url:()=>GO0,sha512_base64:()=>wO0,sha384_hex:()=>JO0,sha384_base64url:()=>KO0,sha384_base64:()=>QO0,sha256_hex:()=>qO0,sha256_base64url:()=>YO0,sha256_base64:()=>UO0,sha1_hex:()=>eD0,sha1_base64url:()=>IO0,sha1_base64:()=>$O0,rfc5322Email:()=>pD0,number:()=>pY,null:()=>OL,nanoid:()=>aO,md5_hex:()=>tD0,md5_base64url:()=>sD0,md5_base64:()=>aD0,mac:()=>YL,lowercase:()=>NL,ksuid:()=>tO,ipv6:()=>UL,ipv4:()=>qL,integer:()=>XL,idnEmail:()=>cD0,httpProtocol:()=>zL,html5Email:()=>iD0,hostname:()=>mD0,hex:()=>rD0,guid:()=>eO,extendedDuration:()=>kD0,emoji:()=>IL,email:()=>$L,e164:()=>wL,duration:()=>sO,domain:()=>oD0,datetime:()=>VL,date:()=>GL,cuid2:()=>mO,cuid:()=>lO,cidrv6:()=>QL,cidrv4:()=>JL,browserEmail:()=>dD0,boolean:()=>DL,bigint:()=>ZL,base64url:()=>sz,base64:()=>KL});var lO=/^[cC][0-9a-z]{6,}$/,mO=/^[0-9a-z]+$/,oO=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,rO=/^[0-9a-vA-V]{20}$/,tO=/^[A-Za-z0-9]{27}$/,aO=/^[a-zA-Z0-9_-]{21}$/,sO=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,kD0=/^[-+]?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)?)??$/,eO=/^([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})$/,A7=($)=>{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})$`)},fD0=A7(4),nD0=A7(6),bD0=A7(7),$L=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iD0=/^[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])?)*$/,pD0=/^(([^<>()\[\]\\.,;:\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,}))$/,Ex=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,cD0=Ex,dD0=/^[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])?)*$/,lD0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function IL(){return new RegExp(lD0,"u")}var qL=/^(?:(?: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])$/,UL=/^(([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}|:))$/,YL=($)=>{let I=W$($??":");return new RegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},JL=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0Line truncated
`).filter((J)=>J),U=Math.min(...q.map((J)=>J.length-J.trimStart().length)),Y=q.map((J)=>J.slice(U)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Y)this.content.push(J)}compile(){let $=Function,I=this?.args,U=[...(this?.content??[""]).map((Y)=>` ${Y}`)];return new $(...I,U.join(`
`))}}var fL={major:4,minor:4,patch:3};var k0=m("$ZodType",($,I)=>{var q;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=fL;let U=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))U.unshift($);for(let Y of U)for(let J of Y._zod.onattach)J($);if(U.length===0)(q=$._zod).deferred??(q.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let Y=(Q,K,z)=>{let w=o5(Q),G;for(let H of K){if(H._zod.def.when){if(pO(Q))continue;if(!H._zod.def.when(Q))continue}else if(w)continue;let W=Q.issues.length,V=H._zod.check(Q);if(V instanceof Promise&&z?.async===!1)throw new U8;if(G||V instanceof Promise)G=(G??Promise.resolve()).then(async()=>{if(await V,Q.issues.length===W)return;if(!w)w=o5(Q,W)});else{if(Q.issues.length===W)continue;if(!w)w=o5(Q,W)}}if(G)return G.then(()=>{return Q});return Q},J=(Q,K,z)=>{if(o5(Q))return Q.aborted=!0,Q;let w=Y(K,U,z);if(w instanceof Promise){if(z.async===!1)throw new U8;return w.then((G)=>$._zod.parse(G,z))}return $._zod.parse(w,z)};$._zod.run=(Q,K)=>{if(K.skipChecks)return $._zod.parse(Q,K);if(K.direction==="backward"){let w=$._zod.parse({value:Q.value,issues:[]},{...K,skipChecks:!0});if(w instanceof Promise)return w.then((G)=>{return J(G,Q,K)});return J(w,Q,K)}let z=$._zod.parse(Q,K);if(z instanceof Promise){if(K.async===!1)throw new U8;return z.then((w)=>Y(w,U,K))}return Y(z,U,K)}}r0($,"~standard",()=>({validate:(Y)=>{try{let J=VI($,Y);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return iY($,Y).then((Q)=>Q.success?{value:Q.data}:{issues:Q.error?.issues})}},vendor:"zod",version:1}))}),g7=m("$ZodString",($,I)=>{k0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??WL($._zod.bag),$._zod.parse=(q,U)=>{if(I.coerce)try{q.value=String(q.value)}catch(Y){}if(typeof q.value==="string")return q;return q.issues.push({expected:"string",code:"invalid_type",input:q.value,inst:$}),q}}),_1=m("$ZodStringFormat",($,I)=>{ZI.init($,I),g7.init($,I)}),bL=m("$ZodGUID",($,I)=>{I.pattern??(I.pattern=eO),_1.init($,I)}),iL=m("$ZodUUID",($,I)=>{if(I.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(U===void 0)throw Error(`Invalid UUID version: "${I.version}"`);I.pattern??(I.pattern=A7(U))}else I.pattern??(I.pattern=A7());_1.init($,I)}),pL=m("$ZodEmail",($,I)=>{I.pattern??(I.pattern=$L),_1.init($,I)}),cL=m("$ZodURL",($,I)=>{_1.init($,I),$._zod.check=(q)=>{try{let U=q.value.trim();if(!I.normalize&&I.protocol?.source===zL.source){if(!/^https?:\/\//i.test(U)){q.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:q.value,inst:$,continue:!I.abort});return}}let Y=new URL(U);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(Y.hostname))q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:q.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(Y.protocol.endsWith(":")?Y.protocol.slice(0,-1):Y.protocol))q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:q.value,inst:$,continue:!I.abort})}if(I.normalize)q.value=Y.href;else q.value=U;return}catch(U){q.issues.push({code:"invalid_format",format:"url",input:q.value,inst:$,continue:!I.abort})}}}),dL=m("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=IL()),_1.init($,I)}),lL=m("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=aO),_1.init($,I)}),mL=m("$ZodCUID",($,I)=>{I.pattern??(I.pattern=lO),_1.init($,I)}),oL=m("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=mO),_1.init($,I)}),rL=m("$ZodULID",($,I)=>{I.pattern??(I.pattern=oO),_1.init($,I)}),tL=m("$ZodXID",($,I)=>{I.pattern??(I.pattern=rO),_1.init($,I)}),aL=m("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=tO),_1.init($,I)}),sL=m("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=VL(I)),_1.init($,I)}),eL=m("$ZodISODate",($,I)=>{I.pattern??(I.pattern=GL),_1.init($,I)}),$N=m("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=HL(I)),_1.init($,I)}),IN=m("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=sO),_1.init($,I)}),qN=m("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=qL),_1.init($,I),$._zod.bag.format="ipv4"}),UN=m("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=UL),_1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(q)=>{try{new URL(`http://[${q.value}]`)}catch{q.issues.push({code:"invalid_format",format:"ipv6",input:q.value,inst:$,continue:!I.abort})}}}),YN=m("$ZodMAC",($,I)=>{I.pattern??(I.pattern=YL(I.delimiter)),_1.init($,I),$._zod.bag.format="mac"}),JN=m("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=JL),_1.init($,I)}),QN=m("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=QL),_1.init($,I),$._zod.check=(q)=>{let U=q.value.split("/");try{if(U.length!==2)throw Error();let[Y,J]=U;if(!J)throw Error();let Q=Number(J);if(`${Q}`!==J)throw Error();if(Q<0||Q>128)throw Error();new URL(`http://[${Y}]`)}catch{q.issues.push({code:"invalid_format",format:"cidrv6",input:q.value,inst:$,continue:!I.abort})}}});function KN($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}} Line truncated
if (${g}.issues.length) {
if (${B} in input) {
payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
*/var x1=r("fs"),CL=r("os"),x4=r("path"),dW0=r("crypto"),f8={fs:x1.constants,os:CL.constants},rW0=/XXXXXX/,tW0=(f8.O_CREAT||f8.fs.O_CREAT)|(f8.O_EXCL||f8.fs.O_EXCL)|(f8.O_RDWR||f8.fs.O_RDWR),TQ1=CL.platform()==="win32",EQ1=f8.EBADF||f8.os.errno.EBADF,BQ1=f8.ENOENT||f8.os.errno.ENOENT,VJ=[],aW0=x1.rmdirSync.bind(x1),sW0=!1;function vQ1($,I){return x1.rm($,{recursive:!0},I)}function eW0($){return x1.rmSync($,{recursive:!0})}function ly($,I){let U=wJ($,I),Y=U[0],J=U[1];kQ1(Y,function(Q,K){if(Q)return J(Q);let q=K.tries;(function G(){try{let H=IV0(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 oy($){let I=wJ($),U=I[0],Y=uQ1(U),J=Y.tries;do{let Q=IV0(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 RQ1($,I){let U=wJ($,I),Y=U[0],J=U[1];ly(Y,function(K,q){if(K)return J(K);x1.open(q,tW0,Y.mode||384,function(H,W){if(H)return J(H);if(Y.discardDescriptor)return x1.close(W,function(w){return J(w,q,void 0,dy(q,-1,Y,!1))});else{let V=Y.discardDescriptor||Y.detachDescriptor;J(null,q,W,dy(q,V?-1:W,Y,!1))}})})}function CQ1($){let I=wJ($),U=I[0],Y=U.discardDescriptor||U.detachDescriptor,J=oy(U),Q=x1.openSync(J,tW0,U.mode||384);if(U.discardDescriptor)x1.closeSync(Q),Q=void 0;return{name:J,fd:Q,removeCallback:dy(J,Y?-1:Q,U,!0)}}function jQ1($,I){let U=wJ($,I),Y=U[0],J=U[1];ly(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,$V0(q,Y,!1))})})}function _Q1($){let I=wJ($),U=I[0],Y=oy(U);return x1.mkdirSync(Y,U.mode||448),{name:Y,removeCallback:$V0(Y,U,!0)}}function SQ1($,I){let U=function(Y){if(Y&&!my(Y))return I(Y);I()};if(0<=$[0])x1.close($[0],function(){x1.unlink($[1],U)});else x1.unlink($[1],U)}function gQ1($){let I=null;try{if(0<=$[0])x1.closeSync($[0])}catch(U){if(!fQ1(U)&&!my(U))throw U}finally{try{x1.unlinkSync($[1])}catch(U){if(!my(U))I=U}}if(I!==null)throw I}function dy($,I,U,Y){let J=RL(gQ1,[I,$],Y),Q=RL(SQ1,[I,$],Y,J);if(!U.keep)VJ.unshift(J);return Y?J:Q}function $V0($,I,U){let Y=I.unsafeCleanup?vQ1:x1.rmdir.bind(x1),J=I.unsafeCleanup?eW0:aW0,Q=RL(J,$,U),K=RL(Y,$,U,Q);if(!I.keep)VJ.unshift(Q);return U?Q:K}function RL($,I,U,Y){let J=!1;return function Q(K){if(!J){let q=Y||Q,G=VJ.indexOf(q);if(G>=0)VJ.splice(G,1);if(J=!0,U||$===aW0||$===eW0)return $(I);else return $(I,K||function(){})}}}function yQ1(){if(!sW0)return;while(VJ.length)try{VJ[0]()}catch($){}}function mW0($){let I=[],U=null;try{U=dW0.randomBytes($)}catch(Y){U=dW0.pseudoRandomBytes($)}for(let Y=0;Y<$;Y++)I.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[U[Y]%62]);return I.join("")}function o6($){return typeof $>"u"}function wJ($,I){if(typeof $==="function")return[{},$];if(o6($))return[{},I];let U={};for(let Y of Object.getOwnPropertyNames($))U[Y]=$[Y];return[U,I]}function hQ1($,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 xQ1($,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 IV0($){let I=$.tmpdir;if(!o6($.name))return x4.join(I,$.dir,$.name);if(!o6($.template))return x4.join(I,$.dir,$.template).replace(rW0,mW0(6));let U=[$.prefix?$.prefix:"tmp","-",process.pid,"-",mW0(12),$.postfix?"-"+$.postfix:""].join("");return x4.join(I,$.dir,U)}function cy($,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 UV0($){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(rW0))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)?"":cy("prefix",$.prefix),$.postfix=o6($.postfix)?"":cy("postfix",$.postfix),$.template=o6($.template)?void 0:cy("template",$.template)}function lW0($,I,U,Y){if(o6(I))return Y(null);hQ1(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 oW0($,I,U){if(o6(I))return;let Y=xQ1(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 kw0=O((Oq1)=>{var rh=f5().Buffer;Oq1._dbcs=i5;var H6=-1,xw0=-2,x$=-10,g6=-1000,PJ=Array(256),UG=-1;for(IG=0;IG<256;IG++)PJ[IG]=H6;var IG;function i5($,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]=PJ.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(PJ.slice(0));var Q=this.decodeTables.length;this.decodeTables.push(PJ.slice(0));var K=this.decodeTables[0];for(var Y=129;Y<=254;Y++){var q=this.decodeTables[g6-K[Y]];for(var G=48;G<=57;G++){if(q[G]===H6)q[G]=g6-J;else if(q[G]>g6)throw Error("gb18030 decode tables conflict at byte 2");var H=this.decodeTables[g6-q[G]];for(var W=129;W<=254;W++){if(H[W]===H6)H[W]=g6-Q;else if(H[W]===g6-Q)continue;else if(H[W]>g6)throw Error("gb18030 decode tables conflict at byte 3");var V=this.decodeTables[g6-H[W]];for(var w=48;w<=57;w++)if(V[w]===H6)V[w]=xw0}}}}this.defaultCharUnicode=I.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var Z={};if($.encodeSkipVals)for(var Y=0;Y<$.encodeSkipVals.length;Y++){var z=$.encodeSkipVals[Y];if(typeof z==="number")Z[z]=!0;else for(var G=z.from;G<=z.to;G++)Z[G]=!0}if(this._fillEncodeTable(0,0,Z),$.encodeAdd){for(var L in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,L))this._setEncodeChar(L.charCodeAt(0),$.encodeAdd[L])}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}i5.prototype.encoder=sL;i5.prototype.decoder=th;i5.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]]=g6-this.decodeTables.length,this.decodeTables.push(U=PJ.slice(0));else if(J<=g6)U=this.decodeTables[g6-J];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return U};i5.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++]=x$-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 OI=($)=>(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 K8;if(K.issues.length){let q=new(J?.Err??$)(K.issues.map((G)=>A6(G,Q,w4())));throw nG(q,J?.callee),q}return K.value},cJ=OI(x6),FI=($)=>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,w4())));throw nG(q,J?.callee),q}return K.value},dJ=FI(x6),NI=($)=>(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 K8;return Q.issues.length?{success:!1,error:new($??iJ)(Q.issues.map((K)=>A6(K,J,w4())))}:{success:!0,data:Q.value}},MI=NI(x6),AI=($)=>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,w4())))}:{success:!0,data:Q.value}},mJ=AI(x6),pG=($)=>(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return OI($)(I,U,J)},vk=pG(x6),cG=($)=>(I,U,Y)=>{return OI($)(I,U,Y)},Rk=cG(x6),dG=($)=>async(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return FI($)(I,U,J)},Ck=dG(x6),mG=($)=>async(I,U,Y)=>{return FI($)(I,U,Y)},jk=mG(x6),lG=($)=>(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return NI($)(I,U,J)},_k=lG(x6),oG=($)=>(I,U,Y)=>{return NI($)(I,U,Y)},Sk=oG(x6),rG=($)=>async(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return AI($)(I,U,J)},gk=rG(x6),tG=($)=>async(I,U,Y)=>{return AI($)(I,U,Y)},yk=tG(x6);var e6={};o8(e6,{xid:()=>UO,uuid7:()=>gL0,uuid6:()=>SL0,uuid4:()=>_L0,uuid:()=>T7,uppercase:()=>vO,unicodeEmail:()=>hk,undefined:()=>EO,ulid:()=>IO,time:()=>OO,string:()=>NO,sha512_hex:()=>$D0,sha512_base64url:()=>UD0,sha512_base64:()=>ID0,sha384_hex:()=>aL0,sha384_base64url:()=>eL0,sha384_base64:()=>sL0,sha256_hex:()=>oL0,sha256_base64url:()=>tL0,sha256_base64:()=>rL0,sha1_hex:()=>dL0,sha1_base64url:()=>lL0,sha1_base64:()=>mL0,rfc5322Email:()=>hL0,number:()=>lJ,null:()=>TO,nanoid:()=>JO,md5_hex:()=>nL0,md5_base64url:()=>cL0,md5_base64:()=>pL0,mac:()=>VO,lowercase:()=>BO,ksuid:()=>YO,ipv6:()=>WO,ipv4:()=>HO,integer:()=>AO,idnEmail:()=>xL0,httpProtocol:()=>zO,html5Email:()=>yL0,hostname:()=>fL0,hex:()=>iL0,guid:()=>KO,extendedDuration:()=>jL0,emoji:()=>GO,email:()=>qO,e164:()=>LO,duration:()=>QO,domain:()=>bL0,datetime:()=>FO,date:()=>DO,cuid2:()=>$O,cuid:()=>eD,cidrv6:()=>ZO,cidrv4:()=>wO,browserEmail:()=>kL0,boolean:()=>PO,bigint:()=>MO,base64url:()=>aG,base64:()=>XO});var eD=/^[cC][0-9a-z]{6,}$/,$O=/^[0-9a-z]+$/,IO=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,UO=/^[0-9a-vA-V]{20}$/,YO=/^[A-Za-z0-9]{27}$/,JO=/^[a-zA-Z0-9_-]{21}$/,QO=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jL0=/^[-+]?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)?)??$/,KO=/^([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})$/,T7=($)=>{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})$`)},_L0=T7(4),SL0=T7(6),gL0=T7(7),qO=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,yL0=/^[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])?)*$/,hL0=/^(([^<>()\[\]\\.,;:\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,}))$/,hk=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,xL0=hk,kL0=/^[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])?)*$/,uL0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function GO(){return new RegExp(uL0,"u")}var HO=/^(?:(?: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])$/,WO=/^(([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}|:))$/,VO=($)=>{let I=z$($??":");return new RegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},wO=/^((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 mO={major:4,minor:4,patch:3};var i0=o("$ZodType",($,I)=>{var U;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=mO;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=a5(K),W;for(let V of q){if(V._zod.def.when){if(tD(K))continue;if(!V._zod.def.when(K))continue}else if(H)continue;let w=K.issues.length,Z=V._zod.check(K);if(Z instanceof Promise&&G?.async===!1)throw new K8;if(W||Z instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await Z,K.issues.length===w)return;if(!H)H=a5(K,w)});else{if(K.issues.length===w)continue;if(!H)H=a5(K,w)}}if(W)return W.then(()=>{return K});return K},Q=(K,q,G)=>{if(a5(K))return K.aborted=!0,K;let H=J(q,Y,G);if(H instanceof Promise){if(G.async===!1)throw new K8;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 K8;return G.then((H)=>J(H,Y,q))}return J(G,Y,q)}}e0($,"~standard",()=>({validate:(J)=>{try{let Q=MI($,J);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return mJ($,J).then((K)=>K.success?{value:K.data}:{issues:K.error?.issues})}},vendor:"zod",version:1}))}),E7=o("$ZodString",($,I)=>{i0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??NO($._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)=>{PI.init($,I),E7.init($,I)}),oO=o("$ZodGUID",($,I)=>{I.pattern??(I.pattern=KO),S1.init($,I)}),rO=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=T7(Y))}else I.pattern??(I.pattern=T7());S1.init($,I)}),tO=o("$ZodEmail",($,I)=>{I.pattern??(I.pattern=qO),S1.init($,I)}),aO=o("$ZodURL",($,I)=>{S1.init($,I),$._zod.check=(U)=>{try{let Y=U.value.trim();if(!I.normalize&&I.protocol?.source===zO.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})}}}),sO=o("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=GO()),S1.init($,I)}),eO=o("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=JO),S1.init($,I)}),$F=o("$ZodCUID",($,I)=>{I.pattern??(I.pattern=eD),S1.init($,I)}),IF=o("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=$O),S1.init($,I)}),UF=o("$ZodULID",($,I)=>{I.pattern??(I.pattern=IO),S1.init($,I)}),YF=o("$ZodXID",($,I)=>{I.pattern??(I.pattern=UO),S1.init($,I)}),JF=o("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=YO),S1.init($,I)}),QF=o("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=FO(I)),S1.init($,I)}),KF=o("$ZodISODate",($,I)=>{I.pattern??(I.pattern=DO),S1.init($,I)}),qF=o("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=OO(I)),S1.init($,I)}),GF=o("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=QO),S1.init($,I)}),HF=o("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=HO),S1.init($,I),$._zod.bag.format="ipv4"}),WF=o("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=WO),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})}}}),VF=o("$ZodMAC",($,I)=>{I.pattern??(I.pattern=VO(I.delimiter)),S1.init($,I),$._zod.bag.format="mac"}),wF=o("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=wO),S1.init($,I)}),ZF=o("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=ZO),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 XF($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}} Line truncated
if (${A}.issues.length) {
if (${R} in input) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${B}, ...iss.path] : [${B}]
path: iss.path ? [${R}, ...iss.path] : [${R}]
})));
}
}
if (${g}.value === undefined) {
if (${B} in input) {
newResult[${B}] = undefined;
if (${A}.value === undefined) {
if (${R} in input) {
newResult[${R}] = undefined;
}
} else {
newResult[${B}] = ${g}.value;
newResult[${R}] = ${A}.value;
}
`);else if(!h)V.write(`
const ${g}_present = ${B} in input;
if (${g}.issues.length) {
payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
`);else if(!g)Z.write(`
const ${A}_present = ${R} in input;
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${B}, ...iss.path] : [${B}]
path: iss.path ? [${R}, ...iss.path] : [${R}]
})));
}
if (!${g}_present && !${g}.issues.length) {
if (!${A}_present && !${A}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${B}]
path: [${R}]
});
}
if (${g}_present) {
if (${g}.value === undefined) {
newResult[${B}] = undefined;
if (${A}_present) {
if (${A}.value === undefined) {
newResult[${R}] = undefined;
} else {
newResult[${B}] = ${g}.value;
newResult[${R}] = ${A}.value;
}
}
`);else V.write(`
if (${g}.issues.length) {
payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
`);else Z.write(`
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${B}, ...iss.path] : [${B}]
path: iss.path ? [${R}, ...iss.path] : [${R}]
})));
}
if (${g}.value === undefined) {
if (${B} in input) {
newResult[${B}] = undefined;
if (${A}.value === undefined) {
if (${R} in input) {
newResult[${R}] = undefined;
}
} else {
newResult[${B}] = ${g}.value;
newResult[${R}] = ${A}.value;
}
`)}V.write("payload.value = newResult;"),V.write("return payload;");let T=V.compile();return(P,g)=>T(W,P,g)},J,Q=M7,K=!N7.jitless,w=K&&xO.value,G=I.catchall,H;$._zod.parse=(W,V)=>{H??(H=U.value);let X=W.value;if(!Q(X))return W.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),W;if(K&&w&&V?.async===!1&&V.jitless!==!0){if(!J)J=Y(I.shape);if(W=J(W,V),!G)return W;return tx([],X,W,V,H,$)}return q(W,V)}});function Sx($,I,q,U){for(let J of $)if(J.issues.length===0)return I.value=J.value,I;let Y=$.filter((J)=>!o5(J));if(Y.length===1)return I.value=Y[0].value,Y[0];return I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:$.map((J)=>J.issues.map((Q)=>M6(Q,U,V4())))}),I}var mY=m("$ZodUnion",($,I)=>{k0.init($,I),r0($._zod,"optin",()=>I.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),r0($._zod,"optout",()=>I.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),r0($._zod,"values",()=>{if(I.options.every((U)=>U._zod.values))return new Set(I.options.flatMap((U)=>Array.from(U._zod.values)));return}),r0($._zod,"pattern",()=>{if(I.options.every((U)=>U._zod.pattern)){let U=I.options.map((Y)=>Y._zod.pattern);return new RegExp(`^(${U.map((Y)=>hY(Y.source)).join("|")})$`)}return});let q=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(U,Y)=>{if(q)return q(U,Y);let J=!1,Q=[];for(let K of I.options){let z=K._zod.run({value:U.value,issues:[]},Y);if(z instanceof Promise)Q.push(z),J=!0;else{if(z.issues.length===0)return z;Q.push(z)}}if(!J)return Sx(Q,U,$,Y);return Promise.all(Q).then((K)=>{return Sx(K,U,$,Y)})}});function yx($,I,q,U){let Y=$.filter((J)=>J.issues.length===0);if(Y.length===1)return I.value=Y[0].value,I;if(Y.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:$.map((J)=>J.issues.map((Q)=>M6(Q,U,V4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:[],inclusive:!1});return I}var TN=m("$ZodXor",($,I)=>{mY.init($,I),I.inclusive=!1;let q=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(U,Y)=>{if(q)return q(U,Y);let J=!1,Q=[];for(let K of I.options){let z=K._zod.run({value:U.value,issues:[]},Y);if(z instanceof Promise)Q.push(z),J=!0;else Q.push(z)}if(!J)return yx(Q,U,$,Y);return Promise.all(Q).then((K)=>{return yx(K,U,$,Y)})}}),jN=m("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,mY.init($,I);let q=$._zod.parse;r0($._zod,"propValues",()=>{let Y={};for(let J of I.options){let Q=J._zod.propValues;if(!Q||Object.keys(Q).length===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(J)}"`);for(let[K,z]of Object.entries(Q)){if(!Y[K])Y[K]=new Set;for(let w of z)Y[K].add(w)}}return Y});let U=KI(()=>{let Y=I.options,J=new Map;for(let Q of Y){let K=Q._zod.propValues?.[I.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(Q)}"`);for(let z of K){if(J.has(z))throw Error(`Duplicate discriminator value "${String(z)}"`);J.set(z,Q)}}return J});$._zod.parse=(Y,J)=>{let Q=Y.value;if(!M7(Q))return Y.issues.push({code:"invalid_type",expected:"object",input:Q,inst:$}),Y;let K=U.value.get(Q?.[I.discriminator]);if(K)return K._zod.run(Y,J);if(I.unionFallback||J.direction==="backward")return q(Y,J);return Y.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(U.value.keys()),input:Q,path:[I.discriminator],inst:$}),Y}}),EN=m("$ZodIntersection",($,I)=>{k0.init($,I),$._zod.parse=(q,U)=>{let Y=q.value,J=I.left._zod.run({value:Y,issues:[]},U),Q=I.right._zod.run({value:Y,issues:[]},U);if(J instanceof Promise||Q instanceof Promise)return Promise.all([J,Q]).then(([z,w])=>{return ux(q,z,w)});return ux(q,J,Q)}});function nL($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(m5($)&&m5(I)){let q=Object.keys(I),U=Object.keys($).filter((J)=>q.indexOf(J)!==-1),Y={...$,...I};for(let J of U){let Q=nL($[J],I[J]);if(!Q.valid)return{valid:!1,mergeErrorPath:[J,...Q.mergeErrorPath]};Y[J]=Q.data}return{valid:!0,data:Y}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let q=[];for(let U=0;U<$.length;U++){let Y=$[U],J=I[U],Q=nL(Y,J);if(!Q.valid)return{valid:!1,mergeErrorPath:[U,...Q.mergeErrorPath]};q.push(Q.data)}return{valid:!0,data:q}}return{valid:!1,mergeErrorPath:[]}}function ux($,I,q){let U=new Map,Y;for(let K of I.issues)if(K.code==="unrecognized_keys"){Y??(Y=K);for(let z of K.keys){if(!U.has(z))U.set(z,{});U.get(z).l=!0}}else $.issues.push(K);for(let K of q.issues)if(K.code==="unrecognized_keys")for(let z of K.keys){if(!U.has(z))U.set(z,{});U.get(z).r=!0}else $.issues.push(K);let J=[...U].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(J.length&&Y)$.issues.push({...Y,keys:J});if(o5($))return $;let Q=nL(I.value,q.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return $.value=Q.data,$}var zw=m("$ZodTuple",($,I)=>{k0. Line truncated
`)}Z.write("payload.value = newResult;"),Z.write("return payload;");let E=Z.compile();return(T,A)=>E(w,T,A)},Q,K=P7,q=!M7.jitless,H=q&&cD.value,W=I.catchall,V;$._zod.parse=(w,Z)=>{V??(V=Y.value);let z=w.value;if(!K(z))return w.issues.push({expected:"object",code:"invalid_type",input:z,inst:$}),w;if(q&&H&&Z?.async===!1&&Z.jitless!==!0){if(!Q)Q=J(I.shape);if(w=Q(w,Z),!W)return w;return Ju([],z,w,Z,V,$)}return U(w,Z)}});function nk($,I,U,Y){for(let Q of $)if(Q.issues.length===0)return I.value=Q.value,I;let J=$.filter((Q)=>!a5(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,w4())))}),I}var aJ=o("$ZodUnion",($,I)=>{i0.init($,I),e0($._zod,"optin",()=>I.options.some((Y)=>Y._zod.optin==="optional")?"optional":void 0),e0($._zod,"optout",()=>I.options.some((Y)=>Y._zod.optout==="optional")?"optional":void 0),e0($._zod,"values",()=>{if(I.options.every((Y)=>Y._zod.values))return new Set(I.options.flatMap((Y)=>Array.from(Y._zod.values)));return}),e0($._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)=>kJ(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 nk(K,Y,$,J);return Promise.all(K).then((q)=>{return nk(q,Y,$,J)})}});function pk($,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,w4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:[],inclusive:!1});return I}var SF=o("$ZodXor",($,I)=>{aJ.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 pk(K,Y,$,J);return Promise.all(K).then((q)=>{return pk(q,Y,$,J)})}}),gF=o("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,aJ.init($,I);let U=$._zod.parse;e0($._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=LI(()=>{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(!P7(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}}),yF=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 ck(U,G,H)});return ck(U,Q,K)}});function lO($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(t5($)&&t5(I)){let U=Object.keys(I),Y=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),J={...$,...I};for(let Q of Y){let K=lO($[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=lO(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 ck($,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(a5($))return $;let K=lO(I.value,U.value);if(!K.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}var qH=o("$ZodTuple",($,I)=>{i0. Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let Q of $.seen.entries()){let K=Q[1];if(I===Q[0]){J(Q);continue}if($.external){let w=$.external.registry.get(Q[0])?.id;if(I!==Q[0]&&w){J(Q);continue}}if($.metadataRegistry.get(Q[0])?.id){J(Q);continue}if(K.cycle){J(Q);continue}if(K.count>1){if($.reused==="ref"){J(Q);continue}}}}function e5($,I){let q=$.seen.get(I);if(!q)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(K)=>{let z=$.seen.get(K);if(z.ref===null)return;let w=z.def??z.schema,G={...w},H=z.ref;if(z.ref=null,H){U(H);let V=$.seen.get(H),X=V.schema;if(X.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))w.allOf=w.allOf??[],w.allOf.push(X);else Object.assign(w,X);if(Object.assign(w,G),K._zod.parent===H)for(let O in w){if(O==="$ref"||O==="allOf")continue;if(!(O in G))delete w[O]}if(X.$ref&&V.def)for(let O in w){if(O==="$ref"||O==="allOf")continue;if(O in V.def&&JSON.stringify(w[O])===JSON.stringify(V.def[O]))delete w[O]}}let W=K._zod.parent;if(W&&W!==H){U(W);let V=$.seen.get(W);if(V?.schema.$ref){if(w.$ref=V.schema.$ref,V.def)for(let X in w){if(X==="$ref"||X==="allOf")continue;if(X in V.def&&JSON.stringify(w[X])===JSON.stringify(V.def[X]))delete w[X]}}}$.override({zodSchema:K,jsonSchema:w,path:z.path??[]})};for(let K of[...$.seen.entries()].reverse())U(K[0]);let Y={};if($.target==="draft-2020-12")Y.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")Y.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")Y.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let K=$.external.registry.get(I)?.id;if(!K)throw Error("Schema is missing an `id` property");Y.$id=$.external.uri(K)}Object.assign(Y,q.def??q.schema);let J=$.metadataRegistry.get(I)?.id;if(J!==void 0&&Y.id===J)delete Y.id;let Q=$.external?.defs??{};for(let K of $.seen.entries()){let z=K[1];if(z.def&&z.defId){if(z.def.id===z.defId)delete z.def.id;Q[z.defId]=z.def}}if($.external);else if(Object.keys(Q).length>0)if($.target==="draft-2020-12")Y.$defs=Q;else Y.definitions=Q;try{let K=JSON.parse(JSON.stringify(Y));return Object.defineProperty(K,"~standard",{value:{...I["~standard"],jsonSchema:{input:vI(I,"input",$.processors),output:vI(I,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throw Error("Error converting schema to JSON.")}}function g6($,I){let q=I??{seen:new Set};if(q.seen.has($))return!1;q.seen.add($);let U=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return g6(U.element,q);if(U.type==="set")return g6(U.valueType,q);if(U.type==="lazy")return g6(U.getter(),q);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return g6(U.innerType,q);if(U.type==="intersection")return g6(U.left,q)||g6(U.right,q);if(U.type==="record"||U.type==="map")return g6(U.keyType,q)||g6(U.valueType,q);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return g6(U.in,q)||g6(U.out,q)}if(U.type==="object"){for(let Y in U.shape)if(g6(U.shape[Y],q))return!0;return!1}if(U.type==="union"){for(let Y of U.options)if(g6(Y,q))return!0;return!1}if(U.type==="tuple"){for(let Y of U.items)if(g6(Y,q))return!0;if(U.rest&&g6(U.rest,q))return!0;return!1}return!1}var hM=($,I={})=>(q)=>{let U=a5({...q,processors:I});return E1($,U),s5(U,$),e5(U,$)},vI=($,I,q={})=>(U)=>{let{libraryOptions:Y,target:J}=U??{},Q=a5({...Y??{},target:J,io:I,processors:q});return E1($,Q),s5(Q,$),e5(Q,$)};var _L0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},SM=($,I,q,U)=>{let Y=q;Y.type="string";let{minimum:J,maximum:Q,format:K,patterns:z,contentEncoding:w}=$._zod.bag;if(typeof J==="number")Y.minLength=J;if(typeof Q==="number")Y.maxLength=Q;if(K){if(Y.format=_L0[K]??K,Y.format==="")delete Y.format;if(K==="time")delete Y.format}if(w)Y.contentEncoding=w;if(z&&z.size>0){let G=[...z];if(G.length===1)Y.pattern=G[0].source;else if(G.length>1)Y.allOf=[...G.map((H)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:H.source}))]}},yM=($,I,q,U)=>{let Y=q,{minimum:J,maximum:Q,format:K,multipleOf:z,exclusiveMaximum:w,exclusiveMinimum:G}=$._zod.bag;if(typeof K==="string"&&K.includes("int"))Y.type="integer";else Y.type="number";let H=typeof G==="number"&&G>=(J??Number.NEGATIVE_INFINITY),W=typeof w==="number"&&w<=(Q??Number.POSITIVE_INFINITY),V=I.target==="draft-04"||I.target==="openapi-3.0";if(H)if(V)Y.minimum=G,Y.exclusiveMinimum=!0;else Y.exclusiveMinimum=G;else if(typeof J==="number")Y.minimum=J;if(W)if(V)Y.maximum=w,Y.exclusiveMaximum=!0;else Y.exclusiveMaximum=w;else if(typeof Q==="number")Y.maximum=Q;if(typeof z==="number")Y.multipleOf=z},uM=($,I,q,U)=>{q.type="boolean"},xM=($,I,q,U)=>{if(I.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},kM=($,I,q,U)=>{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),$v0(I)}clear(){this._buffer=void 0}}function $v0($){return Ef.parse(JSON.parse($))}function Tc($){return JSON.stringify($)+`
`}class aP{constructor($=jc.stdin,I=jc.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new tP,this._started=!1,this._ondata=(q)=>{this._readBuffer.append(q),this.processReadBuffer()},this._onerror=(q)=>{this.onerror?.(q)}}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 q=Tc($);if(this._stdout.write(q))I();else this._stdout.once("drain",I)})}}import{dirname as vu,join as yw1}from"node:path";import{fileURLToPath as uw1}from"node:url";class $5 extends Error{name="KyError";get isKyError(){return!0}}class n6 extends $5{name="HTTPError";response;request;options;data;constructor($,I,q){let U=$.status||$.status===0?$.status:"",Y=$.statusText??"",J=`${U} ${Y}`.trim(),Q=J?`status code ${J}`:"an unknown error";super(`Request failed with ${Q}: ${I.method} ${I.url}`);this.response=$,this.request=I,this.options=q}}class aJ extends $5{name="NetworkError";request;constructor($,I){super(`Request failed due to a network error: ${$.method} ${$.url}`,I);this.request=$}}class sJ 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 qq extends $5{name="ForceRetryError";customDelay;code;customRequest;constructor($){let I=$?.cause?$.cause instanceof Error?$.cause:new sJ($.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 sP extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class b$ extends $5{name="TimeoutError";request;constructor($){super(`Request timed out: ${$.method} ${$.url}`);this.request=$}}var eP=(()=>{let $=!1,I=!1,q=typeof globalThis.ReadableStream==="function",U=typeof globalThis.Request==="function";if(q&&U)try{I=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(Y){if(Y instanceof Error&&Y.message==="unsupported BodyInit type")return!1;throw Y}return $&&!I})(),Ec=typeof globalThis.AbortController==="function",ZH=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",Bc=typeof globalThis.ReadableStream==="function",vc=typeof globalThis.FormData==="function",XH=["get","post","put","patch","head","delete"],Iv0=()=>{return};Iv0();var Rc={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Uq=2147483647,Cc=40,DH=Symbol("stop");class OH{options;constructor($){this.options=$}}var _c=($)=>new OH($),hc={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},Sc={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 LH=new TextEncoder,qv0=($)=>{if(!$)return 0;if($ instanceof FormData){let I=0;for(let[q,U]of $)I+=Cc,I+=LH.encode(`Content-Disposition: form-data; name="${q}"`).byteLength,I+=typeof U==="string"?LH.encode(U).byteLength:U.size;return I}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return LH.encode($).byteLength;if($ instanceof URLSearchParams)return LH.encode($.toString()).byteLength;return 0},yc=($,I,q)=>{let U,Y=0;return $.pipeThrough(new TransformStream({transform(J,Q){if(Q.enqueue(J),U){Y+=U.byteLength;let K=I===0?0:Y/I;if(K>=1)K=1-Number.EPSILON;q?.({percent:K,totalBytes:Math.max(I,Y),transferredBytes:Y},U)}U=J},flush(){if(U)Y+=U.byteLength,q?.({percent:1,totalBytes:Math.max(I,Y),transferredBytes:Y},U)}}))},uc=($,I)=>{if(!$.body)return $;let q={status:$.status,statusText:$.statusText,headers:$.headers};if($.status===204)return new Response(null,q);let U=Math.max(0,Number($.headers.get("content-length"))||0);return new Response(yc($.body,U,I),q)},xc=($,I,q)=>{if(!$.body)return $;let U=qv0(q??$.body);return new Request($,{duplex:"half",body:yc($.body,U,I)})};var G8=($)=>$!==null&&typeof $==="object";var Uv0=Symbol("replaceOption"),$T=($)=>G8($)&&$[Uv0]===!0?{isReplace:!0,value:$.value}:{isReplace:!1,value:$};var $Q=(...$)=>{for(let I of $)if( Line truncated
`,{mode:384}),I}function Gq($,I,q=[]){let U=I.corpId?.trim()||void 0,Y=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,J=U??Y;if(J){let K=$.find((z)=>z.id===J);if(K)return K;throw Error(`No enterprise config found for ${J}`)}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 Q=$[0];if(Q)return Q;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(q.length?q.join(", "):"the configured enterprise directories"))}import{readFileSync as qz1}from"node:fs";import{randomBytes as Uz1}from"node:crypto";import{randomBytes as td}from"node:crypto";var sv0=Z.object({staffId:Z.string(),name:Z.string().optional(),code:Z.string().default(""),bindTime:Z.number().optional()}),ev0=Z.object({id:Z.string(),tenantId:Z.string(),name:Z.string(),isAdmin:Z.boolean().default(!1),permissions:Z.array(Z.string()).default([]),providerUserId:Z.string().optional(),hosecloudStaff:sv0.optional()}),$R0=Z.object({apiKey:Z.string().optional(),corporationId:Z.string().optional(),corporationName:Z.string().optional()}),IR0=Z.object({id:Z.string(),name:Z.string(),tenantSlug:Z.string().optional(),isDemo:Z.boolean().default(!1),logoUrl:Z.string().nullable().optional(),hoseCorpConfig:$R0.optional()}),Bd=Z.object({user:ev0,tenant:IR0}),qR0=Z.object({id:Z.string(),name:Z.string(),email:Z.string().nullable().optional(),emailVerified:Z.boolean().optional(),image:Z.string().nullable().optional(),tenantId:Z.string().optional(),provider:Z.string().optional(),providerUserId:Z.string().optional(),mobile:Z.string().nullable().optional(),status:Z.string().optional(),permissions:Z.array(Z.string()).default([]),isAdmin:Z.boolean().default(!1),hosecloudStaff:Z.unknown().optional()}).passthrough(),UR0=Z.object({id:Z.string(),token:Z.string().optional(),expiresAt:Z.string(),createdAt:Z.string().optional(),updatedAt:Z.string().optional(),ipAddress:Z.string().optional(),userAgent:Z.string().optional(),userId:Z.string(),delegationId:Z.string().nullable().optional()}).passthrough(),vd=Z.object({user:qR0,session:UR0}),SH=Z.object({id:Z.string(),tenantId:Z.string().optional(),code:Z.number().optional(),description:Z.string(),scope:Z.string(),strictness:Z.string(),status:Z.string().optional(),createdAt:Z.number().optional(),updatedAt:Z.number().optional()}),Rd=Z.object({rules:Z.array(SH),hasPendingDeletes:Z.boolean().default(!1)}),YR0=Z.object({code:Z.string().optional(),description:Z.string(),scope:Z.string(),strictness:Z.string()}),yH=Z.object({id:Z.string(),tenantId:Z.string().optional(),versionNumber:Z.number(),versionName:Z.string().nullable().optional(),publishedBy:Z.string().nullable().optional(),publishedByName:Z.string().nullable().optional(),rules:Z.array(YR0).default([]),publishedAt:Z.number().optional(),createdAt:Z.number().optional()}),Cd=Z.object({version:yH,rulesCount:Z.number()}),zQ=Z.object({id:Z.string(),tenantId:Z.string().optional(),title:Z.string(),purpose:Z.string().default(""),contentType:Z.string().default("policy"),content:Z.string(),status:Z.string().default("published"),enabled:Z.boolean().default(!0),scenarios:Z.array(Z.string()).default([]),tags:Z.array(Z.string()).default([]),category:Z.string().nullable().optional(),categoryTags:Z.array(Z.string()).default([]),createdBy:Z.string().nullable().optional(),createdByName:Z.string().nullable().optional(),createdAt:Z.number().optional(),updatedAt:Z.number().optional(),updatedBy:Z.string().nullable().optional(),updatedByName:Z.string().nullable().optional(),isDeleted:Z.boolean().default(!1)}),_d=Z.object({articles:Z.array(zQ),total:Z.number().optional()}),JR0=Z.object({explicitApprove:Z.string().default(""),explicitReject:Z.string().default(""),exemptApprove:Z.string().default(""),review:Z.string().default("")}).passthrough(),QR0=Z.object({type:Z.string(),signKey:Z.string().optional(),outboundName:Z.string().optional(),mode:Z.string().optional(),autoApprovalRate:Z.number().optional(),apiKey:Z.string().optional(),apiSecret:Z.string().optional(),apiOrigin:Z.string().optional(),corporationId:Z.string().optional(),ebotSignKey:Z.string().optional(),completionSignKey:Z.string().optional(),outboundMessageId:Z.string().optional(),completionMessageId:Z.string().optional()}).passthrough(),KR0=Z.enum(["assisted","semi_automatic","fully_automatic"]),Ed=Z.object({id:Z.string(),url:Z.string().url()}).passthrough(),wQ=Z.object({type:Z.literal("webhook"),id:Z.string(),name:Z.string(),mode:KR0,incomingDocumentWebhook:Ed,outgoingResultWebhook:Z.string().url(),incomingManualResultWebhook:Ed,secret:Z.string().min(1),autoApprovalRate:Z.number().int().min(0).max(100).optional()}).passthrough(),LT=Z.object({id:Z.string().optional(),tenantId:Z.string().optional(),tone:Z.string().optional(),language:Z.string().optional(),detailLevel:Z.string().optional(),outputFormat:Z.string().optional(),examples:Z.array(Z.string()).default([]),prohibitedPhrases:Z.array(Z.strin Line truncated
`,"utf8"),q}function pl($){return $.map((I,q)=>{let U;if(typeof I.code==="number")U=`#${String(I.code).padStart(4,"0")}`;else if(typeof I.code==="string")U=I.code.startsWith("#")?I.code:`#${I.code}`;else U=`#${String(q+1).padStart(4,"0")}`;return{id:I.id,code:U,name:I.name,description:I.description,scope:I.scope,strictness:I.strictness}})}class k7 extends Error{errors;warnings;constructor($,I=[]){super(`材料包校验失败:${$.length} 个错误`);this.errors=$;this.warnings=I;this.name="MaterialPackValidationError"}}import{createHmac as oR0,randomBytes as rR0}from"node:crypto";function tR0($,I,q,U){return oR0("sha256",U).update(`${$}.${I}.${JSON.stringify(q)}`).digest("hex")}function bT($,I){let q=Math.floor(Date.now()/1000),U=rR0(16).toString("hex");return{Authorization:`Bearer ${I}`,"x-webhook-signature":tR0(q,U,$,I),"x-webhook-timestamp":String(q),"x-webhook-nonce":U}}var Cj=RY(wm(),1),sm=RY(am(),1);var KV={maxEntries:1000,maxTotalSize:524288000,maxCompressionRatio:150};async function em($){return new Promise((I,q)=>{Cj.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0},(U,Y)=>{if(U||!Y)return q(U??Error("无法打开 ZIP"));let J=[];Y.readEntry(),Y.on("entry",(Q)=>{let K=$o(Q);if(!K.endsWith("/")&&!T_0(K))J.push({fileName:K,uncompressedSize:Q.uncompressedSize,compressedSize:Q.compressedSize,raw:Q});Y.readEntry()}),Y.on("end",()=>I(J)),Y.on("error",q)})})}function $o($){if($.fileNameUTF8||$.generalPurposeBitFlag&2048)return $.fileNameUTF8??$.fileName;let I=Buffer.from(String($.fileName),"binary"),q=I.toString("utf8");if(q.includes("�")||/[\u0080-\u00FF]/.test(q)){let U=sm.default.decode(I,"gbk");if(!U.includes("�"))return U}return q}function T_0($){let I=$.split("/").pop()??"";return $.split("/").includes("__MACOSX")||I===".DS_Store"||I.startsWith("._")||I.startsWith(".~")||I.startsWith("~$")}function Io($){let I=[];if($.length>KV.maxEntries)I.push(`文件数超过 ${KV.maxEntries}`);if($.reduce((Y,J)=>Y+J.uncompressedSize,0)>KV.maxTotalSize)I.push("解压后总大小超过 500MB");for(let Y of $){if(Y.fileName.startsWith("/")||Y.fileName.split("/").includes(".."))I.push(`存在不安全路径: ${Y.fileName}`);if(Y.compressedSize>0&&Y.uncompressedSize/Y.compressedSize>KV.maxCompressionRatio)I.push(`压缩比超过 150: ${Y.fileName}`)}if(!$.find((Y)=>Y.fileName==="信息表.xlsx"))I.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");if($.some((Y)=>Y.fileName.toLowerCase().endsWith(".zip")))I.push("不允许嵌套 ZIP");if(I.length)throw new k7(I)}function _j($,I){return new Promise((q,U)=>{Cj.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0},(Y,J)=>{if(Y||!J)return U(Y??Error("无法打开 ZIP"));J.readEntry(),J.on("entry",(Q)=>{if($o(Q)!==I.fileName)return J.readEntry();J.openReadStream(Q,(K,z)=>{if(K||!z)return U(K??Error(`无法读取 ${I.fileName}`));let w=[];z.on("data",(G)=>w.push(G)),z.on("end",()=>q(Buffer.concat(w))),z.on("error",U)})}),J.on("error",U)})})}var jV0=RY(PV0(),1);function aD($,I,q,U){return{key:$,label:I,type:q,value:U}}function EV0($,I,q){return aD($,I,"TEXT",q==null?"":String(q))}function BV0($,I,q){return aD($,I,"AMOUNT",typeof q==="number"?{amount:q,currency:"CNY"}:null)}function vV0($){if($ instanceof Date)return $.toISOString();if(typeof $==="string"&&$.trim())return $.trim();return null}function uK1($){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 DY($){let I=new Map;return $.getRow(1).eachCell((q,U)=>I.set(String(q.value??"").trim(),U)),I}function OY($,I,q){let U=I.get(q);return U?$.getCell(U).value:void 0}function xK1($,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(([U,Y,J])=>{let Q=OY($,I,U);if(Q==null||Q==="")return[];return[J==="TEXT"?EV0(Y,U,Q):J==="AMOUNT"?BV0(Y,U,Q):aD(Y,U,J,vV0(Q))]})}function TV0($,I,q){return q.flatMap(([U,Y,J])=>{let Q=OY($,I,U);if(Q==null||Q==="")return[];return[J==="TEXT"?EV0(Y,U,Q):J==="AMOUNT"?BV0(Y,U,Q):aD(Y,U,J,vV0(Q))]})}var kK1=[["姓名","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"]],fK1=[["报销金额","reimbursement_amount","AMOUNT"],["费用类型","expense_type","TEXT"],["发生时间","occurrence_time","DATE"],["收款人","payee","TEXT"],["开户行","bank","TEXT"],["支行名称","branch_name","TEXT"],["支行行 Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:W7({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:KO(I,["template.name","templateName","form.name","formName","formTitle"]),amount:JO(q,["金额","报销金额","付款金额","合计","价税合计"])??KO(I,["amount","totalAmount","expenseAmount"]),expenseType:JO(q,["费用类型","费用类别","报销类型"]),costCompany:JO(q,["费用承担公司","承担公司","成本中心","费用归属"]),payee:JO(q,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:q.slice(0,30)}),invoices:Mz1($),attachments:pW0($,{summary:!0}).attachments,aiResult:wO($),manualResult:$I($)?.value,hints:W7({amountMentions:CW0(U,["金额","合计","税率"],8),partyMentions:CW0(U,["买方","卖方","甲方","乙方","收款"],8)})}}function pW0($,I={}){let q=[["document",$.document],["result",$.result],["pipelineData",$.pipelineData],["sourceExtendData",$.sourceExtendData]],U=[],Y=new Set;for(let[J,Q]of q)ey(Q,J,U,Y);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,count:U.length,attachments:I.summary?U.map((J)=>W7({path:J.path,kind:J.kind,fileName:J.fileName,mimeType:J.mimeType,fileId:J.fileId,sourceField:J.sourceField})):U}}function Xz1($){let I=[["result.citedRules",n5($,"result.citedRules")],["result.matchedRules",n5($,"result.matchedRules")],["result.ruleResults",n5($,"result.ruleResults")],["result.rules",n5($,"result.rules")],["pipelineData.citedRules",n5($,"pipelineData.citedRules")],["pipelineData.matchedRules",n5($,"pipelineData.matchedRules")]],q=[],U=new Set;for(let[Y,J]of I)(Array.isArray(J)?J:J&&typeof J==="object"?Object.values(J):[]).forEach((K,z)=>{let w=NY(K);if(!w)return;let G=b0(w.runtimeRuleId)??b0(w.runtimeId)??b0(w.id)??b0(w.ruleId),H=b0(w.ruleCode)??b0(w.code)??(G?Pz1(G):void 0),W=W7({runtimeRuleId:G,ruleCode:H,versionNumber:Nz1(w.versionNumber)??$.ruleSetVersionNumber,scope:b0(w.scope),strictness:b0(w.strictness),appliedAnalysis:w.appliedAnalysis??w.analysis??w.reasoning,checkResult:w.checkResult??w.result??w.decision,findings:w.findings??w.riskPoints??w.evidence,sourcePath:`${Y}.${z}`}),V=JSON.stringify(W);if(!U.has(V))U.add(V),q.push(W)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:q.length,rules:q}}function ey($,I,q,U){if(Array.isArray($)){$.forEach((J,Q)=>ey(J,`${I}.${Q}`,q,U));return}let Y=NY($);if(!Y)return;if(Dz1(Y,I)){let J=W7({path:I,fieldPath:I,kind:Oz1(I,Y),fileName:b0(Y.fileName)??b0(Y.filename)??b0(Y.name)??b0(Y.originalName),mimeType:b0(Y.mimeType)??b0(Y.mimetype)??b0(Y.contentType),fileId:b0(Y.fileId)??b0(Y.id)??b0(Y.attachmentId),ossPath:b0(Y.ossPath)??b0(Y.ossKey)??b0(Y.key),url:b0(Y.url)??b0(Y.signedUrl)??b0(Y.downloadUrl)??b0(Y.previewUrl),invoiceId:b0(Y.invoiceId),sourceField:b0(Y.fieldName)??b0(Y.label)}),Q=JSON.stringify(J);if(!U.has(Q))U.add(Q),q.push(J)}for(let[J,Q]of Object.entries(Y))ey(Q,`${I}.${J}`,q,U)}function Dz1($,I){let q=Object.keys($).map((J)=>J.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(I)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((J)=>q.includes(J.toLowerCase()))}function Oz1($,I){let q=`${$} ${b0(I.type)??""}`.toLowerCase();if(q.includes("invoice")||q.includes("发票"))return"invoice";if(q.includes("receipt"))return"receipt";return"attachment"}function KO($,I){if(!$)return;for(let q of I){let U=n5($,q);if(U!==void 0)return U}return}function RW0($,I){if(!$)return 0;for(let q of I){let U=n5($,q);if(Array.isArray(U))return U.length;if(U&&typeof U==="object")return Object.keys(U).length;if(typeof U==="number")return U}return 0}function n5($,I){return I.split(".").reduce((q,U)=>{if(q===void 0||q===null)return;if(Array.isArray(q)){let Y=Number(U);return Number.isInteger(Y)?q[Y]:void 0}if(typeof q==="object")return q[U];return},$)}function Lz1($,I,q){let U=I.split("."),Y=$;for(let J of U.slice(0,-1)){let Q=Y[J];if(!Q||typeof Q!=="object"||Array.isArray(Q))Y[J]={};Y=Y[J]}Y[U[U.length-1]??I]=q}function W7($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function NY($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Nz1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Fz1($){let I=[];return $u($,"document",I),I}function $u($,I,q){if(Array.isArray($)){$.forEach((Q,K)=>$u(Q,`${I}.${K}`,q));return}let U=NY($);if(!U)return;let Y=b0(U.label)??b0(U.name)??b0(U.title)??b0(U.fieldName),J=U.value??U.displayValue??U.text??U.content;if(Y&&J!==void 0&&typeof J!=="object")q.push(W7({path:I,label:Y,value:J,type:b0(U.type)??b0(U.fieldType)}));for(let[Q,K]of Object.entries(U)){if(Q==="attachments")continue;$u(K,`${I}.${Q}`,q)}}function JO($,I){return $.find((U)=>{let 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 U9($,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),z=Z.schema;if(z.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(z);else Object.assign(H,z);if(Object.assign(H,W),q._zod.parent===V)for(let D in H){if(D==="$ref"||D==="allOf")continue;if(!(D in W))delete H[D]}if(z.$ref&&Z.def)for(let D in H){if(D==="$ref"||D==="allOf")continue;if(D in Z.def&&JSON.stringify(H[D])===JSON.stringify(Z.def[D]))delete H[D]}}let w=q._zod.parent;if(w&&w!==V){Y(w);let Z=$.seen.get(w);if(Z?.schema.$ref){if(H.$ref=Z.schema.$ref,Z.def)for(let z in H){if(z==="$ref"||z==="allOf")continue;if(z in Z.def&&JSON.stringify(H[z])===JSON.stringify(Z.def[z]))delete H[z]}}}$.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:uI(I,"input",$.processors),output:uI(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 bM=($,I={})=>(U)=>{let Y=$9({...U,processors:I});return C1($,Y),I9(Y,$),U9(Y,$)},uI=($,I,U={})=>(Y)=>{let{libraryOptions:J,target:Q}=Y??{},K=$9({...J??{},target:Q,io:I,processors:U});return C1($,K),I9(K,$),U9(K,$)};var TO0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},iM=($,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=TO0[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}))]}},nM=($,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),w=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(w)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},pM=($,I,U,Y)=>{U.type="boolean"},cM=($,I,U,Y)=>{if(I.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},dM=($,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),mR0(I)}clear(){this._buffer=void 0}}function mR0($){return hf.parse(JSON.parse($))}function gc($){return JSON.stringify($)+`
`}class JE{constructor($=yc.stdin,I=yc.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new YE,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=gc($);if(this._stdout.write(U))I();else this._stdout.once("drain",I)})}}import{dirname as kx,join as hH1}from"node:path";import{fileURLToPath as xH1}from"node:url";class Y5 extends Error{name="KyError";get isKyError(){return!0}}class U$ extends Y5{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 I2 extends Y5{name="NetworkError";request;constructor($,I){super(`Request failed due to a network error: ${$.method} ${$.url}`,I);this.request=$}}class U2 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 VU extends Y5{name="ForceRetryError";customDelay;code;customRequest;constructor($){let I=$?.cause?$.cause instanceof Error?$.cause:new U2($.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 QE extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class m$ extends Y5{name="TimeoutError";request;constructor($){super(`Request timed out: ${$.method} ${$.url}`);this.request=$}}var KE=(()=>{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})(),hc=typeof globalThis.AbortController==="function",ZV=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",xc=typeof globalThis.ReadableStream==="function",kc=typeof globalThis.FormData==="function",XV=["get","post","put","patch","head","delete"],lR0=()=>{return};lR0();var uc={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},wU=2147483647,fc=40,zV=Symbol("stop");class LV{options;constructor($){this.options=$}}var bc=($)=>new LV($),ic={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},nc={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 DV=new TextEncoder,oR0=($)=>{if(!$)return 0;if($ instanceof FormData){let I=0;for(let[U,Y]of $)I+=fc,I+=DV.encode(`Content-Disposition: form-data; name="${U}"`).byteLength,I+=typeof Y==="string"?DV.encode(Y).byteLength:Y.size;return I}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return DV.encode($).byteLength;if($ instanceof URLSearchParams)return DV.encode($.toString()).byteLength;return 0},pc=($,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)}}))},cc=($,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(pc($.body,Y,I),U)},dc=($,I,U)=>{if(!$.body)return $;let Y=oR0(U??$.body);return new Request($,{duplex:"half",body:pc($.body,Y,I)})};var Z8=($)=>$!==null&&typeof $==="object";var rR0=Symbol("replaceOption"),qE=($)=>Z8($)&&$[rR0]===!0?{isReplace:!0,value:$.value}:{isReplace:!1,value:$};var J2=(...$)=>{for(let I of $)if( Line truncated
`,{mode:384}),I}function XJ($,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 JG1}from"node:fs";import{randomBytes as QG1}from"node:crypto";var pV0=300000,iV0=new Map;function b21($,I){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>I?U:U.toLowerCase())}function i21($,I){return I?$:$.toLowerCase()}function n21($,I,U,Y){let J=i21($,Y),Q=I.filter((K)=>J.includes(K));if(U==="all"&&Q.length!==I.length)return[];return Q}function p21($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function c21($,I){if(I.fields&&!I.fields.has($.field))return[];let U=p21($.value),Y=[];return U.forEach((J,Q)=>{let K=n21(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:kL(J,I.maxChars),context:{before:I.snippetOnly?[]:U.slice(q,Q).map((W)=>kL(W,I.maxChars)),line:kL(J,I.maxChars),after:I.snippetOnly?[]:U.slice(Q+1,G).map((W)=>kL(W,I.maxChars))},metadata:$.metadata};if(I.snippetOnly)H.context={before:[],line:H.context.line,after:[]};Y.push(H)}),Y}function kL($,I){if(!I||$.length<=I)return $;return`${$.slice(0,Math.max(0,I))}...`}function d21($){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 nV0($){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 m21($){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 l21($){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 o21($,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=iV0.get(J);if(!U.refresh&&Q&&Date.now()<Q.expiresAt)return Q;let[K,q,G]=await Promise.all([r21($,{scope:Y,versionId:U.ruleVersionId,versionNumber:U.ruleVersionNumber,latest:U.latestRuleVersion}),z2($,{limit:U.documentLimit??100}),n1($,I.seal.endpoints.approvalStylePreferences)]),H=Date.now(),W={entries:[...K,...q.articles.flatMap(m21),...l21(G)],fetchedAt:H,expiresAt:H+pV0};return iV0.set(J,W),W}async function r21($,I){if(I.scope==="current")return(await M$($)).rules.flatMap(d21);if(I.scope==="version"){let Y=await t21($,I);return nV0(Y)}return(await Q5($)).flatMap(nV0)}async function t21($,I){if(I.versionId)return X2($,I.versionId);let U=await Q5($),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 cV0($,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 tV0($){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 g$ extends Error{errors;warnings;constructor($,I=[]){super([`材料包校验失败:${$.length} 个错误`,...$.map((U)=>`- ${U}`)].join(`
`));this.errors=$;this.warnings=I;this.name="MaterialPackValidationError"}}import{createHmac as wK1,randomBytes as ZK1}from"node:crypto";function XK1($,I,U,Y){return wK1("sha256",Y).update(`${$}.${I}.${JSON.stringify(U)}`).digest("hex")}function Vh($,I){let U=Math.floor(Date.now()/1000),Y=ZK1(16).toString("hex");return{Authorization:`Bearer ${I}`,"x-webhook-signature":XK1(U,Y,$,I),"x-webhook-timestamp":String(U),"x-webhook-nonce":Y}}var Ix=XI(Lw0(),1),QZ0=XI(JZ0(),1);var UD={maxEntries:1000,maxTotalSize:524288000,maxCompressionRatio:150};async function KZ0($){return new Promise((I,U)=>{Ix.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=qZ0(K);if(!q.endsWith("/")&&!pq1(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 qZ0($){let I=Buffer.isBuffer($.fileName)?$.fileName:Buffer.from(String($.fileName),"binary"),U=I.toString("utf8");if(!U.includes("�"))return U;let Y=QZ0.default.decode(I,"gbk");if(!Y.includes("�"))return Y;return U}function pq1($){let I=$.split("/").pop()??"";return $.split("/").includes("__MACOSX")||I===".DS_Store"||I.startsWith("._")||I.startsWith(".~")||I.startsWith("~$")}function GZ0($,I){let U=[],Y=DU(I);if($.length>UD.maxEntries)U.push(`文件数超过 ${UD.maxEntries}`);if($.reduce((K,q)=>K+q.uncompressedSize,0)>UD.maxTotalSize)U.push("解压后总大小超过 500MB");for(let K of $){if(K.fileName.startsWith("/")||K.fileName.split("/").includes(".."))U.push(`存在不安全路径: ${K.fileName}`);if(K.compressedSize>0&&K.uncompressedSize/K.compressedSize>UD.maxCompressionRatio)U.push(`压缩比超过 150: ${K.fileName}`);if(K.fileName==="信息表.xlsx")continue;cq1(K,Y,U)}if(!$.find((K)=>K.fileName==="信息表.xlsx"))U.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");if($.some((K)=>K.fileName.toLowerCase().endsWith(".zip")))U.push("不允许嵌套 ZIP");if(U.length)throw new g$(U)}function cq1($,I,U){let Y=dq1($.fileName);if(!Y||!I.allowedExtensions.includes(Y))U.push(`附件后缀不在白名单中: ${$.fileName}(允许: ${I.allowedExtensions.join(", ")})`);if($.uncompressedSize<I.minFileSizeBytes)U.push(`附件文件过小: ${$.fileName}(${$.uncompressedSize} B,小于最小值 ${I.minFileSizeBytes} B)`);if(I.maxFileSizeBytes!==void 0&&I.maxFileSizeBytes!==null&&$.uncompressedSize>I.maxFileSizeBytes)U.push(`附件文件过大: ${$.fileName}(${$.uncompressedSize} B,大于最大值 ${I.maxFileSizeBytes} B)`)}function dq1($){let I=$.split("/").pop()??$,U=I.lastIndexOf(".");return U>0?I.slice(U).toLowerCase():""}function Ux($,I){return new Promise((U,Y)=>{Ix.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(qZ0(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 WZ0=XI(ay(),1);function mq1($){return $.startsWith("[附件]")}function VZ0($){return $.startsWith("[附件]")?$.slice(4):$}function lq1($){return VZ0($).toLowerCase().replace(/\s+/g,"_")||"attachment"}function oq1($){if($==null||$==="")return[];return String($).split(/[\n,;,;]/).map((I)=>I.trim()).filter(Boolean)}function Yx($,I){let U=[];for(let[Y,J]of I.entries()){if(!mq1(Y))continue;let Q=$.getCell(J).value,K=oq1(Q);if(!K.length)continue;U.push({key:lq1(Y),label:VZ0(Y),paths:K})}return U}function Jx($){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 YD($,I,U,Y){return{key:$,label:I,type:U,value:Y}}function wZ0($,I,U){return YD($,I,"TEXT",U==null?"":String(U))}function ZZ0($,I,U){return YD($,I,"AMOUNT",typeof U==="number"?{amount:U,currency:"CNY"}:null)}function XZ0($){if($ instanceof Date)return $.toISOString();if(typeof $==="string"&&$.trim())return $.trim();return null}function rq1($){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 KG($){let I=new Map;return $.getRow(1).eachCell((U,Y)=>I.set(String(U.value??"").trim(),Y)),I}function YI($,I,U){let Y=I.get(U);return Y?$.getCell(Y).value:void 0}function tq1($,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"] Line truncated
`);let F=new FormData,E=await Ux(Y.fileBuffer,D),T=L.split("/").pop()??L;F.append("files",new File([new Uint8Array(E)],T));let A=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/attachments`,{method:"POST",headers:Vh({},U.secret),body:F});if(!A.ok)throw Error(`附件上传失败 ${A.status}: ${await A.text()}`);let R=await A.json();W.set(L,R.attachments?.map((u)=>u.data)??(R.data===void 0?[]:[R.data])),process.stderr.write(`✓ 附件上传成功: ${L}
`)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${G.document.documentId}
`);let w=Qx(G.document,H,W),Z=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/document`,{method:"POST",headers:{"Content-Type":"application/json",...Vh({webhookId:Q,...w},U.secret)},body:JSON.stringify(w)});if(!Z.ok)throw Error(`Webhook 单据推送失败 ${Z.status}: ${await Z.text()}`);K.push({documentId:w.documentId,document:w,pushResult:await Z.json()}),process.stderr.write(`✓ 单据推送成功: ${w.documentId}
`)}return{warnings:[],results:K}}function QI($){return{fileBuffer:eq1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}import{existsSync as YG1}from"node:fs";async function QD($,I,U={}){let J=L4().stateful?"stateful":"stateless",Q="ok",K,q,G;try{let A=await N$($);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}:{}})),w=W?{id:H[0].id,name:H[0].name,mode:H[0].mode}:null,Z=U.webhook?L9(H,U.webhook):W?H[0]:void 0,z;if(U.filePath)if(!YG1(U.filePath))z={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在: ${U.filePath}`]};else try{let A=QI(U.filePath),R=await JI(A.fileBuffer,A.fileName,Z?.materialPackFilePolicy);z={valid:!0,filePath:U.filePath,fileName:A.fileName,documentCount:R.documents.length,warnings:R.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 L=z?z.valid:!0,D=Q==="ok"&&V.length>0&&L,F=J==="stateful"?"":` --corp ${I.id}`,E="",T="";if(Q!=="ok")T=`凭证鉴权异常: ${K}`,E=`seal-use auth diagnose${F}`;else if(V.length===0)T="当前企业尚未配置任何 Webhook 集成通道",E=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${F}`;else if(z&&!z.valid)T=`材料包预检失败: ${z.errors?.join("; ")}`,E=`seal-use webhook material-pack preview ${z.filePath}${F}`;else{T=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${V.length} 个 Webhook 通道,等待载入`;let A=z?.filePath??"<材料包.zip>",R=W?"":` --webhook ${w?w.id:"<webhookIdOrName>"}`;E=`seal-use webhook material-pack push ${A}${R}${F}`}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:w,materialPack:z,statusMessage:T,nextAction:E}}var GG=[{name:"seal_whoami",description:"查询当前 Seal 用户身份及租户信息",parameters:X.object({}),handler:async($)=>N$($)},{name:"seal_session_get",description:"查询当前 Seal Bearer session、用户和过期时间",parameters:X.object({}),handler:async($)=>Gm($)},{name:"seal_delegation_list",description:"查询当前 Seal 租户下的授权链接 (Delegation) 列表",parameters:X.object({}),handler:async($)=>ym($)},{name:"seal_delegation_create",description:"创建新的 Seal 授权链接 (Delegation)",parameters:X.object({note:X.string().optional().describe("授权链接的备注或说明信息")}),handler:async($,I)=>OU($,I)},{name:"seal_delegation_revoke",description:"撤销/废除指定的 Seal 授权链接 (Delegation)",parameters:X.object({tokenId:X.string().describe("授权链接 ID (delegation record ID)")}),handler:async($,I)=>hm($,I.tokenId)},{name:"seal_user_create",description:"创建本地 Seal 用户,生成并返回初始随机密码",parameters:X.object({name:X.string().describe("用户姓名"),phone:X.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),permissions:X.array(X.string()).optional().describe("权限列表,默认为 []"),departmentIds:X.array(X.string()).optional().describe("关联部门 ID 数组")}),handler:async($,I)=>xm($,I)},{name:"seal_user_reset_password",description:"重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>fE($,I.userId)},{name:"seal_user_get",description:"获取指定 Seal 用户的详细信息",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>yV($,I.userId)},{name:"seal_user_search",description:"按姓名、手机号或邮箱搜索 Seal 成员用户列表",parameters:X.object({keyword:X.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")}),handler:async($,I)=>hV($,I.keyword??"")},{name:"seal_user_delete",description:"删除指定 Seal 本地用户",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>lm($,I.userId)},{name:"seal_user_activate",description:"启用/激活已离职的 Seal 用户账号",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>bE($,I.userId)},{name:"seal_user_delegation_create",description:"为指定 S Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:TJ({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:VD(I,["template.name","templateName","form.name","formName","formTitle"]),amount:qD(U,["金额","报销金额","付款金额","合计","价税合计"])??VD(I,["amount","totalAmount","expenseAmount"]),expenseType:qD(U,["费用类型","费用类别","报销类型"]),costCompany:qD(U,["费用承担公司","承担公司","成本中心","费用归属"]),payee:qD(U,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:U.slice(0,30)}),invoices:NG1($),attachments:ZJ($,{summary:!0}).attachments,aiResult:ZD($),manualResult:qI($)?.value,hints:TJ({amountMentions:MZ0(Y,["金额","合计","税率"],8),partyMentions:MZ0(Y,["买方","卖方","甲方","乙方","收款"],8)})}}function LG1($){let I=[["result.citedRules",n5($,"result.citedRules")],["result.matchedRules",n5($,"result.matchedRules")],["result.ruleResults",n5($,"result.ruleResults")],["result.rules",n5($,"result.rules")],["pipelineData.citedRules",n5($,"pipelineData.citedRules")],["pipelineData.matchedRules",n5($,"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=HG(q);if(!H)return;let W=I4(H.runtimeRuleId)??I4(H.runtimeId)??I4(H.id)??I4(H.ruleId),V=I4(H.ruleCode)??I4(H.code)??(W?PG1(W):void 0),w=TJ({runtimeRuleId:W,ruleCode:V,versionNumber:OG1(H.versionNumber)??$.ruleSetVersionNumber,scope:I4(H.scope),strictness:I4(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(w);if(!Y.has(Z))Y.add(Z),U.push(w)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:U.length,rules:U}}function VD($,I){if(!$)return;for(let U of I){let Y=n5($,U);if(Y!==void 0)return Y}return}function NZ0($,I){if(!$)return 0;for(let U of I){let Y=n5($,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 n5($,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 DG1($,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 TJ($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function HG($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function OG1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function FG1($){let I=[];return Gx($,"document",I),I}function Gx($,I,U){if(Array.isArray($)){$.forEach((K,q)=>Gx(K,`${I}.${q}`,U));return}let Y=HG($);if(!Y)return;let J=I4(Y.label)??I4(Y.name)??I4(Y.title)??I4(Y.fieldName),Q=Y.value??Y.displayValue??Y.text??Y.content;if(J&&Q!==void 0&&typeof Q!=="object")U.push(TJ({path:I,label:J,value:Q,type:I4(Y.type)??I4(Y.fieldType)}));for(let[K,q]of Object.entries(Y)){if(K==="attachments")continue;Gx(q,`${I}.${K}`,U)}}function qD($,I){return $.find((Y)=>{let J=I4(Y.label)??"";return I.some((Q)=>J.includes(Q))})?.value}function NG1($){let I=[];return wD($.result,"result",I),wD($.document,"document",I),I.slice(0,20)}function wD($,I,U){if(Array.isArray($)){$.forEach((J,Q)=>wD(J,`${I}.${Q}`,U));return}let Y=HG($);if(!Y)return;if(/invoice|发票/i.test(I))U.push(TJ({path:I,fileName:I4(Y.fileName)??I4(Y.filename)??I4(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))wD(Q,`${I}.${J}`,U)}function MZ0($,I,U){return $.split(/\r?\n/).filter((Y)=>I.some((J)=>Y.includes(J))).slice(0,U)}function GD($){return $.map((I)=>{let U=KI(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 Kx($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function MG1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let U=await f4($,I.recordId);if(!U.ruleSetVersionNumber)throw Er Line truncated
`)}
`}function Wz($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function R0($,I={}){xz1($,I);let q=`${JSON.stringify($,null,2)}
`;if(I.outputFile){hz1(I.outputFile,q),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(q,"utf-8")},null,2));return}console.log(q.trimEnd())}function xz1($,I={}){if(I.allowFull||I.outputFile)return;let q=Buffer.byteLength(JSON.stringify($),"utf-8");if(q>uz1)throw Error(`Output is large (${q} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function qZ0($,I){if(I)return;let q=$&&typeof $==="object"?$:{},U=typeof q.count==="number"?q.count:void 0,Y=Array.isArray(q.rules)?q.rules.length:void 0,J=Buffer.byteLength(JSON.stringify($),"utf-8"),Q=U??Y??0;if(Q>Sz1||J>yz1)throw Error(`Rule list is large (${Q} rules, ${J} 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:S0($.full)===!0,outputFile:x($.outputFile)??x($["output-file"])}}function UZ0(){console.log(`seal-use CLI
`}function ZG($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function B0($,I={}){kG1($,I);let U=`${JSON.stringify($,null,2)}
`;if(I.outputFile){gG1(I.outputFile,U),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function kG1($,I={}){if(I.allowFull||I.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>xG1)throw new XD(`Output is large (${U} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function cZ0($,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>yG1||Q>hG1)throw new XD(`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.`,"seal-use rules list --summary")}function V0($){return{allowFull:N0($.full)===!0,outputFile:h($.outputFile)??h($["output-file"])}}function dZ0(){console.log(`seal-use CLI
Usage:
seal-use version
@@ -330,6 +335,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>]
@@ -352,6 +359,12 @@ Usage:
seal-use users reset-password <userId> [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
@@ -359,25 +372,27 @@ Usage:
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--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 webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size 500] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--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] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.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>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--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>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use rules count [--corp <corpId>]
@@ -392,35 +407,40 @@ 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 analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]
seal-use approval-runs url [--corp <corpId>]
seal-use approval-runs url <recordId> [--corp <corpId>]
seal-use approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
seal-use simulation batch-records <batchId> [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--corp <corpId>]
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation status <batchId> [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use simulation clean <batchId> [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation approval-definitions [--corp <corpId>]
seal-use simulation list [--limit 50] [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
seal-use simulation package-upload <材料包.zip> [--corp <corpId>]
`)}function D4($){let I=H8(),q=H6();return Gq(I,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$},y7())}function Zz($=H6()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},lint:$.lint,configFile:wq()}}async function L0($,I,q,U,Y={}){R0(await II($,I,q,U),Y)}async function II($,I,q,U){let Y=Gz.find((K)=>K.name===$);if(!Y)throw Error(`Unknown Seal tool: ${$}`);let J=Object.fromEntries(Object.entries(U).filter(([,K])=>K!==void 0)),Q=Y.handler;return Q(I,J,{corp:q})}async function YZ0($,I,q,U,Y){if($==="summary"){let J=await II("seal_approval_runs_summary",q,U,{date:x(Y.options.date),timezone:x(Y.options.timezone),limit:$1(Y.options.limit),startDate:x(Y.options.startDate),endDate:x(Y.options.endDate),status:x(Y.options.status),taskMode:x(Y.options.taskMode),manualApprovalStatus:x(Y.options.manualApprovalStatus),sourceDocumentSN:x(Y.options.sourceDocumentSN),sourceDocumentId:x(Y.options.sourceDocumentId),humanResult:x(Y.options.humanResult),query:x(Y.options.query)});if(J?.matched===0&&J?.total>0)console.error(`提示:在 ${J.date} 未匹配到记录(该企业共有 ${J.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-use approval-runs list --limit 10 查看最近记录。`);R0(J,O0(Y.options));return}if($==="stats"){await L0("seal_approval_runs_stats",q,U,{since:x(Y.options.since),dedupeBy:x(Y.options.dedupeBy)??x(Y.options["dedupe-by"]),status:x(Y.options.status),sourceSystem:x(Y.options.sourceSystem)??x(Y.options["source-system"]),taskMode:x(Y.options.taskMode)??x(Y.options["task-mode"])},O0(Y.options));return}if($==="count"){await L0("seal_approval_runs_count",q,U,{status:x(Y.options.status),sourceSystem:x(Y.options.sourceSystem)??x(Y.options["source-system"]),taskMode:x(Y.options.taskMode)??x(Y.options["task-mode"]),search:x(Y.options.search)??x(Y.options.query)},O0(Y.options));return}if($==="search"||$==="list"){await L0("seal_approval_runs_search",q,U,{limit:$1(Y.options.limit),offset:$1(Y.options.offset),startDate:x(Y.options.startDate),endDate:x(Y.options.endDate),status:x(Y.options.status),taskMode:x(Y.options.taskMode),manualApprovalStatus:x(Y.options.manualApprovalStatus),sourceDocumentSN:x(Y.options.sourceDocumentSN),sourceDocumentId:x(Y.options.sourceDocumentId),humanResult:x(Y.options.humanResult),query:x(Y.options.query),includeBridge:S0(Y.options.includeBridge)},O0(Y.options));return}if($==="bridge"){await L0("seal_approval_run_langfuse_bridge_get",q,U,{recordId:x(Y.options.recordId),sourceDocumentSN:x(Y.options.sourceDocumentSN),sourceDocumentId:x(Y.options.sourceDocumentId),simulationBatchId:x(Y.options.simulationBatchId),limit:$1(Y.options.limit)},O0(Y.options));return}if($==="pick"){let J=I??x(Y.options.query)??x(Y.options.sn);if(!J)throw Error("Usage: seal-use approval-runs pick --sn <documentSN>");await L0("seal_approval_run_pick",q,U,{query:J,sn:x(Y.options.sn),batchId:x(Y.options.batch)??x(Y.options.batchId),latest:S0(Y.options.latest),fields:x(Y.options.fields),limit:$1(Y.options.limit),includeBridge:S0(Y.options.includeBridge)},O0(Y.options));return}if($==="get"){let J=Y.command[2];if(!J)throw Error("Missing approval run recordId");await L0("seal_approval_run_get",q,U,{recordId:J,fields:x(Y.options.fields),summary:S0(Y.options.summary)},O0(Y.options));return}if($==="cited-rules"){let J=Y.command[2];if(!J)throw Error("Usage: seal-use approval-runs cited-rules <recordId>");await L0("seal_approval_run_cited_rules_get",q,U,{recordId:J},O0(Y.options));return}if($==="document-summary"){let J=Y.command[2];if(!J)throw Error("Usage: seal-use approval-runs document-summary <recordId>");await L0("seal_approval_run_document_summary_get",q,U,{recordId:J},O0(Y.options));return}if($==="attachments"){let J=Y.command[2];if(!J)throw Error("Usage: seal-use approval-runs attachments <recordId>");await L0("seal_approval_run_attachments_get",q,U,{recordId:J,summary:S0(Y.options.summary)},O0(Y.options));return}if($==="result"){let J=Y.command[2];if(!J)throw Error("Usage: seal-use approval-runs result <recordId> [--summary]");await L0("seal_approval_run_result_get",q,U,{recordId:J,summary:S0(Y.options.summary)},O0(Y.options));return}if($==="url"){await L0("seal_approval_run_url_get",q,U,{recordId:I,sourceDocumentSN:x(Y.options.sourceDocumentSN),sourceDocumentId:x(Y.options.sourceDocumentId)},O0(Y.options));return}throw Error(`Unknown approval-runs command: ${$??""}. Run 'seal-use help' for available commands.`)}async function KZ0($,I,q){if($==="diagnose"){R0(await kz1(I));return}if($==="hose-link"){let U=$1(q.options.expire)??7200;R0(await Hd(I,U));return}throw Error(`Unknown auth command: ${$??""}. Run 'seal-use help' for available commands.`)}async function kz1($){if($.source.type!=="hose"){let X=await I4($),D=await W8(X);return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:D.user,tenant:D.tenant}]}}gH($.id);let I=$.source, Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${S.length} candidate administrators:
- ${t}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!D)if(!G&&J)D=J;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let O=b1($,"id")??W,N=V??W,T=b1($,"sealUrl")??`https://${W.toLowerCase()}.sealai.cc`,P={id:O,name:N,seal:{url:T,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:H,appKey:q,appSecurity:U,corpId:W,staffId:D},auth:{refreshTtl:300}};if(G)gH(O),await FY(P);let g=OT();ZZ0(g,{recursive:!0,mode:448});let B=DZ0(g,`${Ku(O)}.json`);if(WZ0(B)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${B}. Pass "overwrite": true to replace it.`);XZ0(B,`${JSON.stringify(P,null,2)}
`,{mode:384}),R0({id:O,name:N,corpId:W,domain:H,staffId:D,verified:G,path:B})}async function cz1($){let I=Z7($,"token"),q=(b1($,"sealUrl")??b1($,"url")??"").replace(/\/+$/,"");if(!q)throw Error("Missing required JSON field: sealUrl");let U=tW0($,"expiresIn")??2592000,Y=$.force===!0||$.verify===!1?!1:!0,J=Y?await lz1(q,I):void 0;LZ0($,{token:I,sealUrl:q,expiresIn:U,verify:Y,remote:J})}async function dz1($,I,q){let U=await PH($),Y=JQ(U.sealUrl,U.token),J=await W8(Y),Q={user:J.user,tenant:J.tenant};TH(U.corpId,Q.tenant),LZ0({id:U.corpId,corpId:U.corpId,name:I,provider:"hosecloud",overwrite:q},{token:U.token,sealUrl:U.sealUrl,expiresIn:U.expiresIn,verify:!0,remote:Q})}function LZ0($,I){let{token:q,sealUrl:U,expiresIn:Y,verify:J,remote:Q}=I,K=Q?.user,z=Q?.tenant,w=b1($,"tenantSlug")??X7(z?.tenantSlug),G=b1($,"tenantId")??X7(z?.id),H=b1($,"tenantName")??X7(z?.name),W=b1($,"id")??w??G;if(!W)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let V=b1($,"staffId")??X7(K?.providerUserId)??X7(K?.id)??"seal",X=b1($,"provider")??X7(K?.provider)??X7(z?.providerConfig?.provider),D=b1($,"corpId")??w??G??W,O={id:W,name:b1($,"name")??H??W,seal:{url:U,tenantSlug:w,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:q,sealUrl:U,expiresIn:Y,staffId:V,corpId:D,tenantId:G,tenantSlug:w,tenantName:H,providerUserId:X7(K?.providerUserId),provider:X},auth:{refreshTtl:300}},N=OT();ZZ0(N,{recursive:!0,mode:448});let T=DZ0(N,`${Ku(W)}.json`);if(WZ0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);XZ0(T,`${JSON.stringify(O,null,2)}
`,{mode:384}),R0({id:W,name:O.name,tenantId:G,tenantSlug:w,verified:J,path:T})}async function lz1($,I){let q=await mz1(`${$}/api/v1/auth/me`,{authorization:`Bearer ${I}`}),U=HO(q.data);return{user:HO(U.user??q.user),tenant:HO(U.tenant??q.tenant)}}async function mz1($,I={}){let q=await fetch($,{headers:I}),U=await q.text();if(!q.ok)throw Error(`${q.status} ${U}`);let Y=JSON.parse(U);return HO(Y)}function HO($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function X7($){return typeof $==="string"&&$?$:void 0}async function NZ0($,I){let q=await PH($),U=JQ(q.sealUrl,q.token),Y=await W8(U);TH(q.corpId,Y.tenant);let J=await Hq(U,{note:I});R0({tenant:{id:Y.tenant.id,name:Y.tenant.name,tenantSlug:Y.tenant.tenantSlug,corpId:q.corpId},user:{id:Y.user.id,name:Y.user.name,providerUserId:Y.user.providerUserId,isAdmin:Y.user.isAdmin},delegation:J,expiresIn:q.expiresIn})}async function FZ0($,I,q,U,Y){if($==="list"){await L0("seal_delegation_list",q,U,{},O0(Y.options));return}if($==="create"){let J=x(Y.options.note)??(I?[I,...Y.command.slice(2)].join(" "):void 0);await L0("seal_delegation_create",q,U,{note:J},O0(Y.options));return}if($==="revoke"){let J=I??x(Y.options.tokenId);if(!J)throw Error("Usage: seal-use delegation revoke <tokenId>");await L0("seal_delegation_revoke",q,U,{tokenId:J},O0(Y.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as oz1}from"node:fs";async function MZ0($,I,q,U,Y,J){if(!$||$==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
`)}function D4($){let I=b8(),U=L4();return XJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},s3())}function GI($=L4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:e3()}}async function D0($,I,U,Y,J={}){B0(await HI($,I,U,Y),J)}async function HI($,I,U,Y){let J=GG.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 mZ0($,I,U,Y,J){if($==="summary"){let Q=await HI("seal_approval_runs_summary",U,Y,{date:h(J.options.date),timezone:h(J.options.timezone),limit:d0(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 查看最近记录。`);B0(Q,V0(J.options));return}if($==="stats"){await D0("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"])},V0(J.options));return}if($==="count"){await D0("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)},V0(J.options));return}if($==="search"||$==="list"){await D0("seal_approval_runs_search",U,Y,{limit:d0(J.options.limit),offset:d0(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:N0(J.options.includeBridge)},V0(J.options));return}if($==="bridge"){await D0("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:d0(J.options.limit)},V0(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 D0("seal_approval_run_pick",U,Y,{query:Q,sn:h(J.options.sn),batchId:h(J.options.batch)??h(J.options.batchId),latest:N0(J.options.latest),fields:h(J.options.fields),limit:d0(J.options.limit),includeBridge:N0(J.options.includeBridge)},V0(J.options));return}if($==="get"){let Q=J.command[2];if(!Q)throw Error("Missing approval run recordId");await D0("seal_approval_run_get",U,Y,{recordId:Q,fields:h(J.options.fields),summary:N0(J.options.summary)},V0(J.options));return}if($==="cited-rules"){let Q=J.command[2];if(!Q)throw Error("Usage: seal-use approval-runs cited-rules <recordId>");await D0("seal_approval_run_cited_rules_get",U,Y,{recordId:Q},V0(J.options));return}if($==="document-summary"){let Q=J.command[2];if(!Q)throw Error("Usage: seal-use approval-runs document-summary <recordId>");await D0("seal_approval_run_document_summary_get",U,Y,{recordId:Q},V0(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 gL({record:W,all:N0(J.options.all),name:h(J.options.name),outDir:h(J.options["out-dir"])??h(J.options.outDir)??h(J.options.dir)});if(B0(V,V0(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(N0(J.options.download)){let H=await f4(U,K),W=await gL({record:H,all:N0(J.options.all)??!0,name:h(J.options.name),outDir:h(J.options["out-dir"])??h(J.options.outDir)??h(J.options.dir)});if(B0(W,V0(J.options)),W.total>0&&W.downloaded===0)throw Error(`所有 ${W.total} 个附件下载均失败。`);return}let q=await f4(U,K),G=ZJ(q,{summary:N0(J.options.summary)});B0(G,V0(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:
- ${p}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!L)if(!W&&Q)L=Q;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let D=i1($,"id")??w,F=Z??w,E=i1($,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,T={id:D,name:F,seal:{url:E,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:V,appKey:U,appSecurity:Y,corpId:w,staffId:L},auth:{refreshTtl:300}};if(W)AV(D),await EJ(T);let A=Jh();QX0(A,{recursive:!0,mode:448});let R=qX0(A,`${zx(D)}.json`);if(JX0(R)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${R}. Pass "overwrite": true to replace it.`);KX0(R,`${JSON.stringify(T,null,2)}
`,{mode:384}),B0({id:D,name:F,corpId:w,domain:V,staffId:L,verified:W,path:R})}async function cG1($){let I=L7($,"token"),U=(i1($,"sealUrl")??i1($,"url")??"").replace(/\/+$/,"");if(!U)throw Error("Missing required JSON field: sealUrl");let Y=uZ0($,"expiresIn")??2592000,J=$.force===!0||$.verify===!1?!1:!0,Q=HX0($),K=J?await mG1(U,I,H2(Q)):void 0;WX0($,{token:I,sealUrl:U,expiresIn:Y,verify:J,remote:K,custom:Q})}function HX0($){return{headers:$h.parse($.headers),cookies:Ih.parse($.cookies)}}async function dG1($,I,U){let Y=await PV($),J=W2(Y.sealUrl,Y.token),Q=await N$(J),K={user:Q.user,tenant:Q.tenant};TV(Y.corpId,K.tenant),WX0({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 WX0($,I){let{token:U,sealUrl:Y,expiresIn:J,verify:Q,remote:K}=I,q=I.custom??HX0($),G=K?.user,H=K?.tenant,W=i1($,"tenantSlug")??D7(H?.tenantSlug),V=i1($,"tenantId")??D7(H?.id),w=i1($,"tenantName")??D7(H?.name),Z=i1($,"id")??W??V;if(!Z)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let z=i1($,"staffId")??D7(G?.providerUserId)??D7(G?.id)??"seal",L=i1($,"provider")??D7(G?.provider)??D7(H?.providerConfig?.provider),D=i1($,"corpId")??W??V??Z,F={id:Z,name:i1($,"name")??w??Z,seal:{url:Y,tenantSlug:W,headers:q.headers,cookies:q.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:U,sealUrl:Y,expiresIn:J,staffId:z,corpId:D,tenantId:V,tenantSlug:W,tenantName:w,providerUserId:D7(G?.providerUserId),provider:L},auth:{refreshTtl:300}},E=Jh();QX0(E,{recursive:!0,mode:448});let T=qX0(E,`${zx(Z)}.json`);if(JX0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);KX0(T,`${JSON.stringify(F,null,2)}
`,{mode:384}),B0({id:Z,name:F.name,tenantId:V,tenantSlug:W,verified:Q,path:T})}async function mG1($,I,U={}){let Y=await lG1(`${$}/api/v1/auth/me`,{...U,authorization:`Bearer ${I}`}),J=OD(Y.data);return{user:OD(J.user??Y.user),tenant:OD(J.tenant??Y.tenant)}}async function lG1($,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 OD(J)}function OD($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function D7($){return typeof $==="string"&&$?$:void 0}async function VX0($,I){let U=await PV($),Y=W2(U.sealUrl,U.token),J=await N$(Y);TV(U.corpId,J.tenant);let Q=await OU(Y,{note:I});B0({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 wX0($,I,U,Y,J){if($==="list"){await D0("seal_delegation_list",U,Y,{},V0(J.options));return}if($==="create"){let Q=h(J.options.note)??(I?[I,...J.command.slice(2)].join(" "):void 0);await D0("seal_delegation_create",U,Y,{note:Q},V0(J.options));return}if($==="revoke"){let Q=I??h(J.options.tokenId);if(!Q)throw Error("Usage: seal-use delegation revoke <tokenId>");await D0("seal_delegation_revoke",U,Y,{tokenId:Q},V0(J.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as oG1}from"node:fs";async function ZX0($,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>
@@ -428,25 +448,25 @@ Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an a
`+` • feishu (飞书审批): 建议使用 Webhook 模式对接
`+` • weaver (泛微 OA): 建议使用 Webhook 模式对接
`+` • helios (汇联易): 建议使用 Webhook 模式对接
`+" • 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 w=$==="maycur"?"每刻报销":"汇联易";throw Error(`${w}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${w}' --result-url <url> --corp <corpId>`)}let Q=$==="hosecloud",K=$==="hosecloud"?I:$,z=$==="hosecloud"?q:I;if(!Q)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(K==="requirements"){await L0("seal_deploy_hosecloud_requirements",U,Y,{},O0(J.options));return}if(K==="list"){await L0("seal_deploy_hosecloud_list",U,Y,{},O0(J.options));return}if(K==="get"){let w=z??x(J.options.signKey)??x(J.options["sign-key"]);if(!w){let H=((await Q4(U)).integrations??[]).filter((W)=>W.type==="hosecloud");if(H.length===0)throw Error(`当前企业 (${Y.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Y.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${Y.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let W of H){let V=W.outboundName??"SealAI 审批",X=W.signKey,D=W.apiOrigin??"production";console.error(` • "${V}" (signKey: ${X}, 环境: ${D})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${X} --corp ${Y.id}
`)}throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。")}await L0("seal_deploy_hosecloud_get",U,Y,{signKey:w},O0(J.options));return}if(K==="status"){await L0("seal_deploy_hosecloud_status",U,Y,{},O0(J.options));return}if(K==="configure"){let w=x(J.options.input),G=w?JSON.parse(oz1(w,"utf8")):r6(J.json);if(!G||Object.keys(G).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await L0("seal_deploy_hosecloud_configure",U,Y,G,O0(J.options));return}if(K==="sync"){let w=z??x(J.options.signKey)??x(J.options["sign-key"]),G=S0(J.options.auto)??S0(J.options.yes);if(!w){let W=((await Q4(U)).integrations??[]).filter((X)=>X.type==="hosecloud");if(W.length===0)throw Error(`当前企业 (${Y.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Y.id}`);let V=W[0];if(V&&W.length===1&&G){let X=V.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${X})`),await L0("seal_deploy_hosecloud_sync",U,Y,{signKey:X},O0(J.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${Y.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of W){let D=X.outboundName??"SealAI 审批",O=X.signKey,N=X.apiOrigin??"production";console.error(` • "${D}" (signKey: ${O}, 环境: ${N})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${O} --corp ${Y.id}
`)}if(W.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${Y.id}
`);throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。")}await L0("seal_deploy_hosecloud_sync",U,Y,{signKey:w},O0(J.options));return}throw Error(`Unknown deploy hosecloud action: ${K??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as ez1}from"node:http";import{URL as tz1}from"node:url";var AZ0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.7",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 D0("seal_deploy_hosecloud_requirements",Y,J,{},V0(Q.options));return}if(q==="list"){await D0("seal_deploy_hosecloud_list",Y,J,{},V0(Q.options));return}if(q==="get"){let H=G??h(Q.options.signKey)??h(Q.options["sign-key"]);if(!H){let V=((await n1(Y)).integrations??[]).filter((w)=>w.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 w of V){let Z=w.outboundName??"SealAI 审批",z=w.signKey,L=w.apiOrigin??"production";console.error(` • "${Z}" (signKey: ${z}, 环境: ${L})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${z} --corp ${J.id}
`)}throw new c8("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,V.length===1?`seal-use deploy hosecloud get ${V[0].signKey} --corp ${J.id}`:void 0)}await D0("seal_deploy_hosecloud_get",Y,J,{signKey:H},V0(Q.options));return}if(q==="status"){await D0("seal_deploy_hosecloud_status",Y,J,{},V0(Q.options));return}if(q==="configure"){let H=h(Q.options.input),W=H?JSON.parse(oG1(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 D0("seal_deploy_hosecloud_configure",Y,J,{...W,dryRun:N0(Q.options.dryRun)??N0(Q.options["dry-run"])},V0(Q.options));return}if(q==="sync"){let H=G??h(Q.options.signKey)??h(Q.options["sign-key"]),W=N0(Q.options.auto)??N0(Q.options.yes);if(!H){let w=((await n1(Y)).integrations??[]).filter((z)=>z.type==="hosecloud");if(w.length===0)throw Error(`当前企业 (${J.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${J.id}`);let Z=w[0];if(Z&&w.length===1&&W){let z=Z.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${z})`),await D0("seal_deploy_hosecloud_sync",Y,J,{signKey:z},V0(Q.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${J.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let z of w){let L=z.outboundName??"SealAI 审批",D=z.signKey,F=z.apiOrigin??"production";console.error(` • "${L}" (signKey: ${D}, 环境: ${F})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${D} --corp ${J.id}
`)}if(w.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${J.id}
`);throw new c8("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,w.length===1?`seal-use deploy hosecloud sync ${w[0].signKey} --corp ${J.id}`:void 0)}await D0("seal_deploy_hosecloud_sync",Y,J,{signKey:H},V0(Q.options));return}throw Error(`Unknown deploy hosecloud action: ${q??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as eG1}from"node:http";import{URL as tG1}from"node:url";var XX0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.14",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${a0})</title>
<title>Seal Home API Docs (v${I1})</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 {
@@ -465,21 +485,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 u4($,I,q,U){let Y=$.handler;return Y(I,q,{corp:U})}async function PZ0($,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 q=$.headers.host||"localhost",U=$.headers["x-forwarded-proto"]||"http",Y=new tz1($.url||"/",`${U}://${q}`),J=Y.pathname.replace(/\/+$/,"")||"/",Q=($.method||"GET").toUpperCase();try{if(Q==="GET"&&J==="/"){d1(I,200,{name:"seal-use",version:a0,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(Q==="GET"&&J==="/docs"){sz1(I,200,gZ0());return}if(Q==="GET"&&J==="/openapi.json"){d1(I,200,VO());return}if(Q==="GET"&&J==="/health"){d1(I,200,{status:"ok",version:a0,name:"seal-use",timestamp:new Date().toISOString()});return}if(Q==="POST"&&(J==="/shutdown"||J==="/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(Q==="POST"&&J==="/api/cli"){let K=await ZO($),z=(typeof K?.command==="string"?K.command:"").trim();if(!z){WO(I,400,"Missing 'command' property in request body");return}let w=Wu(z),G=w[0]==="seal-use"||w[0]==="seal-home"||w[0]?.endsWith("/seal-use")||w[0]?.endsWith("/seal-home")?w.slice(1):w,H=await Dz(G),W=void 0;try{if(H.stdout.trim().startsWith("{")||H.stdout.trim().startsWith("["))W=JSON.parse(H.stdout)}catch{}d1(I,H.isError?400:200,{success:!H.isError,stdout:H.stdout,stderr:H.stderr,exitCode:H.exitCode,data:W});return}if(Q==="POST"&&J.startsWith("/api/tool/")){let K=J.slice(10).trim(),z=B4(K,{includeMcpAliases:!0});if(!z){WO(I,404,`Tool not found: '${K}'`);return}let w=await ZO($)||{},G=_6($,Y,w),H=D4(G),W=await I4(H),V={...w};delete V.corp;let X=await u4(z,W,V,H);d1(I,200,X);return}if(J.startsWith("/v1/")){if(await az1($,I,Q,J,Y))return}WO(I,404,`Cannot ${Q} ${J}. Visit /docs for available endpoints.`)}catch(K){let z=K instanceof Error?K.message:String(K);WO(I,500,z)}}async function az1($,I,q,U,Y){let J=Object.fromEntries(Y.searchParams.entries());if(q==="GET"&&U==="/v1/corps"){let Q=H8(),K=H6();return d1(I,200,{count:Q.length,mode:K.stateful?"stateful":"stateless",defaultCorpId:K.defaultCorpId,corps:Q.map((z)=>({id:z.id,name:z.name,sourceType:z.source.type,sealUrl:z.seal?.url}))}),!0}if(q==="GET"&&U==="/v1/whoami"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_whoami"),G=await u4(w,z,{},K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/session"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_session_get"),G=await u4(w,z,{},K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/summary"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_approval_runs_summary"),G=await u4(w,z,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/stats"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_approval_runs_stats"),G=await u4(w,z,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/pick"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_approval_run_pick"),G=await u4(w,z,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/url"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_approval_run_url_get"),G=await u4(w,z,J,K);return d1(I,200,G),!0}if(U.startsWith("/v1/approval-runs/")){let Q=U.slice(18).split("/"),K=Q[0],z=Q[1];if(K&&!["summary","pick","stats","url","bridge"].includes(K)){let w=_6($,Y,J),G=D4(w),H=await I4(G);if(!z){let W=B4("seal_approval_run_get"),V=await u4(W,H,{recordId:K,...J},G);return d1(I,200,V),!0}if(z==="attachments"){let W=B4("seal_approval_run_attachments_get"),V=await u4(W,H,{recordId:K,...J},G);return d1(I,200,V),!0}if(z==="cited-rules"){let W=B4("seal_approval_run_cited_rules_get"),V=await u4(W,H,{recordId:K,...J},G);return d1(I,200,V),!0}if(z==="document-summary"){let W=B4("seal_approval_run_document_summary_get"),V=await u4(W,H,{recordId:K,...J},G);return d1(I,200,V),!0}if(z==="result"){let W=B4("seal_approval_run_result_get"),V=await u4(W,H,{recordId:K,...J},G);return d1(I,200,V),!0}}}if(q==="GET"&&U==="/v1/approval-runs"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_approval_runs_search"),G=await u4(w,z,{...J,limit:J.limit?Number(J.limit):void 0,offset:J.offset?Number(J.offset):void 0,includeBridge:J.includeBridge==="true"},K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval/rules"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_approval_rules_list"),G=await u4(w,z,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/simulation/batches"){let Q=_6($,Y,J),K=D4(Q),z=await I4(K),w=B4("seal_simulation_batches_list"),G=await u4(w,z,J,K);return d1(I,200,G),!0}if(q==="POST"&&U==="/v1/simulation/create-batch"){let Q=await ZO($)||{},K=_6($,Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${a0}) started`),console.error(` URL: http://${q}:${I}`),console.error(` Docs: http://${q}:${I}/docs`),console.error(` OpenAPI: http://${q}:${I}/openapi.json`),console.error(` CLI Exec: POST http://${q}:${I}/api/cli`),console.error(` REST API: http://${q}:${I}/v1/...
`);Y(U)})})}async function TZ0($){let I=$1($.options.port)??$1($.options.p),q=x($.options.host)??x($.options.h),U=await OO({port:I,host:q}),Y=()=>{U.close(()=>{process.exit(0)})};process.on("SIGINT",Y),process.on("SIGTERM",Y),await new Promise(()=>{})}async function jZ0($,I,q,U){if($==="config"||$==="get"){await L0("seal_llm_config_get",I,q,{},O0(U.options));return}if($==="providers"||$==="list"){await L0("seal_llm_providers_list",I,q,{},O0(U.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}async function EZ0($,I){if($==="config"||$==="json"){Zu();return}await Xu()}function Zu(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function BZ0($){let I=VO();R0(I,{...O0($.options),allowFull:!0})}async function vZ0($,I,q,U){if($==="available"){await L0("seal_permissions_available_list",I,q,{},O0(U.options));return}if($==="configs"||$==="list"){await L0("seal_permissions_configs_list",I,q,{},O0(U.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as RZ0}from"node:fs";async function CZ0($,I,q,U,Y,J,Q){if(!$||$==="get"){await L0("seal_preference_get",Y,J,{},O0(Q.options));return}if($==="decision"){if(I==="update"||!I){let K=x(Q.options.input),z=K?JSON.parse(RZ0(K,"utf8")):r6(Q.json);if(!z||Object.keys(z).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await L0("seal_preference_decision_update",Y,J,z,O0(Q.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let K=x(Q.options.default)??x(Q.options.level)??U;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await L0("seal_preference_thinking_depth_set",Y,J,{defaultLevel:K},O0(Q.options));return}if(I==="policies"){if(q==="list"||!q){await L0("seal_preference_thinking_depth_policies_list",Y,J,{},O0(Q.options));return}if(q==="upsert"){let K=x(Q.options.input),z=K?JSON.parse(RZ0(K,"utf8")):r6(Q.json);if(!z||!z.id||!z.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await L0("seal_preference_thinking_depth_policies_upsert",Y,J,z,O0(Q.options));return}if(q==="remove"||q==="delete"){let K=U??x(Q.options.id)??x(Q.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await L0("seal_preference_thinking_depth_policies_remove",Y,J,{policyId:K},O0(Q.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function _Z0($={}){let I=H8(),q=H6(),U=Gq(I,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$.corpId},y7());console.log(`[probe] corp=${U.id} source=${U.source.type}`);let Y=await FY(U);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Y,null,2));let J=await I4(U),Q=await bH(J,{documentLimit:20,stylePreferencesEndpoint:U.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:Q.rules.rules.length,hasPendingRuleDeletes:Q.rules.hasPendingDeletes,documents:Q.documents.articles.length,documentsTotal:Q.documents.total,stylePreferences:Q.stylePreferences.ok?"ok":`error: ${Q.stylePreferences.error}`},null,2))}async function hZ0($,I,q){let U=I??x(q.options.corp)??($&&$!=="--corp"?$:void 0);await _Z0({corpId:U})}async function Du($,I,q,U,Y){if($==="count"){await L0("seal_approval_rules_list",q,U,{countOnly:!0},O0(Y.options));return}if($==="list"){if(S0(Y.options.count)){await L0("seal_approval_rules_list",q,U,{countOnly:!0},O0(Y.options));return}let J=$1(Y.options.limit),Q=$1(Y.options.offset);if(S0(Y.options.summary)){await L0("seal_approval_rules_list",q,U,{fields:IZ0,limit:J,offset:Q},O0(Y.options));return}let K=await II("seal_approval_rules_list",q,U,{limit:J,offset:Q});qZ0(K,S0(Y.options.full)===!0),R0(K);return}if($==="clear"){let J=S0(Y.options.yes)===!0,Q=S0(Y.options.dryRun)??S0(Y.options["dry-run"])??!J;if(!J&&!Q)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let K=await II("seal_approval_rules_clear",q,U,{dryRun:Q,recode:S0(Y.options.recode)});if(!J&&Q&&K&&typeof K==="object"){R0({...K,nextCommand:`seal-use rules clear --corp ${U.id} --yes`},O0(Y.options));return}R0(K,O0(Y.options));return}if($==="versions"){await L0("seal_approval_rule_versions_list",q,U,{},O0(Y.options));return}if($==="version"){let J=I??x(Y.options.version);if(!J)throw Error("Usage: seal-use rules version <versionId|versionNumber|latest>");await L0("seal_approval_rule_version_get",q,U,Hz(J),O0(Y.options));return}if($==="get"){await L0("seal_approval_rule_get",q,U,{...$Z0(x(Y.options.version)),code:x(Y.options.code),runtimeId:x(Y.options.runtimeId)??x(Y.options["runtime-id"]),recordId:x(Y.options.r Line truncated
`).filter(Boolean),J=Y.slice(-I);return{logFile:q,lines:J,totalLines:Y.length}}async function Yw1($){let I=MO($),q=Nu($),U=Oz($);xZ0($.stateDir);let Y=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):XO),J=$.host??(process.env.HOST?process.env.HOST:DO);NO(I,`${process.pid}
`,{mode:384}),NO(q,JSON.stringify({pid:process.pid,port:Y,host:J,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),MY(U,`service starting on http://${J}:${Y} pid=${process.pid}`);let Q=null;try{Q=await OO({port:Y,host:J,silent:!0}),MY(U,`service listening pid=${process.pid}`)}catch(z){if(MY(U,`service failed to bind port ${Y}: ${z instanceof Error?z.message:String(z)}`),FO(I)===process.pid)i8(I,{force:!0}),i8(q,{force:!0});throw z}let K=()=>{if(Q)Q.close(),Q=null;if(FO(I)===process.pid)i8(I,{force:!0}),i8(q,{force:!0});MY(U,`stopped pid=${process.pid}`)};await new Promise((z)=>{let w=!1,G=()=>{if(w)return;w=!0,K(),process.off("SIGTERM",G),process.off("SIGINT",G),z()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function SZ0($){xZ0($.stateDir);let I=AY($);if(I.running)return I;let q=$.launcher??{command:process.execPath,args:[$.entryFile]},U=[...q.args??[],"service","run"];if($.port)U.push("--port",String($.port));if($.host)U.push("--host",String($.host));let Y=$w1(q.command,U,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Y.unref();let J=MO($);return NO(J,`${Y.pid}
`,{mode:384}),MY(Oz($),`started pid=${Y.pid}`),{started:!0,...AY($)}}function yZ0($,I={}){let q=MO($),U=Nu($),Y=FO(q);if(!Y||!uZ0(Y,$.appRoot))return i8(q,{force:!0}),i8(U,{force:!0}),I.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(Y,"SIGTERM"),i8(q,{force:!0}),i8(U,{force:!0}),MY(Oz($),`stop requested pid=${Y}`),I.quiet?void 0:{stopped:!0,pid:Y}}function uZ0($,I){if(!Jw1($))return!1;try{let q=Iw1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(q.includes(I)||q.includes("seal-use")||q.includes("src/cli.ts"))&&q.includes("service")&&q.includes("run")}catch{return!1}}function Jw1($){try{return process.kill($,0),!0}catch{return!1}}function MO($){return Lu($.stateDir,"service.pid")}function Nu($){return Lu($.stateDir,"service.json")}function Oz($){return Lu($.stateDir,"service.log")}function FO($){if(!LO($))return;let I=Number(Ou($,"utf8").trim());return Number.isInteger(I)&&I>0?I:void 0}function xZ0($){qw1($,{recursive:!0,mode:448})}function MY($,I){NO($,`${new Date().toISOString()} ${I}
`,{flag:"a",mode:384})}var Fu=Kw1(Qw1(),".config","seal-use");async function Mu($,I,q){let U=q?$1(q.options.port)??$1(q.options.p):void 0,Y=q?x(q.options.host)??x(q.options.h):void 0,J=q?$1(q.options.lines)??$1(q.options.n):void 0,Q=await qI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:Fu,version:a0,launcher:I.launcher,port:U,host:Y},{maxLines:J});if(Q!==void 0)R0(Q)}import{existsSync as zw1,readFileSync as kZ0}from"node:fs";async function fZ0($,I,q,U,Y){if($==="batch-records"||$==="records"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation batch-records <batchId>");await L0("seal_simulation_batch_records_get",q,U,{batchId:J,query:x(Y.options.query)},O0(Y.options));return}if($==="create"||$==="run"){let J=x(Y.options.mode)??x(Y.options.sourceSystem)??x(Y.options["source-system"])??"hosecloud",Q=J==="material-pack"?"material_pack":J,K=x(Y.options.schemaConfig)??x(Y.options["schema-config"]),z=K?JSON.parse(kZ0(K,"utf8")):void 0,w=x(Y.options.input),G=w?JSON.parse(kZ0(w,"utf8")):r6(Y.json),H=x(Y.options.packageId)??x(Y.options["package-id"]),W=N6(Y.options.packageIds)??N6(Y.options["package-ids"])??(H?[H]:void 0),V=N6(Y.options.flowIds)??N6(Y.options["flow-ids"])??N6(Y.options.documentSn)??N6(Y.options["document-sn"]),X=x(Y.options.signKey)??x(Y.options["sign-key"])??x(Y.options.integration);await L0("seal_simulation_batch_create",q,U,{mode:Q,sourceSystem:Q,flowIds:V,documentSn:V,rejectNodeName:x(Y.options.rejectNode)??x(Y.options["reject-node"])??null,thinkingDepthOverride:x(Y.options.thinkingDepth)??x(Y.options["thinking-depth"]),skipInvoiceGeneration:S0(Y.options.skipInvoiceGeneration)??S0(Y.options["skip-invoice-generation"]),skipExpenseExtraction:S0(Y.options.skipExpenseExtraction)??S0(Y.options["skip-expense-extraction"]),disableAttachmentCache:S0(Y.options.disableAttachmentCache)??S0(Y.options["disable-attachment-cache"]),signKey:X,packageIds:W,packageId:H,templateId:x(Y.options.templateId)??x(Y.options["template-id"]),schemaConfig:z,requestIds:N6(Y.options.requestIds)??N6(Y.options["request-ids"]),workflowTypeId:x(Y.options.workflowTypeId)??x(Y.options["workflow-type-id"]),flowStatusList:N6(Y.options.flowStatusList)?.map(Number)??N6(Y.options["flow-status-list"])?.map(Number),businessCodes:N6(Y.options.businessCodes)??N6(Y.options["business-codes"]),documentType:x(Y.options.documentType)??x(Y.options["document-type"]),startTime:$1(Y.options.startTime)??$1(Y.options["start-time"]),endTime:$1(Y.options.endTime)??$1(Y.options["end-time"]),status:N6(Y.options.status),limit:$1(Y.options.limit),rawParams:G},O0(Y.options));return}if($==="wait"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await L0("seal_simulation_batch_wait",q,U,{batchId:J,timeout:x(Y.options.timeout),pollInterval:x(Y.options.pollInterval)??x(Y.options["poll-interval"])},O0(Y.options));return}if($==="clean"||$==="delete"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation clean <batchId>");await L0("seal_simulation_batch_clean",q,U,{batchId:J},O0(Y.options));return}if($==="specifications"){let J=I??x(Y.options.integration)??x(Y.options.signKey)??x(Y.options["sign-key"]);await L0("seal_simulation_specifications_list",q,U,{signKey:J},O0(Y.options));return}if($==="list"){await L0("seal_simulation_batches_list",q,U,{limit:$1(Y.options.limit)},O0(Y.options));return}if($==="get"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation get <batchId>");await L0("seal_simulation_batch_get",q,U,{batchId:J},O0(Y.options));return}if($==="templates"){await L0("seal_simulation_templates_get",q,U,{},O0(Y.options));return}if($==="integrations"){await L0("seal_simulation_integrations_get",q,U,{},O0(Y.options));return}if($==="package-upload"){let J=I??x(Y.options.file);if(!J)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!zw1(J))throw Error(`File not found: ${J}`);await L0("seal_simulation_material_package_upload",q,U,{filePath:J},O0(Y.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as UX0}from"node:fs";import{join as AO}from"node:path";import{existsSync as Au,mkdirSync as aZ0,rmSync as Fw1,writeFileSync as Mw1}from"node:fs";import{homedir as sZ0}from"node:os";import{dirname as Aw1,join as gu}from"node:path";var nZ0=`---
</html>`}async function k4($,I,U,Y){let J=$.handler;return J(I,U,{corp:Y})}async function LX0($,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 tG1($.url||"/",`${Y}://${U}`),Q=J.pathname.replace(/\/+$/,"")||"/",K=($.method||"GET").toUpperCase();try{if(K==="GET"&&Q==="/"){m1(I,200,{name:"seal-use",version:I1,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"){sG1(I,200,zX0());return}if(K==="GET"&&Q==="/openapi.json"){m1(I,200,FD());return}if(K==="GET"&&Q==="/health"){m1(I,200,{status:"ok",version:I1,name:"seal-use",timestamp:new Date().toISOString()});return}if(K==="POST"&&(Q==="/shutdown"||Q==="/api/shutdown")){m1(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 MD($),G=(typeof q?.command==="string"?q.command:"").trim();if(!G){ND(I,400,"Missing 'command' property in request body");return}let H=Mx(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 zG(W),w=void 0;try{if(V.stdout.trim().startsWith("{")||V.stdout.trim().startsWith("["))w=JSON.parse(V.stdout)}catch{}m1(I,V.isError?400:200,{success:!V.isError,stdout:V.stdout,stderr:V.stderr,exitCode:V.exitCode,data:w});return}if(K==="POST"&&Q.startsWith("/api/tool/")){let q=Q.slice(10).trim(),G=C4(q);if(!G){ND(I,404,`Tool not found: '${q}'`);return}let H=await MD($)||{},W=y6($,J,H),V=D4(W),w=await Y4(V),Z={...H};delete Z.corp;let z=await k4(G,w,Z,V);m1(I,200,z);return}if(Q.startsWith("/v1/")){if(await aG1($,I,K,Q,J))return}ND(I,404,`Cannot ${K} ${Q}. Visit /docs for available endpoints.`)}catch(q){let G=q instanceof Error?q.message:String(q);ND(I,500,G)}}async function aG1($,I,U,Y,J){let Q=Object.fromEntries(J.searchParams.entries());if(U==="GET"&&Y==="/v1/corps"){let K=b8(),q=L4();return m1(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=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_whoami"),W=await k4(H,G,{},q);return m1(I,200,W),!0}if(U==="GET"&&Y==="/v1/session"){let K=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_session_get"),W=await k4(H,G,{},q);return m1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/summary"){let K=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_approval_runs_summary"),W=await k4(H,G,Q,q);return m1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/stats"){let K=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_approval_runs_stats"),W=await k4(H,G,Q,q);return m1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/pick"){let K=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_approval_run_pick"),W=await k4(H,G,Q,q);return m1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/url"){let K=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_approval_run_url_get"),W=await k4(H,G,Q,q);return m1(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=y6($,J,Q),W=D4(H),V=await Y4(W);if(!G){let w=C4("seal_approval_run_get"),Z=await k4(w,V,{recordId:q,...Q},W);return m1(I,200,Z),!0}if(G==="attachments"){let w=C4("seal_approval_run_attachments_get"),Z=await k4(w,V,{recordId:q,...Q},W);return m1(I,200,Z),!0}if(G==="cited-rules"){let w=C4("seal_approval_run_cited_rules_get"),Z=await k4(w,V,{recordId:q,...Q},W);return m1(I,200,Z),!0}if(G==="document-summary"){let w=C4("seal_approval_run_document_summary_get"),Z=await k4(w,V,{recordId:q,...Q},W);return m1(I,200,Z),!0}if(G==="result"){let w=C4("seal_approval_run_result_get"),Z=await k4(w,V,{recordId:q,...Q},W);return m1(I,200,Z),!0}}}if(U==="GET"&&Y==="/v1/approval-runs"){let K=y6($,J,Q),q=D4(K),G=await Y4(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 m1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval/rules"){let K=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_approval_rules_list"),W=await k4(H,G,Q,q);return m1(I,200,W),!0}if(U==="GET"&&Y==="/v1/simulation/batches"){let K=y6($,J,Q),q=D4(K),G=await Y4(q),H=C4("seal_simulation_batches_list"),W=await k4(H,G,Q,q);return m1(I,200,W),!0}if(U==="POST"&&Y==="/v1/simulation/create-batch"){let K=await MD($)||{},q=y6($,J,K),G=D4(q),H=await Y4Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${I1}) 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 DX0($){let I=d0($.options.port)??d0($.options.p),U=h($.options.host)??h($.options.h),Y=await TD({port:I,host:U}),J=()=>{Y.close(()=>{process.exit(0)})};process.on("SIGINT",J),process.on("SIGTERM",J),await new Promise(()=>{})}async function OX0($,I,U,Y){if($==="config"||$==="get"){await D0("seal_llm_config_get",I,U,{},V0(Y.options));return}if($==="providers"||$==="list"){await D0("seal_llm_providers_list",I,U,{},V0(Y.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}async function FX0($,I){if($==="config"||$==="json"){Ax();return}await Px()}function Ax(){B0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function NX0($){let I=FD();B0(I,{...V0($.options),allowFull:!0})}async function MX0($,I,U,Y){if($==="available"){await D0("seal_permissions_available_list",I,U,{},V0(Y.options));return}if($==="configs"||$==="list"){await D0("seal_permissions_configs_list",I,U,{},V0(Y.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as AX0}from"node:fs";async function PX0($,I,U,Y,J,Q,K){if(!$||$==="get"){await D0("seal_preference_get",J,Q,{},V0(K.options));return}if($==="decision"){if(I==="update"||!I){let q=h(K.options.input),G=q?JSON.parse(AX0(q,"utf8")):t6(K.json);if(!G||Object.keys(G).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await D0("seal_preference_decision_update",J,Q,{...G,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(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 D0("seal_preference_thinking_depth_set",J,Q,{defaultLevel:q,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}if(I==="policies"){if(U==="list"||!U){await D0("seal_preference_thinking_depth_policies_list",J,Q,{},V0(K.options));return}if(U==="upsert"){let q=h(K.options.input),G=q?JSON.parse(AX0(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 D0("seal_preference_thinking_depth_policies_upsert",J,Q,{...G,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(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 D0("seal_preference_thinking_depth_policies_remove",J,Q,{policyId:q,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function TX0($={}){let I=b8(),U=L4(),Y=XJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},s3());console.log(`[probe] corp=${Y.id} source=${Y.source.type}`);let J=await EJ(Y);console.log("[probe] seal enterprise"),console.log(JSON.stringify(J,null,2));let Q=await Y4(Y),K=await bV(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 EX0($,I,U){let Y=I??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await TX0({corpId:Y})}async function Tx($,I,U,Y,J){if($==="count"){await D0("seal_approval_rules_list",U,Y,{countOnly:!0},V0(J.options));return}if($==="list"){if(N0(J.options.count)){await D0("seal_approval_rules_list",U,Y,{countOnly:!0},V0(J.options));return}let Q=d0(J.options.limit),K=d0(J.options.offset);if(N0(J.options.summary)){await D0("seal_approval_rules_list",U,Y,{fields:pZ0,limit:Q,offset:K},V0(J.options));return}let q=await HI("seal_approval_rules_list",U,Y,{limit:Q,offset:K});cZ0(q,N0(J.options.full)===!0),B0(q);return}if($==="clear"){let Q=N0(J.options.yes)===!0,K=N0(J.options.dryRun)??N0(J.options["dry-run"])??!Q;if(!Q&&!K)throw zD("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${Y.id} --dry-run`);let q=await HI("seal_approval_rules_clear",U,Y,{dryRun:K,recode:N0(J.options.recode)});if(!Q&&K&&q&&typeof q==="object"){B0({...q,nextCommand:`seal-use rules clear --corp ${Y.id} --yes`},V0(J.options));return}B0(q,V0(J.options));return}if($==="versions"){await D0("seal_approval_rule_versions_list",U,Y,{},V0(J.options));return}if($==="version"){let Q=I??h(J.options.version);if(!Q)throw Error("Usage: seal-use rules version <versionId|versionNumber|l Line truncated
`).filter(Boolean),Q=J.slice(-I);return{logFile:U,lines:Q,totalLines:J.length}}async function JH1($){let I=RD($),U=vx($),Y=LG($);CX0($.stateDir);let J=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):AD),Q=$.host??(process.env.HOST?process.env.HOST:PD);BD(I,`${process.pid}
`,{mode:384}),BD(U,JSON.stringify({pid:process.pid,port:J,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),BJ(Y,`service starting on http://${Q}:${J} pid=${process.pid}`);let K=null;try{K=await TD({port:J,host:Q,silent:!0}),BJ(Y,`service listening pid=${process.pid}`)}catch(G){if(BJ(Y,`service failed to bind port ${J}: ${G instanceof Error?G.message:String(G)}`),vD(I)===process.pid)d8(I,{force:!0}),d8(U,{force:!0});throw G}let q=()=>{if(K)K.close(),K=null;if(vD(I)===process.pid)d8(I,{force:!0}),d8(U,{force:!0});BJ(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 BX0($){CX0($.stateDir);let I=vJ($);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=$H1(U.command,Y,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});J.unref();let Q=RD($);return BD(Q,`${J.pid}
`,{mode:384}),BJ(LG($),`started pid=${J.pid}`),{started:!0,...vJ($)}}function vX0($,I={}){let U=RD($),Y=vx($),J=vD(U);if(!J||!RX0(J,$.appRoot))return d8(U,{force:!0}),d8(Y,{force:!0}),I.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(J,"SIGTERM"),d8(U,{force:!0}),d8(Y,{force:!0}),BJ(LG($),`stop requested pid=${J}`),I.quiet?void 0:{stopped:!0,pid:J}}function RX0($,I){if(!QH1($))return!1;try{let U=IH1("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 QH1($){try{return process.kill($,0),!0}catch{return!1}}function RD($){return Bx($.stateDir,"service.pid")}function vx($){return Bx($.stateDir,"service.json")}function LG($){return Bx($.stateDir,"service.log")}function vD($){if(!ED($))return;let I=Number(Ex($,"utf8").trim());return Number.isInteger(I)&&I>0?I:void 0}function CX0($){UH1($,{recursive:!0,mode:448})}function BJ($,I){BD($,`${new Date().toISOString()} ${I}
`,{flag:"a",mode:384})}var Rx=qH1(KH1(),".config","seal-use");async function Cx($,I,U){let Y=U?d0(U.options.port)??d0(U.options.p):void 0,J=U?h(U.options.host)??h(U.options.h):void 0,Q=U?d0(U.options.lines)??d0(U.options.n):void 0,K=await WI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:Rx,version:I1,launcher:I.launcher,port:Y,host:J},{maxLines:Q});if(K!==void 0)B0(K)}import{existsSync as GH1,readFileSync as jX0}from"node:fs";async function _X0($,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 D0("seal_simulation_batch_records_get",U,Y,{batchId:Q,query:h(J.options.query)},V0(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(jX0(q,"utf8")):void 0,H=h(J.options.input),W=H?JSON.parse(jX0(H,"utf8")):t6(J.json),V=h(J.options.packageId)??h(J.options["package-id"]),w=W6(J.options.packageIds)??W6(J.options["package-ids"])??(V?[V]:void 0),Z=W6(J.options.flowIds)??W6(J.options["flow-ids"])??W6(J.options.documentSn)??W6(J.options["document-sn"]),z=h(J.options.signKey)??h(J.options["sign-key"])??h(J.options.integration),L=N0(J.options.noWait)??N0(J.options["no-wait"]);await D0("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:N0(J.options.skipInvoiceGeneration)??N0(J.options["skip-invoice-generation"]),skipExpenseExtraction:N0(J.options.skipExpenseExtraction)??N0(J.options["skip-expense-extraction"]),disableAttachmentCache:N0(J.options.disableAttachmentCache)??N0(J.options["disable-attachment-cache"]),signKey:z,packageIds:w,packageId:V,templateId:h(J.options.templateId)??h(J.options["template-id"]),schemaConfig:G,requestIds:W6(J.options.requestIds)??W6(J.options["request-ids"]),workflowTypeId:h(J.options.workflowTypeId)??h(J.options["workflow-type-id"]),flowStatusList:W6(J.options.flowStatusList)?.map(Number)??W6(J.options["flow-status-list"])?.map(Number),businessCodes:W6(J.options.businessCodes)??W6(J.options["business-codes"]),documentType:h(J.options.documentType)??h(J.options["document-type"]),startTime:d0(J.options.startTime)??d0(J.options["start-time"]),endTime:d0(J.options.endTime)??d0(J.options["end-time"]),status:W6(J.options.status),limit:d0(J.options.limit),noWait:L,rawParams:W},V0(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 D0("seal_simulation_batch_wait",U,Y,{batchId:Q,timeout:h(J.options.timeout),pollInterval:h(J.options.pollInterval)??h(J.options["poll-interval"])},V0(J.options));return}if($==="status"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation status <batchId>");await D0("seal_simulation_batch_status",U,Y,{batchId:Q},V0(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 D0("seal_simulation_batch_clean",U,Y,{batchId:Q},V0(J.options));return}if($==="specifications"){let Q=I??h(J.options.integration)??h(J.options.signKey)??h(J.options["sign-key"]);await D0("seal_simulation_specifications_list",U,Y,{signKey:Q},V0(J.options));return}if($==="approval-definitions"||$==="definitions"){await D0("seal_simulation_feishu_approval_definitions_list",U,Y,{},V0(J.options));return}if($==="list"){await D0("seal_simulation_batches_list",U,Y,{limit:d0(J.options.limit)},V0(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 D0("seal_simulation_batch_get",U,Y,{batchId:Q},V0(J.options));return}if($==="templates"){await D0("seal_simulation_templates_get",U,Y,{},V0(J.options));return}if($==="integrations"){await D0("seal_simulation_integrations_get",U,Y,{},V0(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(!GH1(Q))throw Error(`File not found: ${Q}`);await D0("seal_simulation_material_package_upload",U,Y,{filePath:Q},V0(J.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as rX0}from"node:fs";import{join as CD}from"node:path";import{existsSync as jx,mkdirSync as pX0,rmSync as NH1,writeFileSync as MH1}from"node:fs";import{homedir as cX0}from"node:os";import{dirname as AH1,join as _x}from"node:path";var SX0=`---
name: seal-use
description: "v0.10.7: 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.14: 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.7
short-description: Seal tenant and Hose approval automation (v0.10.7)
version: 0.10.14
short-description: Seal tenant and Hose approval automation (v0.10.14)
---
# Seal Use (v0.10.7)
# Seal Use (v0.10.14)
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.
@@ -512,7 +532,8 @@ seal-use corps list
- Prefer compact commands first: \`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use \`seal-use corps ...\`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For repeat test-environment rule resets, prefer \`rules clear --dry-run\` followed by \`rules clear --yes\`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal \`--dry-run\` preview first (rules clear/push, preferences, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use \`--yes\` only after reviewing its redacted \`changesDiff\`.
- Knowledge document creation is currently irreversible: the upstream API exposes no delete operation. Validate \`contentType\` and \`scenarios\` before creating, and use \`enabled: false\` when the document should be withdrawn.
- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of \`description\`; preserve \`scope\`, \`strictness\`, and unrelated clauses unless the user explicitly approves otherwise.
- Resolve and lock the target enterprise \`corpId\` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing.
- For date questions, use explicit dates and \`--timezone Asia/Shanghai\`.
@@ -528,7 +549,7 @@ seal-use corps list
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read \`references/enterprise-onboarding.md\`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run \`seal-use delegation create --corp <corpId> --note '<enterprise>'\`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read \`references/customer-feedback-rule-remediation.md\`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 模拟测试发布闭环: \`seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>\` (合思指定单号) 或 \`--mode material_pack --package-ids ... --schema-config file.json\` (材料包导入), 支持多源系统 \`--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>\`, \`simulation wait <batchId>\` 轮询等待完成, \`simulation clean <batchId>\` 清理数据, \`simulation specifications\` 列出单据模板, \`simulation list\`/\`get\`/\`batch-records\` 查看批次与记录。创建前确认目标环境为测试环境。
- 模拟测试发布闭环: \`seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>\` (合思指定单号) 或 \`--mode material_pack --package-ids ... --schema-config file.json\` (材料包导入), 支持多源系统 \`--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>\`, \`simulation status <batchId>\` 单次查询状态, \`simulation wait <batchId>\` 轮询等待完成, \`simulation clean <batchId>\` 清理数据, \`simulation specifications\` 列出单据模板, \`simulation list\`/\`get\`/\`batch-records\` 查看批次与记录。创建前确认目标环境为测试环境。
- Seal AI 智能审核发布到合思费控: \`seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\`; read \`references/hose-enterprise-deploy.md\`.
- 审核决策偏好与思考深度: \`seal-use preference get --corp <corpId>\`, \`preference decision update --json '...' --corp <corpId>\`, \`preference thinking-depth set --default <medium|high> --corp <corpId>\`, \`preference thinking-depth policies <list|upsert|remove> --corp <corpId>\`.
- 审核大盘统计与去重分析: \`seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>\`, \`seal-use approval-runs count --corp <corpId>\`.
@@ -538,12 +559,28 @@ 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 material-pack preview <材料包.zip> --corp <corpId>\` 只做本地校验和解析;\`... push <材料包.zip> --webhook <idOrName> --corp <corpId>\` 上传附件并通过入站 Webhook 触发 AI 审批。它与 \`simulation material_pack\` 的官方服务端导入流程相互独立。
- Webhook 准备看板与审批回调管理: \`seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --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\`)。每个 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\`.
## Material-pack Webhook policy and recovery
材料包附件策略保存在目标入站 Webhook 的 \`materialPackFilePolicy\` 下,按 Webhook 生效。新建 Webhook 的默认策略是:最小文件大小 \`500\` 字节、最大文件大小不限制、后缀白名单为常见 PDF/Office/文本/邮件/图片格式。\`信息表.xlsx\` 是材料包根清单,不属于普通附件,不受这三个附件策略限制。完整默认后缀和边界规则见 \`references/cli.md\`。
这套策略允许人工或助手修改。错误处理有两条通道:先通过错误通道明确告诉助手是哪一个文件、哪一条规则失败;再通过配置或文件处置通道完成恢复。遇到附件被拦截时按以下闭环处理:
1. 从错误中识别被拦截的文件、实际大小、失败规则和目标 Webhook。
2. 向用户说明可选处置:替换/压缩文件,或在确认允许该格式/大小后修改 Webhook 策略。
3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置(CLI 使用 \`webhook get\`/\`webhook list\`,MCP 使用 \`seal_webhook_get\`/\`seal_webhook_list\`)。
4. 调用 \`seal_webhook_update\` 或 \`seal-use webhook update\` 修改最小值、最大值或完整后缀白名单,写入后重新读取核对,再重试原来的材料包 push。
push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 \`stderr\` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。
注意:直接执行本地 \`material-pack preview\` 只使用默认策略或命令行临时覆盖,不会自动读取某个 Webhook 的持久化策略;\`webhook ready --file\`(指定 Webhook 时)和 \`material-pack push\` 才使用保存的 Webhook 策略。需要验证实际入站通道策略时,优先使用 \`ready --file --webhook ...\`,或直接重试 push。
## High-Value Commands
\`\`\`bash
@@ -599,14 +636,20 @@ 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 bZ0=`interface:
`;var gX0=`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 iZ0=`# Rule Lightweight Queries
`;var yX0=`# 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.
## Draft and Published Rule Codes
\`rules list\` and \`rules pull\` operate on the current draft and therefore return draft \`code\` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as \`#0038\` is only meaningful together with its version context.
Use the draft \`id\` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version.
## Count Rules
Use count when only scale or existence matters.
@@ -708,7 +751,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 pZ0=`# Approval Bad Case Catalog
`;var hX0=`# 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.
@@ -758,7 +801,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 cZ0="# 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 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 sourceDocumentSN|sourceDocumentId|id]\nseal-uLine truncated
`;var xX0="# 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** with the stable prefix `👉 Next action: seal-use ...`.\n- **`Exit Code`**: `0` on success; `1` runtime/upstream failure, `2` usage/argument error, `10` explicit destructive-operation confirmation required, `11` missing/invalid authentication, and `12` output protection requiring a compact/file/query alternative.\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 contacts departments [<departmentId>] [--corp <corpId>]\nseal-use contacts children <departmentId> [--corp <corpId>]\nseal-use contacts users <departmentId> [--corp <corpId>]\nseal-use contacts sync-time [--corp <corpId>]\nseal-use data expenses --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]\nseal-use data invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]\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>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--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] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]\nseal-use webhook delete <idOrName> [--yes|--dry-run] [--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 hosLine 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.
@@ -979,7 +1022,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 mZ0=`# Customer Feedback Rule Remediation
`;var fX0=`# 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.
@@ -1114,6 +1157,8 @@ seal-use tool seal_approval_rule_update --corp <corpId> \\
Do not send \`scope\` or \`strictness\` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing.
For a complete local rule-set sync, \`rules push\` is incremental: it matches pulled rules by stable \`id\`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with \`rules push --dry-run\` before applying.
## 9. Publish and verify
Publish only when explicitly authorized:
@@ -1143,7 +1188,7 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var oZ0="# 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
`;var bX0="# 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.
@@ -1208,7 +1253,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 tZ0=`# Hose Enterprise Initialization & Automated Discovery
`;var nX0=`# 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.
@@ -1314,12 +1359,12 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var eZ0={"SKILL.md":nZ0,"agents/openai.yaml":bZ0,"references/rule-lightweight.md":iZ0,"references/approval-bad-cases.md":pZ0,"references/cli.md":cZ0,"references/approval-run-lightweight.md":dZ0,"references/approval-attachment-trace.md":lZ0,"references/customer-feedback-rule-remediation.md":mZ0,"references/enterprise-onboarding.md":oZ0,"references/hose-enterprise-auth.md":rZ0,"references/hose-enterprise-init.md":tZ0};function $X0(){return eZ0["SKILL.md"]||""}function Lz(){return gu(sZ0(),".agents","skills","seal-use")}function IX0(){return gu(sZ0(),".agents","skills","seal-home")}function qX0(){let $=IX0();if(Au($))try{return Fw1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Pu($=Lz()){qX0(),aZ0($,{recursive:!0});let I=[];for(let[q,U]of Object.entries(eZ0)){let Y=gu($,q);aZ0(Aw1(Y),{recursive:!0}),Mw1(Y,U,"utf8"),I.push(q)}return{targetDir:$,files:I}}function Tu(){let $=IX0(),I=Lz(),q=Au($),U=Au(I);if(q||U)return qX0(),Pu(I),{synced:!0,targetDir:I};return{synced:!1}}function YX0($,I,q){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${$X0()}
`);return}if($==="install"||$==="init"||$==="sync"){let U=S0(q.options.local)||S0(q.options.workspace),Y=x(q.options.dir)??x(q.options.target)??I,J=Y?Y:U?AO(process.cwd(),".agents","skills","seal-use"):Lz(),Q=Pu(J);R0({installed:!0,targetDir:Q.targetDir,fileCount:Q.files.length,files:Q.files});return}if($==="status"||$==="get"||!$){let U=Lz(),Y=AO(process.cwd(),".agents","skills","seal-use");R0({global:{dir:U,installed:UX0(AO(U,"SKILL.md"))},local:{dir:Y,installed:UX0(AO(Y,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}async function JX0($,I){if($==="config"){R0(await FY(I));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}async function QX0($,I,q,U){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await L0($,I,q,r6(U.json),O0(U.options))}function KX0(){R0(Gz.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as gw1,mkdirSync as Pw1,renameSync as ju,rmSync as Tw1,unlinkSync as VX0,writeFileSync as zX0}from"node:fs";import{dirname as jw1,join as wX0}from"node:path";import{spawnSync as UI}from"node:child_process";function gO($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let q=$.toLowerCase().replace(/\\/g,"/");return!q.endsWith("/bun")&&!q.endsWith("/bun.exe")&&!q.endsWith("/node")&&!q.endsWith("/node.exe")}var WX0="yunyingk/seal-use",Fz="yunyingk/seal-home";var Ew1="SEAL_USE_GITHUB_REPO",Bw1="SEAL_HOME_GITHUB_REPO";async function ZX0($,I={}){let q={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Fu,version:a0,launcher:$.launcher},U=I.repo||process.env[Ew1]?.trim()||process.env[Bw1]?.trim()||WX0,Y=I.targetVersion?.trim(),J=Y&&Y.toLowerCase()!=="latest"?Y:void 0;if(J){let g=J.replace(/^v/,""),B=XX0(g,a0);if(B<0){R0({updated:!1,currentVersion:a0,targetVersion:g,mode:gO()?"binary":"source",message:`Cannot downgrade seal-use from v${a0} to older version v${g}. Updates must be forward-only.`});return}if(B===0&&!I.force){R0({updated:!1,currentVersion:a0,targetVersion:g,mode:gO()?"binary":"source",message:`seal-use is already at version v${a0}. Use --force to reinstall.`});return}}if(I.changelogOnly){let g=await Eu(U,I.limit??10);R0({currentVersion:a0,totalQueried:g.length,releases:g.map((B)=>({version:B.version,tagName:B.tagName,publishedAt:B.publishedAt,author:B.author,releaseNotes:B.notes,releaseUrl:B.htmlUrl,isCurrent:B.version===a0,isNewer:Nz(B.version,a0)}))});return}if(!gO()){if(I.checkOnly){let B=await Eu(U,30),k=B[0],h=k?.version??a0,n=B.find((p)=>p.version===a0),S=Nz(h,a0),t=B.filter((p)=>Nz(p.version,a0));R0({updated:!1,updateAvailable:S,currentVersion:a0,currentVersionPublishedAt:n?.publishedAt,latestVersion:h,latestVersionPublishedAt:k?.publishedAt,behindCount:t.length,pendingReleases:t.map((p)=>({version:p.version,tagName:p.tagName,publishedAt:p.publishedAt,author:p.author,releaseNotes:p.notes,releaseUrl:p.htmlUrl})),releaseNotes:k?.notes??"",releaseUrl:k?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let g=AY(q).running;if(g)await qI("stop",q);try{HX0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(B){console.error(`git pull skipped: ${B instanceof Error?B.message:String(B)}`)}if(HX0("bun",["install"],{cwd:$.appRoot}),g)await qI("start",q);R0({updated:!0,serviceRestarted:g,version:a0,mode:"source"});return}let Q=vw1(),K=Rw1(),z=await Eu(U,30),w=J?z.find((g)=>g.version===J||g.tagName===J||g.tagName===`v${J}`)??await GX0(U,J):z[0]??await GX0(U);if(!w){R0({updated:!1,currentVersion:a0,mode:"binary",message:`Failed to query releases from repository '${U}'`});return}let G=w.version,H=z.find((g)=>g.version===a0),W=Nz(G,a0),V=W||Boolean(I.force),X=z.filter((g)=>Nz(g.version,a0));if(I.checkOnly){R0({updated:!1,updateAvailable:W,currentVersion:a0,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:w.publishedAt,behindCount:X.length,pendingReleases:X.map((g)=>({version:g.version,tagName:g.tagName,publishedAt:g.publishedAt,author:g.author,releaseNotes:g.notes,releaseUrl:g.htmlUrl})),releaseNotes:w.notes,releaseUrl:w.htmlUrl,mode:"binary"});return}if(!V){R0({updated:!1,currentVersion:a0,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:w.publishedAt,mode:"binary",message:`seal-use is already up to date (v${a0})`});return}let D=Cw1(w.assets,Q,K);if(!D)throw Error(`No compatible binary found for ${Q}-${K} in release v${G}. Available assets: ${w.assets.map((g)=>g.name).join(", ")}`);let O=AY(q).running;if(O)await qI("stop",q);let N=process.execPath,T=jw1(N),P=wX0(T,`.tmp-update-${Date.now()}`);Pw1(P,{recursive:!0});try{let g=wX0(P,D.name);await _w1(D.downloadUrl,g,w.tagName,D.name);let B=g;if(D.name.endsWith(".tar.gz")||D.name.endsWith(".tgz"))B=hw1(g,P,Q);else if(D.name.endsWith(".zip"))B=Sw1(g,P,Q);if(gw1(B,493),process.platform==="darwin")try{UI("/usr/bin/codesig Line truncated
`)}catch{}}async function _w1($,I,q,U){let Y=Bu(),J=[],Q=q?q.startsWith("v")?q:`v${q}`:void 0,K=U||$.split("/").pop()||"";if(Y!=="github"){if(Q&&K)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${Q}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${Q}/${K}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Y!=="gitea")if(Q&&K){let D=`https://github.com/${WX0}/releases/download/${Q}/${K}`;if(!process.env.CI)J.push(`https://ghfast.top/${D}`,`https://gh.ddlc.top/${D}`);J.push(D)}else if($.includes("github.com")){if(!process.env.CI)J.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);J.push($)}else J.push($);let z=Array.from(new Set(J)),w,G=6000,H=6000,W=307200,V=1e4,X=180000;for(let D=0;D<z.length;D++){let O=z[D],N=new AbortController,T="",P=(h)=>{T=h;try{N.abort()}catch{}},g=setTimeout(()=>{P("Connection timed out (no response headers within 6s)")},G),B,k;try{PO(`==> [${D+1}/${z.length}] Downloading via: ${O}`);let h=await fetch(O,{signal:N.signal});if(g)clearTimeout(g),g=void 0;if(!h.ok)throw Error(`HTTP ${h.status} ${h.statusText}`);B=setTimeout(()=>{P("Overall download time exceeded 3 minutes")},X);let n=Number(h.headers.get("content-length"))||0,S=h.body?.getReader();if(!S){let b=Buffer.from(await h.arrayBuffer());if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);zX0(I,b),PO(`✓ Download succeeded (${(b.length/1024/1024).toFixed(1)} MB)`);return}let t=[],p=0,C=0;k=setTimeout(()=>{if(p<W){let b=(p/1024).toFixed(1);P(`Initial transfer too slow (${b} KB < 300 KB in 6s), switching mirror...`)}},H);while(!0){let b=S.read(),J0,j=new Promise((K0,G0)=>{J0=setTimeout(()=>{G0(Error("Data transfer stalled (no chunk received for 10s)"))},V)}),u;try{u=await Promise.race([b,j])}finally{if(J0)clearTimeout(J0)}let{done:d,value:a}=u;if(d)break;if(a){if(t.push(a),p+=a.length,k&&p>=W)clearTimeout(k),k=void 0;let K0=Date.now();if(K0-C>200){C=K0;let G0=n?Math.round(p/n*100):0,M0=(p/1048576).toFixed(1),v0=n?(n/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${G0}% (${M0} / ${v0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let f=Buffer.concat(t);if(f.length<1000)throw Error(`Downloaded content is suspiciously small (${f.length} bytes)`);zX0(I,f),PO(`✓ Download completed successfully (${(f.length/1024/1024).toFixed(1)} MB)`);return}catch(h){if(g)clearTimeout(g);if(k)clearTimeout(k);if(B)clearTimeout(B);let n=T||(h instanceof Error?h.message:String(h));w=Error(n),PO(`
↳ Mirror failed: ${w.message}`)}finally{if(g)clearTimeout(g);if(k)clearTimeout(k);if(B)clearTimeout(B)}}throw Error(`Failed to download asset from all mirrors: ${w?.message}`)}function hw1($,I,q){let U=UI("tar",["-xzf",$,"-C",I],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract tar archive: ${U.stderr.toString()}`);VX0($);let Y=q==="windows"?"seal-use.exe":"seal-use",J=UI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),Q=J.find((K)=>K.endsWith(`/${Y}`)||K.endsWith(Y));if(Q)return Q;return J[0]||$}function Sw1($,I,q){let U=UI("unzip",["-q","-o",$,"-d",I],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract zip archive: ${U.stderr.toString()}`);VX0($);let Y=q==="windows"?"seal-use.exe":"seal-use",J=UI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),Q=J.find((K)=>K.endsWith(`/${Y}`)||K.endsWith(Y));if(Q)return Q;return J[0]||$}function XX0($,I){let q=$.replace(/^v/,"").split(".").map((Y)=>Number.parseInt(Y,10)||0),U=I.replace(/^v/,"").split(".").map((Y)=>Number.parseInt(Y,10)||0);for(let Y=0;Y<Math.max(q.length,U.length);Y++){let J=q[Y]??0,Q=U[Y]??0;if(J>Q)return 1;if(J<Q)return-1}return 0}function Nz($,I){return XX0($,I)>0}function HX0($,I,q={}){let U=UI($,I,{cwd:q.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(U.stdout)console.error(U.stdout.trimEnd());if(U.stderr)console.error(U.stderr.trimEnd());if(U.status!==0)throw Error(`${$} ${I.join(" ")} failed with status ${U.status}`)}async function DX0($,I,q,U,Y){if($==="create"){let J=x(Y.options.name)??I,Q=x(Y.options.phone);if(!J||!Q)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let K=x(Y.options.dept)??x(Y.options.departmentId);await L0("seal_user_create",q,U,{name:J,phone:Q,departmentIds:K?[K]:void 0},O0(Y.options));return}if($==="reset-password"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users reset-password <userId>");await L0("seal_user_reset_password",q,U,{userId:J},O0(Y.options));return}if($==="search"||$==="list"){let J=I??x(Y.options.keyword)??x(Y.options.query)??"";await L0("seal_user_search",q,U,{keyword:J},O0(Y.options));return}if($==="get"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users get <userId>");await L0("seal_user_get",q,U,{userId:J},O0(Y.options));return}if($==="delete"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users delete <userId>");await L0("seal_user_delete",q,U,{userId:J},O0(Y.options));return}if($==="activate"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users activate <userId>");await L0("seal_user_activate",q,U,{userId:J},O0(Y.options));return}if($==="delegation"||$==="impersonate"){let J=I??x(Y.options.userId)??x(Y.options.phone);if(!J)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let Q=x(Y.options.note);await L0("seal_user_delegation_create",q,U,{userIdOrPhone:J,note:Q},O0(Y.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as OX0}from"node:fs";async function LX0($){if(!OX0($))throw Error(`File not found: ${$}`);let I=Kz($);console.log(JSON.stringify(await Qz(I.fileBuffer,I.fileName),null,2))}async function NX0($,I,q,U,Y){if($==="material-pack"||$==="material-pack-push"){let J=$==="material-pack-push"?"push":I,Q=$==="material-pack-push"?x(Y.options.file)??x(Y.options.input):Y.command[3]??x(Y.options.file)??x(Y.options.input);if(!Q)throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");if(!OX0(Q))throw Error(`File not found: ${Q}`);let K=Kz(Q);if(J==="preview"){console.log(JSON.stringify(await Qz(K.fileBuffer,K.fileName),null,2));return}if(J!=="push")throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");let z=x(Y.options.webhook)??x(Y.options.selector);if(!z)throw Error("Push requires --webhook <idOrName>");let w=Wq(await Vq(q),z),G=await UO(K.fileBuffer,K.fileName,{webhookUrl:w.incomingDocumentWebhook.url,secret:w.secret});console.log(JSON.stringify(G,null,2));return}if($==="list"){await L0("seal_webhook_list",q,U,{query:x(Y.options.query)??x(Y.options.keyword),includeSecret:Gu(Y.options)},O0(Y.options));return}if($==="get"||$==="find"){let J=I??x(Y.options.selector)??x(Y.options.id);if(!J)throw Error("Usage: seal-use webhook get <idOrName> [--show-secret]");await L0("seal_webhook_get",q,U,{selector:J,includeSecret:Gu(Y.options)},O0(Y.options));return}if($==="add"||$==="create"){let J=x(Y.options.name)??I,Q=x(Y.options.resultUrl)??x(Y.options["result-url"])??x(Y.options.outgoingResultWebhook)??x(Y.options["outgoing-result-webhook"]);if(!J||!Q)throw Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let K=wu(Y.options);await L0("seal_webhook_add",q,U,{name:J,mode:zu(x(Y.options.mode)),outgoingResultWebhook:Q,autoApprovalRate:K,secret:x(Y.options.secret)},O0(Y.options));return}if($==="update"){let J=I??x(Y.options.selector)??x(Y.options.id);if(!J)throw Error("Usage: seal-use webhook update <idOrName> [options]");let Q=x(Y.options.secret),K=S0(Y.options.rotateSecret)??S0(Y.options["rotate-secret"]);if(Q!==void 0&&K)throw Error("Use either --secret or --rotate-secret, not both");let z=x(Y.options.name),w=zu(x(Y.options.mode)),G=x(Y.options.resultUrl)??x(Y.options["result-url"])??x(Y.options.outgoingResultWebhook)??x(Y.options["outgoing-result-webhook"]),H=wu(Y.options);if(z===void 0&&w===void 0&&G===void 0&&H===void 0&&Q===void 0&&!K)throw Error("Webhook update requires at least one field option");await L0("seal_webhook_update",q,U,{selector:J,name:z,mode:w,outgoingResultWebhook:G,autoApprovalRate:H,secret:Q,rotateSecret:K},O0(Y.options));return}if($==="delete"){let J=I??x(Y.options. Line truncated
`;var dX0={"SKILL.md":SX0,"agents/openai.yaml":gX0,"references/rule-lightweight.md":yX0,"references/approval-bad-cases.md":hX0,"references/cli.md":xX0,"references/approval-run-lightweight.md":kX0,"references/approval-attachment-trace.md":uX0,"references/customer-feedback-rule-remediation.md":fX0,"references/enterprise-onboarding.md":bX0,"references/hose-enterprise-auth.md":iX0,"references/hose-enterprise-init.md":nX0};function mX0(){return dX0["SKILL.md"]||""}function DG(){return _x(cX0(),".agents","skills","seal-use")}function lX0(){return _x(cX0(),".agents","skills","seal-home")}function oX0(){let $=lX0();if(jx($))try{return NH1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Sx($=DG()){oX0(),pX0($,{recursive:!0});let I=[];for(let[U,Y]of Object.entries(dX0)){let J=_x($,U);pX0(AH1(J),{recursive:!0}),MH1(J,Y,"utf8"),I.push(U)}return{targetDir:$,files:I}}function gx(){let $=lX0(),I=DG(),U=jx($),Y=jx(I);if(U||Y)return oX0(),Sx(I),{synced:!0,targetDir:I};return{synced:!1}}function tX0($,I,U){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${mX0()}
`);return}if($==="install"||$==="init"||$==="sync"){let Y=N0(U.options.local)||N0(U.options.workspace),J=h(U.options.dir)??h(U.options.target)??I,Q=J?J:Y?CD(process.cwd(),".agents","skills","seal-use"):DG(),K=Sx(Q);B0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files});return}if($==="status"||$==="get"||!$){let Y=DG(),J=CD(process.cwd(),".agents","skills","seal-use");B0({global:{dir:Y,installed:rX0(CD(Y,"SKILL.md"))},local:{dir:J,installed:rX0(CD(J,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}async function aX0($,I){if($==="config"){B0(await EJ(I));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}async function sX0($,I,U,Y){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await D0($,I,U,t6(Y.json),V0(Y.options))}function eX0(){B0(GG.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as PH1,mkdirSync as TH1,renameSync as yx,rmSync as EH1,unlinkSync as Jz0,writeFileSync as $z0}from"node:fs";import{dirname as BH1,join as Iz0}from"node:path";import{spawnSync as VI}from"node:child_process";function jD($=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 Qz0="yunyingk/seal-use",FG="yunyingk/seal-home";var vH1="SEAL_USE_GITHUB_REPO",RH1="SEAL_HOME_GITHUB_REPO";async function Kz0($,I={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Rx,version:I1,launcher:$.launcher},Y=I.repo||process.env[vH1]?.trim()||process.env[RH1]?.trim()||Qz0,J=I.targetVersion?.trim(),Q=J&&J.toLowerCase()!=="latest"?J:void 0;if(Q){let A=Q.replace(/^v/,""),R=qz0(A,I1);if(R<0){B0({updated:!1,currentVersion:I1,targetVersion:A,mode:jD()?"binary":"source",message:`Cannot downgrade seal-use from v${I1} to older version v${A}. Updates must be forward-only.`});return}if(R===0&&!I.force){B0({updated:!1,currentVersion:I1,targetVersion:A,mode:jD()?"binary":"source",message:`seal-use is already at version v${I1}. Use --force to reinstall.`});return}}if(I.changelogOnly){let A=await hx(Y,I.limit??10);B0({currentVersion:I1,totalQueried:A.length,releases:A.map((R)=>({version:R.version,tagName:R.tagName,publishedAt:R.publishedAt,author:R.author,releaseNotes:R.notes,releaseUrl:R.htmlUrl,isCurrent:R.version===I1,isNewer:OG(R.version,I1)}))});return}if(!jD()){if(I.checkOnly){let R=await hx(Y,30),u=R[0],g=u?.version??I1,b=R.find((n)=>n.version===I1),C=OG(g,I1),p=R.filter((n)=>OG(n.version,I1));B0({updated:!1,updateAvailable:C,currentVersion:I1,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:u?.publishedAt,behindCount:p.length,pendingReleases:p.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.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 A=vJ(U).running;if(A)await WI("stop",U);try{Yz0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(R){console.error(`git pull skipped: ${R instanceof Error?R.message:String(R)}`)}if(Yz0("bun",["install"],{cwd:$.appRoot}),A)await WI("start",U);B0({updated:!0,serviceRestarted:A,version:I1,mode:"source"});return}let K=CH1(),q=jH1(),G=await hx(Y,30),H=Q?G.find((A)=>A.version===Q||A.tagName===Q||A.tagName===`v${Q}`)??await Uz0(Y,Q):G[0]??await Uz0(Y);if(!H){B0({updated:!1,currentVersion:I1,mode:"binary",message:`Failed to query releases from repository '${Y}'`});return}let W=H.version,V=G.find((A)=>A.version===I1),w=OG(W,I1),Z=w||Boolean(I.force),z=G.filter((A)=>OG(A.version,I1));if(I.checkOnly){B0({updated:!1,updateAvailable:w,currentVersion:I1,currentVersionPublishedAt:V?.publishedAt,latestVersion:W,latestVersionPublishedAt:H.publishedAt,behindCount:z.length,pendingReleases:z.map((A)=>({version:A.version,tagName:A.tagName,publishedAt:A.publishedAt,author:A.author,releaseNotes:A.notes,releaseUrl:A.htmlUrl})),releaseNotes:H.notes,releaseUrl:H.htmlUrl,mode:"binary"});return}if(!Z){B0({updated:!1,currentVersion:I1,currentVersionPublishedAt:V?.publishedAt,latestVersion:W,latestVersionPublishedAt:H.publishedAt,mode:"binary",message:`seal-use is already up to date (v${I1})`});return}let L=_H1(H.assets,K,q);if(!L)throw Error(`No compatible binary found for ${K}-${q} in release v${W}. Available assets: ${H.assets.map((A)=>A.name).join(", ")}`);let D=vJ(U).running;if(D)await WI("stop",U);let F=process.execPath,E=BH1(F),T=Iz0(E,`.tmp-update-${Date.now()}`);TH1(T,{recursive:!0});try{let A=Iz0(T,L.name);await SH1(L.downloadUrl,A,H.tagName,L.name);let R=A;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))R=gH1(A,T,K);else if(L.name.endsWith(".zip"))R=yH1(A,T,K);if(PH1(R,493),process.platform==="darwin")try{VI("/usr/bin/codesig Line truncated
`)}catch{}}async function SH1($,I,U,Y){let J=xx(),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 L=`https://github.com/${Qz0}/releases/download/${K}/${q}`;if(!process.env.CI)Q.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);Q.push(L)}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,w=307200,Z=1e4,z=180000;for(let L=0;L<G.length;L++){let D=G[L],F=new AbortController,E="",T=(g)=>{E=g;try{F.abort()}catch{}},A=setTimeout(()=>{T("Connection timed out (no response headers within 6s)")},W),R,u;try{_D(`==> [${L+1}/${G.length}] Downloading via: ${D}`);let g=await fetch(D,{signal:F.signal});if(A)clearTimeout(A),A=void 0;if(!g.ok)throw Error(`HTTP ${g.status} ${g.statusText}`);R=setTimeout(()=>{T("Overall download time exceeded 3 minutes")},z);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)`);$z0(I,i),_D(`✓ Download succeeded (${(i.length/1024/1024).toFixed(1)} MB)`);return}let p=[],n=0,S=0;u=setTimeout(()=>{if(n<w){let i=(n/1024).toFixed(1);T(`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(p.push(t),n+=t.length,u&&n>=w)clearTimeout(u),u=void 0;let K0=Date.now();if(K0-S>200){S=K0;let W0=b?Math.round(n/b*100):0,A0=(n/1048576).toFixed(1),v0=b?(b/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${W0}% (${A0} / ${v0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let f=Buffer.concat(p);if(f.length<1000)throw Error(`Downloaded content is suspiciously small (${f.length} bytes)`);$z0(I,f),_D(`✓ Download completed successfully (${(f.length/1024/1024).toFixed(1)} MB)`);return}catch(g){if(A)clearTimeout(A);if(u)clearTimeout(u);if(R)clearTimeout(R);let b=E||(g instanceof Error?g.message:String(g));H=Error(b),_D(`
↳ Mirror failed: ${H.message}`)}finally{if(A)clearTimeout(A);if(u)clearTimeout(u);if(R)clearTimeout(R)}}throw Error(`Failed to download asset from all mirrors: ${H?.message}`)}function gH1($,I,U){let Y=VI("tar",["-xzf",$,"-C",I],{stdio:"pipe"});if(Y.status!==0)throw Error(`Failed to extract tar archive: ${Y.stderr.toString()}`);Jz0($);let J=U==="windows"?"seal-use.exe":"seal-use",Q=VI("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 yH1($,I,U){let Y=VI("unzip",["-q","-o",$,"-d",I],{stdio:"pipe"});if(Y.status!==0)throw Error(`Failed to extract zip archive: ${Y.stderr.toString()}`);Jz0($);let J=U==="windows"?"seal-use.exe":"seal-use",Q=VI("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 qz0($,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 OG($,I){return qz0($,I)>0}function Yz0($,I,U={}){let Y=VI($,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 Gz0($,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 D0("seal_user_create",U,Y,{name:Q,phone:K,departmentIds:q?[q]:void 0},V0(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 D0("seal_user_reset_password",U,Y,{userId:Q},V0(J.options));return}if($==="search"||$==="list"){let Q=I??h(J.options.keyword)??h(J.options.query)??"";await D0("seal_user_search",U,Y,{keyword:Q},V0(J.options));return}if($==="get"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users get <userId>");await D0("seal_user_get",U,Y,{userId:Q},V0(J.options));return}if($==="delete"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users delete <userId>");await D0("seal_user_delete",U,Y,{userId:Q},V0(J.options));return}if($==="activate"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users activate <userId>");await D0("seal_user_activate",U,Y,{userId:Q},V0(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 D0("seal_user_delegation_create",U,Y,{userIdOrPhone:Q,note:K},V0(J.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as Hz0}from"node:fs";async function Wz0($,I){if(!Hz0($))throw Error(`File not found: ${$}`);let U=QI($);console.log(JSON.stringify(await JI(U.fileBuffer,U.fileName,I),null,2))}async function Vz0($,I,U,Y,J){if($==="ready"||$==="status"){let Q=I??h(J.options.file)??h(J.options.input),K=await QD(U,Y,{filePath:Q,webhook:h(J.options.webhook)??h(J.options.selector)});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(!Hz0(K))throw Error(`File not found: ${K}`);let q=QI(K);if(Q==="preview"){console.log(JSON.stringify(await JI(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=L9(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 w=H.map((Z)=>`"${Z.name}" (${Z.id})`).join(", ");throw Error(`当前租户存在多个 Webhook 通道 [${w}],请通过 --webhook <idOrName> 指定目标通道。`)}else throw new c8("当前租户未配置任何 Webhook 集成通道。",1,`seal-use webhook add --name <name> --result-url <url> --corp ${Y.id}`);let V=await JD(q.fileBuffer,q.fileName,{webhookUrl:W.incomingDocumentWebhook.url,secret:W.secret,materialPackFilePolicy:W.materialPackFilePolicy});console.log(JSON.stringify(V,null,2));return}if($==="list"){await D0("seal_webhook_ Line truncated
`)?"":`
`}`);process.exitCode=$.exitCode}var rw1=Boolean(o.main==o.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&gX0(process.argv[1])===gX0(i5));if(rw1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await ow1();else Xu().catch(($)=>{console.error($),process.exitCode=1});export{Wu as tokenizeCommand,Xu as startServer,dw1 as resolveMcpEnabled,lw1 as createServer,pw1 as SEAL_MCP_ENABLED_ENV,iw1 as SEAL_CLI_TOOL_NAME,cw1 as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=$.exitCode}var rH1=Boolean(r.main==r.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&zz0(process.argv[1])===zz0(d5));if(rH1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await oH1();else Px().catch(($)=>{console.error($),process.exitCode=1});export{Mx as tokenizeCommand,Px as startServer,dH1 as resolveMcpEnabled,mH1 as createServer,pH1 as SEAL_MCP_ENABLED_ENV,nH1 as SEAL_CLI_TOOL_NAME,cH1 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.7",
"version": "0.10.14",
"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.7
version: 0.10.14
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.7",
"version": "0.10.14",
"type": "module",
"module": "src/server.ts",
"bin": {
+25 -8
View File
@@ -1,12 +1,12 @@
---
name: seal-use
description: "v0.10.7: 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.14: 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.7
short-description: Seal tenant and Hose approval automation (v0.10.7)
version: 0.10.14
short-description: Seal tenant and Hose approval automation (v0.10.14)
---
# Seal Use (v0.10.7)
# Seal Use (v0.10.14)
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.
@@ -39,7 +39,8 @@ seal-use corps list
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use `seal-use corps ...`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For repeat test-environment rule resets, prefer `rules clear --dry-run` followed by `rules clear --yes`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal `--dry-run` preview first (rules clear/push, preferences, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use `--yes` only after reviewing its redacted `changesDiff`.
- Knowledge document creation is currently irreversible: the upstream API exposes no delete operation. Validate `contentType` and `scenarios` before creating, and use `enabled: false` when the document should be withdrawn.
- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of `description`; preserve `scope`, `strictness`, and unrelated clauses unless the user explicitly approves otherwise.
- Resolve and lock the target enterprise `corpId` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing.
- For date questions, use explicit dates and `--timezone Asia/Shanghai`.
@@ -55,7 +56,7 @@ seal-use corps list
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation status <batchId>` 单次查询状态, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
- Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`; read `references/hose-enterprise-deploy.md`.
- 审核决策偏好与思考深度: `seal-use preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>`, `seal-use approval-runs count --corp <corpId>`.
@@ -65,12 +66,28 @@ 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 material-pack preview <材料包.zip> --corp <corpId>` 只做本地校验和解析;`... push <材料包.zip> --webhook <idOrName> --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批。它与 `simulation material_pack` 的官方服务端导入流程相互独立。
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --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`)。每个 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`.
## Material-pack Webhook policy and recovery
材料包附件策略保存在目标入站 Webhook 的 `materialPackFilePolicy` 下,按 Webhook 生效。新建 Webhook 的默认策略是:最小文件大小 `500` 字节、最大文件大小不限制、后缀白名单为常见 PDF/Office/文本/邮件/图片格式。`信息表.xlsx` 是材料包根清单,不属于普通附件,不受这三个附件策略限制。完整默认后缀和边界规则见 `references/cli.md`。
这套策略允许人工或助手修改。错误处理有两条通道:先通过错误通道明确告诉助手是哪一个文件、哪一条规则失败;再通过配置或文件处置通道完成恢复。遇到附件被拦截时按以下闭环处理:
1. 从错误中识别被拦截的文件、实际大小、失败规则和目标 Webhook。
2. 向用户说明可选处置:替换/压缩文件,或在确认允许该格式/大小后修改 Webhook 策略。
3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置(CLI 使用 `webhook get`/`webhook list`,MCP 使用 `seal_webhook_get`/`seal_webhook_list`)。
4. 调用 `seal_webhook_update` 或 `seal-use webhook update` 修改最小值、最大值或完整后缀白名单,写入后重新读取核对,再重试原来的材料包 push。
push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 `stderr` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。
注意:直接执行本地 `material-pack preview` 只使用默认策略或命令行临时覆盖,不会自动读取某个 Webhook 的持久化策略;`webhook ready --file`(指定 Webhook 时)和 `material-pack push` 才使用保存的 Webhook 策略。需要验证实际入站通道策略时,优先使用 `ready --file --webhook ...`,或直接重试 push。
## High-Value Commands
```bash
@@ -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`.
+209 -69
View File
@@ -27,8 +27,8 @@ override that path. The legacy `current-corp` file is not read.
## Stream & Exit Code Contract
- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.
- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).
- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.
- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** with the stable prefix `👉 Next action: seal-use ...`.
- **`Exit Code`**: `0` on success; `1` runtime/upstream failure, `2` usage/argument error, `10` explicit destructive-operation confirmation required, `11` missing/invalid authentication, and `12` output protection requiring a compact/file/query alternative.
## Top-Level Commands
@@ -37,6 +37,7 @@ seal-use version
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 <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]
@@ -61,6 +62,12 @@ seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <c
seal-use users reset-password <userId> [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use data invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
@@ -70,41 +77,46 @@ seal-use billing plans [--corp <corpId>]
seal-use billing features [--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 add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--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] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
seal-use webhook delete <idOrName> [--yes|--dry-run] [--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 status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--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>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use source config [--corp <corpId>]
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 analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO>] [--limit <n>]
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>
seal-use approval-runs url --sourceDocumentSN <sourceDocumentSN> --corp <corpId>
seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] --corp <corpId>
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp <corpId>
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] --corp <corpId>
seal-use simulation clean <batchId> --corp <corpId>
seal-use simulation specifications [--integration <sign-key>] --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use simulation list [--limit 50] --corp <corpId>
seal-use simulation get <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
@@ -112,7 +124,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:
@@ -130,8 +142,8 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
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:
@@ -139,18 +151,15 @@ Approval rule maintenance:
- `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 push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
- `seal-use rules clear [--corp <corpId>] [--dry-run|--yes]`
- `seal_approval_rules_list`
- `seal_approval_rules_pull`
- `seal_approval_rules_push`
- `seal_approval_rules_lint`
- `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`
Rule identity and versioning:
- `rules list` and `rules pull` read the current **draft** rule set. Their `code` values belong to the draft code space.
- A published version has its own snapshot and code space. Publishing can recode rules, so a published `code` may differ from the draft `code`, and codes can shift again after later edits and publishes.
- Do not use a draft `#NN` as a cross-version identifier. For current draft work, prefer the stable rule `id`; for historical behavior, select the published `version` and locate the rule by its text/context or runtime rule ID from the approval run.
- `rules get --version ... --code ...` interprets `code` inside that selected published version, while `rules get --record-id ... --runtime-id ...` resolves the version recorded on the run.
Approval run lightweight queries:
@@ -161,61 +170,44 @@ 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>] [--webhook <idOrName>] [--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-use webhook material-pack preview <材料包.zip|信息表.xlsx> --corp <corpId>`
- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> --webhook <idOrName> --corp <corpId>`
- `seal_webhook_list`
- `seal_webhook_get`
- `seal_webhook_add`
- `seal_webhook_update`
- `seal_webhook_delete`
- `seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--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] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]`
- `seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]`
- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.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.
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. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
All supported configuration writes accept `--dry-run`: rules clear/push, preference updates, thinking-depth policy changes, HoseCloud configure, and Webhook add/update/delete. Preview mode performs read-only discovery and returns JSON with `preview: true`, the exact `targetUrl`, a redacted `changesDiff` (`before`/`after`), and `impactCount`. It never sends the mutation request and does not require `--yes`; use the same command with `--yes` only after reviewing the preview.
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 ... --no-wait --corp <corpId>` returns immediately with an `asyncTicket` (creation is non-blocking by default for compatibility).
- `seal-use simulation status <batchId> --corp <corpId>` performs one non-blocking status check and returns `QUEUED`/`RUNNING`/`COMPLETED`/`FAILED`-style state plus counters.
- `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
@@ -338,13 +330,17 @@ Create a document:
"title": "标题",
"purpose": "用途",
"content": "Markdown 内容",
"contentType": "text/markdown",
"status": "可选",
"scenarios": ["场景"],
"contentType": "policy",
"status": "published",
"scenarios": ["audit"],
"tags": ["标签"]
}
```
`contentType` 必须是 `document`、`video`、`pdf`、`feishu_doc` 或 `policy` 之一;`scenarios` 必填且至少包含一个 `fill`(智能填单)或 `audit`(智能审核)。这里的 `scenarios` 是产品能力开关,不是费用类别或业务场景名。
知识文档创建后当前 API 没有删除接口,创建操作不可逆;请在写入前确认标题、正文、内容类型和能力场景。需要撤下内容时,优先使用更新操作并设置 `enabled: false`(如果上游支持该字段),不要通过试探性创建来验证参数。规则支持删除,但知识文档与规则的生命周期能力并不对称。
Update a document:
```json
@@ -373,6 +369,150 @@ 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. **Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`
6. **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>
# Preview with temporary local policy overrides (comma-separated extensions)
seal-use webhook material-pack preview <pack.zip> --min-file-size 500 --max-file-size 20971520 --allowed-extensions .pdf,.xlsx,.docx --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)
```
### Attachment file policy configuration
The policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow. The policy is intentionally mutable: after an authorized configuration change, retrying the same push reads the saved policy again.
Default configuration:
```json
{
"minFileSizeBytes": 500,
"maxFileSizeBytes": null,
"allowedExtensions": [
".pdf", ".xls", ".xlsx", ".csv", ".doc", ".docx", ".ppt", ".pptx",
".txt", ".rtf", ".odt", ".ods", ".odp", ".jpg", ".jpeg", ".png",
".gif", ".bmp", ".webp", ".heic", ".eml", ".msg"
]
}
```
`null` or an omitted `maxFileSizeBytes` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root `信息表.xlsx` remains exempt from attachment policy checks.
```bash
# New Webhook: use the default 500-byte minimum and default extension whitelist
seal-use webhook add --name "材料包入站" --result-url "https://your-domain.com/callback" --corp <corpId>
# Configure an existing Webhook; sizes are bytes and extensions are comma-separated
seal-use webhook update <webhookIdOrName> \
--min-file-size 500 \
--max-file-size 20971520 \
--allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png \
--corp <corpId>
# Allow a newly confirmed format while retaining the rest of the policy:
# first read webhook get/list, then pass the complete desired whitelist.
seal-use webhook update <webhookIdOrName> \
--allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png,.zip \
--corp <corpId>
# Remove only the maximum-size limit (minimum and whitelist are retained).
seal-use webhook update <webhookIdOrName> --clear-max-file-size --corp <corpId>
```
The saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.
### Failure recovery loop
When a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop:
1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary.
2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy.
3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration.
4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins.
The same loop is available through MCP: read with `seal_webhook_get`/`seal_webhook_list`, update with `seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal_webhook_material_pack` in `push` mode. For MCP, set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one.
If the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack.
The direct local `material-pack preview` command and MCP preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use `webhook ready --file --webhook <idOrName>` or the actual push path when validating against the saved inbound policy.
### 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 |
| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |
| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |
| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |
| `附件上传失败 <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.
@@ -133,6 +133,8 @@ seal-use tool seal_approval_rule_update --corp <corpId> \
Do not send `scope` or `strictness` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing.
For a complete local rule-set sync, `rules push` is incremental: it matches pulled rules by stable `id`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with `rules push --dry-run` before applying.
## 9. Publish and verify
Publish only when explicitly authorized:
@@ -2,6 +2,12 @@
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.
## Draft and Published Rule Codes
`rules list` and `rules pull` operate on the current draft and therefore return draft `code` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as `#0038` is only meaningful together with its version context.
Use the draft `id` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version.
## Count Rules
Use count when only scale or existence matters.
+1 -1
View File
@@ -57,7 +57,7 @@ describe("CLI version & help handling", () => {
test("invalid command displays unknown command error with help hint", () => {
const result = runCli(["invalid-command"]);
expect(result.status).toBe(1);
expect(result.status).toBe(2);
expect(result.stderr).toContain("Unknown command: invalid-command. Run 'seal-use help' for available commands.");
});
+30
View File
@@ -0,0 +1,30 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleAnalyticsCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "insight" || action === "insight-stats" || action === "stats") {
await runTool(
"seal_insight_stats_get",
client,
corp,
{
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
limit: numberOption(args.options.limit)
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+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);
+34 -1
View File
@@ -90,5 +90,38 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint. Run 'seal-use help' for available commands.`);
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.`);
}
+42
View File
@@ -0,0 +1,42 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleContactsCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "sync-time" || action === "last-sync-time") {
await runTool("seal_contacts_last_sync_time_get", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "departments" || action === "department") {
if (!maybeName) {
await runTool("seal_contacts_departments_root_list", client, corp, {}, outputOptions(args.options));
return;
}
await runTool("seal_contacts_department_get", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
if (action === "children" || action === "department-children") {
if (!maybeName) throw new Error("Usage: seal-use contacts children <departmentId>");
await runTool("seal_contacts_department_children_list", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
if (action === "users" || action === "department-users") {
if (!maybeName) throw new Error("Usage: seal-use contacts users <departmentId>");
await runTool("seal_contacts_department_users_list", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
throw new Error(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+22 -3
View File
@@ -10,12 +10,14 @@ import {
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
loadCorpConfigs,
loadGlobalConfig,
resolveWritableEnterprisesDir,
saveGlobalConfig
} from "../../core/config/loader.js";
import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js";
import type { CorpConfig } from "../../core/config/types.js";
import { getMe } from "../../domains/seal/api.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
@@ -374,8 +376,20 @@ async function addSealCorp(input: Record<string, unknown>) {
const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60;
const verify = input.force === true || input.verify === false ? false : true;
const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined;
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote });
const custom = sealCustomHeadersFromInput(input);
const remote = verify
? await resolveSealWhoami(sealUrl, token, resolveSealCustomHeaders(custom))
: undefined;
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote, custom });
}
// Validates extra headers/cookies up front so a malformed name fails here
// rather than on the next config load.
function sealCustomHeadersFromInput(input: Record<string, unknown>) {
return {
headers: SealHeaderMapSchema.parse(input.headers),
cookies: SealCookieMapSchema.parse(input.cookies)
};
}
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) {
@@ -419,9 +433,11 @@ function writeSealCorpConfig(
expiresIn: number;
verify: boolean;
remote?: RemoteSealIdentity;
custom?: { headers?: Record<string, string>; cookies?: Record<string, string> };
}
) {
const { token, sealUrl, expiresIn, verify, remote } = auth;
const custom = auth.custom ?? sealCustomHeadersFromInput(input);
const remoteUser = remote?.user;
const remoteTenant = remote?.tenant;
const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug);
@@ -447,6 +463,8 @@ function writeSealCorpConfig(
seal: {
url: sealUrl,
tenantSlug,
headers: custom.headers,
cookies: custom.cookies,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
@@ -522,8 +540,9 @@ async function resolveHoseCorporation(domain: string, appKey: string, appSecurit
: undefined;
}
async function resolveSealWhoami(sealUrl: string, token: string) {
async function resolveSealWhoami(sealUrl: string, token: string, customHeaders: Record<string, string> = {}) {
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
...customHeaders,
authorization: `Bearer ${token}`
});
const data = objectValue(json.data);
+33
View File
@@ -0,0 +1,33 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleDataCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
const params = {
offset: numberOption(args.options.offset),
limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
search: stringOption(args.options.search) ?? stringOption(args.options.query)
};
if (action === "expenses" || action === "expense") {
await runTool("seal_expenses_list", client, corp, params, outputOptions(args.options));
return;
}
if (action === "invoices" || action === "invoice") {
await runTool("seal_invoices_list", client, corp, params, outputOptions(args.options));
return;
}
throw new Error(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+19 -3
View File
@@ -6,6 +6,7 @@ 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";
import { CliError } from "../errors.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -83,7 +84,13 @@ export async function handleDeployCommand(
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。");
throw new CliError(
"缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",
2,
hoseConfigs.length === 1
? `seal-use deploy hosecloud get ${hoseConfigs[0]!.signKey} --corp ${corp.id}`
: undefined
);
}
await runTool("seal_deploy_hosecloud_get", client, corp, { signKey }, outputOptions(args.options));
return;
@@ -102,7 +109,10 @@ export async function handleDeployCommand(
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
}
await runTool("seal_deploy_hosecloud_configure", client, corp, payload, outputOptions(args.options));
await runTool("seal_deploy_hosecloud_configure", client, corp, {
...payload,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
@@ -143,7 +153,13 @@ export async function handleDeployCommand(
console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。");
throw new CliError(
"缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",
2,
hoseConfigs.length === 1
? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --corp ${corp.id}`
: undefined
);
}
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey }, outputOptions(args.options));
+17 -5
View File
@@ -2,7 +2,7 @@ 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";
@@ -29,7 +29,10 @@ export async function handlePreferenceCommand(
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
}
await runTool("seal_preference_decision_update", client, corp, payload, outputOptions(args.options));
await runTool("seal_preference_decision_update", client, corp, {
...payload,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
}
@@ -43,7 +46,10 @@ export async function handlePreferenceCommand(
if (defaultLevel !== "medium" && defaultLevel !== "high") {
throw new Error("Usage: seal-use preference thinking-depth set --default <medium|high>");
}
await runTool("seal_preference_thinking_depth_set", client, corp, { defaultLevel }, outputOptions(args.options));
await runTool("seal_preference_thinking_depth_set", client, corp, {
defaultLevel,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
@@ -61,7 +67,10 @@ export async function handlePreferenceCommand(
if (!payload || !payload.id || !payload.name) {
throw new Error("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
}
await runTool("seal_preference_thinking_depth_policies_upsert", client, corp, payload, outputOptions(args.options));
await runTool("seal_preference_thinking_depth_policies_upsert", client, corp, {
...payload,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
@@ -70,7 +79,10 @@ export async function handlePreferenceCommand(
if (!policyId) {
throw new Error("Usage: seal-use preference thinking-depth policies remove <policyId>");
}
await runTool("seal_preference_thinking_depth_policies_remove", client, corp, { policyId }, outputOptions(args.options));
await runTool("seal_preference_thinking_depth_policies_remove", client, corp, {
policyId,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
}
+5 -1
View File
@@ -1,6 +1,7 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool, runToolResult } from "../helpers.js";
import { confirmationRequired } from "../errors.js";
import {
booleanOption,
numberOption,
@@ -63,7 +64,10 @@ export async function handleRulesCommand(
const confirmed = booleanOption(args.options.yes) === true;
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
if (!confirmed && !dryRun) {
throw new Error("Refusing to clear rules without --yes. Use --dry-run to preview.");
throw confirmationRequired(
"Refusing to clear rules without --yes. Use --dry-run to preview.",
`seal-use rules clear --corp ${corp.id} --dry-run`
);
}
const result = await runToolResult("seal_approval_rules_clear", client, corp, {
dryRun,
+26
View File
@@ -62,6 +62,7 @@ export async function handleSimulationCommand(
stringOption(args.options.signKey) ??
stringOption(args.options["sign-key"]) ??
stringOption(args.options.integration);
const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]);
await runTool(
"seal_simulation_batch_create",
@@ -91,6 +92,7 @@ export async function handleSimulationCommand(
endTime: numberOption(args.options.endTime) ?? numberOption(args.options["end-time"]),
status: splitOption(args.options.status),
limit: numberOption(args.options.limit),
noWait,
rawParams: inputPayload
},
outputOptions(args.options)
@@ -115,6 +117,19 @@ export async function handleSimulationCommand(
return;
}
if (action === "status") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation status <batchId>");
await runTool(
"seal_simulation_batch_status",
client,
corp,
{ batchId },
outputOptions(args.options)
);
return;
}
if (action === "clean" || action === "delete") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation clean <batchId>");
@@ -132,6 +147,17 @@ export async function handleSimulationCommand(
return;
}
if (action === "approval-definitions" || action === "definitions") {
await runTool(
"seal_simulation_feishu_approval_definitions_list",
client,
corp,
{},
outputOptions(args.options)
);
return;
}
if (action === "list") {
await runTool(
"seal_simulation_batches_list",
+94 -15
View File
@@ -4,9 +4,16 @@ 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 { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "../../domains/seal/material-pack/index.js";
import type { WebhookIntegration } from "../../domains/seal/types.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../../domains/seal/material-pack/index.js";
import {
booleanOption,
materialPackFilePolicyOptions,
parseWebhookMode,
stringOption,
webhookRateOption,
@@ -14,11 +21,16 @@ import {
} from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
import { CliError, confirmationRequired, usageError } from "../errors.js";
export async function handleWebhookMaterialPackPreview(filePath: string) {
export async function handleWebhookMaterialPackPreview(
filePath: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
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));
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy), null, 2));
}
export async function handleWebhookCommand(
@@ -28,6 +40,42 @@ 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,
webhook: stringOption(args.options.webhook) ?? stringOption(args.options.selector)
});
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"
@@ -42,11 +90,27 @@ export async function handleWebhookCommand(
}
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);
if (!selector) throw new Error("Push requires --webhook <idOrName>");
const integration = findWebhookIntegration(await api.listWebhookIntegrations(client), 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 CliError(
"当前租户未配置任何 Webhook 集成通道。",
1,
`seal-use webhook add --name <name> --result-url <url> --corp ${corp.id}`
);
}
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret
secret: integration.secret,
materialPackFilePolicy: integration.materialPackFilePolicy
});
console.log(JSON.stringify(result, null, 2));
return;
@@ -92,6 +156,8 @@ export async function handleWebhookCommand(
throw new Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
}
const autoApprovalRate = webhookRateOption(args.options);
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
await runTool(
"seal_webhook_add",
client,
@@ -101,7 +167,9 @@ export async function handleWebhookCommand(
mode: parseWebhookMode(stringOption(args.options.mode)),
outgoingResultWebhook,
autoApprovalRate,
secret: stringOption(args.options.secret)
secret: stringOption(args.options.secret),
materialPackFilePolicy,
dryRun
},
outputOptions(args.options)
);
@@ -114,7 +182,7 @@ export async function handleWebhookCommand(
const secret = stringOption(args.options.secret);
const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]);
if (secret !== undefined && rotateSecret) {
throw new Error("Use either --secret or --rotate-secret, not both");
throw usageError("Use either --secret or --rotate-secret, not both");
}
const name = stringOption(args.options.name);
const mode = parseWebhookMode(stringOption(args.options.mode));
@@ -124,15 +192,19 @@ export async function handleWebhookCommand(
stringOption(args.options.outgoingResultWebhook) ??
stringOption(args.options["outgoing-result-webhook"]);
const autoApprovalRate = webhookRateOption(args.options);
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
if (
name === undefined &&
mode === undefined &&
outgoingResultWebhook === undefined &&
autoApprovalRate === undefined &&
secret === undefined &&
!rotateSecret
!rotateSecret &&
materialPackFilePolicy === undefined &&
!dryRun
) {
throw new Error("Webhook update requires at least one field option");
throw usageError("Webhook update requires at least one field option");
}
await runTool(
"seal_webhook_update",
@@ -145,7 +217,9 @@ export async function handleWebhookCommand(
outgoingResultWebhook,
autoApprovalRate,
secret,
rotateSecret
rotateSecret,
materialPackFilePolicy,
dryRun
},
outputOptions(args.options)
);
@@ -154,9 +228,13 @@ export async function handleWebhookCommand(
if (action === "delete") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> --yes");
if (booleanOption(args.options.yes) !== true) {
throw new Error("Refusing to delete Webhook integration without --yes");
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (booleanOption(args.options.yes) !== true && !dryRun) {
throw confirmationRequired(
"Refusing to delete Webhook integration without --yes",
`seal-use webhook delete ${selector} --corp ${corp.id} --yes`
);
}
await runTool(
"seal_webhook_delete",
@@ -164,7 +242,8 @@ export async function handleWebhookCommand(
corp,
{
selector,
confirm: true
confirm: true,
dryRun
},
outputOptions(args.options)
);
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, test } from "bun:test";
import { CliError, classifyCliError, confirmationRequired, PayloadTooLargeError } from "./errors.js";
describe("CLI semantic errors", () => {
test("preserves explicit exit codes and next actions", () => {
const error = new CliError("missing sign key", 2, "seal-use deploy hosecloud get <sign-key>");
expect(classifyCliError(error)).toEqual({
exitCode: 2,
nextAction: "seal-use deploy hosecloud get <sign-key>"
});
});
test("classifies confirmation and output protection distinctly", () => {
expect(classifyCliError(confirmationRequired("Refusing to delete", "seal-use webhook delete <id> --yes"))).toMatchObject({
exitCode: 10,
nextAction: "seal-use webhook delete <id> --yes"
});
expect(classifyCliError(new PayloadTooLargeError("Output too large"))).toEqual({ exitCode: 12 });
});
test("classifies authentication failures from response status", () => {
expect(classifyCliError({ response: { status: 401 } })).toEqual({ exitCode: 11 });
expect(classifyCliError(new Error("bearer token expired"))).toEqual({ exitCode: 11 });
});
test("classifies unknown commands and subcommands across all domains as usage errors", () => {
expect(classifyCliError(new Error("Unknown command: not-a-command"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown contacts command: . Run 'seal-use help' for available commands."))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown data command: bad-subcommand"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown analytics command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown approval-runs command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown billing command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown webhook command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Usage: seal-use contacts children <departmentId>"))).toEqual({ exitCode: 2 });
});
});
+58
View File
@@ -0,0 +1,58 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11 };
}
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
return { exitCode: 1 };
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}
+3
View File
@@ -27,6 +27,9 @@ export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) {
...(config.stateful && config.defaultCorpId
? { defaultCorpId: config.defaultCorpId }
: {}),
...(config.testEnterprisesDir
? { testEnterprisesDir: config.testEnterprisesDir }
: {}),
lint: config.lint,
configFile: resolveGlobalConfigFile()
};
+43 -5
View File
@@ -1,5 +1,7 @@
import type { WebhookMode } from "../domains/seal/types.js";
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
import type { ParsedArgs } from "./types.js";
import { usageError } from "./errors.js";
export function parseArgs(argv: string[]): ParsedArgs {
const command: string[] = [];
@@ -12,8 +14,12 @@ export function parseArgs(argv: string[]): ParsedArgs {
if (arg === "--json") {
const raw = argv[index + 1];
if (!raw) throw new Error("--json requires a JSON object argument");
json = JSON.parse(raw);
if (!raw) throw usageError("--json requires a JSON object argument");
try {
json = JSON.parse(raw);
} catch (error) {
throw usageError(`Invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
}
index += 1;
continue;
}
@@ -46,7 +52,7 @@ export function parseArgs(argv: string[]): ParsedArgs {
export function jsonObject(value: unknown): Record<string, unknown> {
if (value === undefined) return {};
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("--json must be an object");
throw usageError("--json must be an object");
}
return value as Record<string, unknown>;
}
@@ -58,7 +64,7 @@ export function stringOption(value: string | boolean | undefined): string | unde
export function numberOption(value: string | boolean | undefined): number | undefined {
if (typeof value !== "string") return undefined;
const number = Number(value);
if (!Number.isFinite(number)) throw new Error(`Invalid number: ${value}`);
if (!Number.isFinite(number)) throw usageError(`Invalid number: ${value}`);
return number;
}
@@ -73,7 +79,7 @@ export function booleanOption(value: string | boolean | undefined): boolean | un
if (typeof value === "boolean") return value;
if (value === "true") return true;
if (value === "false") return false;
throw new Error(`Invalid boolean: ${value}`);
throw usageError(`Invalid boolean: ${value}`);
}
export function requiredString(input: Record<string, unknown>, key: string): string {
@@ -201,3 +207,35 @@ export function webhookRateOption(options: Record<string, string | boolean>): nu
export function webhookShowSecretOption(options: Record<string, string | boolean>): boolean | undefined {
return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]);
}
export function materialPackFilePolicyOptions(
options: Record<string, string | boolean>
): MaterialPackFilePolicyPatch | undefined {
const clearMaxFileSize = booleanOption(
options.clearMaxFileSize ?? options["clear-max-file-size"]
) === true;
const minFileSizeBytes = numberOption(
options.minFileSizeBytes ?? options["min-file-size-bytes"] ?? options.minFileSize ?? options["min-file-size"]
);
const maxFileSizeBytes = numberOption(
options.maxFileSizeBytes ?? options["max-file-size-bytes"] ?? options.maxFileSize ?? options["max-file-size"]
);
const allowedExtensions = splitOption(
options.allowedExtensions ?? options["allowed-extensions"] ?? options.extensions
);
if (
minFileSizeBytes === undefined &&
maxFileSizeBytes === undefined &&
allowedExtensions === undefined &&
!clearMaxFileSize
) {
return undefined;
}
return {
minFileSizeBytes,
maxFileSizeBytes: clearMaxFileSize ? null : maxFileSizeBytes,
allowedExtensions
};
}
+35 -18
View File
@@ -1,11 +1,12 @@
import { writeFileSync } from "node:fs";
import { booleanOption, stringOption } from "./parser.js";
import { PayloadTooLargeError } from "./errors.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,11 +34,11 @@ 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) {
throw new Error(
throw new PayloadTooLargeError(
`Output is large (${bodyBytes} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`
);
}
@@ -56,8 +57,9 @@ export function protectLargeRuleListOutput(result: unknown, allowFull: boolean)
const effectiveCount = count ?? rulesCount ?? 0;
if (effectiveCount > RULE_LIST_FULL_COUNT_LIMIT || bodyBytes > RULE_LIST_FULL_BYTES_LIMIT) {
throw new Error(
`Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`
throw new PayloadTooLargeError(
`Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`,
"seal-use rules list --summary"
);
}
}
@@ -87,6 +89,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>]
@@ -109,6 +113,12 @@ Usage:
seal-use users reset-password <userId> [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
@@ -116,25 +126,27 @@ Usage:
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--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 webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size 500] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--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] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.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>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--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>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use rules count [--corp <corpId>]
@@ -149,24 +161,29 @@ 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 analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]
seal-use approval-runs url [--corp <corpId>]
seal-use approval-runs url <recordId> [--corp <corpId>]
seal-use approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
seal-use simulation batch-records <batchId> [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--corp <corpId>]
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation status <batchId> [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use simulation clean <batchId> [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation approval-definitions [--corp <corpId>]
seal-use simulation list [--limit 50] [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
+46 -1
View File
@@ -1,3 +1,6 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, test } from "bun:test";
import { runCli } from "./runner.js";
@@ -17,7 +20,49 @@ describe("CLI runner", () => {
const result = await runCli(["not-a-command"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(1);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Unknown command: not-a-command");
});
test("returns a semantic usage exit code for invalid JSON", async () => {
const result = await runCli(["version", "--json", "not-json"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Invalid JSON:");
});
test("returns usage exit code 2 for unknown subcommands across standalone domains", async () => {
const result = await runCli(["skill", "not-a-subcommand"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Unknown skill command: not-a-subcommand");
});
test("returns usage exit code 2 for unknown subcommands with an active enterprise", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "seal-use-runner-test-"));
const originalEnv = process.env.SEAL_USE_ENTERPRISES_DIR;
try {
process.env.SEAL_USE_ENTERPRISES_DIR = tempDir;
writeFileSync(
join(tempDir, "test.json"),
JSON.stringify({
id: "test",
name: "Test Corp",
source: { type: "seal", token: "dummy-token", sealUrl: "https://test.sealai.cc" },
seal: { url: "https://test.sealai.cc" }
})
);
const result = await runCli(["contacts", "not-a-subcommand", "--corp", "test"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Unknown contacts command: not-a-subcommand");
} finally {
if (originalEnv === undefined) delete process.env.SEAL_USE_ENTERPRISES_DIR;
else process.env.SEAL_USE_ENTERPRISES_DIR = originalEnv;
rmSync(tempDir, { recursive: true, force: true });
}
});
});
+37 -4
View File
@@ -6,9 +6,12 @@ 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 { handleAnalyticsCommand } from "./commands/analytics.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleBillingCommand } from "./commands/billing.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleContactsCommand } from "./commands/contacts.js";
import { handleDataCommand } from "./commands/data.js";
import { handleContextCommand } from "./commands/context.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleDelegationCommand, handleDelegationFromHoseLink } from "./commands/delegation.js";
@@ -30,8 +33,15 @@ import { handleToolsListCommand } from "./commands/tools.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleUsersCommand } from "./commands/users.js";
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
import { classifyCliError } from "./errors.js";
import { selectCorp } from "./helpers.js";
import { booleanOption, numberOption, parseArgs, stringOption } from "./parser.js";
import {
booleanOption,
materialPackFilePolicyOptions,
numberOption,
parseArgs,
stringOption
} from "./parser.js";
import {
formatConsoleOutput,
joinOutput,
@@ -56,6 +66,8 @@ const KNOWN_AREAS = new Set([
"auth",
"delegation",
"users",
"contacts",
"data",
"llm",
"permissions",
"billing",
@@ -64,6 +76,7 @@ const KNOWN_AREAS = new Set([
"context",
"rules",
"approval-runs",
"analytics",
"simulation",
"deploy",
"preference",
@@ -131,12 +144,17 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliRe
exitCode: 0
};
} catch (error) {
stderr.push(redactSensitiveText(error instanceof Error ? error.message : String(error)));
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
stderr.push(message);
if (classification.nextAction && !message.includes("Next action:")) {
stderr.push(`👉 Next action: ${classification.nextAction}`);
}
return {
stdout: joinOutput(stdout),
stderr: joinOutput(stderr),
isError: true,
exitCode: 1
exitCode: classification.exitCode
};
} finally {
console.log = originalLog;
@@ -174,7 +192,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
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);
await handleWebhookMaterialPackPreview(filePath, materialPackFilePolicyOptions(args.options));
return;
}
@@ -308,6 +326,16 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "contacts") {
await handleContactsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "data") {
await handleDataCommand(action, client, corp, args);
return;
}
if (area === "llm") {
await handleLlmCommand(action, client, corp, args);
return;
@@ -343,6 +371,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "analytics") {
await handleAnalyticsCommand(action, client, corp, args);
return;
}
if (area === "simulation") {
await handleSimulationCommand(action, maybeName, client, corp, args);
return;
-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> {
+24 -9
View File
@@ -84,21 +84,34 @@ 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", () => {
@@ -114,13 +127,14 @@ describe("loadCorpConfigs", () => {
});
});
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",
testEnterprisesDir: "/tmp/test-corps",
lint: {
enabled: false,
activeLinter: "builtin",
@@ -131,6 +145,7 @@ describe("loadCorpConfigs", () => {
expect(loadGlobalConfig()).toEqual({
stateful: true,
defaultCorpId: "corp-a",
testEnterprisesDir: "/tmp/test-corps",
lint: {
enabled: false,
activeLinter: "builtin",
+13 -18
View File
@@ -3,7 +3,6 @@ import { homedir } from "node:os";
import { dirname, join } from "node:path";
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
];
+59 -1
View File
@@ -1,5 +1,10 @@
import { describe, expect, test } from "bun:test";
import { CorpConfigSchema, GlobalConfigSchema } from "./types.js";
import {
CorpConfigSchema,
GlobalConfigSchema,
SealCookieMapSchema,
SealHeaderMapSchema
} from "./types.js";
describe("CorpConfigSchema", () => {
test("accepts Hose key/password aliases", () => {
@@ -78,6 +83,59 @@ describe("CorpConfigSchema", () => {
expect(config.source.staffId).toBe("seal");
expect(config.source.tenantSlug).toBe("xiezihao");
});
test("leaves custom headers and cookies absent by default", () => {
const config = CorpConfigSchema.parse({
id: "direct",
name: "Direct",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://direct.sealai.cc"
}
});
expect(config.seal.headers).toBeUndefined();
expect(config.seal.cookies).toBeUndefined();
});
test("accepts custom headers and cookies on the Seal endpoint", () => {
const config = CorpConfigSchema.parse({
id: "gated",
name: "Gated",
seal: {
url: "https://gated.sealai.cc",
headers: { "X-Tenant": "acme" },
cookies: { sdp_app_session_20142: "abc" }
},
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://gated.sealai.cc"
}
});
expect(config.seal.headers).toEqual({ "X-Tenant": "acme" });
expect(config.seal.cookies).toEqual({ sdp_app_session_20142: "abc" });
});
});
describe("Seal custom header schemas", () => {
test("rejects an Authorization header supplied through config", () => {
expect(SealHeaderMapSchema.safeParse({ Authorization: "Bearer x" }).success).toBe(false);
expect(SealHeaderMapSchema.safeParse({ authorization: "Bearer x" }).success).toBe(false);
});
test("rejects malformed header and cookie names", () => {
expect(SealHeaderMapSchema.safeParse({ "bad name": "v" }).success).toBe(false);
expect(SealCookieMapSchema.safeParse({ "bad;name": "v" }).success).toBe(false);
});
test("rejects cookie values containing separators", () => {
expect(SealCookieMapSchema.safeParse({ name: "v;other=1" }).success).toBe(false);
expect(SealCookieMapSchema.safeParse({ name: "line\nbreak" }).success).toBe(false);
expect(SealCookieMapSchema.safeParse({ name: "ok-value" }).success).toBe(true);
});
});
describe("GlobalConfigSchema", () => {
+30
View File
@@ -58,9 +58,38 @@ export const SealSourceSchema = z.discriminatedUnion("type", [
NativeSealSourceSchema
]);
// RFC 7230 token: shared by HTTP header names and cookie names.
const HTTP_TOKEN_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
export const SealHeaderMapSchema = z.record(
z.string().regex(HTTP_TOKEN_PATTERN, "Invalid HTTP header name"),
z.string()
).superRefine((headers, ctx) => {
for (const name of Object.keys(headers)) {
if (name.toLowerCase() === "authorization") {
ctx.addIssue({
code: "custom",
path: [name],
message: "seal.headers cannot set Authorization; the Seal session supplies the bearer token"
});
}
}
}).optional();
export const SealCookieMapSchema = z.record(
z.string().regex(HTTP_TOKEN_PATTERN, "Invalid cookie name"),
z.string().refine((value) => !/[\u0000-\u001f\u007f;]/.test(value), {
message: "Cookie value cannot contain control characters or semicolons"
})
).optional();
export const SealEndpointSchema = z.object({
url: z.string().url().optional(),
tenantSlug: z.string().optional(),
// Extra headers/cookies for Seal deployments reachable only through an
// upstream gateway that expects its own session cookie.
headers: SealHeaderMapSchema,
cookies: SealCookieMapSchema,
endpoints: z.object({
approvalStylePreferences: z.string().default("api/v1/agent/ai-approval/config")
}).default({
@@ -97,6 +126,7 @@ export const GlobalLintConfigSchema = z.object({
export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(false),
defaultCorpId: z.string().min(1).optional(),
testEnterprisesDir: z.string().min(1).optional(),
lint: GlobalLintConfigSchema
});
+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 {
+33
View File
@@ -0,0 +1,33 @@
import { afterEach, describe, expect, test } from "bun:test";
import { createSealClientForUrl } from "./factory.js";
const servers: Array<ReturnType<typeof Bun.serve>> = [];
afterEach(() => {
for (const server of servers.splice(0)) server.stop(true);
});
describe("Seal HTTP client errors", () => {
test("includes ky's parsed response body after the response stream is consumed", async () => {
const server = Bun.serve({
port: 0,
fetch: () => new Response(JSON.stringify({
error: {
code: "error:common:invalid-parameter",
message: "contentType 取值非法"
}
}), {
status: 400,
headers: { "content-type": "application/json" }
})
});
servers.push(server);
await expect(
createSealClientForUrl(`http://127.0.0.1:${server.port}`, "dummy-token").get("/")
).rejects.toThrow(
'Request failed with status code 400 Bad Request: GET http://127.0.0.1:' +
`${server.port}/: {"error":{"code":"error:common:invalid-parameter","message":"contentType 取值非法"}}`
);
});
});
+37 -25
View File
@@ -1,6 +1,33 @@
import ky, { HTTPError, KyInstance } from "ky";
import { CorpConfig } from "../config/types.js";
import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js";
import { resolveSealCustomHeaders } from "./request-headers.js";
function formatErrorData(data: unknown): string {
if (data === undefined || data === null || data === "") return "";
if (typeof data === "string") return data;
try {
return JSON.stringify(data);
} catch {
return String(data);
}
}
function withResponseBody(error: unknown): Error {
if (!(error instanceof HTTPError)) return error as Error;
const body = formatErrorData(error.data);
if (body) error.message = `${error.message}: ${body}`;
return error;
}
function createBeforeErrorHook(corpId?: string) {
return async ({ error }: { error: unknown }) => {
if (corpId && error instanceof HTTPError && error.response.status === 401) {
clearSealToken(corpId);
}
return withResponseBody(error);
};
}
export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
const session = await getSealSessionForCorp(corp);
@@ -9,22 +36,11 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
prefix: session.enterprise.sealUrl,
timeout: 30000,
headers: {
...resolveSealCustomHeaders(corp.seal),
Authorization: `Bearer ${session.token}`
},
hooks: {
beforeError: [
async ({ error }) => {
if (error instanceof HTTPError && error.response.status === 401) {
clearSealToken(corp.id);
}
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
beforeError: [createBeforeErrorHook(corp.id)]
}
});
}
@@ -32,27 +48,23 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
const session = await getSealSessionForCorp(corp);
return createSealClientForUrl(session.enterprise.sealUrl, token);
return createSealClientForUrl(session.enterprise.sealUrl, token, resolveSealCustomHeaders(corp.seal));
}
export function createSealClientForUrl(sealUrl: string, token: string): KyInstance {
export function createSealClientForUrl(
sealUrl: string,
token: string,
customHeaders: Record<string, string> = {}
): KyInstance {
return ky.create({
prefix: sealUrl.replace(/\/+$/, ""),
timeout: 30000,
headers: {
...customHeaders,
Authorization: `Bearer ${token}`
},
hooks: {
beforeError: [
async ({ error }) => {
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
beforeError: [createBeforeErrorHook()]
}
});
}
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, test } from "bun:test";
import { createSealClientForUrl } from "./factory.js";
import { formatCookieHeader, resolveSealCustomHeaders } from "./request-headers.js";
describe("formatCookieHeader", () => {
test("returns undefined when there are no cookies", () => {
expect(formatCookieHeader(undefined)).toBeUndefined();
expect(formatCookieHeader({})).toBeUndefined();
});
test("joins cookies with a semicolon and a space", () => {
expect(formatCookieHeader({ a: "1", b: "2" })).toBe("a=1; b=2");
});
});
describe("resolveSealCustomHeaders", () => {
test("returns an empty map when no custom headers are configured", () => {
expect(resolveSealCustomHeaders(undefined)).toEqual({});
});
test("keeps configured headers and renders cookies", () => {
expect(resolveSealCustomHeaders({
headers: { "X-Tenant": "acme" },
cookies: { sdp_session: "token" }
})).toEqual({
"X-Tenant": "acme",
Cookie: "sdp_session=token"
});
});
test("lets configured cookies replace a raw Cookie header", () => {
expect(resolveSealCustomHeaders({
headers: { Cookie: "stale=1" },
cookies: { fresh: "2" }
})).toEqual({ Cookie: "fresh=2" });
});
});
describe("createSealClientForUrl", () => {
test("sends custom headers and keeps the session Authorization", async () => {
const originalFetch = globalThis.fetch;
let sent: Headers | undefined;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = input instanceof Request ? input : new Request(input, init);
sent = new Headers(request.headers);
return new Response(JSON.stringify({ data: {} }), {
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
try {
const client = createSealClientForUrl("https://corp-a.sealai.cc", "session-token", {
Cookie: "sdp_session=token",
Authorization: "Bearer stale"
});
await client.get("api/v1/auth/me");
} finally {
globalThis.fetch = originalFetch;
}
expect(sent?.get("cookie")).toBe("sdp_session=token");
expect(sent?.get("authorization")).toBe("Bearer session-token");
});
});
+20
View File
@@ -0,0 +1,20 @@
import type { CorpConfig } from "../config/types.js";
// The subset of the Seal endpoint config that carries extra request headers.
export type SealCustomHeaderSource = Pick<CorpConfig["seal"], "headers" | "cookies">;
// Renders configured cookies into one Cookie header, joined with "; ".
export function formatCookieHeader(cookies: Record<string, string> | undefined): string | undefined {
const pairs = Object.entries(cookies ?? {}).map(([name, value]) => `${name}=${value}`);
return pairs.length ? pairs.join("; ") : undefined;
}
// Extra tenant headers from corp config. A rendered Cookie header replaces a
// same-named entry, while Authorization is always left to the caller so the
// session bearer token can never be silently replaced by config.
export function resolveSealCustomHeaders(seal: SealCustomHeaderSource | undefined): Record<string, string> {
const headers: Record<string, string> = { ...(seal?.headers ?? {}) };
const cookieHeader = formatCookieHeader(seal?.cookies);
if (cookieHeader) headers.Cookie = cookieHeader;
return headers;
}
+196 -1
View File
@@ -6,6 +6,18 @@ import {
filterWebhookIntegrations,
findWebhookIntegration,
listWebhookIntegrations,
previewAddWebhookIntegration,
previewDeleteWebhookIntegration,
previewUpdateWebhookIntegration,
getDepartment,
getContactsLastSyncTime,
getInsightStats,
listExpenses,
listInvoices,
listFeishuSimulationApprovalDefinitions,
listDepartmentChildren,
listDepartmentUsers,
listRootDepartments,
searchUsers,
updateWebhookIntegration
} from "./api.js";
@@ -35,6 +47,150 @@ describe("Seal contact API", () => {
expect(requestedParams).toEqual({ query: "欧阳楠楠" });
expect(result.users).toEqual([{ _id: "user-1", name: "欧阳楠楠", departmentIds: [], permissions: [] }]);
});
test("reads the department tree, department users, and last sync time", async () => {
const requestedUrls: string[] = [];
const client = {
get: (url: string) => {
requestedUrls.push(url);
const data = url.endsWith("last-sync-time")
? { lastSyncTime: "2026-06-23T08:14:40.000Z" }
: url.endsWith("/users")
? { items: [{ _id: "user-1", name: "测试用户" }] }
: url.endsWith("/children") || url.endsWith("root/children")
? { items: [{ _id: "department-2", name: "财务" }] }
: { _id: "department-1", name: "公司", parentId: null };
return { json: async () => ({ data }) };
}
} as unknown as KyInstance;
await expect(listRootDepartments(client)).resolves.toMatchObject({
items: [{ _id: "department-2", name: "财务" }]
});
await expect(getDepartment(client, "department-1")).resolves.toMatchObject({
_id: "department-1",
name: "公司"
});
await expect(listDepartmentChildren(client, "department-1")).resolves.toMatchObject({
items: [{ _id: "department-2" }]
});
await expect(listDepartmentUsers(client, "department-1")).resolves.toMatchObject({
items: [{ _id: "user-1", name: "测试用户" }]
});
await expect(getContactsLastSyncTime(client)).resolves.toEqual({
lastSyncTime: "2026-06-23T08:14:40.000Z"
});
expect(requestedUrls).toEqual([
"api/v1/contacts/departments/root/children",
"api/v1/contacts/departments/department-1",
"api/v1/contacts/departments/department-1/children",
"api/v1/contacts/departments/department-1/users",
"api/v1/contacts/last-sync-time"
]);
});
test("forwards the insight stats date range and limit", async () => {
let requestedUrl = "";
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
return {
json: async () => ({
data: { tagStats: [], totalRisks: 2, analyzedRisks: 1, pendingRisks: 1 }
})
};
}
} as unknown as KyInstance;
await expect(getInsightStats(client, {
startDate: "2026-09-01T00:00:00+08:00",
endDate: "2026-09-30T23:59:59+08:00",
limit: 10
})).resolves.toEqual({
tagStats: [],
totalRisks: 2,
analyzedRisks: 1,
pendingRisks: 1
});
expect(requestedUrl).toBe(
"api/v1/insight/stats?startDate=2026-09-01T00%3A00%3A00%2B08%3A00&endDate=2026-09-30T23%3A59%3A59%2B08%3A00&limit=10"
);
});
test("defaults insight stats to the current calendar month", async () => {
let requestedUrl = "";
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
return { json: async () => ({ data: {} }) };
}
} as unknown as KyInstance;
await getInsightStats(client);
const parsed = new URL(`https://seal.test/${requestedUrl}`);
const now = new Date();
expect(parsed.searchParams.get("startDate")).toBe(
new Date(now.getFullYear(), now.getMonth(), 1).toISOString()
);
expect(parsed.searchParams.get("endDate")).toBe(
new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999).toISOString()
);
});
test("uses the frontend filter parameter names for expenses and invoices", async () => {
const requestedUrls: string[] = [];
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrls.push(`${url}?${options?.searchParams?.toString() ?? ""}`);
return {
json: async () => ({
data: url.includes("expenses")
? { expenses: [], total: 0 }
: { invoices: [], total: 0, feishuApprovalAppId: null }
})
};
}
} as unknown as KyInstance;
await expect(listExpenses(client, {
startDate: "1757520000000",
endDate: "1789142399999",
search: "zz-probe-no-match",
offset: 0,
limit: 50
})).resolves.toEqual({ expenses: [], total: 0 });
await expect(listInvoices(client, {
startDate: "2026-08-31T16:00:00.000Z",
endDate: "2026-09-30T15:59:59.999Z",
search: "zz-probe-no-match",
offset: 0,
limit: 50
})).resolves.toEqual({ invoices: [], total: 0, feishuApprovalAppId: null });
expect(requestedUrls).toEqual([
"api/v1/expenses/list?filter%5BstartDate%5D=1757520000000&filter%5BendDate%5D=1789142399999&filter%5Bsearch%5D=zz-probe-no-match&offset=0&limit=50",
"api/v1/invoice/list?filter%5BstartDate%5D=2026-08-31T16%3A00%3A00.000Z&filter%5BendDate%5D=2026-09-30T15%3A59%3A59.999Z&filter%5Bsearch%5D=zz-probe-no-match&offset=0&limit=50"
]);
});
test("lists Feishu simulation approval definitions", async () => {
let requestedUrl = "";
const client = {
get: (url: string) => {
requestedUrl = url;
return {
json: async () => ({ data: [{ code: "travel", name: "差旅报销" }] })
};
}
} as unknown as KyInstance;
await expect(listFeishuSimulationApprovalDefinitions(client)).resolves.toEqual([
{ code: "travel", name: "差旅报销" }
]);
expect(requestedUrl).toBe("api/v1/integrations/feishu/simulation/approval-definitions");
});
});
describe("Seal Webhook API", () => {
@@ -112,10 +268,20 @@ describe("Seal Webhook API", () => {
const updated = await updateWebhookIntegration(client, "integration-1", {
name: "Renamed webhook",
rotateSecret: true
rotateSecret: true,
materialPackFilePolicy: {
minFileSizeBytes: 1000,
maxFileSizeBytes: 2000,
allowedExtensions: ["PDF", "xlsx"]
}
});
expect(updated.name).toBe("Renamed webhook");
expect(updated.secret).not.toBe("webhook-secret");
expect(updated.materialPackFilePolicy).toEqual({
minFileSizeBytes: 1000,
maxFileSizeBytes: 2000,
allowedExtensions: [".pdf", ".xlsx"]
});
expect((posted?.integrations as Array<Record<string, unknown>>)[1]).toMatchObject({ type: "hosecloud" });
const found = findWebhookIntegration([updated], "Renamed webhook");
@@ -126,6 +292,35 @@ describe("Seal Webhook API", () => {
expect(deleted.id).toBe("integration-1");
expect((posted?.integrations as Array<Record<string, unknown>>)).toHaveLength(1);
});
test("previews Webhook mutations without sending a write request", async () => {
const writes: string[] = [];
const client = {
get: () => ({
json: async () => ({ data: webhookConfig() })
}),
post: (url: string) => {
writes.push(`post:${url}`);
throw new Error("preview must not write");
},
patch: (url: string) => {
writes.push(`patch:${url}`);
throw new Error("preview must not write");
}
} as unknown as KyInstance;
const added = await previewAddWebhookIntegration(client, "https://seal.test", {
name: "Preview webhook",
outgoingResultWebhook: "https://callback.test/preview"
});
const updated = await previewUpdateWebhookIntegration(client, "integration-1", { name: "Preview rename" });
const deleted = await previewDeleteWebhookIntegration(client, "integration-1");
expect(added.integration?.name).toBe("Preview webhook");
expect(updated.integration?.name).toBe("Preview rename");
expect(deleted.after.integrations).toHaveLength(1);
expect(writes).toEqual([]);
});
});
function webhookConfig() {
+252 -15
View File
@@ -1,6 +1,11 @@
import { randomBytes } from "node:crypto";
import ky, { HTTPError, KyInstance } from "ky";
import { z } from "zod";
import {
mergeMaterialPackFilePolicy,
normalizeMaterialPackFilePolicy,
type MaterialPackFilePolicyPatch
} from "./material-pack/policy.js";
import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import {
@@ -36,6 +41,22 @@ import {
SealUserDetailSchema,
SealContactSearchResult,
SealContactSearchResultSchema,
SealDepartment,
SealDepartmentSchema,
SealDepartmentListData,
SealDepartmentListDataSchema,
SealDepartmentUsersData,
SealDepartmentUsersDataSchema,
SealContactsLastSyncTime,
SealContactsLastSyncTimeSchema,
InsightStats,
InsightStatsSchema,
ExpenseListData,
ExpenseListDataSchema,
InvoiceListData,
InvoiceListDataSchema,
SimulationApprovalDefinition,
SimulationApprovalDefinitionSchema,
LlmConfig,
LlmConfigSchema,
LlmProvider,
@@ -259,6 +280,12 @@ export async function updateApprovalStylePreferences(
);
}
export type WebhookMutationPreview = {
before: ApprovalStylePreferences;
after: ApprovalStylePreferences;
integration?: WebhookIntegration;
};
export async function saveApprovalStylePreferences(
client: KyInstance,
params: Record<string, unknown>,
@@ -289,6 +316,7 @@ export async function addWebhookIntegration(
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration> {
@@ -307,6 +335,29 @@ export async function addWebhookIntegration(
return integration;
}
export async function previewAddWebhookIntegration(
client: KyInstance,
baseUrl: string,
params: {
name: string;
mode?: WebhookMode;
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookMutationPreview> {
const before = await getApprovalStylePreferences(client, endpoint);
const existing = parseWebhookIntegrations(before.integrations);
const integration = createWebhookIntegration(baseUrl, existing, params);
return {
before,
after: { ...before, integrations: [...before.integrations, integration] },
integration
};
}
export async function updateWebhookIntegration(
client: KyInstance,
selector: string,
@@ -317,26 +368,14 @@ export async function updateWebhookIntegration(
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration> {
const preferences = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(preferences.integrations);
const entry = findWebhookEntry(entries, selector);
const updated = WebhookIntegrationSchema.parse({
...entry.integration,
...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }),
...(params.mode === undefined ? {} : { mode: params.mode }),
...(params.outgoingResultWebhook === undefined
? {}
: { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }),
...(params.autoApprovalRate === undefined
? {}
: { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }),
...(params.rotateSecret || params.secret !== undefined
? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") }
: {})
});
const updated = buildUpdatedWebhookIntegration(entry.integration, params);
const saved = await saveApprovalStylePreferences(client, {
...preferences,
@@ -352,6 +391,34 @@ export async function updateWebhookIntegration(
return updated;
}
export async function previewUpdateWebhookIntegration(
client: KyInstance,
selector: string,
params: {
name?: string;
mode?: WebhookMode;
outgoingResultWebhook?: string;
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookMutationPreview> {
const before = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(before.integrations);
const entry = findWebhookEntry(entries, selector);
const integration = buildUpdatedWebhookIntegration(entry.integration, params);
return {
before,
after: {
...before,
integrations: before.integrations.map((item, index) => index === entry.index ? integration : item)
},
integration
};
}
export async function deleteWebhookIntegration(
client: KyInstance,
selector: string,
@@ -372,6 +439,24 @@ export async function deleteWebhookIntegration(
return entry.integration;
}
export async function previewDeleteWebhookIntegration(
client: KyInstance,
selector: string,
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookMutationPreview> {
const before = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(before.integrations);
const entry = findWebhookEntry(entries, selector);
return {
before,
after: {
...before,
integrations: before.integrations.filter((_, index) => index !== entry.index)
},
integration: entry.integration
};
}
export function findWebhookIntegration(
integrations: WebhookIntegration[],
selector: string
@@ -445,6 +530,7 @@ function createWebhookIntegration(
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
}
): WebhookIntegration {
const name = requiredText(params.name, "name");
@@ -470,7 +556,44 @@ function createWebhookIntegration(
url: `${root}/api/v1/integrations/webhook/${webhookId}/manual-result`
},
secret: params.secret ? requiredText(params.secret, "secret") : generateWebhookSecret(),
autoApprovalRate
autoApprovalRate,
materialPackFilePolicy: normalizeMaterialPackFilePolicy(params.materialPackFilePolicy)
});
}
function buildUpdatedWebhookIntegration(
integration: WebhookIntegration,
params: {
name?: string;
mode?: WebhookMode;
outgoingResultWebhook?: string;
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
}
): WebhookIntegration {
return WebhookIntegrationSchema.parse({
...integration,
...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }),
...(params.mode === undefined ? {} : { mode: params.mode }),
...(params.outgoingResultWebhook === undefined
? {}
: { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }),
...(params.autoApprovalRate === undefined
? {}
: { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }),
...(params.rotateSecret || params.secret !== undefined
? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") }
: {}),
...(params.materialPackFilePolicy === undefined
? {}
: {
materialPackFilePolicy: mergeMaterialPackFilePolicy(
integration.materialPackFilePolicy,
params.materialPackFilePolicy
)
})
});
}
@@ -819,6 +942,120 @@ export async function searchUsers(
);
}
export async function listRootDepartments(client: KyInstance): Promise<SealDepartmentListData> {
return unwrap(
await client.get("api/v1/contacts/departments/root/children"),
SealDepartmentListDataSchema
);
}
export async function getDepartment(
client: KyInstance,
departmentId: string
): Promise<SealDepartment> {
return unwrap(
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}`),
SealDepartmentSchema
);
}
export async function listDepartmentChildren(
client: KyInstance,
departmentId: string
): Promise<SealDepartmentListData> {
return unwrap(
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}/children`),
SealDepartmentListDataSchema
);
}
export async function listDepartmentUsers(
client: KyInstance,
departmentId: string
): Promise<SealDepartmentUsersData> {
return unwrap(
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}/users`),
SealDepartmentUsersDataSchema
);
}
export async function getContactsLastSyncTime(client: KyInstance): Promise<SealContactsLastSyncTime> {
return unwrap(await client.get("api/v1/contacts/last-sync-time"), SealContactsLastSyncTimeSchema);
}
export async function getInsightStats(
client: KyInstance,
params: { startDate?: string; endDate?: string; limit?: number } = {}
): Promise<InsightStats> {
const defaultRange = currentMonthDateRange();
const searchParams = new URLSearchParams();
setOptional(searchParams, "startDate", params.startDate ?? defaultRange.startDate);
setOptional(searchParams, "endDate", params.endDate ?? defaultRange.endDate);
if (params.limit !== undefined) searchParams.set("limit", String(params.limit));
return unwrap(
await client.get("api/v1/insight/stats", { searchParams }),
InsightStatsSchema
);
}
function currentMonthDateRange(): { startDate: string; endDate: string } {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), 1);
const end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
return {
startDate: start.toISOString(),
endDate: end.toISOString()
};
}
export type DataListParams = {
offset?: number;
limit?: number;
startDate?: string;
endDate?: string;
search?: string;
};
function dataListSearchParams(params: DataListParams): URLSearchParams {
const searchParams = new URLSearchParams();
setOptional(searchParams, "filter[startDate]", params.startDate);
setOptional(searchParams, "filter[endDate]", params.endDate);
setOptional(searchParams, "filter[search]", params.search);
searchParams.set("offset", String(params.offset ?? 0));
searchParams.set("limit", String(params.limit ?? 50));
return searchParams;
}
export async function listExpenses(
client: KyInstance,
params: DataListParams = {}
): Promise<ExpenseListData> {
return unwrap(
await client.get("api/v1/expenses/list", { searchParams: dataListSearchParams(params) }),
ExpenseListDataSchema
);
}
export async function listInvoices(
client: KyInstance,
params: DataListParams = {}
): Promise<InvoiceListData> {
return unwrap(
await client.get("api/v1/invoice/list", { searchParams: dataListSearchParams(params) }),
InvoiceListDataSchema
);
}
export async function listFeishuSimulationApprovalDefinitions(
client: KyInstance
): Promise<SimulationApprovalDefinition[]> {
return unwrap(
await client.get("api/v1/integrations/feishu/simulation/approval-definitions"),
z.array(SimulationApprovalDefinitionSchema)
);
}
export async function deleteLocalUser(
client: KyInstance,
userId: string
@@ -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
};
}
+1 -1
View File
@@ -46,7 +46,7 @@ export function listAvailableLinters(): Array<{ name: string; type: "builtin" |
return list;
}
export function resolveLinterPath(nameOrPath: string): string | undefined {
function resolveLinterPath(nameOrPath: string): string | undefined {
if (!nameOrPath || nameOrPath === "builtin") {
return undefined;
}
+146 -43
View File
@@ -1,51 +1,154 @@
import { pinyin } from "pinyin-pro";
import type { MaterialAttachmentPlan, MaterialDocument, MaterialField } from "./types.js";
import type { ZipEntry } from "./validate.js";
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"
function keyFromLabel(value: string): string {
const label = value.replace(/^\d+[\s.\-_—]*/, "").trim();
const parts = pinyin(label, { toneType: "none", type: "all", nonZh: "consecutive" })
.map((item: any) => item.pinyin ? item.pinyin : String(item.origin).toLowerCase().replace(/[^a-z0-9]+/g, ""))
.filter(Boolean);
return parts.join("") || "attachments";
// ─── 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}` }
})
}
export function buildAttachmentPlans(entries: ZipEntry[], documents: Array<{ document: MaterialDocument; laborNames: string[] }>): MaterialAttachmentPlan[] {
return documents.map(({ document, laborNames }) => {
const plan: MaterialAttachmentPlan = { documentId: document.documentId, categoryFields: [], personAttachments: {} };
for (const entry of entries) {
if (entry.fileName === "信息表.xlsx") continue;
const segments = entry.fileName.split("/");
if (segments[0] !== document.documentId || segments.length < 2) continue;
const add = (list: Array<{ key: string; label: string; entries: any[] }>, label: string) => {
const clean = label.replace(/^\d+[\s.\-_—]*/, "");
const item = list.find((value) => value.label === clean) ?? { key: clean === "附件" ? "attachments" : keyFromLabel(clean), label: clean, entries: [] };
if (!list.includes(item)) list.push(item);
item.entries.push({ fileName: entry.fileName, path: entry.fileName, size: entry.uncompressedSize });
};
if (segments.length === 2) add(plan.categoryFields, "附件");
else if (laborNames.includes(segments[1]!)) {
const list = plan.personAttachments[segments[1]!] ?? (plan.personAttachments[segments[1]!] = []);
add(list, segments.length === 3 ? "附件" : segments[2]!);
} else add(plan.categoryFields, segments[1]!);
// ─── 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 }])
}
}
return plan;
});
}
export function injectAttachmentPlan(document: MaterialDocument, plan: MaterialAttachmentPlan, uploaded: Map<string, unknown[]>): MaterialDocument {
const clone = structuredClone(document);
const lookup = (path: string) => uploaded.get(path) ?? [];
for (const category of plan.categoryFields) {
const value = category.entries.flatMap((entry) => lookup(entry.path));
clone.fields.push({ key: category.key, label: category.label, type: "ATTACHMENT", value });
}
const list = clone.fields.find((item) => item.key === "daoshi_list" && item.type === "LIST");
if (list && Array.isArray(list.value)) {
for (const row of list.value as MaterialField[][]) {
const name = row.find((item) => item.key === "name")?.value;
for (const category of plan.personAttachments[String(name)] ?? []) row.push({ key: category.key, label: category.label, type: "ATTACHMENT", value: category.entries.flatMap((entry) => lookup(entry.path)) });
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})。禁止复用同一路径,若需在不同单据或不同字段使用,请分别放置到独立的附件文件路径。`
)
}
}
return clone;
// 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
}
+2
View File
@@ -1,6 +1,8 @@
export * from "./types.js";
export * from "./policy.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";
@@ -1,29 +1,489 @@
import ExcelJS from "exceljs";
import { describe, expect, test } from "bun:test";
import { previewMaterialPack } from "./service.js";
import { signWebhookPayload } from "./signature.js";
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());
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" }));
});
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");
});
});
.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")
})
})
+158 -57
View File
@@ -1,44 +1,107 @@
import ExcelJS from "exceljs";
import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js";
import ExcelJS from "exceljs"
import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js"
type Parsed = { document: MaterialDocument; laborNames: string[] };
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 };
return { key, label, type, value }
}
function text(key: string, label: string, value: unknown) {
return field(key, label, "TEXT", value == null ? "" : String(value));
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);
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;
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 (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);
const timestamp = Date.parse(value.trim().replace(" ", "T"))
if (Number.isFinite(timestamp)) return Math.floor(timestamp / 1000)
}
return null;
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;
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;
const index = map.get(name)
return index ? row.getCell(index).value : undefined
}
function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialField[] {
@@ -47,53 +110,91 @@ function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialFi
["总金额", "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))];
});
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 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"]];
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 maps = sheets.map(headerMap);
const mainMap = maps[0]!;
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 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 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 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, headerMap(laborSheet!), "姓名") ?? "").trim()).filter(Boolean);
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, document: { type: "document", documentId: id, documentSN: id, startTime: startTimeValue(apply), fields } };
});
return parsed;
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
}
+83
View File
@@ -0,0 +1,83 @@
import { z } from "zod"
export const DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS = [
".pdf",
".xls",
".xlsx",
".csv",
".doc",
".docx",
".ppt",
".pptx",
".txt",
".rtf",
".odt",
".ods",
".odp",
".jpg",
".jpeg",
".png",
".gif",
".bmp",
".webp",
".heic",
".eml",
".msg"
] as const
export const DEFAULT_MATERIAL_PACK_FILE_POLICY = {
minFileSizeBytes: 500,
allowedExtensions: [...DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS]
}
const fileExtensionSchema = z.string().trim().min(1).transform((value) => {
const normalized = value.toLowerCase()
return normalized.startsWith(".") ? normalized : `.${normalized}`
}).refine((value) => /^\.[a-z0-9][a-z0-9+_-]*$/.test(value), {
message: "文件后缀必须是简单扩展名,例如 .pdf 或 xlsx"
})
export const MaterialPackFilePolicySchema = z.object({
minFileSizeBytes: z.number().int().min(0).default(DEFAULT_MATERIAL_PACK_FILE_POLICY.minFileSizeBytes),
maxFileSizeBytes: z.number().int().positive().nullable().optional(),
allowedExtensions: z.array(fileExtensionSchema).min(1).default([...DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS])
.transform((extensions) => [...new Set(extensions)])
}).superRefine((policy, ctx) => {
if (
policy.maxFileSizeBytes !== undefined &&
policy.maxFileSizeBytes !== null &&
policy.maxFileSizeBytes < policy.minFileSizeBytes
) {
ctx.addIssue({
code: "custom",
path: ["maxFileSizeBytes"],
message: "最大文件大小不能小于最小文件大小"
})
}
})
export const MaterialPackFilePolicyPatchSchema = z.object({
minFileSizeBytes: z.number().int().min(0).optional(),
maxFileSizeBytes: z.number().int().positive().nullable().optional(),
allowedExtensions: z.array(fileExtensionSchema).min(1)
.transform((extensions) => [...new Set(extensions)])
}).optional()
export type MaterialPackFilePolicy = z.infer<typeof MaterialPackFilePolicySchema>
export type MaterialPackFilePolicyPatch = Partial<MaterialPackFilePolicy>
export function normalizeMaterialPackFilePolicy(
policy: MaterialPackFilePolicyPatch | undefined = undefined
): MaterialPackFilePolicy {
return MaterialPackFilePolicySchema.parse(policy ?? {})
}
export function mergeMaterialPackFilePolicy(
current: MaterialPackFilePolicy | undefined,
patch: MaterialPackFilePolicyPatch
): MaterialPackFilePolicy {
return normalizeMaterialPackFilePolicy({
...normalizeMaterialPackFilePolicy(current),
...patch
})
}
+156
View File
@@ -0,0 +1,156 @@
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; webhook?: 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;
const materialPackWebhook = options.webhook
? api.findWebhookIntegration(rawWebhooks, options.webhook)
: isSingle
? rawWebhooks[0]
: undefined;
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,
materialPackWebhook?.materialPackFilePolicy
);
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
};
}
+138 -51
View File
@@ -1,71 +1,158 @@
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 type { MaterialPackPreview, MaterialPackPushResult } from "./types.js";
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"
import type { MaterialPackFilePolicyPatch } from "./policy.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]! };
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"));
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"))
}
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);
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}@.../」。`
)
}
}
const parsed = await parseMaterialWorkbook(workbook);
const plans = buildAttachmentPlans(entries, parsed);
const documents = parsed.map((item) => item.document);
return { entries, parsed, plans, documents, fileBuffer };
// 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)
}
export async function previewMaterialPack(fileBuffer: Uint8Array, fileName: string): Promise<MaterialPackPreview> {
const prepared = await prepare(fileBuffer, fileName);
return { warnings: [], documents: prepared.documents, attachmentPlan: prepared.plans };
async function prepare(
fileBuffer: Uint8Array,
fileName: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
let entries: ZipEntry[] = []
let workbook = fileBuffer
if (isZip(fileBuffer, fileName)) {
entries = await readZipEntries(fileBuffer)
validatePackEntries(entries, filePolicy)
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 pushMaterialPack(fileBuffer: Uint8Array, fileName: string, config: { webhookUrl: string; secret: string }): Promise<MaterialPackPushResult> {
const prepared = await prepare(fileBuffer, fileName);
const { baseUrl, webhookId } = webhookInfo(config.webhookUrl);
const results: MaterialPackPushResult["results"] = [];
export async function previewMaterialPack(
fileBuffer: Uint8Array,
fileName: string,
filePolicy?: MaterialPackFilePolicyPatch
): Promise<MaterialPackPreview> {
const prepared = await prepare(fileBuffer, fileName, filePolicy)
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;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
}
): Promise<MaterialPackPushResult> {
const prepared = await prepare(fileBuffer, fileName, config.materialPackFilePolicy)
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[]>();
for (const category of [...plan.categoryFields, ...Object.values(plan.personAttachments).flat()]) {
for (const entry of category.entries) {
const zipEntry = prepared.entries.find((candidate) => candidate.fileName === entry.path);
if (!zipEntry) continue;
const body = new FormData();
const attachment = await extractZipEntry(prepared.fileBuffer, zipEntry);
body.append("files", new File([new Uint8Array(attachment)], entry.fileName));
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(entry.path, json.attachments?.map((value) => value.data) ?? (json.data === undefined ? [] : [json.data]));
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`)
}
}
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(`📤 推送单据: ${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 };
return { warnings: [], results }
}
export function readMaterialPackFile(filePath: string): { fileBuffer: Buffer; fileName: string } {
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\/]/).pop() ?? "material-pack.zip" };
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\\/]/).pop() ?? "material-pack.zip" }
}
+56 -8
View File
@@ -13,16 +13,17 @@ export type MaterialDocument = {
fields: MaterialField[];
};
export type MaterialAttachmentEntry = {
fileName: string;
size: number;
path: string;
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: Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>;
personAttachments: Record<string, Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>>;
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 = {
@@ -38,7 +39,54 @@ export type MaterialPackPushResult = {
export class MaterialPackValidationError extends Error {
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
super(`材料包校验失败:${errors.length} 个错误`);
this.name = "MaterialPackValidationError";
super([`材料包校验失败:${errors.length} 个错误`, ...errors.map((error) => `- ${error}`)].join("\n"))
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,46 @@
import { describe, expect, test } from "bun:test"
import { validatePackEntries, type ZipEntry } from "./validate.js"
function entries(attachment: Partial<ZipEntry> = {}): ZipEntry[] {
return [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{
fileName: "DOC-001/合同/合同.pdf",
uncompressedSize: 500,
compressedSize: 400,
raw: {},
...attachment
}
]
}
describe("material pack attachment file policy", () => {
test("accepts the default 500-byte minimum and common PDF extension", () => {
expect(() => validatePackEntries(entries())).not.toThrow()
})
test("rejects attachments smaller than the configured minimum", () => {
expect(() => validatePackEntries(entries({ uncompressedSize: 499 }))).toThrow(
"附件文件过小"
)
})
test("rejects attachments larger than the configured maximum", () => {
expect(() => validatePackEntries(entries({ uncompressedSize: 1001 }), {
maxFileSizeBytes: 1000
})).toThrow("附件文件过大")
})
test("rejects extensions outside the configured whitelist", () => {
expect(() => validatePackEntries(entries({ fileName: "DOC-001/合同/合同.exe" }), {
allowedExtensions: [".pdf"]
})).toThrow("附件后缀不在白名单中")
})
test("rejects an invalid size range before any upload can start", () => {
expect(() => validatePackEntries(entries(), {
minFileSizeBytes: 1000,
maxFileSizeBytes: 999
})).toThrow("最大文件大小不能小于最小文件大小")
})
})
+51 -10
View File
@@ -1,6 +1,11 @@
import yauzl from "yauzl";
import iconv from "iconv-lite";
import { MaterialPackValidationError } from "./types.js";
import {
normalizeMaterialPackFilePolicy,
type MaterialPackFilePolicy,
type MaterialPackFilePolicyPatch
} from "./policy.js";
export const MATERIAL_PACK_LIMITS = { maxEntries: 1000, maxTotalSize: 500 * 1024 * 1024, maxCompressionRatio: 150 };
@@ -8,7 +13,7 @@ export type ZipEntry = { fileName: string; uncompressedSize: number; compressedS
export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
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();
@@ -26,29 +31,32 @@ export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
}
function decodeZipEntryName(entry: any): string {
if (entry.fileNameUTF8 || (entry.generalPurposeBitFlag & 0x800)) return entry.fileNameUTF8 ?? entry.fileName;
const raw = Buffer.from(String(entry.fileName), "binary");
const raw: Buffer = Buffer.isBuffer(entry.fileName)
? entry.fileName
: Buffer.from(String(entry.fileName), "binary");
const utf8 = raw.toString("utf8");
if (utf8.includes("\uFFFD") || /[\u0080-\u00FF]/.test(utf8)) {
const gbk = iconv.decode(raw, "gbk");
if (!gbk.includes("\uFFFD")) return gbk;
}
if (!utf8.includes("\uFFFD")) return utf8;
const gbk = iconv.decode(raw, "gbk");
if (!gbk.includes("\uFFFD")) return gbk;
return utf8;
}
export function isJunk(name: string): boolean {
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 {
export function validatePackEntries(entries: ZipEntry[], policy?: MaterialPackFilePolicyPatch): void {
const errors: string[] = [];
const filePolicy = normalizeMaterialPackFilePolicy(policy);
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}`);
if (entry.fileName === "信息表.xlsx") continue;
validateAttachmentFile(entry, filePolicy, errors);
}
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
if (!info) errors.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");
@@ -56,9 +64,42 @@ export function validatePackEntries(entries: ZipEntry[]): void {
if (errors.length) throw new MaterialPackValidationError(errors);
}
function validateAttachmentFile(
entry: ZipEntry,
policy: MaterialPackFilePolicy,
errors: string[]
): void {
const extension = getFileExtension(entry.fileName);
if (!extension || !policy.allowedExtensions.includes(extension)) {
errors.push(
`附件后缀不在白名单中: ${entry.fileName}(允许: ${policy.allowedExtensions.join(", ")})`
);
}
if (entry.uncompressedSize < policy.minFileSizeBytes) {
errors.push(
`附件文件过小: ${entry.fileName}(${entry.uncompressedSize} B,小于最小值 ${policy.minFileSizeBytes} B)`
);
}
if (
policy.maxFileSizeBytes !== undefined &&
policy.maxFileSizeBytes !== null &&
entry.uncompressedSize > policy.maxFileSizeBytes
) {
errors.push(
`附件文件过大: ${entry.fileName}(${entry.uncompressedSize} B,大于最大值 ${policy.maxFileSizeBytes} B)`
);
}
}
function getFileExtension(fileName: string): string {
const baseName = fileName.split("/").pop() ?? fileName;
const dotIndex = baseName.lastIndexOf(".");
return dotIndex > 0 ? baseName.slice(dotIndex).toLowerCase() : "";
}
export function extractZipEntry(buffer: Uint8Array, target: ZipEntry): Promise<Buffer> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
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) => {
+33 -2
View File
@@ -501,7 +501,12 @@ describe("simulation tool handlers", () => {
sourceSystem: "hosecloud"
});
expect(postedBody).not.toHaveProperty("limit");
expect(result).toMatchObject({ batchId: "batch-1", created: true });
expect(result).toMatchObject({
batchId: "batch-1",
created: true,
noWait: true,
asyncTicket: "batch-1"
});
});
test("create tool surface exposes mode, flowIds, and rawParams", () => {
@@ -509,18 +514,44 @@ describe("simulation tool handlers", () => {
const { z } = require("zod") as typeof import("zod");
const schema = z.toJSONSchema(tool!.parameters) as { properties?: Record<string, unknown> };
expect(Object.keys(schema.properties ?? {})).toEqual(
expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds"])
expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds", "noWait"])
);
});
test("includes the simulation management tool set", () => {
expect(sealTools.find((item) => item.name === "seal_simulation_batches_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_status")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_templates_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_integrations_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_material_package_upload")).toBeDefined();
});
test("status tool performs one non-blocking check and exposes the next action", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_status");
expect(tool).toBeDefined();
const client = {
get: (url: string) => {
expect(url).toBe("api/v1/simulation/batch/batch-1");
return { json: async () => ({ data: { ...hosecloudBatchFixture, id: "batch-1" } }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, { batchId: "batch-1" }, fakeContext()) as Record<string, unknown>;
expect(result).toMatchObject({
batchId: "batch-1",
status: "SYNCING",
terminal: false,
next: {
status: "seal-use simulation status batch-1",
wait: "seal-use simulation wait batch-1"
}
});
});
});
describe("simulation response schemas", () => {
+142 -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 { buildRulePushPlan, findSealTool, sealTools } from "./tools.js";
type ToolHandler = (
client: KyInstance,
@@ -84,6 +84,27 @@ describe("sealTools", () => {
expect(userDelegationTool).toBeDefined();
});
test("includes read-only contacts directory tools", () => {
expect(sealTools.find((item) => item.name === "seal_contacts_departments_root_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_department_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_department_children_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_department_users_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_last_sync_time_get")).toBeDefined();
});
test("includes the read-only insight stats tool", () => {
expect(sealTools.find((item) => item.name === "seal_insight_stats_get")).toBeDefined();
});
test("includes read-only financial data tools", () => {
expect(sealTools.find((item) => item.name === "seal_expenses_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_invoices_list")).toBeDefined();
});
test("includes the Feishu simulation approval definition tool", () => {
expect(sealTools.find((item) => item.name === "seal_simulation_feishu_approval_definitions_list")).toBeDefined();
});
test("includes system configuration tools", () => {
expect(sealTools.find((item) => item.name === "seal_llm_config_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_llm_providers_list")).toBeDefined();
@@ -223,6 +244,124 @@ describe("sealTools", () => {
expect(await countFakeRules(client)).toBe(0);
});
test("preference dry run reads config without patching it", async () => {
const tool = sealTools.find((item) => item.name === "seal_preference_decision_update");
expect(tool).toBeDefined();
let patched = false;
const client = {
get: () => ({
json: async () => ({
data: {
decisionPreferences: {
explicitApprove: "old",
explicitReject: "reject",
exemptApprove: "exempt",
review: "review"
},
integrations: []
}
})
}),
patch: () => {
patched = true;
throw new Error("preview must not patch");
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, { explicitApprove: "new", dryRun: true }, fakeContext()) as {
preview: boolean;
targetUrl: string;
changesDiff: { after: { decisionPreferences: { explicitApprove: string } } };
};
expect(result.preview).toBe(true);
expect(result.targetUrl).toBe("https://seal.test/api/v1/agent/ai-approval/config");
expect(result.changesDiff.after.decisionPreferences.explicitApprove).toBe("new");
expect(patched).toBe(false);
});
test("plans incremental rule updates without rebuilding matched rules", () => {
const plan = buildRulePushPlan(
[
{
id: "rule-1",
code: 1,
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
},
{
id: "rule-2",
code: 2,
description: "Keep attendee names",
scope: "meal",
strictness: "SHOULD_FOLLOW"
}
],
[
{
id: "rule-1",
description: "Keep complete receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
},
{
description: "Require cost center",
scope: "all",
strictness: "SUGGESTION"
}
]
);
expect(plan.updated).toMatchObject([
{ id: "rule-1", changedFields: ["description"] }
]);
expect(plan.created).toMatchObject([
{ description: "Require cost center" }
]);
expect(plan.deleted).toMatchObject([{ id: "rule-2", code: 2 }]);
expect(plan.unchanged).toEqual([]);
});
test("matches legacy local rules by unique content when no id is present", () => {
const plan = buildRulePushPlan(
[{
id: "rule-1",
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}],
[{
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}]
);
expect(plan.created).toEqual([]);
expect(plan.updated).toEqual([]);
expect(plan.deleted).toEqual([]);
expect(plan.unchanged).toEqual([{ id: "rule-1" }]);
});
test("rejects local rule ids that are absent from the current draft", () => {
expect(() => buildRulePushPlan(
[{
id: "rule-1",
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}],
[{
id: "stale-rule",
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}]
)).toThrow("stale-rule");
});
test("includes approval run Langfuse bridge tools", () => {
expect(sealTools.find((item) => item.name === "seal_approval_runs_search")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_approval_runs_summary")).toBeDefined();
@@ -230,51 +369,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_webhook_material_pack",
"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 () => {
+455 -362
View File
File diff suppressed because it is too large. Load diff
+62 -1
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { DEFAULT_MATERIAL_PACK_FILE_POLICY, MaterialPackFilePolicySchema } from "./material-pack/policy.js";
export const HosecloudStaffSchema = z.object({
staffId: z.string(),
@@ -181,7 +182,8 @@ export const WebhookIntegrationSchema = z.object({
outgoingResultWebhook: z.string().url(),
incomingManualResultWebhook: WebhookEndpointSchema,
secret: z.string().min(1),
autoApprovalRate: z.number().int().min(0).max(100).optional()
autoApprovalRate: z.number().int().min(0).max(100).optional(),
materialPackFilePolicy: MaterialPackFilePolicySchema.default(DEFAULT_MATERIAL_PACK_FILE_POLICY)
}).passthrough();
export const ApprovalStylePreferencesSchema = z.object({
@@ -286,6 +288,56 @@ export const SealContactSearchResultSchema = z.object({
users: z.array(SealUserDetailSchema).default([])
}).passthrough();
export const SealDepartmentSchema = z.object({
_id: z.string(),
tenantId: z.string().optional(),
name: z.string().optional(),
parentId: z.string().nullable().optional(),
ancestors: z.array(z.string()).default([]),
provider: z.string().optional(),
permissions: z.array(z.string()).default([]),
isDeleted: z.boolean().optional(),
syncedAt: z.string().optional(),
createdAt: z.string().optional(),
updatedAt: z.string().optional()
}).passthrough();
export const SealDepartmentListDataSchema = z.object({
items: z.array(SealDepartmentSchema).default([])
}).passthrough();
export const SealDepartmentUsersDataSchema = z.object({
items: z.array(SealUserDetailSchema).default([])
}).passthrough();
export const SealContactsLastSyncTimeSchema = z.object({
lastSyncTime: z.union([z.string(), z.number(), z.null()])
}).passthrough();
export const InsightTagStatsSchema = z.record(z.string(), z.unknown());
export const InsightStatsSchema = z.object({
tagStats: z.array(InsightTagStatsSchema).default([]),
totalRisks: z.number().default(0),
analyzedRisks: z.number().default(0),
pendingRisks: z.number().default(0)
}).passthrough();
const DataRecordSchema = z.record(z.string(), z.unknown());
export const ExpenseListDataSchema = z.object({
expenses: z.array(DataRecordSchema).default([]),
total: z.number().optional()
}).passthrough();
export const InvoiceListDataSchema = z.object({
invoices: z.array(DataRecordSchema).default([]),
total: z.number().optional(),
feishuApprovalAppId: z.string().nullable().optional()
}).passthrough();
export const SimulationApprovalDefinitionSchema = z.record(z.string(), z.unknown());
export const LlmConfigSchema = z.object({
provider: z.string(),
config: z.record(z.string(), z.unknown()).default({})
@@ -486,6 +538,7 @@ export const ThinkingDepthPreferenceSchema = z.object({
}).passthrough();
export const HosecloudConfigInputSchema = z.object({
dryRun: z.boolean().optional(),
signKey: z.string().min(1).optional(),
outboundName: z.string().optional(),
specificationId: z.string().optional(),
@@ -536,6 +589,14 @@ export type SealUserCreateResult = z.infer<typeof SealUserCreateResultSchema>;
export type SealUserResetPasswordResult = z.infer<typeof SealUserResetPasswordResultSchema>;
export type SealUserDetail = z.infer<typeof SealUserDetailSchema>;
export type SealContactSearchResult = z.infer<typeof SealContactSearchResultSchema>;
export type SealDepartment = z.infer<typeof SealDepartmentSchema>;
export type SealDepartmentListData = z.infer<typeof SealDepartmentListDataSchema>;
export type SealDepartmentUsersData = z.infer<typeof SealDepartmentUsersDataSchema>;
export type SealContactsLastSyncTime = z.infer<typeof SealContactsLastSyncTimeSchema>;
export type InsightStats = z.infer<typeof InsightStatsSchema>;
export type ExpenseListData = z.infer<typeof ExpenseListDataSchema>;
export type InvoiceListData = z.infer<typeof InvoiceListDataSchema>;
export type SimulationApprovalDefinition = z.infer<typeof SimulationApprovalDefinitionSchema>;
export type LlmConfig = z.infer<typeof LlmConfigSchema>;
export type LlmProvider = z.infer<typeof LlmProviderSchema>;
export type AvailablePermissionsData = z.infer<typeof AvailablePermissionsDataSchema>;
+1 -1
View File
@@ -124,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;
+4 -2
View File
@@ -7,6 +7,7 @@ import {
ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
import { runCli } from "./cli/runner.js";
import { classifyCliError } from "./cli/errors.js";
import { VERSION } from "./version.js";
const serverEntryFile = fileURLToPath(import.meta.url);
@@ -69,7 +70,7 @@ export function createServer(options: { enableCli?: boolean } = {}) {
stdout: "",
stderr: "seal_cli requires a non-empty command string",
isError: true,
exitCode: 1
exitCode: 2
});
}
@@ -89,11 +90,12 @@ export function createServer(options: { enableCli?: boolean } = {}) {
}
}));
} catch (error) {
const classification = classifyCliError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: 1
exitCode: classification.exitCode
});
}
});