Compare commits

...
34 Commits
Author SHA1 Message Date
yunyingk a03731671e Merge pull request #107 from yunyingk/codex/release-v0.10.23
🧪 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.23: Hose flow alignment, targeted SN export, and minute timestamp suffix
2026-09-15 10:42:11 +08:00
gitea 564566032d Release v0.10.23: Hose flow alignment, targeted SN export, and minute timestamp suffix 2026-09-15 10:40:55 +08:00
yunyingk 5a95fa2bd5 Merge pull request #106 from yunyingk/codex/hose-flow-alignment
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add Hose flow alignment, targeted SN export, and minute timestamp suffix
2026-09-15 10:40:01 +08:00
gitea 9e85305098 Update CLI help, skill documentation, and next-step stderr guidance 2026-09-15 10:38:54 +08:00
gitea a7c7ecb0c7 Add target SN export filter and minute timestamp suffix 2026-09-15 10:36:31 +08:00
gitea 643676afd9 Add distinctive emojis for special actions in Hose human opinions 2026-09-15 10:28:24 +08:00
gitea e3c7f93dd9 Preserve strict flow sequence numbers when hoisting mid-flow modifications 2026-09-15 10:22:13 +08:00
gitea a91f4b5f25 Refine Hose flow alignment for rejection targets and mid-flow modifications 2026-09-15 10:19:20 +08:00
gitea f493d5911b Refine subsequent human event filtering to use effectiveRunTime 2026-09-15 09:50:41 +08:00
gitea cfc6ff3b88 Anchor AI runs to Hose flow via exact nodeId with 60s queue delay fallback 2026-09-15 09:48:26 +08:00
gitea 8264865aec Fix isLatestRun cross-period blindspot: detect subsequent ebot/AI runs in Hose history 2026-09-15 09:37:51 +08:00
gitea 577ad0415c Fix time-windowed rejection scoping, revert synthetic mapping on system fields, and make E columns strictly opt-in via --with-flow 2026-09-15 09:23:06 +08:00
gitea de79e9735b Make --with-flow opt-in: E人工行为/E人工意见 columns require explicit --with-flow flag 2026-09-14 18:28:38 +08:00
gitea 870975b5f7 Use 提交人(xxx): 单据撤回 prefix for retract events (no Hose nodeName) 2026-09-14 18:18:25 +08:00
gitea 047c877c1f Fix retracted run status and eliminate synthetic node leakage 2026-09-14 18:11:21 +08:00
gitea 86ac075c48 Refine flow alignment with native Hose states, numbering, and prefix 2026-09-14 17:55:52 +08:00
gitea 2d4b0b1d36 Translate freeflow.back and refine payment and CC actions 2026-09-14 17:42:09 +08:00
gitea 6c351b34df Prioritize reject event and Seal rejection over post-AI mutation 2026-09-14 17:39:06 +08:00
gitea 6c6b3034a0 Support paid flow states, freeflow pay actions, and clean pending nodes 2026-09-14 17:34:35 +08:00
gitea d5f68ea2f3 Map EXEMPT_APPROVE to 备注通过 and ERROR to 错误 in AI decision column 2026-09-14 17:27:05 +08:00
gitea 1a2c41c70c Fix flow alignment for retracted runs and add cancel cell styling 2026-09-14 17:24:27 +08:00
gitea b9ea04adc6 Add Hose approval flow alignment for approval runs export
- Add Hose flow domain with OpenAPI & CloseAPI timeline and staff opinion parsing
- Add E人工行为 and E人工意见 columns in approval runs Excel export
- Add pre-flight scale/duration warning and smooth concurrency throttling (default concurrency 3, batch delay 150ms)
- Add seal-use approval-runs flow diagnostic CLI command and tool
- Support --to-downloads and --flow-concurrency CLI flags
2026-09-14 17:20:19 +08:00
yunyingk 19c04df1bb Merge pull request #105 from yunyingk/codex/release-v0.10.22
🧪 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.22: Webhook resource pack export and HLab rule linter
2026-09-14 11:48:14 +08:00
gitea 3082919d76 Release v0.10.22: Webhook resource pack export and HLab rule linter 2026-09-14 11:47:10 +08:00
yunyingk 4238018f3c Merge pull request #104 from yunyingk/codex/webhook-resource-pack-export
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add Webhook resource pack export and rename dataset to resource-pack
2026-09-14 11:19:36 +08:00
gitea e54bf6f2a4 Add Webhook resource pack export and rename dataset to resource-pack
- Clarify dataset naming as Webhook 资源包 (CLI: resource-pack, alias: pack), distinguishing from backend native simulation material pack while retaining material-pack as backward-compatible alias
- Implement exportApprovalRunsToResourcePack for exporting online approval runs and attachments into local resource pack ZIP
- Support seal-use webhook resource-pack export with record filters, docId prefix/suffix, and destination options
- Refine bidirectional directory validation to allow documents without attachments
- Update CLI runner, help definitions, and skill references
- Add comprehensive export, preview, and CLI command unit tests
2026-09-14 11:18:23 +08:00
yunyingk 9afd169b50 Merge pull request #103 from yunyingk/codex/add-hlab-rule-linter
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add official HLab structured rule linter
2026-09-14 11:03:48 +08:00
gitea 8e06b7035c Add official HLab structured rule linter
- Implement hlabRuleLinter enforcing HLab SOP structure, ternary decision closure, disposal action decoupling, and false-skip prevention
- Register hlab.ts template in official templates for automatic plaintext sync
- Support hlab and aliases (hlab-sop, hlab-rules, hlab-standard) in linter loader
- Document HLab linter and detection rules in skill references
- Add comprehensive unit tests in linter.test.ts
2026-09-14 11:02:38 +08:00
yunyingk 38968f2373 Merge pull request #102 from yunyingk/codex/release-v0.10.21
🧪 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.21: Standardized export date range, 180-day safety limit, and count time filters
2026-09-14 10:18:15 +08:00
gitea db79d5bc6a Release v0.10.21: Standardized export date range, 180-day safety limit, and count time filters 2026-09-14 10:17:09 +08:00
yunyingk 2a7ccd267c Merge pull request #101 from yunyingk/codex/export-filename-date-range-safety-and-defaults
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Standardize export date range, defaults, and 180-day safety limit
2026-09-14 10:14:56 +08:00
gitea a39ad09278 Standardize export date range, defaults, and 180-day safety limit 2026-09-14 10:13:19 +08:00
yunyingk c5aa1c9958 Merge pull request #100 from yunyingk/codex/fix-issue-99-approval-runs-export-and-count
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Fix export filename date tag and add time range to approval-runs count
2026-09-14 10:02:30 +08:00
gitea c7433db265 Fix export filename date tag and add time range to approval-runs count 2026-09-14 10:01:20 +08:00
52 changed files with 7335 additions and 409 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.20",
"version": "0.10.23",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+52
View File
@@ -7,6 +7,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.10.23] - 2026-09-15
### Added & Enhanced
- **Hose Native Approval Flow Alignment (`--with-flow`)**:
- Added opt-in `--with-flow` flag to `seal-use approval-runs export` to enrich reports with **E人工行为** and **E人工意见** columns from native Hose/Ekuaibao approval timelines.
- **Rejection Formatting (样式 2-B 三行展开式)**: Cleanly structures rejections with explicit reject target nodes, staff names with roles, and resubmission routing (`↳ 驳回至: ...` / `↳ 重新提交后由...继续审批`).
- **Mid-Flow Modification Detection**: Identifies mid-flow edits (`已支付 (中途修改)` / `审批通过 (中途修改)`), hoists modification events to top (`✏️: 修改了单据`) for instant fact visibility while strictly preserving genuine approval-flow chronological sequence numbers.
- **Action Emojis**: Visual distinction across approval actions (`✏️` 修改、`🤖` 自动同意、`❌` 驳回、`💰` 支付、`💬` 附言、`↩️` 撤回、`🔀` 转审),while normal approvals maintain a clean text format (`: 同意`).
- **Targeted Document SN Export Filter (`--sn` / `--sns`)**:
- Supported `--sn <SN1,SN2>` or `--sns` option for `seal-use approval-runs export` to filter specific documents by single or comma-separated document SNs.
- Direct indexed lookup via Seal backend `search: sn`, bypassing full pagination scans and reducing export runtimes from 30+ seconds to ~1.5 seconds.
- Smart time windowing: searches across full history without artificial 1-day truncation when start/end dates are omitted, and dynamically computes filename date interval from retrieved records.
- **Strict Clean Export Filenames with Forced Minute Timestamp**:
- Enforced a standard format `${safeCorpName}_审核记录_${dateTag}_${countTag}_${YYYYMMDD_HHmm}.xlsx`.
- Filename timestamp suffix accurate to the minute prevents accidental overwrites and ambiguity.
- Eradicated document SN numbers from the output filename to maintain a concise, standard pattern regardless of export batch size.
- **CLI Help, Guidance & Diagnostics Channel**:
- Enhanced `seal-use approval-runs export --help` with complete option table.
- Added next-step command suggestions (`👉 查看导出文件: open "..."`) and flow enrichment hints to `stderr`.
- Synchronized `skills/seal-use/SKILL.md` and CLI documentation references.
## [0.10.22] - 2026-09-14
### Added & Enhanced
- **Webhook Resource Pack Export & Dataset Renaming**:
- Formally renamed the Webhook dataset format to **Webhook 资源包** (Webhook Resource Pack, CLI: `resource-pack`, alias: `pack`), cleanly distinguishing it from Seal backend's native simulation material pack while keeping `material-pack` 100% backward-compatible.
- Implemented `exportApprovalRunsToResourcePack` and CLI command `seal-use webhook resource-pack export` to export online approval runs and downloaded attachments into a local standard `.zip` resource pack for offline distribution via third-party channels.
- Refined bidirectional ZIP validation so documents without attachments do not trigger false directory-missing errors.
- **Official HLab Structured Rule Linter (`hlab`)**:
- Implemented the official HLab Rule Linter (`hlab`, aliases: `hlab-sop`, `hlab-rules`, `hlab-standard`) based on industrial Rule-as-SOP standards.
- Enforces check methods (`**检查方法**`), evaluation standards (`**判定标准**`), ternary decision closure (`- PASS`, `- FAIL`, `- 证据不足` with manual review), disposal action decoupling, and false-skip prevention.
- Automatically synchronizes plaintext template to `~/.config/seal-use/linters/official/hlab.ts`.
## [0.10.21] - 2026-09-14
### Added & Enhanced
- **Standardized Export Date Range & Filename Contract**:
- Unified all Excel export filenames (`approval-runs export` and `analytics export`) into a strict closed interval format `${safeCorpName}_..._${startDate}至${endDate}...`.
- Completely eradicated open-ended naming phrases (`至今` and `截至`), guaranteeing 100% deterministic and parseable filenames across the CLI and MCP tools.
- **Smart Date Boundary Defaults & Stderr Notifications**:
- Implemented intuitive interval fallbacks when date boundaries are omitted:
- Omitted both: defaults to yesterday through today (`yesterday至today`).
- Omitted end date: defaults to today (`startDate至today`).
- Omitted start date: defaults to 30 days prior to end date (`endDate - 30d至endDate`).
- Emits explicit interval fallback declarations to `stderr` (`ℹ️ 未指定导出起止时间...`) while keeping `stdout` strictly machine-parseable JSON.
- **180-Day Safety Guardrail & `--force` Flag**:
- Added an automatic 180-day (~6 months) span guardrail for both approval run audit logs and smart insights risk exports.
- Export requests exceeding 180 days are cleanly intercepted with non-zero exit code and diagnostic guidance unless `--force` is explicitly provided.
- Emits a prominent warning to `stderr` when `--force` is applied to massive exports.
- **Approval Runs Count Time Filtering**:
- Extended `seal-use approval-runs count` to support `--start <YYYY-MM-DD|ms>` and `--end <YYYY-MM-DD|ms>` options for bounded quantity counts without requiring full record retrieval.
## [0.10.20] - 2026-09-13
### Added & Enhanced
+80 -14
View File
@@ -5,6 +5,7 @@
"": {
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"archiver": "^8.0.0",
"exceljs": "^4.4.0",
"iconv-lite": "^0.7.3",
"ky": "^2.0.2",
@@ -13,6 +14,7 @@
"zod": "^4.4.3",
},
"devDependencies": {
"@types/archiver": "^8.0.0",
"@types/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
"bun-types": "^1.3.14",
@@ -30,25 +32,43 @@
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"@types/archiver": ["@types/archiver@8.0.0", "", { "dependencies": { "@types/node": "*", "@types/readdir-glob": "*" } }, "sha512-YpXPbEuv9+eUIPPQWUPahj3cvs9isWRuF+J4z+KbdYVDO3rWorWQFxUVHnwPu2AgKwvgpki5F2VMX0Xx+mX45A=="],
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
"@types/readdir-glob": ["@types/readdir-glob@1.1.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg=="],
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
"abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"archiver": ["archiver@5.3.2", "", { "dependencies": { "archiver-utils": "^2.1.0", "async": "^3.2.4", "buffer-crc32": "^0.2.1", "readable-stream": "^3.6.0", "readdir-glob": "^1.1.2", "tar-stream": "^2.2.0", "zip-stream": "^4.1.0" } }, "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw=="],
"archiver": ["archiver@8.0.0", "", { "dependencies": { "async": "^3.2.4", "buffer-crc32": "^1.0.0", "is-stream": "^4.0.0", "lazystream": "^1.0.0", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0", "readdir-glob": "^3.0.0", "tar-stream": "^3.0.0", "zip-stream": "^7.0.2" } }, "sha512-fV1orZfsnPn9BaSByR/qE67rJCLJEy2Ox5bq7nJh+jquWaNh6Sfec75kJ2T6PtdGUbPQlrVoSVCEOa5SdiTQ1g=="],
"archiver-utils": ["archiver-utils@2.1.0", "", { "dependencies": { "glob": "^7.1.4", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^2.0.0" } }, "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw=="],
"async": ["async@3.2.6", "", {}, "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="],
"balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"b4a": ["b4a@1.9.0", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ=="],
"balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"bare-events": ["bare-events@2.9.2", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA=="],
"bare-fs": ["bare-fs@4.8.1", "", { "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", "bare-stream": "^2.6.4", "bare-url": "^2.2.2", "fast-fifo": "^1.3.2" }, "peerDependencies": { "bare-buffer": "*" }, "optionalPeers": ["bare-buffer"] }, "sha512-N1nnXdHZAOSstz0XiHikGS4HGMH4CnSwhqWdGQQMqqdvp4Jybm9sE3R1WVnpWVd4SFkc8ryPDBLViNLwiEqECg=="],
"bare-path": ["bare-path@3.1.2", "", {}, "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw=="],
"bare-stream": ["bare-stream@2.13.4", "", { "dependencies": { "b4a": "^1.8.1", "streamx": "^2.25.0", "teex": "^1.0.1" }, "peerDependencies": { "bare-abort-controller": "*", "bare-buffer": "*", "bare-events": "*" }, "optionalPeers": ["bare-abort-controller", "bare-buffer", "bare-events"] }, "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA=="],
"bare-url": ["bare-url@2.5.4", "", { "dependencies": { "bare-path": "^3.0.0" } }, "sha512-Gxa7UVWBr0/edU1b+TJhn/AZvMQUj9OGspvYsaTYQrAbZA4BOTZGL3LiZxvD+CeMlDH4juwD84+eTAp/bLYW5g=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
@@ -62,11 +82,11 @@
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
"brace-expansion": ["brace-expansion@5.0.9", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="],
"buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="],
"buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"buffer-crc32": ["buffer-crc32@1.0.0", "", {}, "sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w=="],
"buffer-indexof-polyfill": ["buffer-indexof-polyfill@1.0.2", "", {}, "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A=="],
@@ -82,7 +102,7 @@
"chainsaw": ["chainsaw@0.1.0", "", { "dependencies": { "traverse": ">=0.3.0 <0.4" } }, "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ=="],
"compress-commons": ["compress-commons@4.1.2", "", { "dependencies": { "buffer-crc32": "^0.2.13", "crc32-stream": "^4.0.2", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg=="],
"compress-commons": ["compress-commons@7.0.1", "", { "dependencies": { "crc-32": "^1.2.0", "crc32-stream": "^7.0.1", "is-stream": "^4.0.0", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0" } }, "sha512-g0S8KAD8qf4+V//pr3BfB1aBnARLXNz2Gx+jmHU0LEriUuoQUOPOulVquHKTJ8+EAIIO7fhseNDr9wK5Q9FKBQ=="],
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
@@ -100,7 +120,7 @@
"crc-32": ["crc-32@1.2.2", "", { "bin": { "crc32": "bin/crc32.njs" } }, "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ=="],
"crc32-stream": ["crc32-stream@4.0.3", "", { "dependencies": { "crc-32": "^1.2.0", "readable-stream": "^3.4.0" } }, "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw=="],
"crc32-stream": ["crc32-stream@7.0.1", "", { "dependencies": { "crc-32": "^1.2.0", "readable-stream": "^4.0.0" } }, "sha512-IBWsY8xznyQrcHn8h4bC8/4ErNke5elzgG8GcqF4RFPw6aHkWWRc7Tgw6upjaTX/CT/yQgqYENkxYsTYN+hW2g=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
@@ -130,6 +150,12 @@
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="],
"events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],
"events-universal": ["events-universal@1.0.1", "", { "dependencies": { "bare-events": "^2.7.0" } }, "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
@@ -144,6 +170,8 @@
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
"fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
"finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
@@ -194,6 +222,8 @@
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="],
"isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
@@ -250,7 +280,7 @@
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
@@ -284,6 +314,8 @@
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
@@ -294,9 +326,9 @@
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"readable-stream": ["readable-stream@4.7.0", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="],
"readdir-glob": ["readdir-glob@1.1.3", "", { "dependencies": { "minimatch": "^5.1.0" } }, "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA=="],
"readdir-glob": ["readdir-glob@3.0.0", "", { "dependencies": { "minimatch": "^10.2.2" } }, "sha512-AhNB2KgKeVJr16nK9LLZbJNWnYoT23ZrumNKFDebHBdkC8KHSqWo871JAUhoWC/RtjEVdqNMFpM6qrwRbaUqpw=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
@@ -332,9 +364,15 @@
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"streamx": ["streamx@2.28.1", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA=="],
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"tar-stream": ["tar-stream@3.2.1", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-nqsEO8zLZJvrOMdEwkA0QdCLFbetHMn95Zqu4fKwX+hkaTWJPZZOrxx/PwtxoK0MMGQmBQNRW3CPs8IFYQz4cQ=="],
"teex": ["teex@1.0.1", "", { "dependencies": { "streamx": "^2.12.5" } }, "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg=="],
"text-decoder": ["text-decoder@1.2.7", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="],
"tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="],
@@ -368,7 +406,7 @@
"yauzl": ["yauzl@3.4.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw=="],
"zip-stream": ["zip-stream@4.1.1", "", { "dependencies": { "archiver-utils": "^3.0.4", "compress-commons": "^4.1.2", "readable-stream": "^3.6.0" } }, "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ=="],
"zip-stream": ["zip-stream@7.0.5", "", { "dependencies": { "compress-commons": "^7.0.0", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0" } }, "sha512-dSvYKdvLsAHCDqPOhIwk/q5CvuWtTB3Dgpoe0uVEFjTzIOAmsQpprX25InCvrvJsirEbu1OHyy67n/kAj1Sw/w=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
@@ -380,10 +418,18 @@
"archiver-utils/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"bl/buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"bl/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"body-parser/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"duplexer2/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"exceljs/archiver": ["archiver@5.3.2", "", { "dependencies": { "archiver-utils": "^2.1.0", "async": "^3.2.4", "buffer-crc32": "^0.2.1", "readable-stream": "^3.6.0", "readdir-glob": "^1.1.2", "tar-stream": "^2.2.0", "zip-stream": "^4.1.0" } }, "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw=="],
"exceljs/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"glob/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
"jszip/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
@@ -398,12 +444,18 @@
"unzipper/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"zip-stream/archiver-utils": ["archiver-utils@3.0.4", "", { "dependencies": { "glob": "^7.2.3", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw=="],
"archiver-utils/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"duplexer2/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"exceljs/archiver/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"exceljs/archiver/readdir-glob": ["readdir-glob@1.1.3", "", { "dependencies": { "minimatch": "^5.1.0" } }, "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA=="],
"exceljs/archiver/tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"exceljs/archiver/zip-stream": ["zip-stream@4.1.1", "", { "dependencies": { "archiver-utils": "^3.0.4", "compress-commons": "^4.1.2", "readable-stream": "^3.6.0" } }, "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ=="],
"glob/minimatch/brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
"jszip/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
@@ -411,5 +463,19 @@
"lazystream/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"unzipper/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"exceljs/archiver/readdir-glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
"exceljs/archiver/zip-stream/archiver-utils": ["archiver-utils@3.0.4", "", { "dependencies": { "glob": "^7.2.3", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw=="],
"exceljs/archiver/zip-stream/compress-commons": ["compress-commons@4.1.2", "", { "dependencies": { "buffer-crc32": "^0.2.13", "crc32-stream": "^4.0.2", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg=="],
"glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"exceljs/archiver/readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
"exceljs/archiver/zip-stream/compress-commons/crc32-stream": ["crc32-stream@4.0.3", "", { "dependencies": { "crc-32": "^1.2.0", "readable-stream": "^3.4.0" } }, "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw=="],
"exceljs/archiver/readdir-glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
}
}
+468 -206
View File
@@ -1,161 +1,161 @@
import{createRequire as LM0}from"node:module";var QM0=Object.create;var{getPrototypeOf:KM0,defineProperty:OF,getOwnPropertyNames:wM0}=Object;var GM0=Object.prototype.hasOwnProperty;function HM0($){return this[$]}var WM0,VM0,$3=($,I,z)=>{var q=$!=null&&typeof $==="object";if(q){var U=I?WM0??=new WeakMap:VM0??=new WeakMap,Y=U.get($);if(Y)return Y}z=$!=null?QM0(KM0($)):{};let J=I||!$||!$.__esModule?OF(z,"default",{value:$,enumerable:!0}):z;for(let Q of wM0($))if(!GM0.call(J,Q))OF(J,Q,{get:HM0.bind($,Q),enumerable:!0});if(q)U.set($,J);return J};var F=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);var ZM0=($)=>$;function XM0($,I){this[$]=ZM0.bind(null,I)}var A$=($,I)=>{for(var z in I)OF($,z,{get:I[z],enumerable:!0,configurable:!0,set:XM0.bind(I,z)})};var K0=($,I)=>()=>($&&(I=$($=0)),I);var t=LM0(import.meta.url);function r($,I,z){function q(Q,K){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:K,constr:J,traits:new Set},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),I(Q,K);let w=J.prototype,G=Object.keys(w);for(let H=0;H<G.length;H++){let W=G[H];if(!(W in Q))Q[W]=w[W].bind(Q)}}let U=z?.Parent??Object;class Y extends U{}Object.defineProperty(Y,"name",{value:$});function J(Q){var K;let w=z?.Parent?new Y:this;q(w,Q),(K=w._zod).deferred??(K.deferred=[]);for(let G of w._zod.deferred)G();return w}return Object.defineProperty(J,"init",{value:q}),Object.defineProperty(J,Symbol.hasInstance,{value:(Q)=>{if(z?.Parent&&Q instanceof z.Parent)return!0;return Q?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}function E4($){if($)Object.assign(I3,$);return I3}var rf,FF,NF,S8,z3,I3;var q3=K0(()=>{FF=Object.freeze({status:"aborted"});NF=Symbol("zod_brand");S8=class S8 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};z3=class z3 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(rf=globalThis).__zod_globalConfig??(rf.__zod_globalConfig={});I3=globalThis.__zod_globalConfig});var F0={};A$(F0,{unwrapMessage:()=>PY,uint8ArrayToHex:()=>nM0,uint8ArrayToBase64url:()=>fM0,uint8ArrayToBase64:()=>sf,stringifyPrimitive:()=>X0,slugify:()=>PF,shallowClone:()=>EF,safeExtend:()=>hM0,required:()=>uM0,randomString:()=>BM0,propertyKeyTypes:()=>BY,promiseAllObject:()=>EM0,primitiveTypes:()=>BF,prefixIssues:()=>I$,pick:()=>gM0,partial:()=>yM0,parsedType:()=>D0,optionalKeys:()=>jF,omit:()=>_M0,objectClone:()=>AM0,numKeys:()=>jM0,nullish:()=>A9,normalizeParams:()=>P0,mergeDefs:()=>M5,merge:()=>SM0,jsonStringifyReplacer:()=>oI,joinValues:()=>z0,issue:()=>tI,isPlainObject:()=>T9,isObject:()=>U3,hexToUint8Array:()=>bM0,getSizableOrigin:()=>jY,getParsedType:()=>vM0,getLengthableOrigin:()=>vY,getEnumValues:()=>TY,getElementAtPath:()=>TM0,floatSafeRemainder:()=>AF,finalizeIssue:()=>b6,extend:()=>CM0,explicitlyAborted:()=>gF,escapeRegex:()=>c$,esc:()=>bw,defineLazy:()=>U1,createTransparentProxy:()=>RM0,cloneDef:()=>PM0,clone:()=>f6,cleanRegex:()=>EY,cleanEnum:()=>xM0,captureStackTrace:()=>nw,cached:()=>rI,base64urlToUint8Array:()=>kM0,base64ToUint8Array:()=>af,assignProp:()=>P9,assertNotEqual:()=>OM0,assertNever:()=>NM0,assertIs:()=>FM0,assertEqual:()=>DM0,assert:()=>MM0,allowsEval:()=>TF,aborted:()=>E9,NUMBER_FORMAT_RANGES:()=>vF,Class:()=>ef,BIGINT_FORMAT_RANGES:()=>RF});function DM0($){return $}function OM0($){return $}function FM0($){}function NM0($){throw Error("Unexpected value in exhaustive check")}function MM0($){}function TY($){let I=Object.values($).filter((q)=>typeof q==="number");return Object.entries($).filter(([q,U])=>I.indexOf(+q)===-1).map(([q,U])=>U)}function z0($,I="|"){return $.map((z)=>X0(z)).join(I)}function oI($,I){if(typeof I==="bigint")return I.toString();return I}function rI($){return{get value(){{let z=$();return Object.defineProperty(this,"value",{value:z}),z}throw Error("cached value already set")}}}function A9($){return $===null||$===void 0}function EY($){let I=$.startsWith("^")?1:0,z=$.endsWith("$")?$.length-1:$.length;return $.slice(I,z)}function AF($,I){let z=$/I,q=Math.round(z),U=Number.EPSILON*Math.max(Math.abs(z),1);if(Math.abs(z-q)<U)return 0;return z-q}function U1($,I,z){let q=void 0;Object.defineProperty($,I,{get(){if(q===tf)return;if(q===void 0)q=tf,q=z();return q},set(U){Object.defineProperty($,I,{value:U})},configurable:!0})}function AM0($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function P9($,I,z){Object.defineProperty($,I,{value:z,writable:!0,enumerable:!0,configurable:!0})}function M5(...$){let I={};for(let z of $){let q=Object.getOwnPropertyDescriptors(z);Object.assign(I,q)}return Object.defineProperties({},I)}function PM0($){return M5($._zod.def)}function TM0($,I){if(!I)return $;return I.reduce((z,q)=>z?.[q],$)}function EM0($){let I=Object.keys($),z=I.map((q)=>$[q]);return Promise.all(z).then((q)=>{let U={};for(let Y=0;Y<I.length;Y++)U[I[Y]]=q[Y];return U})}function BM0($=10){let z=Line truncated
`)}var $b=($,I)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:I,enumerable:!1}),$.message=JSON.stringify(I,oI,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},RY,z$;var hF=K0(()=>{q3();h0();RY=r("$ZodError",$b),z$=r("$ZodError",$b,{Parent:Error})});var aI=($)=>(I,z,q,U)=>{let Y=q?{...q,async:!1}:{async:!1},J=I._zod.run({value:z,issues:[]},Y);if(J instanceof Promise)throw new S8;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>b6(K,Y,E4())));throw nw(Q,U?.callee),Q}return J.value},CY,sI=($)=>async(I,z,q,U)=>{let Y=q?{...q,async:!0}:{async:!0},J=I._zod.run({value:z,issues:[]},Y);if(J instanceof Promise)J=await J;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>b6(K,Y,E4())));throw nw(Q,U?.callee),Q}return J.value},hY,eI=($)=>(I,z,q)=>{let U=q?{...q,async:!1}:{async:!1},Y=I._zod.run({value:z,issues:[]},U);if(Y instanceof Promise)throw new S8;return Y.issues.length?{success:!1,error:new($??RY)(Y.issues.map((J)=>b6(J,U,E4())))}:{success:!0,data:Y.value}},$z,Iz=($)=>async(I,z,q)=>{let U=q?{...q,async:!0}:{async:!0},Y=I._zod.run({value:z,issues:[]},U);if(Y instanceof Promise)Y=await Y;return Y.issues.length?{success:!1,error:new $(Y.issues.map((J)=>b6(J,U,E4())))}:{success:!0,data:Y.value}},SY,iw=($)=>(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return aI($)(I,z,U)},zb,pw=($)=>(I,z,q)=>{return aI($)(I,z,q)},qb,cw=($)=>async(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return sI($)(I,z,U)},Ub,dw=($)=>async(I,z,q)=>{return sI($)(I,z,q)},Yb,mw=($)=>(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return eI($)(I,z,U)},Jb,lw=($)=>(I,z,q)=>{return eI($)(I,z,q)},Qb,ow=($)=>async(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return Iz($)(I,z,U)},Kb,rw=($)=>async(I,z,q)=>{return Iz($)(I,z,q)},wb;var SF=K0(()=>{q3();hF();h0();CY=aI(z$),hY=sI(z$),$z=eI(z$),SY=Iz(z$),zb=iw(z$),qb=pw(z$),Ub=cw(z$),Yb=dw(z$),Jb=mw(z$),Qb=lw(z$),Kb=ow(z$),wb=rw(z$)});var P$={};A$(P$,{xid:()=>kF,uuid7:()=>mM0,uuid6:()=>dM0,uuid4:()=>cM0,uuid:()=>Y3,uppercase:()=>wN,unicodeEmail:()=>Gb,undefined:()=>QN,ulid:()=>xF,time:()=>$N,string:()=>zN,sha512_hex:()=>VA0,sha512_base64url:()=>XA0,sha512_base64:()=>ZA0,sha384_hex:()=>GA0,sha384_base64url:()=>WA0,sha384_base64:()=>HA0,sha256_hex:()=>QA0,sha256_base64url:()=>wA0,sha256_base64:()=>KA0,sha1_hex:()=>UA0,sha1_base64url:()=>JA0,sha1_base64:()=>YA0,rfc5322Email:()=>oM0,number:()=>yY,null:()=>JN,nanoid:()=>bF,md5_hex:()=>IA0,md5_base64url:()=>qA0,md5_base64:()=>zA0,mac:()=>lF,lowercase:()=>KN,ksuid:()=>fF,ipv6:()=>mF,ipv4:()=>dF,integer:()=>UN,idnEmail:()=>rM0,httpProtocol:()=>aF,html5Email:()=>lM0,hostname:()=>sM0,hex:()=>$A0,guid:()=>iF,extendedDuration:()=>pM0,emoji:()=>cF,email:()=>pF,e164:()=>sF,duration:()=>nF,domain:()=>eM0,datetime:()=>IN,date:()=>eF,cuid2:()=>uF,cuid:()=>yF,cidrv6:()=>rF,cidrv4:()=>oF,browserEmail:()=>tM0,boolean:()=>YN,bigint:()=>qN,base64url:()=>tw,base64:()=>tF});function cF(){return new RegExp(aM0,"u")}function Wb($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function $N($){return new RegExp(`^${Wb($)}$`)}function IN($){let I=Wb({precision:$.precision}),z=["Z"];if($.local)z.push("");if($.offset)z.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let q=`${I}(?:${z.join("|")})`;return new RegExp(`^${Hb}T(?:${q})$`)}function uY($,I){return new RegExp(`^[A-Za-z0-9+/]{${$}}${I}$`)}function xY($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var yF,uF,xF,kF,fF,bF,nF,pM0,iF,Y3=($)=>{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})$`)},cM0,dM0,mM0,pF,lM0,oM0,Gb,rM0,tM0,aM0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",dF,mF,lF=($)=>{let I=c$($??":");return new RegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},oF,rF,tF,tw,sM0,eM0,aF,sF,Hb="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",eF,zN=($)=>{let I=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${I}$`)},qN,UN,yY,YN,JN,QN,KN,wN,$A0,IA0,zA0,qA0,UA0,YA0,JA0,QA0,KA0,wA0,GA0,HA0,WA0,VA0,ZA0,XA0;var aw=K0(()=>{h0();yF=/^[cC][0-9a-z]{6,}$/,uF=/^[0-9a-z]+$/,xF=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,kF=/^[0-9a-vA-V]{20}$/,fF=/^[A-Za-z0-9]{27}$/,bF=/^[a-zA-Z0-9_-]{21}$/,nF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\dLine truncated
`).filter((Y)=>Y),q=Math.min(...z.map((Y)=>Y.length-Y.trimStart().length)),U=z.map((Y)=>Y.slice(q)).map((Y)=>" ".repeat(this.indent*2)+Y);for(let Y of U)this.content.push(Y)}compile(){let $=Function,I=this?.args,q=[...(this?.content??[""]).map((U)=>` ${U}`)];return new $(...I,q.join(`
`))}}var vN;var RN=K0(()=>{vN={major:4,minor:4,patch:3}});function aN($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function gb($){if(!tw.test($))return!1;let I=$.replace(/[-_]/g,(q)=>q==="-"?"+":"/"),z=I.padEnd(Math.ceil(I.length/4)*4,"=");return aN(z)}function _b($,I=null){try{let z=$.split(".");if(z.length!==3)return!1;let[q]=z;if(!q)return!1;let U=JSON.parse(atob(q));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if(I&&(!("alg"in U)||U.alg!==I))return!1;return!0}catch{return!1}}function Lb($,I,z){if($.issues.length)I.issues.push(...I$(z,$.issues));I.value[z]=$.value}function YG($,I,z,q,U,Y){let J=z in q;if($.issues.length){if(U&&Y&&!J)return;I.issues.push(...I$(z,$.issues))}if(!J&&!U){if(!$.issues.length)I.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[z]});return}if($.value===void 0){if(J)I.value[z]=void 0}else I.value[z]=$.value}function Cb($){let I=Object.keys($.shape);for(let q of I)if(!$.shape?.[q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${q}": expected a Zod schema`);let z=jF($.shape);return{...$,keys:I,keySet:new Set(I),numKeys:I.length,optionalKeys:new Set(z)}}function hb($,I,z,q,U,Y){let J=[],Q=U.keySet,K=U.catchall._zod,w=K.def.type,G=K.optin==="optional",H=K.optout==="optional";for(let W in I){if(W==="__proto__")continue;if(Q.has(W))continue;if(w==="never"){J.push(W);continue}let V=K.run({value:I[W],issues:[]},q);if(V instanceof Promise)$.push(V.then((X)=>YG(X,z,W,I,G,H)));else YG(V,z,W,I,G,H)}if(J.length)z.issues.push({code:"unrecognized_keys",keys:J,input:I,inst:Y});if(!$.length)return z;return Promise.all($).then(()=>{return z})}function Db($,I,z,q){for(let Y of $)if(Y.issues.length===0)return I.value=Y.value,I;let U=$.filter((Y)=>!E9(Y));if(U.length===1)return I.value=U[0].value,U[0];return I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:$.map((Y)=>Y.issues.map((J)=>b6(J,q,E4())))}),I}function Ob($,I,z,q){let U=$.filter((Y)=>Y.issues.length===0);if(U.length===1)return I.value=U[0].value,I;if(U.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:$.map((Y)=>Y.issues.map((J)=>b6(J,q,E4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:[],inclusive:!1});return I}function gN($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(T9($)&&T9(I)){let z=Object.keys(I),q=Object.keys($).filter((Y)=>z.indexOf(Y)!==-1),U={...$,...I};for(let Y of q){let J=gN($[Y],I[Y]);if(!J.valid)return{valid:!1,mergeErrorPath:[Y,...J.mergeErrorPath]};U[Y]=J.data}return{valid:!0,data:U}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let z=[];for(let q=0;q<$.length;q++){let U=$[q],Y=I[q],J=gN(U,Y);if(!J.valid)return{valid:!1,mergeErrorPath:[q,...J.mergeErrorPath]};z.push(J.data)}return{valid:!0,data:z}}return{valid:!1,mergeErrorPath:[]}}function Fb($,I,z){let q=new Map,U;for(let Q of I.issues)if(Q.code==="unrecognized_keys"){U??(U=Q);for(let K of Q.keys){if(!q.has(K))q.set(K,{});q.get(K).l=!0}}else $.issues.push(Q);for(let Q of z.issues)if(Q.code==="unrecognized_keys")for(let K of Q.keys){if(!q.has(K))q.set(K,{});q.get(K).r=!0}else $.issues.push(Q);let Y=[...q].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(Y.length&&U)$.issues.push({...U,keys:Y});if(E9($))return $;let J=gN(I.value,z.value);if(!J.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function Nb($,I){for(let z=$.length-1;z>=0;z--)if($[z]._zod[I]!=="optional")return z+1;return 0}function Mb($,I,z){if($.issues.length)I.issues.push(...I$(z,$.issues));I.value[z]=$.value}function Ab($,I,z,q,U){for(let Y=0;Y<z.length;Y++){let J=$[Y],Q=Y<q.length;if(J.issues.length){if(!Q&&Y>=U){I.value.length=Y;break}I.issues.push(...I$(Y,J.issues))}I.value[Y]=J.value}for(let Y=I.value.length-1;Y>=q.length;Y--)if(z[Y]._zod.optout==="optional"&&I.value[Y]===void 0)I.value.length=Y;else break;return I}function Pb($,I,z,q,U,Y,J){if($.issues.length)if(BY.has(typeof q))z.issues.push(...I$(q,$.issues));else z.issues.push({code:"invalid_key",origin:"map",input:U,inst:Y,issues:$.issues.map((Q)=>b6(Q,J,E4()))});if(I.issues.length)if(BY.has(typeof q))z.issues.push(...I$(q,I.issues));else z.issues.push({origin:"map",code:"invalid_element",input:U,inst:Y,key:q,issues:I.issues.map((Q)=>b6(Q,J,E4()))});z.value.set($.value,I.value)}function Tb($,I){if($.issues.length)I.issues.push(...$.issues);I.value.add($.value)}function Eb($,I){if(I===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Bb($,I){if($.value===void 0)$.value=I.defaultValue;return $}function jb($,I){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:I});return $}function zG($,I,z){if($.issues.length)return $.aborted=!0,$;return I._zod.run({value:$.value,issues:$.issues,f Line truncated
if (${M}.issues.length) {
if (${v} in input) {
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
import{createRequire as sS0}from"node:module";var iS0=Object.create;var{getPrototypeOf:nS0,defineProperty:NP,getOwnPropertyNames:cS0}=Object;var pS0=Object.prototype.hasOwnProperty;function dS0($){return this[$]}var mS0,lS0,S4=($,q,Y)=>{var z=$!=null&&typeof $==="object";if(z){var U=q?mS0??=new WeakMap:lS0??=new WeakMap,I=U.get($);if(I)return I}Y=$!=null?iS0(nS0($)):{};let J=q||!$||!$.__esModule?NP(Y,"default",{value:$,enumerable:!0}):Y;for(let Q of cS0($))if(!pS0.call(J,Q))NP(J,Q,{get:dS0.bind($,Q),enumerable:!0});if(z)U.set($,J);return J};var M=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);var oS0=($)=>$;function rS0($,q){this[$]=oS0.bind(null,q)}var $$=($,q)=>{for(var Y in q)NP($,Y,{get:q[Y],enumerable:!0,configurable:!0,set:rS0.bind(q,Y)})};var e=($,q)=>()=>($&&(q=$($=0)),q);var m=sS0(import.meta.url);function a($,q,Y){function z(Q,K){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:K,constr:J,traits:new Set},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),q(Q,K);let H=J.prototype,G=Object.keys(H);for(let Z=0;Z<G.length;Z++){let V=G[Z];if(!(V in Q))Q[V]=H[V].bind(Q)}}let U=Y?.Parent??Object;class I extends U{}Object.defineProperty(I,"name",{value:$});function J(Q){var K;let H=Y?.Parent?new I:this;z(H,Q),(K=H._zod).deferred??(K.deferred=[]);for(let G of H._zod.deferred)G();return H}return Object.defineProperty(J,"init",{value:z}),Object.defineProperty(J,Symbol.hasInstance,{value:(Q)=>{if(Y?.Parent&&Q instanceof Y.Parent)return!0;return Q?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}function m4($){if($)Object.assign(V2,$);return V2}var _m,DP,AP,B5,w2,V2;var L2=e(()=>{DP=Object.freeze({status:"aborted"});AP=Symbol("zod_brand");B5=class B5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};w2=class w2 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(_m=globalThis).__zod_globalConfig??(_m.__zod_globalConfig={});V2=globalThis.__zod_globalConfig});var A0={};$$(A0,{unwrapMessage:()=>kJ,uint8ArrayToHex:()=>Dy0,uint8ArrayToBase64url:()=>My0,uint8ArrayToBase64:()=>vm,stringifyPrimitive:()=>O0,slugify:()=>TP,shallowClone:()=>jP,safeExtend:()=>Xy0,required:()=>Ly0,randomString:()=>Jy0,propertyKeyTypes:()=>bJ,promiseAllObject:()=>Iy0,primitiveTypes:()=>_P,prefixIssues:()=>h8,pick:()=>Gy0,partial:()=>wy0,parsedType:()=>N0,optionalKeys:()=>CP,omit:()=>Zy0,objectClone:()=>Yy0,numKeys:()=>Qy0,nullish:()=>P3,normalizeParams:()=>B0,mergeDefs:()=>F9,merge:()=>Vy0,jsonStringifyReplacer:()=>RY,joinValues:()=>I0,issue:()=>hY,isPlainObject:()=>T3,isObject:()=>F2,hexToUint8Array:()=>Ny0,getSizableOrigin:()=>iJ,getParsedType:()=>Ky0,getLengthableOrigin:()=>nJ,getEnumValues:()=>uJ,getElementAtPath:()=>Uy0,floatSafeRemainder:()=>BP,finalizeIssue:()=>w8,extend:()=>Wy0,explicitlyAborted:()=>hP,escapeRegex:()=>O$,esc:()=>xW,defineLazy:()=>H1,createTransparentProxy:()=>Hy0,cloneDef:()=>zy0,clone:()=>V8,cleanRegex:()=>fJ,cleanEnum:()=>Fy0,captureStackTrace:()=>kW,cached:()=>vY,base64urlToUint8Array:()=>Oy0,base64ToUint8Array:()=>Rm,assignProp:()=>B3,assertNotEqual:()=>aS0,assertNever:()=>$y0,assertIs:()=>eS0,assertEqual:()=>tS0,assert:()=>qy0,allowsEval:()=>EP,aborted:()=>E3,NUMBER_FORMAT_RANGES:()=>RP,Class:()=>hm,BIGINT_FORMAT_RANGES:()=>vP});function tS0($){return $}function aS0($){return $}function eS0($){}function $y0($){throw Error("Unexpected value in exhaustive check")}function qy0($){}function uJ($){let q=Object.values($).filter((z)=>typeof z==="number");return Object.entries($).filter(([z,U])=>q.indexOf(+z)===-1).map(([z,U])=>U)}function I0($,q="|"){return $.map((Y)=>O0(Y)).join(q)}function RY($,q){if(typeof q==="bigint")return q.toString();return q}function vY($){return{get value(){{let Y=$();return Object.defineProperty(this,"value",{value:Y}),Y}throw Error("cached value already set")}}}function P3($){return $===null||$===void 0}function fJ($){let q=$.startsWith("^")?1:0,Y=$.endsWith("$")?$.length-1:$.length;return $.slice(q,Y)}function BP($,q){let Y=$/q,z=Math.round(Y),U=Number.EPSILON*Math.max(Math.abs(Y),1);if(Math.abs(Y-z)<U)return 0;return Y-z}function H1($,q,Y){let z=void 0;Object.defineProperty($,q,{get(){if(z===Cm)return;if(z===void 0)z=Cm,z=Y();return z},set(U){Object.defineProperty($,q,{value:U})},configurable:!0})}function Yy0($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function B3($,q,Y){Object.defineProperty($,q,{value:Y,writable:!0,enumerable:!0,configurable:!0})}function F9(...$){let q={};for(let Y of $){let z=Object.getOwnPropertyDescriptors(Y);Object.assign(q,z)}return Object.defineProperties({},q)}function zy0($){return F9($._zod.def)}function Uy0($,q){if(!q)return $;return q.reduce((Y,z)=>Y?.[z],$)}function Iy0($){let q=Object.keys($),Y=q.map((z)=>$[z]);return Promise.all(Y).then((z)=>{let U={};for(let I=0;I<q.length;I++)U[q[I]]=z[I];return U})}function Jy0($=10){let Y=""Line truncated
`)}var gm=($,q)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:q,enumerable:!1}),$.message=JSON.stringify(q,RY,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},cJ,g8;var yP=e(()=>{L2();y0();cJ=a("$ZodError",gm),g8=a("$ZodError",gm,{Parent:Error})});var gY=($)=>(q,Y,z,U)=>{let I=z?{...z,async:!1}:{async:!1},J=q._zod.run({value:Y,issues:[]},I);if(J instanceof Promise)throw new B5;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>w8(K,I,m4())));throw kW(Q,U?.callee),Q}return J.value},mJ,SY=($)=>async(q,Y,z,U)=>{let I=z?{...z,async:!0}:{async:!0},J=q._zod.run({value:Y,issues:[]},I);if(J instanceof Promise)J=await J;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>w8(K,I,m4())));throw kW(Q,U?.callee),Q}return J.value},lJ,yY=($)=>(q,Y,z)=>{let U=z?{...z,async:!1}:{async:!1},I=q._zod.run({value:Y,issues:[]},U);if(I instanceof Promise)throw new B5;return I.issues.length?{success:!1,error:new($??cJ)(I.issues.map((J)=>w8(J,U,m4())))}:{success:!0,data:I.value}},xY,kY=($)=>async(q,Y,z)=>{let U=z?{...z,async:!0}:{async:!0},I=q._zod.run({value:Y,issues:[]},U);if(I instanceof Promise)I=await I;return I.issues.length?{success:!1,error:new $(I.issues.map((J)=>w8(J,U,m4())))}:{success:!0,data:I.value}},oJ,uW=($)=>(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return gY($)(q,Y,U)},ym,fW=($)=>(q,Y,z)=>{return gY($)(q,Y,z)},xm,bW=($)=>async(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return SY($)(q,Y,U)},km,iW=($)=>async(q,Y,z)=>{return SY($)(q,Y,z)},um,nW=($)=>(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return yY($)(q,Y,U)},fm,cW=($)=>(q,Y,z)=>{return yY($)(q,Y,z)},bm,pW=($)=>async(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return kY($)(q,Y,U)},im,dW=($)=>async(q,Y,z)=>{return kY($)(q,Y,z)},nm;var xP=e(()=>{L2();yP();y0();mJ=gY(g8),lJ=SY(g8),xY=yY(g8),oJ=kY(g8),ym=uW(g8),xm=fW(g8),km=bW(g8),um=iW(g8),fm=nW(g8),bm=cW(g8),im=pW(g8),nm=dW(g8)});var q$={};$$(q$,{xid:()=>bP,uuid7:()=>Ey0,uuid6:()=>Ty0,uuid4:()=>By0,uuid:()=>O2,uppercase:()=>ZB,unicodeEmail:()=>cm,undefined:()=>HB,ulid:()=>fP,time:()=>YB,string:()=>UB,sha512_hex:()=>ly0,sha512_base64url:()=>ry0,sha512_base64:()=>oy0,sha384_hex:()=>py0,sha384_base64url:()=>my0,sha384_base64:()=>dy0,sha256_hex:()=>iy0,sha256_base64url:()=>cy0,sha256_base64:()=>ny0,sha1_hex:()=>uy0,sha1_base64url:()=>by0,sha1_base64:()=>fy0,rfc5322Email:()=>_y0,number:()=>rJ,null:()=>KB,nanoid:()=>nP,md5_hex:()=>yy0,md5_base64url:()=>ky0,md5_base64:()=>xy0,mac:()=>rP,lowercase:()=>GB,ksuid:()=>iP,ipv6:()=>oP,ipv4:()=>lP,integer:()=>JB,idnEmail:()=>Cy0,httpProtocol:()=>eP,html5Email:()=>jy0,hostname:()=>hy0,hex:()=>Sy0,guid:()=>pP,extendedDuration:()=>Py0,emoji:()=>mP,email:()=>dP,e164:()=>$B,duration:()=>cP,domain:()=>gy0,datetime:()=>zB,date:()=>qB,cuid2:()=>uP,cuid:()=>kP,cidrv6:()=>tP,cidrv4:()=>sP,browserEmail:()=>Ry0,boolean:()=>QB,bigint:()=>IB,base64url:()=>mW,base64:()=>aP});function mP(){return new RegExp(vy0,"u")}function dm($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function YB($){return new RegExp(`^${dm($)}$`)}function zB($){let q=dm({precision:$.precision}),Y=["Z"];if($.local)Y.push("");if($.offset)Y.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${q}(?:${Y.join("|")})`;return new RegExp(`^${pm}T(?:${z})$`)}function sJ($,q){return new RegExp(`^[A-Za-z0-9+/]{${$}}${q}$`)}function tJ($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var kP,uP,fP,bP,iP,nP,cP,Py0,pP,O2=($)=>{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})$`)},By0,Ty0,Ey0,dP,jy0,_y0,cm,Cy0,Ry0,vy0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lP,oP,rP=($)=>{let q=O$($??":");return new RegExp(`^(?:[0-9A-F]{2}${q}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${q}){5}[0-9a-f]{2}$`)},sP,tP,aP,mW,hy0,gy0,eP,$B,pm="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",qB,UB=($)=>{let q=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${q}$`)},IB,JB,rJ,QB,KB,HB,GB,ZB,Sy0,yy0,xy0,ky0,uy0,fy0,by0,iy0,ny0,cy0,py0,dy0,my0,ly0,oy0,ry0;var lW=e(()=>{y0();kP=/^[cC][0-9a-z]{6,}$/,uP=/^[0-9a-z]+$/,fP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bP=/^[0-9a-vA-V]{20}$/,iP=/^[A-Za-z0-9]{27}$/,nP=/^[a-zA-Z0-9_-]{21}$/,cP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?Line truncated
`).filter((I)=>I),z=Math.min(...Y.map((I)=>I.length-I.trimStart().length)),U=Y.map((I)=>I.slice(z)).map((I)=>" ".repeat(this.indent*2)+I);for(let I of U)this.content.push(I)}compile(){let $=Function,q=this?.args,z=[...(this?.content??[""]).map((U)=>` ${U}`)];return new $(...q,z.join(`
`))}}var RB;var vB=e(()=>{RB={major:4,minor:4,patch:3}});function eB($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Hl($){if(!mW.test($))return!1;let q=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),Y=q.padEnd(Math.ceil(q.length/4)*4,"=");return eB(Y)}function Gl($,q=null){try{let Y=$.split(".");if(Y.length!==3)return!1;let[z]=Y;if(!z)return!1;let U=JSON.parse(atob(z));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if(q&&(!("alg"in U)||U.alg!==q))return!1;return!0}catch{return!1}}function rm($,q,Y){if($.issues.length)q.issues.push(...h8(Y,$.issues));q.value[Y]=$.value}function qX($,q,Y,z,U,I){let J=Y in z;if($.issues.length){if(U&&I&&!J)return;q.issues.push(...h8(Y,$.issues))}if(!J&&!U){if(!$.issues.length)q.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[Y]});return}if($.value===void 0){if(J)q.value[Y]=void 0}else q.value[Y]=$.value}function Zl($){let q=Object.keys($.shape);for(let z of q)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${z}": expected a Zod schema`);let Y=CP($.shape);return{...$,keys:q,keySet:new Set(q),numKeys:q.length,optionalKeys:new Set(Y)}}function Wl($,q,Y,z,U,I){let J=[],Q=U.keySet,K=U.catchall._zod,H=K.def.type,G=K.optin==="optional",Z=K.optout==="optional";for(let V in q){if(V==="__proto__")continue;if(Q.has(V))continue;if(H==="never"){J.push(V);continue}let X=K.run({value:q[V],issues:[]},z);if(X instanceof Promise)$.push(X.then((w)=>qX(w,Y,V,q,G,Z)));else qX(X,Y,V,q,G,Z)}if(J.length)Y.issues.push({code:"unrecognized_keys",keys:J,input:q,inst:I});if(!$.length)return Y;return Promise.all($).then(()=>{return Y})}function sm($,q,Y,z){for(let I of $)if(I.issues.length===0)return q.value=I.value,q;let U=$.filter((I)=>!E3(I));if(U.length===1)return q.value=U[0].value,U[0];return q.issues.push({code:"invalid_union",input:q.value,inst:Y,errors:$.map((I)=>I.issues.map((J)=>w8(J,z,m4())))}),q}function tm($,q,Y,z){let U=$.filter((I)=>I.issues.length===0);if(U.length===1)return q.value=U[0].value,q;if(U.length===0)q.issues.push({code:"invalid_union",input:q.value,inst:Y,errors:$.map((I)=>I.issues.map((J)=>w8(J,z,m4())))});else q.issues.push({code:"invalid_union",input:q.value,inst:Y,errors:[],inclusive:!1});return q}function hB($,q){if($===q)return{valid:!0,data:$};if($ instanceof Date&&q instanceof Date&&+$===+q)return{valid:!0,data:$};if(T3($)&&T3(q)){let Y=Object.keys(q),z=Object.keys($).filter((I)=>Y.indexOf(I)!==-1),U={...$,...q};for(let I of z){let J=hB($[I],q[I]);if(!J.valid)return{valid:!1,mergeErrorPath:[I,...J.mergeErrorPath]};U[I]=J.data}return{valid:!0,data:U}}if(Array.isArray($)&&Array.isArray(q)){if($.length!==q.length)return{valid:!1,mergeErrorPath:[]};let Y=[];for(let z=0;z<$.length;z++){let U=$[z],I=q[z],J=hB(U,I);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};Y.push(J.data)}return{valid:!0,data:Y}}return{valid:!1,mergeErrorPath:[]}}function am($,q,Y){let z=new Map,U;for(let Q of q.issues)if(Q.code==="unrecognized_keys"){U??(U=Q);for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).l=!0}}else $.issues.push(Q);for(let Q of Y.issues)if(Q.code==="unrecognized_keys")for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).r=!0}else $.issues.push(Q);let I=[...z].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(I.length&&U)$.issues.push({...U,keys:I});if(E3($))return $;let J=hB(q.value,Y.value);if(!J.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function em($,q){for(let Y=$.length-1;Y>=0;Y--)if($[Y]._zod[q]!=="optional")return Y+1;return 0}function $l($,q,Y){if($.issues.length)q.issues.push(...h8(Y,$.issues));q.value[Y]=$.value}function ql($,q,Y,z,U){for(let I=0;I<Y.length;I++){let J=$[I],Q=I<z.length;if(J.issues.length){if(!Q&&I>=U){q.value.length=I;break}q.issues.push(...h8(I,J.issues))}q.value[I]=J.value}for(let I=q.value.length-1;I>=z.length;I--)if(Y[I]._zod.optout==="optional"&&q.value[I]===void 0)q.value.length=I;else break;return q}function Yl($,q,Y,z,U,I,J){if($.issues.length)if(bJ.has(typeof z))Y.issues.push(...h8(z,$.issues));else Y.issues.push({code:"invalid_key",origin:"map",input:U,inst:I,issues:$.issues.map((Q)=>w8(Q,J,m4()))});if(q.issues.length)if(bJ.has(typeof z))Y.issues.push(...h8(z,q.issues));else Y.issues.push({origin:"map",code:"invalid_element",input:U,inst:I,key:z,issues:q.issues.map((Q)=>w8(Q,J,m4()))});Y.value.set($.value,q.value)}function zl($,q){if($.issues.length)q.issues.push(...$.issues);q.value.add($.value)}function Ul($,q){if(q===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Il($,q){if($.value===void 0)$.value=q.defaultValue;return $}function Jl($,q){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:q});return $}function aW($,q,Y){if($.issues.length)return $.aborted=!0,$;return q._zod.run({value:$.value,issues:$.issues,fa Line truncated
if (${P}.issues.length) {
if (${T} in input) {
payload.issues = payload.issues.concat(${P}.issues.map(iss => ({
...iss,
path: iss.path ? [${v}, ...iss.path] : [${v}]
path: iss.path ? [${T}, ...iss.path] : [${T}]
})));
}
}
if (${M}.value === undefined) {
if (${v} in input) {
newResult[${v}] = undefined;
if (${P}.value === undefined) {
if (${T} in input) {
newResult[${T}] = undefined;
}
} else {
newResult[${v}] = ${M}.value;
newResult[${T}] = ${P}.value;
}
`);else if(!h)V.write(`
const ${M}_present = ${v} in input;
if (${M}.issues.length) {
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
`);else if(!v)X.write(`
const ${P}_present = ${T} in input;
if (${P}.issues.length) {
payload.issues = payload.issues.concat(${P}.issues.map(iss => ({
...iss,
path: iss.path ? [${v}, ...iss.path] : [${v}]
path: iss.path ? [${T}, ...iss.path] : [${T}]
})));
}
if (!${M}_present && !${M}.issues.length) {
if (!${P}_present && !${P}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${v}]
path: [${T}]
});
}
if (${M}_present) {
if (${M}.value === undefined) {
newResult[${v}] = undefined;
if (${P}_present) {
if (${P}.value === undefined) {
newResult[${T}] = undefined;
} else {
newResult[${v}] = ${M}.value;
newResult[${T}] = ${P}.value;
}
}
`);else V.write(`
if (${M}.issues.length) {
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
`);else X.write(`
if (${P}.issues.length) {
payload.issues = payload.issues.concat(${P}.issues.map(iss => ({
...iss,
path: iss.path ? [${v}, ...iss.path] : [${v}]
path: iss.path ? [${T}, ...iss.path] : [${T}]
})));
}
if (${M}.value === undefined) {
if (${v} in input) {
newResult[${v}] = undefined;
if (${P}.value === undefined) {
if (${T} in input) {
newResult[${T}] = undefined;
}
} else {
newResult[${v}] = ${M}.value;
newResult[${T}] = ${P}.value;
}
`)}V.write("payload.value = newResult;"),V.write("return payload;");let A=V.compile();return(T,M)=>A(W,T,M)},Y,J=U3,Q=!I3.jitless,w=Q&&TF.value,G=I.catchall,H;$._zod.parse=(W,V)=>{H??(H=q.value);let X=W.value;if(!J(X))return W.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),W;if(Q&&w&&V?.async===!1&&V.jitless!==!0){if(!Y)Y=U(I.shape);if(W=Y(W,V),!G)return W;return hb([],X,W,V,H,$)}return z(W,V)}});fY=r("$ZodUnion",($,I)=>{d0.init($,I),U1($._zod,"optin",()=>I.options.some((q)=>q._zod.optin==="optional")?"optional":void 0),U1($._zod,"optout",()=>I.options.some((q)=>q._zod.optout==="optional")?"optional":void 0),U1($._zod,"values",()=>{if(I.options.every((q)=>q._zod.values))return new Set(I.options.flatMap((q)=>Array.from(q._zod.values)));return}),U1($._zod,"pattern",()=>{if(I.options.every((q)=>q._zod.pattern)){let q=I.options.map((U)=>U._zod.pattern);return new RegExp(`^(${q.map((U)=>EY(U.source)).join("|")})$`)}return});let z=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(q,U)=>{if(z)return z(q,U);let Y=!1,J=[];for(let Q of I.options){let K=Q._zod.run({value:q.value,issues:[]},U);if(K instanceof Promise)J.push(K),Y=!0;else{if(K.issues.length===0)return K;J.push(K)}}if(!Y)return Db(J,q,$,U);return Promise.all(J).then((Q)=>{return Db(Q,q,$,U)})}});XM=r("$ZodXor",($,I)=>{fY.init($,I),I.inclusive=!1;let z=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(q,U)=>{if(z)return z(q,U);let Y=!1,J=[];for(let Q of I.options){let K=Q._zod.run({value:q.value,issues:[]},U);if(K instanceof Promise)J.push(K),Y=!0;else J.push(K)}if(!Y)return Ob(J,q,$,U);return Promise.all(J).then((Q)=>{return Ob(Q,q,$,U)})}}),LM=r("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,fY.init($,I);let z=$._zod.parse;U1($._zod,"propValues",()=>{let U={};for(let Y of I.options){let J=Y._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(Y)}"`);for(let[Q,K]of Object.entries(J)){if(!U[Q])U[Q]=new Set;for(let w of K)U[Q].add(w)}}return U});let q=rI(()=>{let U=I.options,Y=new Map;for(let J of U){let Q=J._zod.propValues?.[I.discriminator];if(!Q||Q.size===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(J)}"`);for(let K of Q){if(Y.has(K))throw Error(`Duplicate discriminator value "${String(K)}"`);Y.set(K,J)}}return Y});$._zod.parse=(U,Y)=>{let J=U.value;if(!U3(J))return U.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),U;let Q=q.value.get(J?.[I.discriminator]);if(Q)return Q._zod.run(U,Y);if(I.unionFallback||Y.direction==="backward")return z(U,Y);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(q.value.keys()),input:J,path:[I.discriminator],inst:$}),U}}),DM=r("$ZodIntersection",($,I)=>{d0.init($,I),$._zod.parse=(z,q)=>{let U=z.value,Y=I.left._zod.run({value:U,issues:[]},q),J=I.right._zod.run({value:U,issues:[]},q);if(Y instanceof Promise||J instanceof Promise)return Promise.all([Y,J]).then(([K,w])=>{return Fb(z,K,w)});return Fb(z,Y,J)}});KG=r("$ZodTuple",($,I)=>{d0.init($,I);let z=I.items;$._zod.parse=(q,U)=>{let Y=q.value;if(!Array.isArray(Y))return q.issues.push({input:Y,inst:$,expected:"tuple",code:"invalid_type"}),q;q.value=[];let J=[],Q=Nb(z,"optin"),K=Nb(z,"optout");if(!I.rest){if(Y.length<Q)return q.issues.push({code:"too_small",minimum:Q,inclusive:!0,input:Y,inst:$,origin:"array"}),q;if(Y.length>z.length)q.issues.push({code:"too_big",maximum:z.length,inclusive:!0,input:Y,inst:$,origin:"array"})}let w=Array(z.length);for(let G=0;G<z.length;G++){let H=z[G]._zod.run({value:Y[G],issues:[]},U);if(H instanceof Promise)J.push(H.then((W)=>{w[G]=W}));else w[G]=H}if(I.rest){let G=z.length-1,H=Y.slice(z.length);for(let W of H){G++;let V=I.rest._zod.run({value:W,issues:[]},U);if(V instanceof Promise)J.push(V.then((X)=>Mb(X,q,G)));else Mb(V,q,G)}}if(J.length)return Promise.all(J).then(()=>Ab(w,q,z,Y,K));return Ab(w,q,z,Y,K)}});OM=r("$ZodRecord",($,I)=>{d0.init($,I),$._zod.parse=(z,q)=>{let U=z.value;if(!T9(U))return z.issues.push({expected:"record",code:"invalid_type",input:U,inst:$}),z;let Y=[],J=I.keyType._zod.values;if(J){z.value={};let Q=new Set;for(let w of J)if(typeof w==="string"||typeof w==="number"||typeof w==="symbol"){Q.add(typeof w==="number"?w.toString():w);let G=I.keyType._zod.run({value:w,issues:[]},q);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){z.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((V)=>b6(V,q,E4())),input:w,path:[w],inst:$});continue}let H=G.value,W=I.valueType._zod.run({value:U[w],issues:[]},q);if(W instanceof Promise)Y.push(W.then((V)=>{if(V.issues.length)z.issues.push(...I$(w,V.issues));z.value[H]=V.value}));else{if(W.issues.length)z.issues.push(...I$(w,W.issues));z.value[H]=W.value}}let K;for(let w in U)if(!Q.has(w))K=K??[],K.push(w);if(K&&K.length>0)z.issues.push({code:"unrecognize Line truncated
`)}X.write("payload.value = newResult;"),X.write("return payload;");let A=X.compile();return(B,P)=>A(V,B,P)},I,J=F2,Q=!V2.jitless,H=Q&&EP.value,G=q.catchall,Z;$._zod.parse=(V,X)=>{Z??(Z=z.value);let w=V.value;if(!J(w))return V.issues.push({expected:"object",code:"invalid_type",input:w,inst:$}),V;if(Q&&H&&X?.async===!1&&X.jitless!==!0){if(!I)I=U(q.shape);if(V=I(V,X),!G)return V;return Wl([],w,V,X,Z,$)}return Y(V,X)}});eJ=a("$ZodUnion",($,q)=>{s0.init($,q),H1($._zod,"optin",()=>q.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),H1($._zod,"optout",()=>q.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),H1($._zod,"values",()=>{if(q.options.every((z)=>z._zod.values))return new Set(q.options.flatMap((z)=>Array.from(z._zod.values)));return}),H1($._zod,"pattern",()=>{if(q.options.every((z)=>z._zod.pattern)){let z=q.options.map((U)=>U._zod.pattern);return new RegExp(`^(${z.map((U)=>fJ(U.source)).join("|")})$`)}return});let Y=q.options.length===1?q.options[0]._zod.run:null;$._zod.parse=(z,U)=>{if(Y)return Y(z,U);let I=!1,J=[];for(let Q of q.options){let K=Q._zod.run({value:z.value,issues:[]},U);if(K instanceof Promise)J.push(K),I=!0;else{if(K.issues.length===0)return K;J.push(K)}}if(!I)return sm(J,z,$,U);return Promise.all(J).then((Q)=>{return sm(Q,z,$,U)})}});FT=a("$ZodXor",($,q)=>{eJ.init($,q),q.inclusive=!1;let Y=q.options.length===1?q.options[0]._zod.run:null;$._zod.parse=(z,U)=>{if(Y)return Y(z,U);let I=!1,J=[];for(let Q of q.options){let K=Q._zod.run({value:z.value,issues:[]},U);if(K instanceof Promise)J.push(K),I=!0;else J.push(K)}if(!I)return tm(J,z,$,U);return Promise.all(J).then((Q)=>{return tm(Q,z,$,U)})}}),OT=a("$ZodDiscriminatedUnion",($,q)=>{q.inclusive=!1,eJ.init($,q);let Y=$._zod.parse;H1($._zod,"propValues",()=>{let U={};for(let I of q.options){let J=I._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${q.options.indexOf(I)}"`);for(let[Q,K]of Object.entries(J)){if(!U[Q])U[Q]=new Set;for(let H of K)U[Q].add(H)}}return U});let z=vY(()=>{let U=q.options,I=new Map;for(let J of U){let Q=J._zod.propValues?.[q.discriminator];if(!Q||Q.size===0)throw Error(`Invalid discriminated union option at index "${q.options.indexOf(J)}"`);for(let K of Q){if(I.has(K))throw Error(`Duplicate discriminator value "${String(K)}"`);I.set(K,J)}}return I});$._zod.parse=(U,I)=>{let J=U.value;if(!F2(J))return U.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),U;let Q=z.value.get(J?.[q.discriminator]);if(Q)return Q._zod.run(U,I);if(q.unionFallback||I.direction==="backward")return Y(U,I);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:q.discriminator,options:Array.from(z.value.keys()),input:J,path:[q.discriminator],inst:$}),U}}),MT=a("$ZodIntersection",($,q)=>{s0.init($,q),$._zod.parse=(Y,z)=>{let U=Y.value,I=q.left._zod.run({value:U,issues:[]},z),J=q.right._zod.run({value:U,issues:[]},z);if(I instanceof Promise||J instanceof Promise)return Promise.all([I,J]).then(([K,H])=>{return am(Y,K,H)});return am(Y,I,J)}});UX=a("$ZodTuple",($,q)=>{s0.init($,q);let Y=q.items;$._zod.parse=(z,U)=>{let I=z.value;if(!Array.isArray(I))return z.issues.push({input:I,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let J=[],Q=em(Y,"optin"),K=em(Y,"optout");if(!q.rest){if(I.length<Q)return z.issues.push({code:"too_small",minimum:Q,inclusive:!0,input:I,inst:$,origin:"array"}),z;if(I.length>Y.length)z.issues.push({code:"too_big",maximum:Y.length,inclusive:!0,input:I,inst:$,origin:"array"})}let H=Array(Y.length);for(let G=0;G<Y.length;G++){let Z=Y[G]._zod.run({value:I[G],issues:[]},U);if(Z instanceof Promise)J.push(Z.then((V)=>{H[G]=V}));else H[G]=Z}if(q.rest){let G=Y.length-1,Z=I.slice(Y.length);for(let V of Z){G++;let X=q.rest._zod.run({value:V,issues:[]},U);if(X instanceof Promise)J.push(X.then((w)=>$l(w,z,G)));else $l(X,z,G)}}if(J.length)return Promise.all(J).then(()=>ql(H,z,Y,I,K));return ql(H,z,Y,I,K)}});NT=a("$ZodRecord",($,q)=>{s0.init($,q),$._zod.parse=(Y,z)=>{let U=Y.value;if(!T3(U))return Y.issues.push({expected:"record",code:"invalid_type",input:U,inst:$}),Y;let I=[],J=q.keyType._zod.values;if(J){Y.value={};let Q=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){Q.add(typeof H==="number"?H.toString():H);let G=q.keyType._zod.run({value:H,issues:[]},z);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){Y.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((X)=>w8(X,z,m4())),input:H,path:[H],inst:$});continue}let Z=G.value,V=q.valueType._zod.run({value:U[H],issues:[]},z);if(V instanceof Promise)I.push(V.then((X)=>{if(X.issues.length)Y.issues.push(...h8(H,X.issues));Y.value[Z]=X.value}));else{if(V.issues.length)Y.issues.push(...h8(H,V.issues));Y.value[Z]=V.value}}let K;for(let H in U)if(!Q.has(H))K=K??[],K.push(H);if(K&&K.length>0)Y.issues.push({code:"unrecognize Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let J of $.seen.entries()){let Q=J[1];if(I===J[0]){Y(J);continue}if($.external){let w=$.external.registry.get(J[0])?.id;if(I!==J[0]&&w){Y(J);continue}}if($.metadataRegistry.get(J[0])?.id){Y(J);continue}if(Q.cycle){Y(J);continue}if(Q.count>1){if($.reused==="ref"){Y(J);continue}}}}function g9($,I){let z=$.seen.get(I);if(!z)throw Error("Unprocessed schema. This is a bug in Zod.");let q=(Q)=>{let K=$.seen.get(Q);if(K.ref===null)return;let w=K.def??K.schema,G={...w},H=K.ref;if(K.ref=null,H){q(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),Q._zod.parent===H)for(let D in w){if(D==="$ref"||D==="allOf")continue;if(!(D in G))delete w[D]}if(X.$ref&&V.def)for(let D in w){if(D==="$ref"||D==="allOf")continue;if(D in V.def&&JSON.stringify(w[D])===JSON.stringify(V.def[D]))delete w[D]}}let W=Q._zod.parent;if(W&&W!==H){q(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:Q,jsonSchema:w,path:K.path??[]})};for(let Q of[...$.seen.entries()].reverse())q(Q[0]);let U={};if($.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")U.$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");U.$id=$.external.uri(Q)}Object.assign(U,z.def??z.schema);let Y=$.metadataRegistry.get(I)?.id;if(Y!==void 0&&U.id===Y)delete U.id;let J=$.external?.defs??{};for(let Q of $.seen.entries()){let K=Q[1];if(K.def&&K.defId){if(K.def.id===K.defId)delete K.def.id;J[K.defId]=K.def}}if($.external);else if(Object.keys(J).length>0)if($.target==="draft-2020-12")U.$defs=J;else U.definitions=J;try{let Q=JSON.parse(JSON.stringify(U));return Object.defineProperty(Q,"~standard",{value:{...I["~standard"],jsonSchema:{input:Dz(I,"input",$.processors),output:Dz(I,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throw Error("Error converting schema to JSON.")}}function i6($,I){let z=I??{seen:new Set};if(z.seen.has($))return!1;z.seen.add($);let q=$._zod.def;if(q.type==="transform")return!0;if(q.type==="array")return i6(q.element,z);if(q.type==="set")return i6(q.valueType,z);if(q.type==="lazy")return i6(q.getter(),z);if(q.type==="promise"||q.type==="optional"||q.type==="nonoptional"||q.type==="nullable"||q.type==="readonly"||q.type==="default"||q.type==="prefault")return i6(q.innerType,z);if(q.type==="intersection")return i6(q.left,z)||i6(q.right,z);if(q.type==="record"||q.type==="map")return i6(q.keyType,z)||i6(q.valueType,z);if(q.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return i6(q.in,z)||i6(q.out,z)}if(q.type==="object"){for(let U in q.shape)if(i6(q.shape[U],z))return!0;return!1}if(q.type==="union"){for(let U of q.options)if(i6(U,z))return!0;return!1}if(q.type==="tuple"){for(let U of q.items)if(i6(U,z))return!0;if(q.rest&&i6(q.rest,z))return!0;return!1}return!1}var vP=($,I={})=>(z)=>{let q=v9({...z,processors:I});return x1($,q),R9(q,$),g9(q,$)},Dz=($,I,z={})=>(q)=>{let{libraryOptions:U,target:Y}=q??{},J=v9({...U??{},target:Y,io:I,processors:z});return x1($,J),R9(J,$),g9(J,$)};var rY=K0(()=>{mY()});function bG($,I){if("_idmap"in $){let q=$,U=v9({...I,processors:xG}),Y={};for(let K of q._idmap.entries()){let[w,G]=K;x1(G,U)}let J={},Q={registry:q,uri:I?.uri,defs:Y};U.external=Q;for(let K of q._idmap.entries()){let[w,G]=K;R9(U,G),J[w]=g9(U,G)}if(Object.keys(Y).length>0){let K=U.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[K]:Y}}return{schemas:J}}let z=v9({...I,processors:xG});return x1($,z),R9(z,$),g9(z,$)}var xP0,RP=($,I,z,q)=>{let U=z;U.type="string";let{minimum:Y,maximum:J,format:Q,patterns:K,contentEncoding:w}=$._zod.bag;if(typeof Y==="number")U.minLength=Y;if(typeof J==="number")U.maxLength=J;if(Q){if(U.format=xP0[Q]??Q,U.format==="")delete U.format;if(Q==="time")delete U.format}if(w)U.contentEncoding=w;if(K&&K.size>0){let G=[...K];if(G.length===1)U.pattern=G[0].source;else if(G.length>1)U.allOf=[...G.map((H)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:H.source}))]}},gP=($,I,z,q)=>{let U=z,{minimum:Y,maximum:J,format:Q,multipleOf:K,exclusiveMaximum:w,exclusiveMinimum:G}=$._zod.bag;if(typeof Q==="string"&&Q.includes("int"))U.type="integer";else U.type="number";let H=typeof G==="number"&&G>=(Y??Number.NEGATIVE_INFINITY),W=typeof w==="number"&&w<=(J??Number.POSITIVE_INFINITY),V=I.target==="draft-04"||I.target==="openapi-3.0";if(H)if(V)U.minimum=G,U.exclusiveMinimum=!0;else U.exclusiveMinimLine truncated
`:""},this._extScope=$,this._scope=new Z8.Scope({parent:$}),this._nodes=[new xp]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,I){let z=this._extScope.value($,I);return(this._values[z.prefix]||(this._values[z.prefix]=new Set)).add(z),z}getScopeValue($,I){return this._extScope.getValue($,I)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,I,z,q){let U=this._scope.toName(I);if(z!==void 0&&q)this._constants[U.str]=z;return this._leafNode(new _p($,U,z)),U}const($,I,z){return this._def(Z8.varKinds.const,$,I,z)}let($,I,z){return this._def(Z8.varKinds.let,$,I,z)}var($,I,z){return this._def(Z8.varKinds.var,$,I,z)}assign($,I,z){return this._leafNode(new rE($,I,z))}add($,I){return this._leafNode(new Cp($,J$.operators.ADD,I))}code($){if(typeof $=="function")$();else if($!==X1.nil)this._leafNode(new up($));return this}object(...$){let I=["{"];for(let[z,q]of $){if(I.length>1)I.push(",");if(I.push(z),z!==q||this.opts.es5)I.push(":"),(0,X1.addCodeArg)(I,q)}return I.push("}"),new X1._Code(I)}if($,I,z){if(this._blockNode(new E5($)),I&&z)this.code(I).else().code(z).endIf();else if(I)this.code(I).endIf();else if(z)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new E5($))}else(){return this._elseNode(new jJ)}endIf(){return this._endBlockNode(E5,jJ)}_for($,I){if(this._blockNode($),I)this.code(I).endFor();return this}for($,I){return this._for(new kp($),I)}forRange($,I,z,q,U=this.opts.es5?Z8.varKinds.var:Z8.varKinds.let){let Y=this._scope.toName($);return this._for(new fp(U,Y,I,z),()=>q(Y))}forOf($,I,z,q=Z8.varKinds.const){let U=this._scope.toName($);if(this.opts.es5){let Y=I instanceof X1.Name?I:this.var("_arr",I);return this.forRange("_i",0,X1._`${Y}.length`,(J)=>{this.var(U,X1._`${Y}[${J}]`),z(U)})}return this._for(new lE("of",q,U,I),()=>z(U))}forIn($,I,z,q=this.opts.es5?Z8.varKinds.var:Z8.varKinds.const){if(this.opts.ownProperties)return this.forOf($,X1._`Object.keys(${I})`,z);let U=this._scope.toName($);return this._for(new lE("in",q,U,I),()=>z(U))}endFor(){return this._endBlockNode(Cz)}label($){return this._leafNode(new hp($))}break($){return this._leafNode(new Sp($))}return($){let I=new xH;if(this._blockNode(I),this.code($),I.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(xH)}try($,I,z){if(!I&&!z)throw Error('CodeGen: "try" without "catch" and "finally"');let q=new bp;if(this._blockNode(q),this.code($),I){let U=this.name("e");this._currNode=q.catch=new kH(U),I(U)}if(z)this._currNode=q.finally=new fH,this.code(z);return this._endBlockNode(kH,fH)}throw($){return this._leafNode(new yp($))}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 z=this._nodes.length-I;if(z<0||$!==void 0&&z!==$)throw Error(`CodeGen: wrong number of nodes: ${z} vs ${$} expected`);return this._nodes.length=I,this}func($,I=X1.nil,z,q){if(this._blockNode(new uH($,I,z)),q)this.code(q).endFunc();return this}endFunc(){return this._endBlockNode(uH)}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 z=this._currNode;if(z instanceof $||I&&z 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 E5))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]=$}}J$.CodeGen=np;function H3($,I){for(let z in I)$[z]=($[z]||0)+(I[z]||0);return $}function bH($,I){return I instanceof X1._CodeOrName?H3($,I.names):$}function hz($,I,z){if($ instanceof X1.Name)return q($);if(!U($))return $;return new X1._Code($._items.reduce((Y,J)=>{if(J instanceof X1.Name)J=q(J);if(J instanceof X1._Code)Y.push(...J._items);else Y.push(J);return Y},[]));function q(Y){let J=z[Y.str];if(J===void 0||I[Y.str]!==1)return Y;return delete I[Y.str],J}function U(Y){return Y instanceof X1._Code&&Y._items.some((J)=>J instanceof X1.Name&&I[J.str]===1&&z[J.str]!==void 0)}}function QB0($,I){for(let z in I)$[z]=($[z]||0)-(I[z]||0)}function ip($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:X1._`!${oE($)}`}J$.not=ip;var KB0=pp(J$.operators.AND);function wB0(...$){return $.reduce(KB0)}J$.and=wB0;var GB0=pp(J$.operators.OR);function HB0(...$){return $.reduce(GB0)}J$.or=HB0;function pp($){return(I,z)=>I===X1.nil?z:z===X1.nil?I:X1._`${oE(I)} ${$} ${oE(z)}`}function oE($){return $ instanceof X1.Name?$:X1._`(${Line truncated
|| (${J} == "string" && ${U} && ${U} == +${U})`).assign(Q,e0._`+${U}`);return;case"integer":q.elseIf(e0._`${J} === "boolean" || ${U} === null
|| (${J} === "string" && ${U} && ${U} == +${U} && !(${U} % 1))`).assign(Q,e0._`+${U}`);return;case"boolean":q.elseIf(e0._`${U} === "false" || ${U} === 0 || ${U} === null`).assign(Q,!1).elseIf(e0._`${U} === "true" || ${U} === 1`).assign(Q,!0);return;case"null":q.elseIf(e0._`${U} === "" || ${U} === 0 || ${U} === false`),q.assign(Q,null);return;case"array":q.elseIf(e0._`${J} === "string" || ${J} === "number"
|| ${J} === "boolean" || ${U} === null`).assign(Q,e0._`[${U}]`)}}}function Tj0({gen:$,parentData:I,parentDataProperty:z},q){$.if(e0._`${I} !== undefined`,()=>$.assign(e0._`${I}[${z}]`,q))}function zB($,I,z,q=Sz.Correct){let U=q===Sz.Correct?e0.operators.EQ:e0.operators.NEQ,Y;switch($){case"null":return e0._`${I} ${U} null`;case"array":Y=e0._`Array.isArray(${I})`;break;case"object":Y=e0._`${I} && typeof ${I} == "object" && !Array.isArray(${I})`;break;case"integer":Y=J(e0._`!(${I} % 1) && !isNaN(${I})`);break;case"number":Y=J();break;default:return e0._`typeof ${I} ${U} ${$}`}return q===Sz.Correct?Y:(0,e0.not)(Y);function J(Q=e0.nil){return(0,e0.and)(e0._`typeof ${I} == "number"`,Q,z?e0._`isFinite(${I})`:e0.nil)}}Fc.checkDataType=zB;function qB($,I,z,q){if($.length===1)return zB($[0],I,z,q);let U,Y=(0,Lc.toHash)($);if(Y.array&&Y.object){let J=e0._`typeof ${I} != "object"`;U=Y.null?J:e0._`!${I} || ${J}`,delete Y.null,delete Y.array,delete Y.object}else U=e0.nil;if(Y.number)delete Y.integer;for(let J in Y)U=(0,e0.and)(U,zB(J,I,z,q));return U}Fc.checkDataTypes=qB;var Ej0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:I})=>typeof $=="string"?e0._`{type: ${$}}`:e0._`{type: ${I}}`};function UB($){let I=Bj0($);(0,Fj0.reportError)(I,Ej0)}Fc.reportTypeError=UB;function Bj0($){let{gen:I,data:z,schema:q}=$,U=(0,Lc.schemaRefOrVal)($,q,"type");return{gen:I,keyword:"type",data:z,schema:q.type,schemaCode:U,schemaValue:U,parentSchema:q,params:{},it:$}}});var Tc=F((Ac)=>{Object.defineProperty(Ac,"__esModule",{value:!0});Ac.assignDefaults=void 0;var yz=z1(),hj0=F1();function Sj0($,I){let{properties:z,items:q}=$.schema;if(I==="object"&&z)for(let U in z)Mc($,U,z[U].default);else if(I==="array"&&Array.isArray(q))q.forEach((U,Y)=>Mc($,Y,U.default))}Ac.assignDefaults=Sj0;function Mc($,I,z){let{gen:q,compositeRule:U,data:Y,opts:J}=$;if(z===void 0)return;let Q=yz._`${Y}${(0,yz.getProperty)(I)}`;if(U){(0,hj0.checkStrictMode)($,`default is ignored for: ${Q}`);return}let K=yz._`${Q} === undefined`;if(J.useDefaults==="empty")K=yz._`${K} || ${Q} === null || ${Q} === ""`;q.if(K,yz._`${Q} = ${(0,yz.stringify)(z)}`)}});var l$=F((jc)=>{Object.defineProperty(jc,"__esModule",{value:!0});jc.validateUnion=jc.validateArray=jc.usePattern=jc.callValidateCode=jc.schemaProperties=jc.allSchemaProperties=jc.noPropertyInData=jc.propertyInData=jc.isOwnProperty=jc.hasPropFunc=jc.reportMissingProp=jc.checkMissingProp=jc.checkReportMissingProp=void 0;var $4=z1(),YB=F1(),k9=B5(),yj0=F1();function uj0($,I){let{gen:z,data:q,it:U}=$;z.if(QB(z,q,I,U.opts.ownProperties),()=>{$.setParams({missingProperty:$4._`${I}`},!0),$.error()})}jc.checkReportMissingProp=uj0;function xj0({gen:$,data:I,it:{opts:z}},q,U){return(0,$4.or)(...q.map((Y)=>(0,$4.and)(QB($,I,Y,z.ownProperties),$4._`${U} = ${Y}`)))}jc.checkMissingProp=xj0;function kj0($,I){$.setParams({missingProperty:I},!0),$.error()}jc.reportMissingProp=kj0;function Ec($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:$4._`Object.prototype.hasOwnProperty`})}jc.hasPropFunc=Ec;function JB($,I,z){return $4._`${Ec($)}.call(${I}, ${z})`}jc.isOwnProperty=JB;function fj0($,I,z,q){let U=$4._`${I}${(0,$4.getProperty)(z)} !== undefined`;return q?$4._`${U} && ${JB($,I,z)}`:U}jc.propertyInData=fj0;function QB($,I,z,q){let U=$4._`${I}${(0,$4.getProperty)(z)} === undefined`;return q?(0,$4.or)(U,(0,$4.not)(JB($,I,z))):U}jc.noPropertyInData=QB;function Bc($){return $?Object.keys($).filter((I)=>I!=="__proto__"):[]}jc.allSchemaProperties=Bc;function bj0($,I){return Bc(I).filter((z)=>!(0,YB.alwaysValidSchema)($,I[z]))}jc.schemaProperties=bj0;function nj0({schemaCode:$,data:I,it:{gen:z,topSchemaRef:q,schemaPath:U,errorPath:Y},it:J},Q,K,w){let G=w?$4._`${$}, ${I}, ${q}${U}`:I,H=[[k9.default.instancePath,(0,$4.strConcat)(k9.default.instancePath,Y)],[k9.default.parentData,J.parentData],[k9.default.parentDataProperty,J.parentDataProperty],[k9.default.rootData,k9.default.rootData]];if(J.opts.dynamicRef)H.push([k9.default.dynamicAnchors,k9.default.dynamicAnchors]);let W=$4._`${G}, ${z.object(...H)}`;return K!==$4.nil?$4._`${Q}.call(${K}, ${W})`:$4._`${Q}(${W})`}jc.callValidateCode=nj0;var ij0=$4._`new RegExp`;function pj0({gen:$,it:{opts:I}},z){let q=I.unicodeRegExp?"u":"",{regExp:U}=I.code,Y=U(z,q);return $.scopeValue("pattern",{key:Y.toString(),ref:Y,code:$4._`${U.code==="new RegExp"?ij0:(0,yj0.useFunc)($,U)}(${z}, ${q})`})}jc.usePattern=pj0;function cj0($){let{gen:I,data:z,keyword:q,it:U}=$,Y=I.name("valid");if(U.allErrors){let Q=I.let("valid",!0);return J(()=>I.assign(Q,!1)),Q}return I.var(Y,!0),J(()=>I.break()),Y;function J(Q){let K=I.const("len",$4._`${z}.length`);I.forRange("i",0,K,(w)=>{$.subschema({keyword:q,dataProp:w,dataPropType:YB.Type.Num},Y),I.if((0,$4.not)(Y),Q)})}}jc.validateArray=cj0;function dj0($){let{gen:I,schema:z,keyword:q,it:U}=$;if(!Array.isArray(z))throw Error("ajv implementation error");if(z.some((K)=>(0,YB.alwaysValidSchema)(U,K))&&!U.opts.unevaluated)return;le Line truncated
missingProperty: ${q},
depsCount: ${I},
deps: ${z}}`};var GC0={keyword:"dependencies",type:"object",schemaType:"object",error:cm.error,code($){let[I,z]=HC0($);im($,I),pm($,z)}};function HC0({schema:$}){let I={},z={};for(let q in $){if(q==="__proto__")continue;let U=Array.isArray($[q])?I:z;U[q]=$[q]}return[I,z]}function im($,I=$.schema){let{gen:z,data:q,it:U}=$;if(Object.keys(I).length===0)return;let Y=z.let("missing");for(let J in I){let Q=I[J];if(Q.length===0)continue;let K=(0,dJ.propertyInData)(z,q,J,U.opts.ownProperties);if($.setParams({property:J,depsCount:Q.length,deps:Q.join(", ")}),U.allErrors)z.if(K,()=>{for(let w of Q)(0,dJ.checkReportMissingProp)($,w)});else z.if(gB._`${K} && (${(0,dJ.checkMissingProp)($,Q,Y)})`),(0,dJ.reportMissingProp)($,Y),z.else()}}cm.validatePropertyDeps=im;function pm($,I=$.schema){let{gen:z,data:q,keyword:U,it:Y}=$,J=z.name("valid");for(let Q in I){if((0,wC0.alwaysValidSchema)(Y,I[Q]))continue;z.if((0,dJ.propertyInData)(z,q,Q,Y.opts.ownProperties),()=>{let K=$.subschema({keyword:U,schemaProp:Q},J);$.mergeValidEvaluated(K,J)},()=>z.var(J,!0)),$.ok(J)}}cm.validateSchemaDeps=pm;cm.default=GC0});var tm=F((rm)=>{Object.defineProperty(rm,"__esModule",{value:!0});var om=z1(),ZC0=F1(),XC0={message:"property name must be valid",params:({params:$})=>om._`{propertyName: ${$.propertyName}}`},LC0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:XC0,code($){let{gen:I,schema:z,data:q,it:U}=$;if((0,ZC0.alwaysValidSchema)(U,z))return;let Y=I.name("valid");I.forIn("key",q,(J)=>{$.setParams({propertyName:J}),$.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},Y),I.if((0,om.not)(Y),()=>{if($.error(!0),!U.allErrors)I.break()})}),$.ok(Y)}};rm.default=LC0});var _B=F((am)=>{Object.defineProperty(am,"__esModule",{value:!0});var KW=l$(),D8=z1(),OC0=B5(),wW=F1(),FC0={message:"must NOT have additional properties",params:({params:$})=>D8._`{additionalProperty: ${$.additionalProperty}}`},NC0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:FC0,code($){let{gen:I,schema:z,parentSchema:q,data:U,errsCount:Y,it:J}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:Q,opts:K}=J;if(J.props=!0,K.removeAdditional!=="all"&&(0,wW.alwaysValidSchema)(J,z))return;let w=(0,KW.allSchemaProperties)(q.properties),G=(0,KW.allSchemaProperties)(q.patternProperties);H(),$.ok(D8._`${Y} === ${OC0.default.errors}`);function H(){I.forIn("key",U,(D)=>{if(!w.length&&!G.length)X(D);else I.if(W(D),()=>X(D))})}function W(D){let O;if(w.length>8){let A=(0,wW.schemaRefOrVal)(J,q.properties,"properties");O=(0,KW.isOwnProperty)(I,A,D)}else if(w.length)O=(0,D8.or)(...w.map((A)=>D8._`${D} === ${A}`));else O=D8.nil;if(G.length)O=(0,D8.or)(O,...G.map((A)=>D8._`${(0,KW.usePattern)($,A)}.test(${D})`));return(0,D8.not)(O)}function V(D){I.code(D8._`delete ${U}[${D}]`)}function X(D){if(K.removeAdditional==="all"||K.removeAdditional&&z===!1){V(D);return}if(z===!1){if($.setParams({additionalProperty:D}),$.error(),!Q)I.break();return}if(typeof z=="object"&&!(0,wW.alwaysValidSchema)(J,z)){let O=I.name("valid");if(K.removeAdditional==="failing")L(D,O,!1),I.if((0,D8.not)(O),()=>{$.reset(),V(D)});else if(L(D,O),!Q)I.if((0,D8.not)(O),()=>I.break())}}function L(D,O,A){let T={keyword:"additionalProperties",dataProp:D,dataPropType:wW.Type.Str};if(A===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(T,O)}}};am.default=NC0});var Il=F(($l)=>{Object.defineProperty($l,"__esModule",{value:!0});var AC0=hJ(),sm=l$(),CB=F1(),em=_B(),PC0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:z,parentSchema:q,data:U,it:Y}=$;if(Y.opts.removeAdditional==="all"&&q.additionalProperties===void 0)em.default.code(new AC0.KeywordCxt(Y,em.default,"additionalProperties"));let J=(0,sm.allSchemaProperties)(z);for(let H of J)Y.definedProperties.add(H);if(Y.opts.unevaluated&&J.length&&Y.props!==!0)Y.props=CB.mergeEvaluated.props(I,(0,CB.toHash)(J),Y.props);let Q=J.filter((H)=>!(0,CB.alwaysValidSchema)(Y,z[H]));if(Q.length===0)return;let K=I.name("valid");for(let H of Q){if(w(H))G(H);else{if(I.if((0,sm.propertyInData)(I,U,H,Y.opts.ownProperties)),G(H),!Y.allErrors)I.else().var(K,!0);I.endIf()}$.it.definedProperties.add(H),$.ok(K)}function w(H){return Y.opts.useDefaults&&!Y.compositeRule&&z[H].default!==void 0}function G(H){$.subschema({keyword:"properties",schemaProp:H,dataProp:H},K)}}};$l.default=PC0});var Jl=F((Yl)=>{Object.defineProperty(Yl,"__esModule",{value:!0});var zl=l$(),GW=z1(),ql=F1(),Ul=F1(),EC0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:z,data:q,parentSchema:U,it:Y}=$,{opts:J}=Y,Q=(0,zl.allSchemaProperties)(z),K=Q.filter((L)=>(0,ql.alwaysValidSchema)(Y,z[L]));if(Q.length===0||K.length===Q.length&&(!Y.opts.unevaluated||Y.props===!0))return;let w=J.strictSchema&&!J.allowMatchingProperties&&U.properties,G=I.name("valid");if(Y.props!==!0&&!(Y.props instanceo Line truncated
\x00`,n+=a1(k,2),n+=Q.magic,n+=a1(D,2),n+=a1(O,2),n+=a1(h.crc32,4),n+=a1(h.compressedSize,4),n+=a1(h.uncompressedSize,4),n+=a1(w.length,2),n+=a1(A.length,2);var g=aV.LOCAL_FILE_HEADER+n+w+A,b=aV.CENTRAL_FILE_HEADER+a1(f,2)+n+a1(W.length,2)+"\x00\x00\x00\x00"+a1(E,4)+a1(q,4)+w+A+W;return{fileRecord:g,dirRecord:b}},Ii0=function($,I,z,q,U){var Y="",J=Aq.transformTo("string",U(q));return Y=aV.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+a1($,2)+a1($,2)+a1(I,4)+a1(z,4)+a1(J.length,2)+J,Y},zi0=function($){var I="";return I=aV.DATA_DESCRIPTOR+a1($.crc32,4)+a1($.compressedSize,4)+a1($.uncompressedSize,4),I};function T8($,I,z,q){Pq.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=I,this.zipPlatform=z,this.encodeFileName=q,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}Aq.inherits(T8,Pq);T8.prototype.push=function($){var I=$.meta.percent||0,z=this.entriesCount,q=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,Pq.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:z?(I+100*(z-q-1))/z:100}})};T8.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var I=this.streamFiles&&!$.file.dir;if(I){var z=w10($,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:z.fileRecord,meta:{percent:0}})}else this.accumulate=!0};T8.prototype.closedSource=function($){this.accumulate=!1;var I=this.streamFiles&&!$.file.dir,z=w10($,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(z.dirRecord),I)this.push({data:zi0($),meta:{percent:100}});else{this.push({data:z.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};T8.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 z=this.bytesWritten-$,q=Ii0(this.dirRecords.length,z,$,this.zipComment,this.encodeFileName);this.push({data:q,meta:{percent:100}})};T8.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};T8.prototype.registerPrevious=function($){this._sources.push($);var I=this;return $.on("data",function(z){I.processChunk(z)}),$.on("end",function(){if(I.closedSource(I.previous.streamInfo),I._sources.length)I.prepareNextSource();else I.end()}),$.on("error",function(z){I.error(z)}),this};T8.prototype.resume=function(){if(!Pq.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};T8.prototype.error=function($){var I=this._sources;if(!Pq.prototype.error.call(this,$))return!1;for(var z=0;z<I.length;z++)try{I[z].error($)}catch(q){}return!0};T8.prototype.lock=function(){Pq.prototype.lock.call(this);var $=this._sources;for(var I=0;I<$.length;I++)$[I].lock()};G10.exports=T8});var W10=F((Ji0)=>{var qi0=OR(),Ui0=H10(),Yi0=function($,I){var z=$||I,q=qi0[z];if(!q)throw Error(z+" is not a valid compression method !");return q};Ji0.generateWorker=function($,I,z){var q=new Ui0(I.streamFiles,z,I.platform,I.encodeFileName),U=0;try{$.forEach(function(Y,J){U++;var Q=Yi0(J.options.compression,I.compression),K=J.options.compressionOptions||I.compressionOptions||{},w=J.dir,G=J.date;J._compressWorker(Q,K).withStreamInfo("file",{name:Y,dir:w,date:G,comment:J.comment||"",unixPermissions:J.unixPermissions,dosPermissions:J.dosPermissions}).pipe(q)}),q.entriesCount=U}catch(Y){q.error(Y)}return q}});var Z10=F((WR1,V10)=>{var Ki0=D4(),sV=R$();function oQ($,I){sV.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(I)}Ki0.inherits(oQ,sV);oQ.prototype._bindStream=function($){var I=this;this._stream=$,$.pause(),$.on("data",function(z){I.push({data:z,meta:{percent:0}})}).on("error",function(z){if(I.isPaused)this.generatedError=z;else I.error(z)}).on("end",function(){if(I.isPaused)I._upstreamEnded=!0;else I.end()})};oQ.prototype.pause=function(){if(!sV.prototype.pause.call(this))return!1;return this._stream.pause(),!0};oQ.prototype.resume=function(){if(!sV.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};V10.exports=oQ});var T10=F((VR1,P10)=>{var wi0=Wq(),rQ=D4(),O10=R$(),Gi0=Tv(),F10=Ev(),X10=hV(),Hi0=Le(),Wi0=W10(),L10=jQ(),Vi0=Z10(),N10=function($,I,z){var q=rQ.getTypeOf(I),U,Y=rQ.extend(z||{},F10);if(Y.date=Y.date||new Date,Y.compression!==null)Y.compression=Y.compression.toUpperCase();if(typeof Y.unixPermissions==="string")Y.unixPermissions=parseInt(Y.unixPermissions,8);if(Y.unixPermissions&&Y.unixPermissions&16384)Y.dir=!0;if(Y.dosPermissions&&Y.dosPermissions Line truncated
`)}openNode($,I){let z=this.tos,q=this._xml;if(z&&this.open)q.push(">");this._stack.push($),q.push("<"),q.push($),zg(q,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)Z60(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");zg(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(V60.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,z){if(this.openNode($,I),z!==void 0)this.writeText(z);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("")}}qg.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};X60.exports=qg});var Ug=F((Ud0)=>{var L60=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function qd0($){if(typeof $==="string")return $;if(L60)return L60.decode($);return $.toString()}Ud0.bufferToString=qd0});var M60=F((O60)=>{Object.defineProperty(O60,"__esModule",{value:!0});O60.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;O60.S=` \r
`;O60.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";O60.NAME_CHAR="-"+O60.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";O60.CHAR_RE=new RegExp("^["+O60.CHAR+"]$","u");O60.S_RE=new RegExp("^["+O60.S+"]+$","u");O60.NAME_START_CHAR_RE=new RegExp("^["+O60.NAME_START_CHAR+"]$","u");O60.NAME_CHAR_RE=new RegExp("^["+O60.NAME_CHAR+"]$","u");O60.NAME_RE=new RegExp("^["+O60.NAME_START_CHAR+"]["+O60.NAME_CHAR+"]*$","u");O60.NMTOKEN_RE=new RegExp("^["+O60.NAME_CHAR+"]+$","u");var Yg=9,Jg=10,Qg=13,Kg=32;O60.S_LIST=[Kg,Jg,Qg,Yg];function Jd0($){return $>=Kg&&$<=55295||$===Jg||$===Qg||$===Yg||$>=57344&&$<=65533||$>=65536&&$<=1114111}O60.isChar=Jd0;function Qd0($){return $===Kg||$===Jg||$===Qg||$===Yg}O60.isS=Qd0;function D60($){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}O60.isNameStartChar=D60;function Kd0($){return D60($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}O60.isNameChar=Kd0});var _60=F((j60)=>{Object.defineProperty(j60,"__esModule",{value:!0});j60.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";j60.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";j60.S=` \r
`;j60.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";j60.NAME_CHAR="-"+j60.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";j60.CHAR_RE=new RegExp("^["+j60.CHAR+"]$","u");j60.RESTRICTED_CHAR_RE=new RegExp("^["+j60.RESTRICTED_CHAR+"]$","u");j60.S_RE=new RegExp("^["+j60.S+"]+$","u");j60.NAME_START_CHAR_RE=new RegExp("^["+j60.NAME_START_CHAR+"]$","u");j60.NAME_CHAR_RE=new RegExp("^["+j60.NAME_CHAR+"]$","u");j60.NAME_RE=new RegExp("^["+j60.NAME_START_CHAR+"]["+j60.NAME_CHAR+"]*$","u");j60.NMTOKEN_RE=new RegExp("^["+j60.NAME_CHAR+"]+$","u");var A60=9,P60=10,T60=13,E60=32;j60.S_LIST=[E60,P60,T60,A60];function Nd0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}j60.isChar=Nd0;function Md0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}j60.isRestrictedChar=Md0;function Ad0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}j60.isCharAndNotRestricted=Ad0;function Pd0($){return $===E60||$===P60||$===T60||$===A60}j60.isS=Pd0;function B60($){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}j60.isNameStartChar=B60;function Td0($){return B60($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}j60.isNameChar=Td0});var S60=F((h60)=>{Object.defineProperty(h60,"__esModule",{value:!0});h60.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";h60.NC_NAME_CHAR="-"+h60.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";h60.NC_NAME_START_CHAR_RE=new RegExp("^["+h60.NC_NAME_START_CHAR+"]$","u");h60.NC_NAME_CHAR_RE=new RegExp("^["+h60.NC_NAME_CHAR+"]$","u");h60.NC_NAME_RE=new RegExp("^["+h60.NC_NAME_START_CHAR+"]["+h60.NC_NAME_CHAR+"]*$","u");function C60($){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}h60.isNCNameStartChar=C60;function fd0($){return C60($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}h60.isNCNameChar=fd0});var z$0=F((I$0)=>{Object.defineProperty(I$0,"__esModule",{value:!0});var Sq=M60(),dd0=_60(),Ag=S60(),W$=Sq.isS,md0=Sq.isChar,K2=Sq.isNameStartChar,y60=Sq.isNameChar,r60=Sq.S_LIST,ld0=Sq.NAME_RE,od0=dd0.isChar,rd0=Ag.isNCNameStartChar,td0=Ag.isNCNameChar,ad0=Ag.NC_NAME_RE,jZ="http://www.w3.org/XML/1998/namespace",hq="http://www.w3.org/2000/xmlns/",sd0={__proto__:null,xml:jZ,xmlns:hq},ed0={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},V4=-1,I5=-2,u60=0,$m0=1,Gg=2,Im0=3,gq=4,zm0=5,qm0=6,Um0=7,Hg=8,Ym0=9,Jm0=10,Qm0=11,Km0=12,l6=13,AZ=14,Wg=15,wm0=16,Vg=17,Gm0=18,Hm0=19,Zg=20,Wm0=21,Vm0=22,Zm0=23,x60=24,Xg=25,PZ=26,k60=27,Xm0=28,Lm0=29,f60=30,Dm0=31,Om0=32,n3=33,Fm0=34,Lg=35,w2=36,Dg=37,Nm0=38,b60=39,n60=40,Mm0=41,i60=42,Am0=43,Pm0=44,Og=9,B8=10,Fg=13,p60=32,c60=33,t60=34,G2=38,a60=39,TZ=45,EZ=47,Tm0=59,w7=60,_q=61,m4=62,L6=63,s60=91,Cq=93,d60=133,m60=8232,BZ=($)=>$===t60||$===a60,e60=[t60,a60],Em0=[...e60,s60,m4],Bm0=[...e60,w7,Cq],jm0=[_q,L6,...r60],vm0=[...r60,m4,G2,w7];function Mg($,I,z){switch(I){case"xml":if(z!==jZ)$.fail(`xml prefix must be bound to ${jZ}.`);break;case"xmlns":if(z!==hq)$.fail(`xmlns prefix must be bound to ${hq}.`);break;default:}switch(z){case hq:$.fail(I===""?`the default namespace may not be set to ${z}.`:`may not assign a prefix (even "xmlns") to the URI ${hq}.`);break;case jZ:switch(I){case"xml":break;case"":$.fail(`the default namespace may not be set to ${z}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function Rm0($,I){for(let z of Object.keys(I))Mg($,z,I[z])}var gm0=($)=>ad0.test($),_m0=($)=>ld0.test($),i3=0,l60=1,Ng=2;I$0.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var o60={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 $$0{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=rd0,this.nameCheck=td0,this.isName=gm0,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},sd0);let z=this.opt.additionalNamesp Line truncated
`,I=this.i}}captureToChar($){let{i:I}=this,{chunk:z}=this;while(!0){let q=this.getCode();switch(q){case I5:this.text+=`${z.slice(I,this.prevI)}
`,I=this.i,q=B8;break;case V4:return this.text+=z.slice(I),!1;default:}if(q===$)return this.text+=z.slice(I,this.prevI),!0}}captureNameChars(){let{chunk:$,i:I}=this;while(!0){let z=this.getCode();if(z===V4)return this.name+=$.slice(I),V4;if(!y60(z))return this.name+=$.slice(I,this.prevI),z===I5?B8:z}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===V4||!W$($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=md0,this.getCode=this.getCode10;else this.isChar=od0,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=$m0}sBeginWhitespace(){let $=this.i,I=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(I){case w7:if(this.state=Wg,this.text.length!==0)throw Error("no-empty text at start");break;case V4:break;default:this.unget(),this.state=l6,this.xmlDeclPossible=!1}}sDoctype(){var $;let I=this.captureTo(Em0);switch(I){case m4:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=l6,this.doctype=!0;break}case V4:break;default:if(this.text+=String.fromCodePoint(I),I===s60)this.state=gq;else if(BZ(I))this.state=Im0,this.q=I}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=Gg}sDTD(){let $=this.captureTo(Bm0);if($===V4)return;if(this.text+=String.fromCodePoint($),$===Cq)this.state=Gg;else if($===w7)this.state=qm0;else if(BZ($))this.state=zm0,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=gq,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case c60:this.state=Um0,this.openWakaBang="";break;case L6:this.state=Qm0;break;default:this.state=gq}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),I=this.openWakaBang+=$;if(this.text+=$,I!=="-")this.state=I==="--"?Hg:gq,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(TZ))this.text+="-",this.state=Ym0}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===TZ?Jm0:Hg}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===m4)this.state=gq;else this.fail("malformed comment."),this.state=Hg}sDTDPI(){if(this.captureToChar(L6))this.text+="?",this.state=Km0}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===m4)this.state=gq}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:I}=this;$:while(!0)switch(this.getCode()){case I5:this.entity+=`${I.slice($,this.prevI)}
`,$=this.i;break;case Tm0:{let{entityReturnState:z}=this,q=this.entity+I.slice($,this.prevI);this.state=z;let U;if(q==="")this.fail("empty entity name."),U="&;";else U=this.parseEntity(q),this.entity="";if(z!==l6||this.textHandler!==void 0)this.text+=U;break $}case V4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(K2($))this.state=Fm0,this.unget(),this.xmlDeclPossible=!1;else switch($){case EZ:this.state=Am0,this.xmlDeclPossible=!1;break;case c60:this.state=wm0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case L6:this.state=Zm0;break;default:this.fail("disallowed character in tag name"),this.state=l6,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=Zg,this.openWakaBang="";break;case"--":this.state=Vg,this.openWakaBang="";break;case"DOCTYPE":if(this.state=Gg,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(TZ))this.state=Gm0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===TZ)this.state=Hm0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=Vg}sCommentEnded(){let $=this.getCodeNorm();if($!==m4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Vg;else this.state=l6}sCData(){if(this.captureToChar(Cq))this.state=Wm0}sCDataEnding(){let $=this.getCodeNorm();if($===Cq)this.state=Vm0;else this.text+=`]${String.fromCodePoint($)}`,this.state=Zg}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case m4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=l6;break}case Cq:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=Zg}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=x60;else if($===L6||W$($))this.fail("processing instruction without a target."),this.state=$===L6?PZ:Xg;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=x60}sPIRest(){let{chunk:$,i:I}=this;while(!0){let z=this.getCodeNorm();if(z===V4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(z)){this.piTarget+=$.slice(I,this.prevI);let q=z===L6;if(q||W$(z))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=q?n3:k60}else this.state=q?PZ:Xg;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(z);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===L6)this.state=PZ;else if(!W$($))this.text=String.fromCodePoint($)}else if(this.captureToChar(L6))this.state=PZ}sPIEnding(){var $;let I=this.getCodeNorm();if(I===m4){let{piTarget:z}=this;if(z.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:z,body:this.text}),this.piTarget=this.text="",this.state=l6}else if(I===L6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=Xg;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===L6){this.state=n3;return}if($!==V4)this.state=Xm0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(jm0);if($===L6){this.state=n3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(W$($)||$===_q))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=$===_q?f60:Lm0}sXMLDeclEq(){let $=this.getCodeNorm();if($===L6){this.state=n3,this.fail("XML declaration is incomplete.");return}if(W$($))return;if($!==_q)this.fail("value required.");this.state=f60}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===L6){this.state=n3,this.fail("XML declaration is incomplete.");return}if(W$($))return;if(!BZ($))this.fail("value must be quoted."),this.q=p60;else this.q=$;this.state=Dm0}sXMLDeclValue(){let $=this.captureTo([this.q,L6]);if($===L6){this.state=n3,this.text="",this.fail("XML declaration is incomplete.");return}if($===V4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let z=I;if(this.xmlDecl.version=z,!/^1\.[0-9]+$/.test(z))this.fail("ver Line truncated
`;$=this.i,I=i3;break;case V4:if(q!==void 0)this.text+=z.slice($);break $;default:I=i3}this.forbiddenState=I}handleTextOutsideRoot(){let{i:$}=this,{chunk:I,textHandler:z}=this,q=!1;$:while(!0){let U=this.getCode();switch(U){case w7:{if(this.state=Wg,z!==void 0){let{text:Y}=this,J=I.slice($,this.prevI);if(Y.length!==0)z(Y+J),this.text="";else if(J.length!==0)z(J)}break $}case G2:if(this.state=AZ,this.entityReturnState=l6,z!==void 0)this.text+=I.slice($,this.prevI);q=!0;break $;case I5:if(z!==void 0)this.text+=`${I.slice($,this.prevI)}
`;$=this.i;break;case V4:if(z!==void 0)this.text+=I.slice($);break $;default:if(!W$(U))q=!0}}if(!q)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 z;let{prefix:q,local:U}=this.qname($),Y={name:$,prefix:q,local:U,value:I};if(this.attribList.push(Y),(z=this.attributeHandler)===null||z===void 0||z.call(this,Y),q==="xmlns"){let J=I.trim();if(this.currentXMLVersion==="1.0"&&J==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[U]=J,Mg(this,U,J)}else if($==="xmlns"){let J=I.trim();this.topNS[""]=J,Mg(this,"",J)}}pushAttribPlain($,I){var z;let q={name:$,value:I};this.attribList.push(q),(z=this.attributeHandler)===null||z===void 0||z.call(this,q)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:z}=this;while(z.length>0){let U=z.pop();this.fail(`unclosed tag: ${U.name}`)}if(this.state!==u60&&this.state!==l6)this.fail("unexpected end.");let{text:q}=this;if(q.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,q),this.text="";return this._closed=!0,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,z;let q=this.topNS[$];if(q!==void 0)return q;let{tags:U}=this;for(let Y=U.length-1;Y>=0;Y--)if(q=U[Y].ns[$],q!==void 0)return q;if(q=this.ns[$],q!==void 0)return q;return(z=(I=this.opt).resolvePrefix)===null||z===void 0?void 0:z.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let z=$.slice(I+1),q=$.slice(0,I);if(q===""||z===""||z.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:q,local:z}}processAttribsNS(){var $;let{attribList:I}=this,z=this.tag;{let{prefix:Y,local:J}=this.qname(z.name);z.prefix=Y,z.local=J;let Q=z.uri=($=this.resolve(Y))!==null&&$!==void 0?$:"";if(Y!==""){if(Y==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(Q==="")this.fail(`unbound namespace prefix: ${JSON.stringify(Y)}.`),z.uri=Y}}if(I.length===0)return;let{attributes:q}=z,U=new Set;for(let Y of I){let{name:J,prefix:Q,local:K}=Y,w,G;if(Q==="")w=J==="xmlns"?hq:"",G=J;else{if(w=this.resolve(Q),w===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(Q)}.`),w=Q;G=`{${w}}${K}`}if(U.has(G))this.fail(`duplicate attribute: ${G}.`);U.add(G),Y.uri=w,q[J]=Y}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:z,value:q}of $){if(I[z]!==void 0)this.fail(`duplicate attribute: ${z}.`);I[z]=q}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,z=this.tag;z.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,z),I.push(z),this.state=l6,this.name=""}openSelfClosingTag(){var $,I,z;this.processAttribs();let{tags:q}=this,U=this.tag;if(U.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,U),(I=this.closeTagHandler)===null||I===void 0||I.call(this,U),(this.tag=(z=q[q.length-1])!==null&&z!==void 0?z:null)===null)this.closedRoot=!0;this.state=l6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=l6,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let z=this.closeTagHandler,q=$.length;while(q-- >0){let U=this.tag=$.pop();if(this.topNS=U.ns,z===null||z===void 0||z(U),U.name===I)break;this.fail("unexpected close tag.")}if(q===0)this.closedRoot=!0;else if(q<0)this.fail(`unmatched closing tag: ${I}.`),this.text+=`</${I}>`}parseEntity($){if($[0]!=="#"){let z=this.ENTITIES[$];if(z!==void 0)return z;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)}}I$0.SaxesParser=$$0});var H2=F((tR1,q$0)=>{var{SaxesParser:Sm0}=z$0(),{PassThrough:ym0}=g6(),{bufferToString:um0}=Ug();q$0.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new ym0);let I=new Sm0,z;I.on("error",(U)=>{z=U});let q=[];I.on("opentag",(U)=>q.push({eventType:"opentag",value:U})),I.on("text",(U)=>q.push({eventType:"text",value:U})),I.on("closetag",(U)=>q.push({eventType:"closetag",value:U}));for await(let U of $){if(I.write(um0(U)),z)throw z;yield q,q=[]}}});var O0=F((aR1,U$0)=>{var xm0=H2(),km0=X6();class yq{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof yq)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let I of $)for(let{eventType:z,value:q}of I)if(z==="opentag")this.parseOpen(q);else if(z==="text")this.parseText(q);else if(z==="closetag"){if(!this.parseClose(q.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}`}}SI0.FormatterOptions=hI0});var JX=F((AC1,fI0)=>{var os0="[object AsyncFunction]",rs0="[object Function]",ts0="[object GeneratorFunction]",as0="[object Null]",ss0="[object Proxy]",es0="[object Undefined]",$e0=typeof global=="object"&&global&&global.Object===Object&&global,Ie0=typeof self=="object"&&self&&self.Object===Object&&self,ze0=$e0||Ie0||Function("return this")(),xI0=Object.prototype,qe0=xI0.hasOwnProperty,kI0=xI0.toString,uI0=ze0.Symbol,r3=uI0?uI0.toStringTag:void 0;function Ue0($){if($==null)return $===void 0?es0:as0;return r3&&r3 in Object($)?Ye0($):Je0($)}function Ye0($){var I=qe0.call($,r3),z=$[r3];try{$[r3]=void 0;var q=!0}catch(Y){}var U=kI0.call($);if(q)if(I)$[r3]=z;else delete $[r3];return U}function Je0($){return kI0.call($)}function Qe0($){if(!Ke0($))return!1;var I=Ue0($);return I==rs0||I==ts0||I==os0||I==ss0}function Ke0($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}fI0.exports=Qe0});var Nz0=F((QX,dq)=>{var we0=200,d_="__lodash_hash_undefined__",XX=1,aI0=2,sI0=9007199254740991,KX="[object Arguments]",k_="[object Array]",Ge0="[object AsyncFunction]",eI0="[object Boolean]",$z0="[object Date]",Iz0="[object Error]",zz0="[object Function]",He0="[object GeneratorFunction]",wX="[object Map]",qz0="[object Number]",We0="[object Null]",cq="[object Object]",bI0="[object Promise]",Ve0="[object Proxy]",Uz0="[object RegExp]",GX="[object Set]",Yz0="[object String]",Ze0="[object Symbol]",Xe0="[object Undefined]",f_="[object WeakMap]",Jz0="[object ArrayBuffer]",HX="[object DataView]",Le0="[object Float32Array]",De0="[object Float64Array]",Oe0="[object Int8Array]",Fe0="[object Int16Array]",Ne0="[object Int32Array]",Me0="[object Uint8Array]",Ae0="[object Uint8ClampedArray]",Pe0="[object Uint16Array]",Te0="[object Uint32Array]",Ee0=/[\\^$.*+?()[\]{}|]/g,Be0=/^\[object .+?Constructor\]$/,je0=/^(?:0|[1-9]\d*)$/,z4={};z4[Le0]=z4[De0]=z4[Oe0]=z4[Fe0]=z4[Ne0]=z4[Me0]=z4[Ae0]=z4[Pe0]=z4[Te0]=!0;z4[KX]=z4[k_]=z4[Jz0]=z4[eI0]=z4[HX]=z4[$z0]=z4[Iz0]=z4[zz0]=z4[wX]=z4[qz0]=z4[cq]=z4[Uz0]=z4[GX]=z4[Yz0]=z4[f_]=!1;var Qz0=typeof global=="object"&&global&&global.Object===Object&&global,ve0=typeof self=="object"&&self&&self.Object===Object&&self,c5=Qz0||ve0||Function("return this")(),Kz0=typeof QX=="object"&&QX&&!QX.nodeType&&QX,nI0=Kz0&&typeof dq=="object"&&dq&&!dq.nodeType&&dq,wz0=nI0&&nI0.exports===Kz0,y_=wz0&&Qz0.process,iI0=function(){try{return y_&&y_.binding&&y_.binding("util")}catch($){}}(),pI0=iI0&&iI0.isTypedArray;function Re0($,I){var z=-1,q=$==null?0:$.length,U=0,Y=[];while(++z<q){var J=$[z];if(I(J,z,$))Y[U++]=J}return Y}function ge0($,I){var z=-1,q=I.length,U=$.length;while(++z<q)$[U+z]=I[z];return $}function _e0($,I){var z=-1,q=$==null?0:$.length;while(++z<q)if(I($[z],z,$))return!0;return!1}function Ce0($,I){var z=-1,q=Array($);while(++z<$)q[z]=I(z);return q}function he0($){return function(I){return $(I)}}function Se0($,I){return $.has(I)}function ye0($,I){return $==null?void 0:$[I]}function ue0($){var I=-1,z=Array($.size);return $.forEach(function(q,U){z[++I]=[U,q]}),z}function xe0($,I){return function(z){return $(I(z))}}function ke0($){var I=-1,z=Array($.size);return $.forEach(function(q){z[++I]=q}),z}var fe0=Array.prototype,be0=Function.prototype,LX=Object.prototype,u_=c5["__core-js_shared__"],Gz0=be0.toString,q5=LX.hasOwnProperty,cI0=function(){var $=/[^.]+$/.exec(u_&&u_.keys&&u_.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),Hz0=LX.toString,ne0=RegExp("^"+Gz0.call(q5).replace(Ee0,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),dI0=wz0?c5.Buffer:void 0,WX=c5.Symbol,mI0=c5.Uint8Array,Wz0=LX.propertyIsEnumerable,ie0=fe0.splice,t3=WX?WX.toStringTag:void 0,lI0=Object.getOwnPropertySymbols,pe0=dI0?dI0.isBuffer:void 0,ce0=xe0(Object.keys,Object),b_=mq(c5,"DataView"),O2=mq(c5,"Map"),n_=mq(c5,"Promise"),i_=mq(c5,"Set"),p_=mq(c5,"WeakMap"),F2=mq(Object,"create"),de0=e3(b_),me0=e3(O2),le0=e3(n_),oe0=e3(i_),re0=e3(p_),oI0=WX?WX.prototype:void 0,x_=oI0?oI0.valueOf:void 0;function a3($){var I=-1,z=$==null?0:$.length;this.clear();while(++I<z){var q=$[I];this.set(q[0],q[1])}}function te0(){this.__data__=F2?F2(null):{},this.size=0}function ae0($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function se0($){var I=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(I)}set headers($){this._headers=$}shouldQuote($,I){let z=I?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(U11.default(z))return z;if(Array.isArray(z))return z[$];if(this._headers!==null)return z[this._headers[$]];return!1}format($,I,z){let q=`${Y11.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:U}=this;if(U.quote!==""){if(q.indexOf(U.quote)!==-1)return this.quoteField(q.replace(this.REPLACE_REGEXP,U.escapedQuote))}if(q.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(I,z))return this.quoteField(q);return q}quoteField($){let{quote:I}=this.formatterOptions;return`${I}${$}${I}`}}lq.FieldFormatter=Rz0});var t_=F((gz0)=>{Object.defineProperty(gz0,"__esModule",{value:!0});gz0.isSyncTransform=void 0;gz0.isSyncTransform=($)=>$.length===1});var hz0=F((oq)=>{var Cz0=oq&&oq.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(oq,"__esModule",{value:!0});oq.RowFormatter=void 0;var Q11=Cz0(JX()),K11=Cz0(Nz0()),w11=r_(),G11=t_();class $I{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new w11.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($I.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(G11.isSyncTransform($))return(I,z)=>{let q=null;try{q=$(I)}catch(U){return z(U)}return z(null,q)};return(I,z)=>{$(I,z)}}set rowTransform($){if(!Q11.default($))throw TypeError("The transform should be a function");this._rowTransform=$I.createTransform($)}format($,I){this.callTransformer($,(z,q)=>{if(z)return I(z);if(!$)return I(null);let U=[];if(q){let{shouldFormatColumns:Y,headers:J}=this.checkHeaders(q);if(this.shouldWriteHeaders&&J&&!this.hasWrittenHeaders)U.push(this.formatColumns(J,!0)),this.hasWrittenHeaders=!0;if(Y){let Q=this.gatherColumns(q);U.push(this.formatColumns(Q,!1))}}return I(null,U)})}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=$I.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!K11.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($I.isRowHashArray($))return this.headers.map((I,z)=>{let q=$[z];if(q)return q[1];return""});if($I.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((I,z)=>$[z])}callTransformer($,I){if(!this._rowTransform)return I(null,$);return this._rowTransform($,I)}formatColumns($,I){let z=$.map((U,Y)=>this.fieldFormatter.format(U,Y,I)).join(this.formatterOptions.delimiter),{rowCount:q}=this;if(this.rowCount+=1,q)return[this.formatterOptions.rowDelimiter,z].join("");return z}}oq.RowFormatter=$I});var Sz0=F((FX)=>{Object.defineProperty(FX,"__esModule",{value:!0});FX.FieldFormatter=FX.RowFormatter=void 0;var H11=hz0();Object.defineProperty(FX,"RowFormatter",{enumerable:!0,get:function(){return H11.RowFormatter}});var W11=r_();Object.defineProperty(FX,"FieldFormatter",{enumerable:!0,get:function(){return W11.FieldFormatter}})});var a_=F((uz0)=>{Object.defineProperty(uz0,"__esModule",{value:!0});uz0.CsvFormatterStream=void 0;var Z11=t("stream"),X11=Sz0();class yz0 extends Z11.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new X11.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,I,z){let q=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(U,Y)=>{if(U)return q=!0,z(U);if(Y)Y.forEach((J)=>{this.push(Buffer.from(J,"utf8"))});return q=!0,z()})}catch(U){if(q)throw U;z(U)}}_flush($){this.rowFormatter.finish((I,z)=>{if(I)return $(I);if(z)z.forEach((q)=>{this.push(Buffer.from(q,"utf8"))});return $()})}}uz0.CsvFormatterStream=yz0});var fz0=F((j1)=>{var kz0=j1&&j1.__createBinding||(Object.create?function($,I,z,q){if(q===void 0)q=z;Object.defineProperty($,q,{enumerable:!0,get:function(){return I[z]}})}:function($,I,z,q){if(q===void 0)q=z;$[q]=I[z]}),L11=j1&&j1.__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}}bq0.Token=fq0});var MC=F((cq0)=>{Object.defineProperty(cq0,"__esModule",{value:!0});cq0.Scanner=void 0;var iq0=N7(),T$1=/((?:\r\n)|\n|\r)/;class pq0{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 z=I.exec($);if(z==null)return null;let q=z[1],U=this.cursor+(z.index||0);return new iq0.Token({token:q,startCursor:U,endCursor:U+q.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:I}=this;if(I<=$)return null;return new iq0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=T$1.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}}cq0.Scanner=pq0});var iX=F((lq0)=>{Object.defineProperty(lq0,"__esModule",{value:!0});lq0.ColumnFormatter=void 0;class mq0{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}}lq0.ColumnFormatter=mq0});var AC=F((aq0)=>{Object.defineProperty(aq0,"__esModule",{value:!0});aq0.NonQuotedColumnParser=void 0;var E$1=iX(),rq0=N7();class tq0{constructor($){this.parserOptions=$,this.columnFormatter=new E$1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:I}=this,z=[],q=$.nextCharacterToken;for(;q;q=$.nextCharacterToken){if(rq0.Token.isTokenDelimiter(q,I)||rq0.Token.isTokenRowDelimiter(q))break;z.push(q.token),$.advancePastToken(q)}return this.columnFormatter.format(z.join(""))}}aq0.NonQuotedColumnParser=tq0});var PC=F(($U0)=>{Object.defineProperty($U0,"__esModule",{value:!0});$U0.QuotedColumnParser=void 0;var B$1=iX(),YU=N7();class eq0{constructor($){this.parserOptions=$,this.columnFormatter=new B$1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let I=$.cursor,{foundClosingQuote:z,col:q}=this.gatherDataBetweenQuotes($);if(!z){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($),q}gatherDataBetweenQuotes($){let{parserOptions:I}=this,z=!1,q=!1,U=[],Y=$.nextCharacterToken;for(;!q&&Y!==null;Y=$.nextCharacterToken){let J=YU.Token.isTokenQuote(Y,I);if(!z&&J)z=!0;else if(z)if(YU.Token.isTokenEscapeCharacter(Y,I)){$.advancePastToken(Y);let Q=$.nextCharacterToken;if(Q!==null&&(YU.Token.isTokenQuote(Q,I)||YU.Token.isTokenEscapeCharacter(Q,I)))U.push(Q.token),Y=Q;else if(J)q=!0;else U.push(Y.token)}else if(J)q=!0;else U.push(Y.token);$.advancePastToken(Y)}return{col:this.columnFormatter.format(U.join("")),foundClosingQuote:q}}checkForMalformedColumn($){let{parserOptions:I}=this,{nextNonSpaceToken:z}=$;if(z){let q=YU.Token.isTokenDelimiter(z,I),U=YU.Token.isTokenRowDelimiter(z);if(!(q||U)){let Y=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${I.escapedDelimiter}' OR new line got: '${z.token}'. at '${Y}`)}$.advanceToToken(z)}else if(!$.hasMoreData)$.advancePastLine()}}$U0.QuotedColumnParser=eq0});var YU0=F((qU0)=>{Object.defineProperty(qU0,"__esModule",{value:!0});qU0.ColumnParser=void 0;var j$1=AC(),v$1=PC(),R$1=N7();class zU0{constructor($){this.parserOptions=$,this.quotedColumnParser=new v$1.QuotedColumnParser($),this.nonQuotedColumnParser=new j$1.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:I}=$;if(I!==null&&R$1.Token.isTokenQuote(I,this.parserOptions))return $.advanceToToken(I),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}qU0.ColumnParser=zU0});var TC=F((JU)=>{Object.defineProperty(JU,"__esModule",{value:!0});JU.ColumnFormatter=JU.QuotedColumnParser=JU.NonQuotedColumnParser=JU.ColumnParser=void 0;var g$1=YU0();Object.defineProperty(JU,"ColumnParser",{enumerable:!0,get:function(){return g$1.ColumnParser}});var _$1=AC();Object.defineProperty(JU,"NonQuotedColumnParser",{enumerable:!0,get:function(){return _$1.NonQuotedColumnParser}});var C$1=PC();Object.defineProperty(JU,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,x,x,V,q);let h=V.type==="*"?bC:V.type==="?"?pC:"\\"+V.type;U=!0,q=q.slice(0,V.reStart)+h+"\\("+x}if(T(),Y)q+="\\\\";let M=P81[q.charAt(0)];for(let x=Q.length-1;x>-1;x--){let h=Q[x],k=q.slice(0,h.reStart),E=q.slice(h.reStart,h.reEnd-8),f=q.slice(h.reEnd),n=q.slice(h.reEnd-8,h.reEnd)+f,g=k.split(")").length,b=k.split("(").length-g,p=f;for(let R=0;R<b;R++)p=p.replace(/\)[+*?]?/,"");f=p;let q0=f===""&&I!==nC?"(?:$|\\/)":"";q=k+E+f+q0+n}if(q!==""&&U)q="(?=.)"+q;if(M)q=O()+q;if(I===nC)return[q,U];if(z.nocase&&!U)U=$.toUpperCase()!==$.toLowerCase();if(!U)return E81($);let v=z.nocase?"i":"";try{return Object.assign(new RegExp("^"+q+"$",v),{_glob:$,_src:q})}catch(x){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,z=I.noglobstar?bC:I.dot?M81:A81,q=I.nocase?"i":"",U=$.map((Y)=>{return Y=Y.map((J)=>typeof J==="string"?j81(J):J===o6?o6:J._src).reduce((J,Q)=>{if(!(J[J.length-1]===o6&&Q===o6))J.push(Q);return J},[]),Y.forEach((J,Q)=>{if(J!==o6||Y[Q-1]===o6)return;if(Q===0)if(Y.length>1)Y[Q+1]="(?:\\/|"+z+"\\/)?"+Y[Q+1];else Y[Q]=z;else if(Q===Y.length-1)Y[Q-1]+="(?:\\/|"+z+")?";else Y[Q-1]+="(?:\\/|\\/"+z+"\\/)"+Y[Q+1],Y[Q+1]=o6}),Y.filter((J)=>J!==o6).join("/")}).join("|");if(U="^(?:"+U+")$",this.negate)U="^(?!"+U+").*$";try{this.regexp=new RegExp(U,q)}catch(Y){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 z=this.options;if(iC.sep!=="/")$=$.split(iC.sep).join("/");$=$.split(aU0),this.debug(this.pattern,"split",$);let q=this.set;this.debug(this.pattern,"set",q);let U;for(let Y=$.length-1;Y>=0;Y--)if(U=$[Y],U)break;for(let Y=0;Y<q.length;Y++){let J=q[Y],Q=$;if(z.matchBase&&J.length===1)Q=[U];if(this.matchOne(Q,J,I)){if(z.flipNegate)return!0;return!this.negate}}if(z.flipNegate)return!1;return this.negate}static defaults($){return C$.defaults($).Minimatch}}C$.Minimatch=j2});var YY0=F((_h1,UY0)=>{UY0.exports=qY0;var mC=t("fs"),{EventEmitter:R81}=t("events"),{Minimatch:dC}=$Y0(),{resolve:g81}=t("path");function _81($,I){return new Promise((z,q)=>{mC.readdir($,{withFileTypes:!0},(U,Y)=>{if(U)switch(U.code){case"ENOTDIR":if(I)q(U);else z([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":z([]);break;case"ELOOP":default:q(U);break}else z(Y)})})}function IY0($,I){return new Promise((z,q)=>{(I?mC.stat:mC.lstat)($,(Y,J)=>{if(Y)switch(Y.code){case"ENOENT":if(I)z(IY0($,!1));else z(null);break;default:z(null);break}else z(J)})})}async function*zY0($,I,z,q,U,Y){let J=await _81(I+$,Y);for(let Q of J){let K=Q.name;if(K===void 0)K=Q,q=!0;let w=$+"/"+K,G=w.slice(1),H=I+"/"+G,W=null;if(q||z)W=await IY0(H,z);if(!W&&Q.name!==void 0)W=Q;if(W===null)W={isDirectory:()=>!1};if(W.isDirectory()){if(!U(G))yield{relative:G,absolute:H,stats:W},yield*zY0(w,I,z,q,U,!1)}else yield{relative:G,absolute:H,stats:W}}}async function*C81($,I,z,q){yield*zY0("",$,I,z,q,!0)}function h81($){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 lC extends R81{constructor($,I,z){super();if(typeof I==="function")z=I,I=null;if(this.options=h81(I||{}),this.matchers=[],this.options.pattern){let q=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=q.map((U)=>new dC(U,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let q=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=q.map((U)=>new dC(U,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let q=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=q.map((U)=>new dC(U,{dot:!0}))}if(this.iterator=C81(g81($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,z)this._matches=[],this.on("match",(q)=>this._matches.push(this.options.absolute?q.absolute:q.relative)),this.on("error",(q)=>z(q)),this.on("end",()=>z(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((I)=>I.match($))}_fileMatches($,I){let z=$+(I?"/":"");return(this.matchers.length===0||this.matchers.some((q)=>q.match(z)))&&!this.ignoreMatchers.some((q)=>q.match(z))&&(!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 z=$.value.relative,q=$.value.absolute;if(this.options.mark&&I)z+="/",q+="/";if(this.options.stat)this.emit("match",{relative:z,absolute:q,stat:$.value.stats});else this.emit("match",{relative:z,ab Line truncated
`,y);y=I0===-1?B.length:I0}else if(d!==-1&&B[y]==="/"&&B[y+1]==="*"){let I0=B.indexOf("*/",y);if(I0!==-1)y=I0+2,d=B.indexOf("*/",y);else C+=B[y],y++}else C+=B[y],y++;return C}function n$(B){let C=k6(B.toString()),y=C.match(T4);if(!y)y=C.match(S4);if(!y)throw Error(`could not parse args in autoInject
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let J of $.seen.entries()){let Q=J[1];if(q===J[0]){I(J);continue}if($.external){let H=$.external.registry.get(J[0])?.id;if(q!==J[0]&&H){I(J);continue}}if($.metadataRegistry.get(J[0])?.id){I(J);continue}if(Q.cycle){I(J);continue}if(Q.count>1){if($.reused==="ref"){I(J);continue}}}}function v3($,q){let Y=$.seen.get(q);if(!Y)throw Error("Unprocessed schema. This is a bug in Zod.");let z=(Q)=>{let K=$.seen.get(Q);if(K.ref===null)return;let H=K.def??K.schema,G={...H},Z=K.ref;if(K.ref=null,Z){z(Z);let X=$.seen.get(Z),w=X.schema;if(w.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(w);else Object.assign(H,w);if(Object.assign(H,G),Q._zod.parent===Z)for(let F in H){if(F==="$ref"||F==="allOf")continue;if(!(F in G))delete H[F]}if(w.$ref&&X.def)for(let F in H){if(F==="$ref"||F==="allOf")continue;if(F in X.def&&JSON.stringify(H[F])===JSON.stringify(X.def[F]))delete H[F]}}let V=Q._zod.parent;if(V&&V!==Z){z(V);let X=$.seen.get(V);if(X?.schema.$ref){if(H.$ref=X.schema.$ref,X.def)for(let w in H){if(w==="$ref"||w==="allOf")continue;if(w in X.def&&JSON.stringify(H[w])===JSON.stringify(X.def[w]))delete H[w]}}}$.override({zodSchema:Q,jsonSchema:H,path:K.path??[]})};for(let Q of[...$.seen.entries()].reverse())z(Q[0]);let U={};if($.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")U.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let Q=$.external.registry.get(q)?.id;if(!Q)throw Error("Schema is missing an `id` property");U.$id=$.external.uri(Q)}Object.assign(U,Y.def??Y.schema);let I=$.metadataRegistry.get(q)?.id;if(I!==void 0&&U.id===I)delete U.id;let J=$.external?.defs??{};for(let Q of $.seen.entries()){let K=Q[1];if(K.def&&K.defId){if(K.def.id===K.defId)delete K.def.id;J[K.defId]=K.def}}if($.external);else if(Object.keys(J).length>0)if($.target==="draft-2020-12")U.$defs=J;else U.definitions=J;try{let Q=JSON.parse(JSON.stringify(U));return Object.defineProperty(Q,"~standard",{value:{...q["~standard"],jsonSchema:{input:eY(q,"input",$.processors),output:eY(q,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throw Error("Error converting schema to JSON.")}}function F8($,q){let Y=q??{seen:new Set};if(Y.seen.has($))return!1;Y.seen.add($);let z=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")return F8(z.element,Y);if(z.type==="set")return F8(z.valueType,Y);if(z.type==="lazy")return F8(z.getter(),Y);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")return F8(z.innerType,Y);if(z.type==="intersection")return F8(z.left,Y)||F8(z.right,Y);if(z.type==="record"||z.type==="map")return F8(z.keyType,Y)||F8(z.valueType,Y);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return F8(z.in,Y)||F8(z.out,Y)}if(z.type==="object"){for(let U in z.shape)if(F8(z.shape[U],Y))return!0;return!1}if(z.type==="union"){for(let U of z.options)if(F8(U,Y))return!0;return!1}if(z.type==="tuple"){for(let U of z.items)if(F8(U,Y))return!0;if(z.rest&&F8(z.rest,Y))return!0;return!1}return!1}var Rj=($,q={})=>(Y)=>{let z=C3({...Y,processors:q});return s1($,z),R3(z,$),v3(z,$)},eY=($,q,Y={})=>(z)=>{let{libraryOptions:U,target:I}=z??{},J=C3({...U??{},target:I,io:q,processors:Y});return s1($,J),R3(J,$),v3(J,$)};var HQ=e(()=>{JQ()});function xX($,q){if("_idmap"in $){let z=$,U=C3({...q,processors:gX}),I={};for(let K of z._idmap.entries()){let[H,G]=K;s1(G,U)}let J={},Q={registry:z,uri:q?.uri,defs:I};U.external=Q;for(let K of z._idmap.entries()){let[H,G]=K;R3(U,G),J[H]=v3(U,G)}if(Object.keys(I).length>0){let K=U.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[K]:I}}return{schemas:J}}let Y=C3({...q,processors:gX});return s1($,Y),R3(Y,$),v3(Y,$)}var Fk0,vj=($,q,Y,z)=>{let U=Y;U.type="string";let{minimum:I,maximum:J,format:Q,patterns:K,contentEncoding:H}=$._zod.bag;if(typeof I==="number")U.minLength=I;if(typeof J==="number")U.maxLength=J;if(Q){if(U.format=Fk0[Q]??Q,U.format==="")delete U.format;if(Q==="time")delete U.format}if(H)U.contentEncoding=H;if(K&&K.size>0){let G=[...K];if(G.length===1)U.pattern=G[0].source;else if(G.length>1)U.allOf=[...G.map((Z)=>({...q.target==="draft-07"||q.target==="draft-04"||q.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}},hj=($,q,Y,z)=>{let U=Y,{minimum:I,maximum:J,format:Q,multipleOf:K,exclusiveMaximum:H,exclusiveMinimum:G}=$._zod.bag;if(typeof Q==="string"&&Q.includes("int"))U.type="integer";else U.type="number";let Z=typeof G==="number"&&G>=(I??Number.NEGATIVE_INFINITY),V=typeof H==="number"&&H<=(J??Number.POSITIVE_INFINITY),X=q.target==="draft-04"||q.target==="openapi-3.0";if(Z)if(X)U.minimum=G,U.exclusiveMinimum=!0;else U.exclusiveMinimuLine truncated
`:""},this._extScope=$,this._scope=new e$.Scope({parent:$}),this._nodes=[new Ls]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,q){let Y=this._extScope.value($,q);return(this._values[Y.prefix]||(this._values[Y.prefix]=new Set)).add(Y),Y}getScopeValue($,q){return this._extScope.getValue($,q)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,q,Y,z){let U=this._scope.toName(q);if(Y!==void 0&&z)this._constants[U.str]=Y;return this._leafNode(new Gs($,U,Y)),U}const($,q,Y){return this._def(e$.varKinds.const,$,q,Y)}let($,q,Y){return this._def(e$.varKinds.let,$,q,Y)}var($,q,Y){return this._def(e$.varKinds.var,$,q,Y)}assign($,q,Y){return this._leafNode(new tC($,q,Y))}add($,q){return this._leafNode(new Zs($,k8.operators.ADD,q))}code($){if(typeof $=="function")$();else if($!==P1.nil)this._leafNode(new ws($));return this}object(...$){let q=["{"];for(let[Y,z]of $){if(q.length>1)q.push(",");if(q.push(Y),Y!==z||this.opts.es5)q.push(":"),(0,P1.addCodeArg)(q,z)}return q.push("}"),new P1._Code(q)}if($,q,Y){if(this._blockNode(new D9($)),q&&Y)this.code(q).else().code(Y).endIf();else if(q)this.code(q).endIf();else if(Y)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new D9($))}else(){return this._elseNode(new iQ)}endIf(){return this._endBlockNode(D9,iQ)}_for($,q){if(this._blockNode($),q)this.code(q).endFor();return this}for($,q){return this._for(new Fs($),q)}forRange($,q,Y,z,U=this.opts.es5?e$.varKinds.var:e$.varKinds.let){let I=this._scope.toName($);return this._for(new Os(U,I,q,Y),()=>z(I))}forOf($,q,Y,z=e$.varKinds.const){let U=this._scope.toName($);if(this.opts.es5){let I=q instanceof P1.Name?q:this.var("_arr",q);return this.forRange("_i",0,P1._`${I}.length`,(J)=>{this.var(U,P1._`${I}[${J}]`),Y(U)})}return this._for(new rC("of",z,U,q),()=>Y(U))}forIn($,q,Y,z=this.opts.es5?e$.varKinds.var:e$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,P1._`Object.keys(${q})`,Y);let U=this._scope.toName($);return this._for(new rC("in",z,U,q),()=>Y(U))}endFor(){return this._endBlockNode(Vz)}label($){return this._leafNode(new Ws($))}break($){return this._leafNode(new Xs($))}return($){let q=new gV;if(this._blockNode(q),this.code($),q.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(gV)}try($,q,Y){if(!q&&!Y)throw Error('CodeGen: "try" without "catch" and "finally"');let z=new Ms;if(this._blockNode(z),this.code($),q){let U=this.name("e");this._currNode=z.catch=new SV(U),q(U)}if(Y)this._currNode=z.finally=new yV,this.code(Y);return this._endBlockNode(SV,yV)}throw($){return this._leafNode(new Vs($))}block($,q){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(q);return this}endBlock($){let q=this._blockStarts.pop();if(q===void 0)throw Error("CodeGen: not in self-balancing block");let Y=this._nodes.length-q;if(Y<0||$!==void 0&&Y!==$)throw Error(`CodeGen: wrong number of nodes: ${Y} vs ${$} expected`);return this._nodes.length=q,this}func($,q=P1.nil,Y,z){if(this._blockNode(new hV($,q,Y)),z)this.code(z).endFunc();return this}endFunc(){return this._endBlockNode(hV)}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($,q){let Y=this._currNode;if(Y instanceof $||q&&Y instanceof q)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${q?`${$.kind}/${q.kind}`:$.kind}"`)}_elseNode($){let q=this._currNode;if(!(q instanceof D9))throw Error('CodeGen: "else" without "if"');return this._currNode=q.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let q=this._nodes;q[q.length-1]=$}}k8.CodeGen=Ns;function B2($,q){for(let Y in q)$[Y]=($[Y]||0)+(q[Y]||0);return $}function xV($,q){return q instanceof P1._CodeOrName?B2($,q.names):$}function wz($,q,Y){if($ instanceof P1.Name)return z($);if(!U($))return $;return new P1._Code($._items.reduce((I,J)=>{if(J instanceof P1.Name)J=z(J);if(J instanceof P1._Code)I.push(...J._items);else I.push(J);return I},[]));function z(I){let J=Y[I.str];if(J===void 0||q[I.str]!==1)return I;return delete q[I.str],J}function U(I){return I instanceof P1._Code&&I._items.some((J)=>J instanceof P1.Name&&q[J.str]===1&&Y[J.str]!==void 0)}}function if0($,q){for(let Y in q)$[Y]=($[Y]||0)-(q[Y]||0)}function Ds($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:P1._`!${sC($)}`}k8.not=Ds;var nf0=As(k8.operators.AND);function cf0(...$){return $.reduce(nf0)}k8.and=cf0;var pf0=As(k8.operators.OR);function df0(...$){return $.reduce(pf0)}k8.or=df0;function As($){return(q,Y)=>q===P1.nil?Y:Y===P1.nil?q:P1._`${sC(q)} ${$} ${sC(Y)}`}function sC($){return $ instanceof P1.Name?$:P1._`(${Line truncated
|| (${J} == "string" && ${U} && ${U} == +${U})`).assign(Q,I1._`+${U}`);return;case"integer":z.elseIf(I1._`${J} === "boolean" || ${U} === null
|| (${J} === "string" && ${U} && ${U} == +${U} && !(${U} % 1))`).assign(Q,I1._`+${U}`);return;case"boolean":z.elseIf(I1._`${U} === "false" || ${U} === 0 || ${U} === null`).assign(Q,!1).elseIf(I1._`${U} === "true" || ${U} === 1`).assign(Q,!0);return;case"null":z.elseIf(I1._`${U} === "" || ${U} === 0 || ${U} === false`),z.assign(Q,null);return;case"array":z.elseIf(I1._`${J} === "string" || ${J} === "number"
|| ${J} === "boolean" || ${U} === null`).assign(Q,I1._`[${U}]`)}}}function Ui0({gen:$,parentData:q,parentDataProperty:Y},z){$.if(I1._`${q} !== undefined`,()=>$.assign(I1._`${q}[${Y}]`,z))}function UR($,q,Y,z=Lz.Correct){let U=z===Lz.Correct?I1.operators.EQ:I1.operators.NEQ,I;switch($){case"null":return I1._`${q} ${U} null`;case"array":I=I1._`Array.isArray(${q})`;break;case"object":I=I1._`${q} && typeof ${q} == "object" && !Array.isArray(${q})`;break;case"integer":I=J(I1._`!(${q} % 1) && !isNaN(${q})`);break;case"number":I=J();break;default:return I1._`typeof ${q} ${U} ${$}`}return z===Lz.Correct?I:(0,I1.not)(I);function J(Q=I1.nil){return(0,I1.and)(I1._`typeof ${q} == "number"`,Q,Y?I1._`isFinite(${q})`:I1.nil)}}as.checkDataType=UR;function IR($,q,Y,z){if($.length===1)return UR($[0],q,Y,z);let U,I=(0,rs.toHash)($);if(I.array&&I.object){let J=I1._`typeof ${q} != "object"`;U=I.null?J:I1._`!${q} || ${J}`,delete I.null,delete I.array,delete I.object}else U=I1.nil;if(I.number)delete I.integer;for(let J in I)U=(0,I1.and)(U,UR(J,q,Y,z));return U}as.checkDataTypes=IR;var Ii0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:q})=>typeof $=="string"?I1._`{type: ${$}}`:I1._`{type: ${q}}`};function JR($){let q=Ji0($);(0,eb0.reportError)(q,Ii0)}as.reportTypeError=JR;function Ji0($){let{gen:q,data:Y,schema:z}=$,U=(0,rs.schemaRefOrVal)($,z,"type");return{gen:q,keyword:"type",data:Y,schema:z.type,schemaCode:U,schemaValue:U,parentSchema:z,params:{},it:$}}});var zt=M((qt)=>{Object.defineProperty(qt,"__esModule",{value:!0});qt.assignDefaults=void 0;var Fz=J1(),Xi0=j1();function Vi0($,q){let{properties:Y,items:z}=$.schema;if(q==="object"&&Y)for(let U in Y)$t($,U,Y[U].default);else if(q==="array"&&Array.isArray(z))z.forEach((U,I)=>$t($,I,U.default))}qt.assignDefaults=Vi0;function $t($,q,Y){let{gen:z,compositeRule:U,data:I,opts:J}=$;if(Y===void 0)return;let Q=Fz._`${I}${(0,Fz.getProperty)(q)}`;if(U){(0,Xi0.checkStrictMode)($,`default is ignored for: ${Q}`);return}let K=Fz._`${Q} === undefined`;if(J.useDefaults==="empty")K=Fz._`${K} || ${Q} === null || ${Q} === ""`;z.if(K,Fz._`${Q} = ${(0,Fz.stringify)(Y)}`)}});var D$=M((Jt)=>{Object.defineProperty(Jt,"__esModule",{value:!0});Jt.validateUnion=Jt.validateArray=Jt.usePattern=Jt.callValidateCode=Jt.schemaProperties=Jt.allSchemaProperties=Jt.noPropertyInData=Jt.propertyInData=Jt.isOwnProperty=Jt.hasPropFunc=Jt.reportMissingProp=Jt.checkMissingProp=Jt.checkReportMissingProp=void 0;var L4=J1(),QR=j1(),f3=A9(),wi0=j1();function Li0($,q){let{gen:Y,data:z,it:U}=$;Y.if(HR(Y,z,q,U.opts.ownProperties),()=>{$.setParams({missingProperty:L4._`${q}`},!0),$.error()})}Jt.checkReportMissingProp=Li0;function Fi0({gen:$,data:q,it:{opts:Y}},z,U){return(0,L4.or)(...z.map((I)=>(0,L4.and)(HR($,q,I,Y.ownProperties),L4._`${U} = ${I}`)))}Jt.checkMissingProp=Fi0;function Oi0($,q){$.setParams({missingProperty:q},!0),$.error()}Jt.reportMissingProp=Oi0;function Ut($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:L4._`Object.prototype.hasOwnProperty`})}Jt.hasPropFunc=Ut;function KR($,q,Y){return L4._`${Ut($)}.call(${q}, ${Y})`}Jt.isOwnProperty=KR;function Mi0($,q,Y,z){let U=L4._`${q}${(0,L4.getProperty)(Y)} !== undefined`;return z?L4._`${U} && ${KR($,q,Y)}`:U}Jt.propertyInData=Mi0;function HR($,q,Y,z){let U=L4._`${q}${(0,L4.getProperty)(Y)} === undefined`;return z?(0,L4.or)(U,(0,L4.not)(KR($,q,Y))):U}Jt.noPropertyInData=HR;function It($){return $?Object.keys($).filter((q)=>q!=="__proto__"):[]}Jt.allSchemaProperties=It;function Ni0($,q){return It(q).filter((Y)=>!(0,QR.alwaysValidSchema)($,q[Y]))}Jt.schemaProperties=Ni0;function Di0({schemaCode:$,data:q,it:{gen:Y,topSchemaRef:z,schemaPath:U,errorPath:I},it:J},Q,K,H){let G=H?L4._`${$}, ${q}, ${z}${U}`:q,Z=[[f3.default.instancePath,(0,L4.strConcat)(f3.default.instancePath,I)],[f3.default.parentData,J.parentData],[f3.default.parentDataProperty,J.parentDataProperty],[f3.default.rootData,f3.default.rootData]];if(J.opts.dynamicRef)Z.push([f3.default.dynamicAnchors,f3.default.dynamicAnchors]);let V=L4._`${G}, ${Y.object(...Z)}`;return K!==L4.nil?L4._`${Q}.call(${K}, ${V})`:L4._`${Q}(${V})`}Jt.callValidateCode=Di0;var Ai0=L4._`new RegExp`;function Pi0({gen:$,it:{opts:q}},Y){let z=q.unicodeRegExp?"u":"",{regExp:U}=q.code,I=U(Y,z);return $.scopeValue("pattern",{key:I.toString(),ref:I,code:L4._`${U.code==="new RegExp"?Ai0:(0,wi0.useFunc)($,U)}(${Y}, ${z})`})}Jt.usePattern=Pi0;function Bi0($){let{gen:q,data:Y,keyword:z,it:U}=$,I=q.name("valid");if(U.allErrors){let Q=q.let("valid",!0);return J(()=>q.assign(Q,!1)),Q}return q.var(I,!0),J(()=>q.break()),I;function J(Q){let K=q.const("len",L4._`${Y}.length`);q.forRange("i",0,K,(H)=>{$.subschema({keyword:z,dataProp:H,dataPropType:QR.Type.Num},I),q.if((0,L4.not)(I),Q)})}}Jt.validateArray=Bi0;function Ti0($){let{gen:q,schema:Y,keyword:z,it:U}=$;if(!Array.isArray(Y))throw Error("ajv implementation error");if(Y.some((K)=>(0,QR.alwaysValidSchema)(U,K))&&!U.opts.unevaluated)return;le Line truncated
missingProperty: ${z},
depsCount: ${q},
deps: ${Y}}`};var pd0={keyword:"dependencies",type:"object",schemaType:"object",error:Pe.error,code($){let[q,Y]=dd0($);De($,q),Ae($,Y)}};function dd0({schema:$}){let q={},Y={};for(let z in $){if(z==="__proto__")continue;let U=Array.isArray($[z])?q:Y;U[z]=$[z]}return[q,Y]}function De($,q=$.schema){let{gen:Y,data:z,it:U}=$;if(Object.keys(q).length===0)return;let I=Y.let("missing");for(let J in q){let Q=q[J];if(Q.length===0)continue;let K=(0,IK.propertyInData)(Y,z,J,U.opts.ownProperties);if($.setParams({property:J,depsCount:Q.length,deps:Q.join(", ")}),U.allErrors)Y.if(K,()=>{for(let H of Q)(0,IK.checkReportMissingProp)($,H)});else Y.if(hR._`${K} && (${(0,IK.checkMissingProp)($,Q,I)})`),(0,IK.reportMissingProp)($,I),Y.else()}}Pe.validatePropertyDeps=De;function Ae($,q=$.schema){let{gen:Y,data:z,keyword:U,it:I}=$,J=Y.name("valid");for(let Q in q){if((0,cd0.alwaysValidSchema)(I,q[Q]))continue;Y.if((0,IK.propertyInData)(Y,z,Q,I.opts.ownProperties),()=>{let K=$.subschema({keyword:U,schemaProp:Q},J);$.mergeValidEvaluated(K,J)},()=>Y.var(J,!0)),$.ok(J)}}Pe.validateSchemaDeps=Ae;Pe.default=pd0});var Ce=M((_e)=>{Object.defineProperty(_e,"__esModule",{value:!0});var je=J1(),od0=j1(),rd0={message:"property name must be valid",params:({params:$})=>je._`{propertyName: ${$.propertyName}}`},sd0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:rd0,code($){let{gen:q,schema:Y,data:z,it:U}=$;if((0,od0.alwaysValidSchema)(U,Y))return;let I=q.name("valid");q.forIn("key",z,(J)=>{$.setParams({propertyName:J}),$.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},I),q.if((0,je.not)(I),()=>{if($.error(!0),!U.allErrors)q.break()})}),$.ok(I)}};_e.default=sd0});var gR=M((Re)=>{Object.defineProperty(Re,"__esModule",{value:!0});var Uw=D$(),Y5=J1(),ad0=A9(),Iw=j1(),ed0={message:"must NOT have additional properties",params:({params:$})=>Y5._`{additionalProperty: ${$.additionalProperty}}`},$m0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ed0,code($){let{gen:q,schema:Y,parentSchema:z,data:U,errsCount:I,it:J}=$;if(!I)throw Error("ajv implementation error");let{allErrors:Q,opts:K}=J;if(J.props=!0,K.removeAdditional!=="all"&&(0,Iw.alwaysValidSchema)(J,Y))return;let H=(0,Uw.allSchemaProperties)(z.properties),G=(0,Uw.allSchemaProperties)(z.patternProperties);Z(),$.ok(Y5._`${I} === ${ad0.default.errors}`);function Z(){q.forIn("key",U,(F)=>{if(!H.length&&!G.length)w(F);else q.if(V(F),()=>w(F))})}function V(F){let O;if(H.length>8){let A=(0,Iw.schemaRefOrVal)(J,z.properties,"properties");O=(0,Uw.isOwnProperty)(q,A,F)}else if(H.length)O=(0,Y5.or)(...H.map((A)=>Y5._`${F} === ${A}`));else O=Y5.nil;if(G.length)O=(0,Y5.or)(O,...G.map((A)=>Y5._`${(0,Uw.usePattern)($,A)}.test(${F})`));return(0,Y5.not)(O)}function X(F){q.code(Y5._`delete ${U}[${F}]`)}function w(F){if(K.removeAdditional==="all"||K.removeAdditional&&Y===!1){X(F);return}if(Y===!1){if($.setParams({additionalProperty:F}),$.error(),!Q)q.break();return}if(typeof Y=="object"&&!(0,Iw.alwaysValidSchema)(J,Y)){let O=q.name("valid");if(K.removeAdditional==="failing")L(F,O,!1),q.if((0,Y5.not)(O),()=>{$.reset(),X(F)});else if(L(F,O),!Q)q.if((0,Y5.not)(O),()=>q.break())}}function L(F,O,A){let B={keyword:"additionalProperties",dataProp:F,dataPropType:Iw.Type.Str};if(A===!1)Object.assign(B,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(B,O)}}};Re.default=$m0});var Se=M((ge)=>{Object.defineProperty(ge,"__esModule",{value:!0});var Ym0=lQ(),ve=D$(),SR=j1(),he=gR(),zm0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:q,schema:Y,parentSchema:z,data:U,it:I}=$;if(I.opts.removeAdditional==="all"&&z.additionalProperties===void 0)he.default.code(new Ym0.KeywordCxt(I,he.default,"additionalProperties"));let J=(0,ve.allSchemaProperties)(Y);for(let Z of J)I.definedProperties.add(Z);if(I.opts.unevaluated&&J.length&&I.props!==!0)I.props=SR.mergeEvaluated.props(q,(0,SR.toHash)(J),I.props);let Q=J.filter((Z)=>!(0,SR.alwaysValidSchema)(I,Y[Z]));if(Q.length===0)return;let K=q.name("valid");for(let Z of Q){if(H(Z))G(Z);else{if(q.if((0,ve.propertyInData)(q,U,Z,I.opts.ownProperties)),G(Z),!I.allErrors)q.else().var(K,!0);q.endIf()}$.it.definedProperties.add(Z),$.ok(K)}function H(Z){return I.opts.useDefaults&&!I.compositeRule&&Y[Z].default!==void 0}function G(Z){$.subschema({keyword:"properties",schemaProp:Z,dataProp:Z},K)}}};ge.default=zm0});var fe=M((ue)=>{Object.defineProperty(ue,"__esModule",{value:!0});var ye=D$(),Jw=J1(),xe=j1(),ke=j1(),Im0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:q,schema:Y,data:z,parentSchema:U,it:I}=$,{opts:J}=I,Q=(0,ye.allSchemaProperties)(Y),K=Q.filter((L)=>(0,xe.alwaysValidSchema)(I,Y[L]));if(Q.length===0||K.length===Q.length&&(!I.opts.unevaluated||I.props===!0))return;let H=J.strictSchema&&!J.allowMatchingProperties&&U.properties,G=q.name("valid");if(I.props!==!0&&!(I.props instanceo Line truncated
\x00`,n+=W4(k,2),n+=Q.magic,n+=W4(F,2),n+=W4(O,2),n+=W4(v.crc32,4),n+=W4(v.compressedSize,4),n+=W4(v.uncompressedSize,4),n+=W4(H.length,2),n+=W4(A.length,2);var g=dL.LOCAL_FILE_HEADER+n+H+A,b=dL.CENTRAL_FILE_HEADER+W4(c,2)+n+W4(V.length,2)+"\x00\x00\x00\x00"+W4(R,4)+W4(z,4)+H+A+V;return{fileRecord:g,dirRecord:b}},y11=function($,q,Y,z,U){var I="",J=JU.transformTo("string",U(z));return I=dL.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+W4($,2)+W4($,2)+W4(q,4)+W4(Y,4)+W4(J.length,2)+J,I},x11=function($){var q="";return q=dL.DATA_DESCRIPTOR+W4($.crc32,4)+W4($.compressedSize,4)+W4($.uncompressedSize,4),q};function H5($,q,Y,z){QU.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=q,this.zipPlatform=Y,this.encodeFileName=z,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}JU.inherits(H5,QU);H5.prototype.push=function($){var q=$.meta.percent||0,Y=this.entriesCount,z=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,QU.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:Y?(q+100*(Y-z-1))/Y:100}})};H5.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var q=this.streamFiles&&!$.file.dir;if(q){var Y=b90($,q,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:Y.fileRecord,meta:{percent:0}})}else this.accumulate=!0};H5.prototype.closedSource=function($){this.accumulate=!1;var q=this.streamFiles&&!$.file.dir,Y=b90($,q,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(Y.dirRecord),q)this.push({data:x11($),meta:{percent:100}});else{this.push({data:Y.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};H5.prototype.flush=function(){var $=this.bytesWritten;for(var q=0;q<this.dirRecords.length;q++)this.push({data:this.dirRecords[q],meta:{percent:100}});var Y=this.bytesWritten-$,z=y11(this.dirRecords.length,Y,$,this.zipComment,this.encodeFileName);this.push({data:z,meta:{percent:100}})};H5.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};H5.prototype.registerPrevious=function($){this._sources.push($);var q=this;return $.on("data",function(Y){q.processChunk(Y)}),$.on("end",function(){if(q.closedSource(q.previous.streamInfo),q._sources.length)q.prepareNextSource();else q.end()}),$.on("error",function(Y){q.error(Y)}),this};H5.prototype.resume=function(){if(!QU.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};H5.prototype.error=function($){var q=this._sources;if(!QU.prototype.error.call(this,$))return!1;for(var Y=0;Y<q.length;Y++)try{q[Y].error($)}catch(z){}return!0};H5.prototype.lock=function(){QU.prototype.lock.call(this);var $=this._sources;for(var q=0;q<$.length;q++)$[q].lock()};i90.exports=H5});var c90=M((b11)=>{var k11=Dg(),u11=n90(),f11=function($,q){var Y=$||q,z=k11[Y];if(!z)throw Error(Y+" is not a valid compression method !");return z};b11.generateWorker=function($,q,Y){var z=new u11(q.streamFiles,Y,q.platform,q.encodeFileName),U=0;try{$.forEach(function(I,J){U++;var Q=f11(J.options.compression,q.compression),K=J.options.compressionOptions||q.compressionOptions||{},H=J.dir,G=J.date;J._compressWorker(Q,K).withStreamInfo("file",{name:I,dir:H,date:G,comment:J.comment||"",unixPermissions:J.unixPermissions,dosPermissions:J.dosPermissions}).pipe(z)}),z.entriesCount=U}catch(I){z.error(I)}return z}});var d90=M((C04,p90)=>{var n11=k4(),mL=I$();function QH($,q){mL.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(q)}n11.inherits(QH,mL);QH.prototype._bindStream=function($){var q=this;this._stream=$,$.pause(),$.on("data",function(Y){q.push({data:Y,meta:{percent:0}})}).on("error",function(Y){if(q.isPaused)this.generatedError=Y;else q.error(Y)}).on("end",function(){if(q.isPaused)q._upstreamEnded=!0;else q.end()})};QH.prototype.pause=function(){if(!mL.prototype.pause.call(this))return!1;return this._stream.pause(),!0};QH.prototype.resume=function(){if(!mL.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};p90.exports=QH});var q30=M((R04,$30)=>{var c11=sz(),KH=k4(),r90=I$(),p11=jh(),s90=_h(),m90=jL(),d11=l$0(),m11=c90(),l90=bK(),l11=d90(),t90=function($,q,Y){var z=KH.getTypeOf(q),U,I=KH.extend(Y||{},s90);if(I.date=I.date||new Date,I.compression!==null)I.compression=I.compression.toUpperCase();if(typeof I.unixPermissions==="string")I.unixPermissions=parseInt(I.unixPermissions,8);if(I.unixPermissions&&I.unixPermissions&16384)I.dir=!0;if(I.dosPermissions&&I.dosPermission Line truncated
`)}openNode($,q){let Y=this.tos,z=this._xml;if(Y&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),US(z,q),this.leaf=!0,this.open=!0}addAttribute($,q){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(q!==void 0)d70(this._xml,$,q)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");US(this._xml,$)}writeText($){let q=this._xml;if(this.open)q.push(">"),this.open=!1;this.leaf=!1,q.push(p70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),q=this._xml;if(this.leaf)q.push("/>");else q.push("</"),q.push($),q.push(">");this.open=!1,this.leaf=!1}leafNode($,q,Y){if(this.openNode($,q),Y!==void 0)this.writeText(Y);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("")}}IS.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};m70.exports=IS});var JS=M((u81)=>{var l70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function k81($){if(typeof $==="string")return $;if(l70)return l70.decode($);return $.toString()}u81.bufferToString=k81});var a70=M((r70)=>{Object.defineProperty(r70,"__esModule",{value:!0});r70.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;r70.S=` \r
`;r70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";r70.NAME_CHAR="-"+r70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";r70.CHAR_RE=new RegExp("^["+r70.CHAR+"]$","u");r70.S_RE=new RegExp("^["+r70.S+"]+$","u");r70.NAME_START_CHAR_RE=new RegExp("^["+r70.NAME_START_CHAR+"]$","u");r70.NAME_CHAR_RE=new RegExp("^["+r70.NAME_CHAR+"]$","u");r70.NAME_RE=new RegExp("^["+r70.NAME_START_CHAR+"]["+r70.NAME_CHAR+"]*$","u");r70.NMTOKEN_RE=new RegExp("^["+r70.NAME_CHAR+"]+$","u");var QS=9,KS=10,HS=13,GS=32;r70.S_LIST=[GS,KS,HS,QS];function b81($){return $>=GS&&$<=55295||$===KS||$===HS||$===QS||$>=57344&&$<=65533||$>=65536&&$<=1114111}r70.isChar=b81;function i81($){return $===GS||$===KS||$===HS||$===QS}r70.isS=i81;function o70($){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}r70.isNameStartChar=o70;function n81($){return o70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}r70.isNameChar=n81});var K20=M((U20)=>{Object.defineProperty(U20,"__esModule",{value:!0});U20.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";U20.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";U20.S=` \r
`;U20.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";U20.NAME_CHAR="-"+U20.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";U20.CHAR_RE=new RegExp("^["+U20.CHAR+"]$","u");U20.RESTRICTED_CHAR_RE=new RegExp("^["+U20.RESTRICTED_CHAR+"]$","u");U20.S_RE=new RegExp("^["+U20.S+"]+$","u");U20.NAME_START_CHAR_RE=new RegExp("^["+U20.NAME_START_CHAR+"]$","u");U20.NAME_CHAR_RE=new RegExp("^["+U20.NAME_CHAR+"]$","u");U20.NAME_RE=new RegExp("^["+U20.NAME_START_CHAR+"]["+U20.NAME_CHAR+"]*$","u");U20.NMTOKEN_RE=new RegExp("^["+U20.NAME_CHAR+"]+$","u");var e70=9,$20=10,q20=13,Y20=32;U20.S_LIST=[Y20,$20,q20,e70];function $$1($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}U20.isChar=$$1;function q$1($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}U20.isRestrictedChar=q$1;function Y$1($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}U20.isCharAndNotRestricted=Y$1;function z$1($){return $===Y20||$===$20||$===q20||$===e70}U20.isS=z$1;function z20($){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}U20.isNameStartChar=z20;function U$1($){return z20($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}U20.isNameChar=U$1});var Z20=M((G20)=>{Object.defineProperty(G20,"__esModule",{value:!0});G20.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";G20.NC_NAME_CHAR="-"+G20.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";G20.NC_NAME_START_CHAR_RE=new RegExp("^["+G20.NC_NAME_START_CHAR+"]$","u");G20.NC_NAME_CHAR_RE=new RegExp("^["+G20.NC_NAME_CHAR+"]$","u");G20.NC_NAME_RE=new RegExp("^["+G20.NC_NAME_START_CHAR+"]["+G20.NC_NAME_CHAR+"]*$","u");function H20($){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}G20.isNCNameStartChar=H20;function M$1($){return H20($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}G20.isNCNameChar=M$1});var g20=M((h20)=>{Object.defineProperty(h20,"__esModule",{value:!0});var MU=a70(),T$1=K20(),BS=Z20(),c8=MU.isS,E$1=MU.isChar,DH=MU.isNameStartChar,W20=MU.isNameChar,E20=MU.S_LIST,j$1=MU.NAME_RE,_$1=T$1.isChar,C$1=BS.isNCNameStartChar,R$1=BS.isNCNameChar,v$1=BS.NC_NAME_RE,DF="http://www.w3.org/XML/1998/namespace",OU="http://www.w3.org/2000/xmlns/",h$1={__proto__:null,xml:DF,xmlns:OU},g$1={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},v4=-1,d5=-2,X20=0,S$1=1,WS=2,y$1=3,wU=4,x$1=5,k$1=6,u$1=7,XS=8,f$1=9,b$1=10,i$1=11,n$1=12,P8=13,LF=14,VS=15,c$1=16,wS=17,p$1=18,d$1=19,LS=20,m$1=21,l$1=22,o$1=23,V20=24,FS=25,FF=26,w20=27,r$1=28,s$1=29,L20=30,t$1=31,a$1=32,e2=33,e$1=34,OS=35,AH=36,MS=37,$51=38,F20=39,O20=40,q51=41,M20=42,Y51=43,z51=44,NS=9,Z5=10,DS=13,N20=32,D20=33,j20=34,PH=38,_20=39,OF=45,MF=47,U51=59,G7=60,LU=61,O6=62,p6=63,C20=91,FU=93,A20=133,P20=8232,NF=($)=>$===j20||$===_20,R20=[j20,_20],I51=[...R20,C20,O6],J51=[...R20,G7,FU],Q51=[LU,p6,...E20],K51=[...E20,O6,PH,G7];function PS($,q,Y){switch(q){case"xml":if(Y!==DF)$.fail(`xml prefix must be bound to ${DF}.`);break;case"xmlns":if(Y!==OU)$.fail(`xmlns prefix must be bound to ${OU}.`);break;default:}switch(Y){case OU:$.fail(q===""?`the default namespace may not be set to ${Y}.`:`may not assign a prefix (even "xmlns") to the URI ${OU}.`);break;case DF:switch(q){case"xml":break;case"":$.fail(`the default namespace may not be set to ${Y}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function H51($,q){for(let Y of Object.keys(q))PS($,Y,q[Y])}var G51=($)=>v$1.test($),Z51=($)=>j$1.test($),$q=0,B20=1,AS=2;h20.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var T20={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 v20{constructor($){this.opt=$!==null&&$!==void 0?$:{},this.fragmentOpt=!!this.opt.fragment;let q=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,q){this.nameStartCheck=C$1,this.nameCheck=R$1,this.isName=G51,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},h$1);let Y=this.opt.additionalNamesp Line truncated
`,q=this.i}}captureToChar($){let{i:q}=this,{chunk:Y}=this;while(!0){let z=this.getCode();switch(z){case d5:this.text+=`${Y.slice(q,this.prevI)}
`,q=this.i,z=Z5;break;case v4:return this.text+=Y.slice(q),!1;default:}if(z===$)return this.text+=Y.slice(q,this.prevI),!0}}captureNameChars(){let{chunk:$,i:q}=this;while(!0){let Y=this.getCode();if(Y===v4)return this.name+=$.slice(q),v4;if(!W20(Y))return this.name+=$.slice(q,this.prevI),Y===d5?Z5:Y}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===v4||!c8($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=E$1,this.getCode=this.getCode10;else this.isChar=_$1,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=S$1}sBeginWhitespace(){let $=this.i,q=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(q){case G7:if(this.state=VS,this.text.length!==0)throw Error("no-empty text at start");break;case v4:break;default:this.unget(),this.state=P8,this.xmlDeclPossible=!1}}sDoctype(){var $;let q=this.captureTo(I51);switch(q){case O6:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=P8,this.doctype=!0;break}case v4:break;default:if(this.text+=String.fromCodePoint(q),q===C20)this.state=wU;else if(NF(q))this.state=y$1,this.q=q}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=WS}sDTD(){let $=this.captureTo(J51);if($===v4)return;if(this.text+=String.fromCodePoint($),$===FU)this.state=WS;else if($===G7)this.state=k$1;else if(NF($))this.state=x$1,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=wU,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case D20:this.state=u$1,this.openWakaBang="";break;case p6:this.state=i$1;break;default:this.state=wU}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),q=this.openWakaBang+=$;if(this.text+=$,q!=="-")this.state=q==="--"?XS:wU,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(OF))this.text+="-",this.state=f$1}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===OF?b$1:XS}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===O6)this.state=wU;else this.fail("malformed comment."),this.state=XS}sDTDPI(){if(this.captureToChar(p6))this.text+="?",this.state=n$1}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===O6)this.state=wU}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:q}=this;$:while(!0)switch(this.getCode()){case d5:this.entity+=`${q.slice($,this.prevI)}
`,$=this.i;break;case U51:{let{entityReturnState:Y}=this,z=this.entity+q.slice($,this.prevI);this.state=Y;let U;if(z==="")this.fail("empty entity name."),U="&;";else U=this.parseEntity(z),this.entity="";if(Y!==P8||this.textHandler!==void 0)this.text+=U;break $}case v4:this.entity+=q.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(DH($))this.state=e$1,this.unget(),this.xmlDeclPossible=!1;else switch($){case MF:this.state=Y51,this.xmlDeclPossible=!1;break;case D20:this.state=c$1,this.openWakaBang="",this.xmlDeclPossible=!1;break;case p6:this.state=o$1;break;default:this.fail("disallowed character in tag name"),this.state=P8,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=LS,this.openWakaBang="";break;case"--":this.state=wS,this.openWakaBang="";break;case"DOCTYPE":if(this.state=WS,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(OF))this.state=p$1}sCommentEnding(){var $;let q=this.getCodeNorm();if(q===OF)this.state=d$1,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(q)}`,this.state=wS}sCommentEnded(){let $=this.getCodeNorm();if($!==O6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=wS;else this.state=P8}sCData(){if(this.captureToChar(FU))this.state=m$1}sCDataEnding(){let $=this.getCodeNorm();if($===FU)this.state=l$1;else this.text+=`]${String.fromCodePoint($)}`,this.state=LS}sCDataEnding2(){var $;let q=this.getCodeNorm();switch(q){case O6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=P8;break}case FU:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(q)}`,this.state=LS}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=V20;else if($===p6||c8($))this.fail("processing instruction without a target."),this.state=$===p6?FF:FS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=V20}sPIRest(){let{chunk:$,i:q}=this;while(!0){let Y=this.getCodeNorm();if(Y===v4){this.piTarget+=$.slice(q);return}if(!this.nameCheck(Y)){this.piTarget+=$.slice(q,this.prevI);let z=Y===p6;if(z||c8(Y))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?e2:w20}else this.state=z?FF:FS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(Y);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===p6)this.state=FF;else if(!c8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(p6))this.state=FF}sPIEnding(){var $;let q=this.getCodeNorm();if(q===O6){let{piTarget:Y}=this;if(Y.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:Y,body:this.text}),this.piTarget=this.text="",this.state=P8}else if(q===p6)this.text+="?";else this.text+=`?${String.fromCodePoint(q)}`,this.state=FS;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===p6){this.state=e2;return}if($!==v4)this.state=r$1,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(Q51);if($===p6){this.state=e2,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(c8($)||$===LU))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=$===LU?L20:s$1}sXMLDeclEq(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if($!==LU)this.fail("value required.");this.state=L20}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if(!NF($))this.fail("value must be quoted."),this.q=N20;else this.q=$;this.state=t$1}sXMLDeclValue(){let $=this.captureTo([this.q,p6]);if($===p6){this.state=e2,this.text="",this.fail("XML declaration is incomplete.");return}if($===v4)return;let q=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let Y=q;if(this.xmlDecl.version=Y,!/^1\.[0-9]+$/.test(Y))this.fail("ver Line truncated
`;$=this.i,q=$q;break;case v4:if(z!==void 0)this.text+=Y.slice($);break $;default:q=$q}this.forbiddenState=q}handleTextOutsideRoot(){let{i:$}=this,{chunk:q,textHandler:Y}=this,z=!1;$:while(!0){let U=this.getCode();switch(U){case G7:{if(this.state=VS,Y!==void 0){let{text:I}=this,J=q.slice($,this.prevI);if(I.length!==0)Y(I+J),this.text="";else if(J.length!==0)Y(J)}break $}case PH:if(this.state=LF,this.entityReturnState=P8,Y!==void 0)this.text+=q.slice($,this.prevI);z=!0;break $;case d5:if(Y!==void 0)this.text+=`${q.slice($,this.prevI)}
`;$=this.i;break;case v4:if(Y!==void 0)this.text+=q.slice($);break $;default:if(!c8(U))z=!0}}if(!z)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($,q){var Y;let{prefix:z,local:U}=this.qname($),I={name:$,prefix:z,local:U,value:q};if(this.attribList.push(I),(Y=this.attributeHandler)===null||Y===void 0||Y.call(this,I),z==="xmlns"){let J=q.trim();if(this.currentXMLVersion==="1.0"&&J==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[U]=J,PS(this,U,J)}else if($==="xmlns"){let J=q.trim();this.topNS[""]=J,PS(this,"",J)}}pushAttribPlain($,q){var Y;let z={name:$,value:q};this.attribList.push(z),(Y=this.attributeHandler)===null||Y===void 0||Y.call(this,z)}end(){var $,q;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:Y}=this;while(Y.length>0){let U=Y.pop();this.fail(`unclosed tag: ${U.name}`)}if(this.state!==X20&&this.state!==P8)this.fail("unexpected end.");let{text:z}=this;if(z.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,z),this.text="";return this._closed=!0,(q=this.endHandler)===null||q===void 0||q.call(this),this._init(),this}resolve($){var q,Y;let z=this.topNS[$];if(z!==void 0)return z;let{tags:U}=this;for(let I=U.length-1;I>=0;I--)if(z=U[I].ns[$],z!==void 0)return z;if(z=this.ns[$],z!==void 0)return z;return(Y=(q=this.opt).resolvePrefix)===null||Y===void 0?void 0:Y.call(q,$)}qname($){let q=$.indexOf(":");if(q===-1)return{prefix:"",local:$};let Y=$.slice(q+1),z=$.slice(0,q);if(z===""||Y===""||Y.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:z,local:Y}}processAttribsNS(){var $;let{attribList:q}=this,Y=this.tag;{let{prefix:I,local:J}=this.qname(Y.name);Y.prefix=I,Y.local=J;let Q=Y.uri=($=this.resolve(I))!==null&&$!==void 0?$:"";if(I!==""){if(I==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(Q==="")this.fail(`unbound namespace prefix: ${JSON.stringify(I)}.`),Y.uri=I}}if(q.length===0)return;let{attributes:z}=Y,U=new Set;for(let I of q){let{name:J,prefix:Q,local:K}=I,H,G;if(Q==="")H=J==="xmlns"?OU:"",G=J;else{if(H=this.resolve(Q),H===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(Q)}.`),H=Q;G=`{${H}}${K}`}if(U.has(G))this.fail(`duplicate attribute: ${G}.`);U.add(G),I.uri=H,z[J]=I}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,q=this.tag.attributes;for(let{name:Y,value:z}of $){if(q[Y]!==void 0)this.fail(`duplicate attribute: ${Y}.`);q[Y]=z}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:q}=this,Y=this.tag;Y.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,Y),q.push(Y),this.state=P8,this.name=""}openSelfClosingTag(){var $,q,Y;this.processAttribs();let{tags:z}=this,U=this.tag;if(U.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,U),(q=this.closeTagHandler)===null||q===void 0||q.call(this,U),(this.tag=(Y=z[z.length-1])!==null&&Y!==void 0?Y:null)===null)this.closedRoot=!0;this.state=P8,this.name=""}closeTag(){let{tags:$,name:q}=this;if(this.state=P8,this.name="",q===""){this.fail("weird empty close tag."),this.text+="</>";return}let Y=this.closeTagHandler,z=$.length;while(z-- >0){let U=this.tag=$.pop();if(this.topNS=U.ns,Y===null||Y===void 0||Y(U),U.name===q)break;this.fail("unexpected close tag.")}if(z===0)this.closedRoot=!0;else if(z<0)this.fail(`unmatched closing tag: ${q}.`),this.text+=`</${q}>`}parseEntity($){if($[0]!=="#"){let Y=this.ENTITIES[$];if(Y!==void 0)return Y;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let q=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))q=parseInt($.slice(2),16);else if(/^#[0-9]+$/.test($))q=parseInt($.slice(1),10);if(!this.isChar(q))return this.fail("malformed character entity."),`&${$};`;return String.fromCodePoint(q)}}h20.SaxesParser=v20});var BH=M((X14,S20)=>{var{SaxesParser:V51}=g20(),{PassThrough:w51}=A8(),{bufferToString:L51}=JS();S20.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new w51);let q=new V51,Y;q.on("error",(U)=>{Y=U});let z=[];q.on("opentag",(U)=>z.push({eventType:"opentag",value:U})),q.on("text",(U)=>z.push({eventType:"text",value:U})),q.on("closetag",(U)=>z.push({eventType:"closetag",value:U}));for await(let U of $){if(q.write(L51(U)),Y)throw Y;yield z,z=[]}}});var D0=M((V14,y20)=>{var F51=BH(),O51=c6();class NU{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,q){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof NU)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let q of $)for(let{eventType:Y,value:z}of q)if(Y==="opentag")this.parseOpen(z);else if(Y==="text")this.parseText(z);else if(Y==="closetag"){if(!this.parseClose(z.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&&((q=$.writeHeaders)!==null&&q!==void 0?q:!0),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}ZQ0.FormatterOptions=GQ0});var $O=M((f64,LQ0)=>{var _Y1="[object AsyncFunction]",CY1="[object Function]",RY1="[object GeneratorFunction]",vY1="[object Null]",hY1="[object Proxy]",gY1="[object Undefined]",SY1=typeof global=="object"&&global&&global.Object===Object&&global,yY1=typeof self=="object"&&self&&self.Object===Object&&self,xY1=SY1||yY1||Function("return this")(),VQ0=Object.prototype,kY1=VQ0.hasOwnProperty,wQ0=VQ0.toString,XQ0=xY1.Symbol,Qq=XQ0?XQ0.toStringTag:void 0;function uY1($){if($==null)return $===void 0?gY1:vY1;return Qq&&Qq in Object($)?fY1($):bY1($)}function fY1($){var q=kY1.call($,Qq),Y=$[Qq];try{$[Qq]=void 0;var z=!0}catch(I){}var U=wQ0.call($);if(z)if(q)$[Qq]=Y;else delete $[Qq];return U}function bY1($){return wQ0.call($)}function iY1($){if(!nY1($))return!1;var q=uY1($);return q==CY1||q==RY1||q==_Y1||q==hY1}function nY1($){var q=typeof $;return $!=null&&(q=="object"||q=="function")}LQ0.exports=iY1});var tQ0=M((qO,RU)=>{var cY1=200,ly="__lodash_hash_undefined__",HO=1,_Q0=2,CQ0=9007199254740991,YO="[object Arguments]",by="[object Array]",pY1="[object AsyncFunction]",RQ0="[object Boolean]",vQ0="[object Date]",hQ0="[object Error]",gQ0="[object Function]",dY1="[object GeneratorFunction]",zO="[object Map]",SQ0="[object Number]",mY1="[object Null]",CU="[object Object]",FQ0="[object Promise]",lY1="[object Proxy]",yQ0="[object RegExp]",UO="[object Set]",xQ0="[object String]",oY1="[object Symbol]",rY1="[object Undefined]",iy="[object WeakMap]",kQ0="[object ArrayBuffer]",IO="[object DataView]",sY1="[object Float32Array]",tY1="[object Float64Array]",aY1="[object Int8Array]",eY1="[object Int16Array]",$z1="[object Int32Array]",qz1="[object Uint8Array]",Yz1="[object Uint8ClampedArray]",zz1="[object Uint16Array]",Uz1="[object Uint32Array]",Iz1=/[\\^$.*+?()[\]{}|]/g,Jz1=/^\[object .+?Constructor\]$/,Qz1=/^(?:0|[1-9]\d*)$/,O4={};O4[sY1]=O4[tY1]=O4[aY1]=O4[eY1]=O4[$z1]=O4[qz1]=O4[Yz1]=O4[zz1]=O4[Uz1]=!0;O4[YO]=O4[by]=O4[kQ0]=O4[RQ0]=O4[IO]=O4[vQ0]=O4[hQ0]=O4[gQ0]=O4[zO]=O4[SQ0]=O4[CU]=O4[yQ0]=O4[UO]=O4[xQ0]=O4[iy]=!1;var uQ0=typeof global=="object"&&global&&global.Object===Object&&global,Kz1=typeof self=="object"&&self&&self.Object===Object&&self,b9=uQ0||Kz1||Function("return this")(),fQ0=typeof qO=="object"&&qO&&!qO.nodeType&&qO,OQ0=fQ0&&typeof RU=="object"&&RU&&!RU.nodeType&&RU,bQ0=OQ0&&OQ0.exports===fQ0,ky=bQ0&&uQ0.process,MQ0=function(){try{return ky&&ky.binding&&ky.binding("util")}catch($){}}(),NQ0=MQ0&&MQ0.isTypedArray;function Hz1($,q){var Y=-1,z=$==null?0:$.length,U=0,I=[];while(++Y<z){var J=$[Y];if(q(J,Y,$))I[U++]=J}return I}function Gz1($,q){var Y=-1,z=q.length,U=$.length;while(++Y<z)$[U+Y]=q[Y];return $}function Zz1($,q){var Y=-1,z=$==null?0:$.length;while(++Y<z)if(q($[Y],Y,$))return!0;return!1}function Wz1($,q){var Y=-1,z=Array($);while(++Y<$)z[Y]=q(Y);return z}function Xz1($){return function(q){return $(q)}}function Vz1($,q){return $.has(q)}function wz1($,q){return $==null?void 0:$[q]}function Lz1($){var q=-1,Y=Array($.size);return $.forEach(function(z,U){Y[++q]=[U,z]}),Y}function Fz1($,q){return function(Y){return $(q(Y))}}function Oz1($){var q=-1,Y=Array($.size);return $.forEach(function(z){Y[++q]=z}),Y}var Mz1=Array.prototype,Nz1=Function.prototype,GO=Object.prototype,uy=b9["__core-js_shared__"],iQ0=Nz1.toString,l5=GO.hasOwnProperty,DQ0=function(){var $=/[^.]+$/.exec(uy&&uy.keys&&uy.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),nQ0=GO.toString,Dz1=RegExp("^"+iQ0.call(l5).replace(Iz1,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),AQ0=bQ0?b9.Buffer:void 0,JO=b9.Symbol,PQ0=b9.Uint8Array,cQ0=GO.propertyIsEnumerable,Az1=Mz1.splice,Kq=JO?JO.toStringTag:void 0,BQ0=Object.getOwnPropertySymbols,Pz1=AQ0?AQ0.isBuffer:void 0,Bz1=Fz1(Object.keys,Object),ny=vU(b9,"DataView"),vH=vU(b9,"Map"),cy=vU(b9,"Promise"),py=vU(b9,"Set"),dy=vU(b9,"WeakMap"),hH=vU(Object,"create"),Tz1=Zq(ny),Ez1=Zq(vH),jz1=Zq(cy),_z1=Zq(py),Cz1=Zq(dy),TQ0=JO?JO.prototype:void 0,fy=TQ0?TQ0.valueOf:void 0;function Hq($){var q=-1,Y=$==null?0:$.length;this.clear();while(++q<Y){var z=$[q];this.set(z[0],z[1])}}function Rz1(){this.__data__=hH?hH(null):{},this.size=0}function vz1($){var q=this.has($)&&delete this.__data__[$];return this.size-=q?1:0,q}function hz1($){var q=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(q)}set headers($){this._headers=$}shouldQuote($,q){let Y=q?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(uU1.default(Y))return Y;if(Array.isArray(Y))return Y[$];if(this._headers!==null)return Y[this._headers[$]];return!1}format($,q,Y){let z=`${fU1.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:U}=this;if(U.quote!==""){if(z.indexOf(U.quote)!==-1)return this.quoteField(z.replace(this.REPLACE_REGEXP,U.escapedQuote))}if(z.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(q,Y))return this.quoteField(z);return z}quoteField($){let{quote:q}=this.formatterOptions;return`${q}${$}${q}`}}hU.FieldFormatter=JK0});var ay=M((QK0)=>{Object.defineProperty(QK0,"__esModule",{value:!0});QK0.isSyncTransform=void 0;QK0.isSyncTransform=($)=>$.length===1});var GK0=M((gU)=>{var HK0=gU&&gU.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(gU,"__esModule",{value:!0});gU.RowFormatter=void 0;var iU1=HK0($O()),nU1=HK0(tQ0()),cU1=ty(),pU1=ay();class Wq{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new cU1.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(Wq.isRowHashArray($))return $.map((q)=>q[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(pU1.isSyncTransform($))return(q,Y)=>{let z=null;try{z=$(q)}catch(U){return Y(U)}return Y(null,z)};return(q,Y)=>{$(q,Y)}}set rowTransform($){if(!iU1.default($))throw TypeError("The transform should be a function");this._rowTransform=Wq.createTransform($)}format($,q){this.callTransformer($,(Y,z)=>{if(Y)return q(Y);if(!$)return q(null);let U=[];if(z){let{shouldFormatColumns:I,headers:J}=this.checkHeaders(z);if(this.shouldWriteHeaders&&J&&!this.hasWrittenHeaders)U.push(this.formatColumns(J,!0)),this.hasWrittenHeaders=!0;if(I){let Q=this.gatherColumns(z);U.push(this.formatColumns(Q,!1))}}return q(null,U)})}finish($){let q=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));q.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)q.push(this.formatterOptions.rowDelimiter);return $(null,q)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let q=Wq.gatherHeaders($);if(this.headers=q,this.fieldFormatter.headers=q,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!nU1.default(q,$),headers:q}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((q)=>$[q]);if(Wq.isRowHashArray($))return this.headers.map((q,Y)=>{let z=$[Y];if(z)return z[1];return""});if(Wq.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((q,Y)=>$[Y])}callTransformer($,q){if(!this._rowTransform)return q(null,$);return this._rowTransform($,q)}formatColumns($,q){let Y=$.map((U,I)=>this.fieldFormatter.format(U,I,q)).join(this.formatterOptions.delimiter),{rowCount:z}=this;if(this.rowCount+=1,z)return[this.formatterOptions.rowDelimiter,Y].join("");return Y}}gU.RowFormatter=Wq});var ZK0=M((XO)=>{Object.defineProperty(XO,"__esModule",{value:!0});XO.FieldFormatter=XO.RowFormatter=void 0;var dU1=GK0();Object.defineProperty(XO,"RowFormatter",{enumerable:!0,get:function(){return dU1.RowFormatter}});var mU1=ty();Object.defineProperty(XO,"FieldFormatter",{enumerable:!0,get:function(){return mU1.FieldFormatter}})});var ey=M((XK0)=>{Object.defineProperty(XK0,"__esModule",{value:!0});XK0.CsvFormatterStream=void 0;var oU1=m("stream"),rU1=ZK0();class WK0 extends oU1.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new rU1.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,q,Y){let z=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(U,I)=>{if(U)return z=!0,Y(U);if(I)I.forEach((J)=>{this.push(Buffer.from(J,"utf8"))});return z=!0,Y()})}catch(U){if(z)throw U;Y(U)}}_flush($){this.rowFormatter.finish((q,Y)=>{if(q)return $(q);if(Y)Y.forEach((z)=>{this.push(Buffer.from(z,"utf8"))});return $()})}}XK0.CsvFormatterStream=WK0});var LK0=M((u1)=>{var wK0=u1&&u1.__createBinding||(Object.create?function($,q,Y,z){if(z===void 0)z=Y;Object.defineProperty($,z,{enumerable:!0,get:function(){return q[Y]}})}:function($,q,Y,z){if(z===void 0)z=Y;$[z]=q[Y]}),sU1=u1&&u1.__setModuleDefault||(Object.create?function($,q){Ob Line truncated
`||q===`\r
`}static isTokenCarriageReturn($,q){return $.token===q.carriageReturn}static isTokenComment($,q){return q.supportsComments&&!!$&&$.token===q.comment}static isTokenEscapeCharacter($,q){return $.token===q.escapeChar}static isTokenQuote($,q){return $.token===q.quote}static isTokenDelimiter($,q){return $.token===q.delimiter}}FH0.Token=LH0});var Px=M((DH0)=>{Object.defineProperty(DH0,"__esModule",{value:!0});DH0.Scanner=void 0;var MH0=D7(),UK1=/((?:\r\n)|\n|\r)/;class NH0{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,q=this.parserOptions.NEXT_TOKEN_REGEXP;if($.search(q)===-1)return null;let Y=q.exec($);if(Y==null)return null;let z=Y[1],U=this.cursor+(Y.index||0);return new MH0.Token({token:z,startCursor:U,endCursor:U+z.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:q}=this;if(q<=$)return null;return new MH0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=UK1.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}}DH0.Scanner=NH0});var xO=M((BH0)=>{Object.defineProperty(BH0,"__esModule",{value:!0});BH0.ColumnFormatter=void 0;class PH0{constructor($){if($.trim)this.format=(q)=>q.trim();else if($.ltrim)this.format=(q)=>q.trimLeft();else if($.rtrim)this.format=(q)=>q.trimRight();else this.format=(q)=>q}}BH0.ColumnFormatter=PH0});var Bx=M((_H0)=>{Object.defineProperty(_H0,"__esModule",{value:!0});_H0.NonQuotedColumnParser=void 0;var IK1=xO(),EH0=D7();class jH0{constructor($){this.parserOptions=$,this.columnFormatter=new IK1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:q}=this,Y=[],z=$.nextCharacterToken;for(;z;z=$.nextCharacterToken){if(EH0.Token.isTokenDelimiter(z,q)||EH0.Token.isTokenRowDelimiter(z))break;Y.push(z.token),$.advancePastToken(z)}return this.columnFormatter.format(Y.join(""))}}_H0.NonQuotedColumnParser=jH0});var Tx=M((vH0)=>{Object.defineProperty(vH0,"__esModule",{value:!0});vH0.QuotedColumnParser=void 0;var JK1=xO(),pU=D7();class RH0{constructor($){this.parserOptions=$,this.columnFormatter=new JK1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let q=$.cursor,{foundClosingQuote:Y,col:z}=this.gatherDataBetweenQuotes($);if(!Y){if($.advanceTo(q),!$.hasMoreData)throw Error(`Parse Error: missing closing: '${this.parserOptions.quote||""}' in line: at '${$.lineFromCursor.replace(/[\r\n]/g,"\\n'")}'`);return null}return this.checkForMalformedColumn($),z}gatherDataBetweenQuotes($){let{parserOptions:q}=this,Y=!1,z=!1,U=[],I=$.nextCharacterToken;for(;!z&&I!==null;I=$.nextCharacterToken){let J=pU.Token.isTokenQuote(I,q);if(!Y&&J)Y=!0;else if(Y)if(pU.Token.isTokenEscapeCharacter(I,q)){$.advancePastToken(I);let Q=$.nextCharacterToken;if(Q!==null&&(pU.Token.isTokenQuote(Q,q)||pU.Token.isTokenEscapeCharacter(Q,q)))U.push(Q.token),I=Q;else if(J)z=!0;else U.push(I.token)}else if(J)z=!0;else U.push(I.token);$.advancePastToken(I)}return{col:this.columnFormatter.format(U.join("")),foundClosingQuote:z}}checkForMalformedColumn($){let{parserOptions:q}=this,{nextNonSpaceToken:Y}=$;if(Y){let z=pU.Token.isTokenDelimiter(Y,q),U=pU.Token.isTokenRowDelimiter(Y);if(!(z||U)){let I=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${q.escapedDelimiter}' OR new line got: '${Y.token}'. at '${I}`)}$.advanceToToken(Y)}else if(!$.hasMoreData)$.advancePastLine()}}vH0.QuotedColumnParser=RH0});var xH0=M((SH0)=>{Object.defineProperty(SH0,"__esModule",{value:!0});SH0.ColumnParser=void 0;var QK1=Bx(),KK1=Tx(),HK1=D7();class gH0{constructor($){this.parserOptions=$,this.quotedColumnParser=new KK1.QuotedColumnParser($),this.nonQuotedColumnParser=new QK1.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:q}=$;if(q!==null&&HK1.Token.isTokenQuote(q,this.parserOptions))return $.advanceToToken(q),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}SH0.ColumnParser=gH0});var Ex=M((dU)=>{Object.defineProperty(dU,"__esModule",{value:!0});dU.ColumnFormatter=dU.QuotedColumnParser=dU.NonQuotedColumnParser=dU.ColumnParser=void 0;var GK1=xH0();Object.defineProperty(dU,"ColumnParser",{enumerable:!0,get:function(){return GK1.ColumnParser}});var ZK1=Bx();Object.defineProperty(dU,"NonQuotedColumnParser",{enumerable:!0,get:function(){return ZK1.NonQuotedColumnParser}});var WK1=Tx();Object.defineProperty(dU,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,y,y,X,z);let v=X.type==="*"?ix:X.type==="?"?px:"\\"+X.type;U=!0,z=z.slice(0,X.reStart)+v+"\\("+y}if(B(),I)z+="\\\\";let P=zH1[z.charAt(0)];for(let y=Q.length-1;y>-1;y--){let v=Q[y],k=z.slice(0,v.reStart),R=z.slice(v.reStart,v.reEnd-8),c=z.slice(v.reEnd),n=z.slice(v.reEnd-8,v.reEnd)+c,g=k.split(")").length,b=k.split("(").length-g,i=c;for(let j=0;j<b;j++)i=i.replace(/\)[+*?]?/,"");c=i;let $0=c===""&&q!==nx?"(?:$|\\/)":"";z=k+R+c+$0+n}if(z!==""&&U)z="(?=.)"+z;if(P)z=O()+z;if(q===nx)return[z,U];if(Y.nocase&&!U)U=$.toUpperCase()!==$.toLowerCase();if(!U)return IH1($);let T=Y.nocase?"i":"";try{return Object.assign(new RegExp("^"+z+"$",T),{_glob:$,_src:z})}catch(y){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 q=this.options,Y=q.noglobstar?ix:q.dot?qH1:YH1,z=q.nocase?"i":"",U=$.map((I)=>{return I=I.map((J)=>typeof J==="string"?QH1(J):J===B8?B8:J._src).reduce((J,Q)=>{if(!(J[J.length-1]===B8&&Q===B8))J.push(Q);return J},[]),I.forEach((J,Q)=>{if(J!==B8||I[Q-1]===B8)return;if(Q===0)if(I.length>1)I[Q+1]="(?:\\/|"+Y+"\\/)?"+I[Q+1];else I[Q]=Y;else if(Q===I.length-1)I[Q-1]+="(?:\\/|"+Y+")?";else I[Q-1]+="(?:\\/|\\/"+Y+"\\/)"+I[Q+1],I[Q+1]=B8}),I.filter((J)=>J!==B8).join("/")}).join("|");if(U="^(?:"+U+")$",this.negate)U="^(?!"+U+").*$";try{this.regexp=new RegExp(U,z)}catch(I){this.regexp=!1}return this.regexp}match($,q=this.partial){if(this.debug("match",$,this.pattern),this.comment)return!1;if(this.empty)return $==="";if($==="/"&&q)return!0;let Y=this.options;if(cx.sep!=="/")$=$.split(cx.sep).join("/");$=$.split(CG0),this.debug(this.pattern,"split",$);let z=this.set;this.debug(this.pattern,"set",z);let U;for(let I=$.length-1;I>=0;I--)if(U=$[I],U)break;for(let I=0;I<z.length;I++){let J=z[I],Q=$;if(Y.matchBase&&J.length===1)Q=[U];if(this.matchOne(Q,J,q)){if(Y.flipNegate)return!0;return!this.negate}}if(Y.flipNegate)return!1;return this.negate}static defaults($){return K$.defaults($).Minimatch}}K$.Minimatch=bH});var kG0=M((o84,xG0)=>{xG0.exports=yG0;var lx=m("fs"),{EventEmitter:HH1}=m("events"),{Minimatch:mx}=hG0(),{resolve:GH1}=m("path");function ZH1($,q){return new Promise((Y,z)=>{lx.readdir($,{withFileTypes:!0},(U,I)=>{if(U)switch(U.code){case"ENOTDIR":if(q)z(U);else Y([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":Y([]);break;case"ELOOP":default:z(U);break}else Y(I)})})}function gG0($,q){return new Promise((Y,z)=>{(q?lx.stat:lx.lstat)($,(I,J)=>{if(I)switch(I.code){case"ENOENT":if(q)Y(gG0($,!1));else Y(null);break;default:Y(null);break}else Y(J)})})}async function*SG0($,q,Y,z,U,I){let J=await ZH1(q+$,I);for(let Q of J){let K=Q.name;if(K===void 0)K=Q,z=!0;let H=$+"/"+K,G=H.slice(1),Z=q+"/"+G,V=null;if(z||Y)V=await gG0(Z,Y);if(!V&&Q.name!==void 0)V=Q;if(V===null)V={isDirectory:()=>!1};if(V.isDirectory()){if(!U(G))yield{relative:G,absolute:Z,stats:V},yield*SG0(H,q,Y,z,U,!1)}else yield{relative:G,absolute:Z,stats:V}}}async function*WH1($,q,Y,z){yield*SG0("",$,q,Y,z,!0)}function XH1($){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 ox extends HH1{constructor($,q,Y){super();if(typeof q==="function")Y=q,q=null;if(this.options=XH1(q||{}),this.matchers=[],this.options.pattern){let z=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=z.map((U)=>new mx(U,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let z=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=z.map((U)=>new mx(U,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let z=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=z.map((U)=>new mx(U,{dot:!0}))}if(this.iterator=WH1(GH1($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,Y)this._matches=[],this.on("match",(z)=>this._matches.push(this.options.absolute?z.absolute:z.relative)),this.on("error",(z)=>Y(z)),this.on("end",()=>Y(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((q)=>q.match($))}_fileMatches($,q){let Y=$+(q?"/":"");return(this.matchers.length===0||this.matchers.some((z)=>z.match(Y)))&&!this.ignoreMatchers.some((z)=>z.match(Y))&&(!this.options.nodir||!q)}_next(){if(!this.paused&&!this.aborted)this.iterator.next().then(($)=>{if(!$.done){let q=$.value.stats.isDirectory();if(this._fileMatches($.value.relative,q)){let Y=$.value.relative,z=$.value.absolute;if(this.options.mark&&q)Y+="/",z+="/";if(this.options.stat)this.emit("match",{relative:Y,absolute:z,stat:$.value.stats});else this.emit("match",{relative:Y,ab Line truncated
`,f);f=U0===-1?C.length:U0}else if(s!==-1&&C[f]==="/"&&C[f+1]==="*"){let U0=C.indexOf("*/",f);if(U0!==-1)f=U0+2,s=C.indexOf("*/",f);else S+=C[f],f++}else S+=C[f],f++;return S}function $1(C){let S=b1(C.toString()),f=S.match(R1);if(!f)f=S.match(a0);if(!f)throw Error(`could not parse args in autoInject
Source:
`+C);let[,d]=y;return d.replace(/\s/g,"").split(b$).map((I0)=>I0.replace($$,"").trim())}function N$(B,C){var y={};return Object.keys(B).forEach((d)=>{var I0=B[d],Y0,w0=V(I0),H0=!w0&&I0.length===1||w0&&I0.length===0;if(Array.isArray(I0))Y0=[...I0],I0=Y0.pop(),y[d]=Y0.concat(Y0.length>0?L0:I0);else if(H0)y[d]=I0;else{if(Y0=n$(I0),I0.length===0&&!w0&&Y0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!w0)Y0.pop();y[d]=Y0.concat(L0)}function L0(u0,Z1){var P1=Y0.map((D1)=>u0[D1]);P1.push(Z1),D(I0)(...P1)}}),W1(y,C)}class a7{constructor(){this.head=this.tail=null,this.length=0}removeLink(B){if(B.prev)B.prev.next=B.next;else this.head=B.next;if(B.next)B.next.prev=B.prev;else this.tail=B.prev;return B.prev=B.next=null,this.length-=1,B}empty(){while(this.head)this.shift();return this}insertAfter(B,C){if(C.prev=B,C.next=B.next,B.next)B.next.prev=C;else this.tail=C;B.next=C,this.length+=1}insertBefore(B,C){if(C.prev=B.prev,C.next=B,B.prev)B.prev.next=C;else this.head=C;B.prev=C,this.length+=1}unshift(B){if(this.head)this.insertBefore(this.head,B);else M$(this,B)}push(B){if(this.tail)this.insertAfter(this.tail,B);else M$(this,B)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var B=this.head;while(B)yield B.data,B=B.next}remove(B){var C=this.head;while(C){var{next:y}=C;if(B(C))this.removeLink(C);C=y}return this}}function M$(B,C){B.length=1,B.head=B.tail=C}function N9(B,C,y){if(C==null)C=1;else if(C===0)throw RangeError("Concurrency must not be zero");var d=D(B),I0=0,Y0=[];let w0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function H0(b0,C0){w0[b0].push(C0)}function L0(b0,C0){let n0=(...O1)=>{u0(b0,n0),C0(...O1)};w0[b0].push(n0)}function u0(b0,C0){if(!b0)return Object.keys(w0).forEach((n0)=>w0[n0]=[]);if(!C0)return w0[b0]=[];w0[b0]=w0[b0].filter((n0)=>n0!==C0)}function Z1(b0,...C0){w0[b0].forEach((n0)=>n0(...C0))}var P1=!1;function D1(b0,C0,n0,O1){if(O1!=null&&typeof O1!=="function")throw Error("task callback must be a function");T1.started=!0;var H4,a4;function p$(e7,...AY){if(e7)return n0?a4(e7):H4();if(AY.length<=1)return H4(AY[0]);H4(AY)}var lI=T1._createTaskItem(b0,n0?p$:O1||p$);if(C0)T1._tasks.unshift(lI);else T1._tasks.push(lI);if(!P1)P1=!0,w(()=>{P1=!1,T1.process()});if(n0||!O1)return new Promise((e7,AY)=>{H4=e7,a4=AY})}function i$(b0){return function(C0,...n0){I0-=1;for(var O1=0,H4=b0.length;O1<H4;O1++){var a4=b0[O1],p$=Y0.indexOf(a4);if(p$===0)Y0.shift();else if(p$>0)Y0.splice(p$,1);if(a4.callback(C0,...n0),C0!=null)Z1("error",C0,a4.data)}if(I0<=T1.concurrency-T1.buffer)Z1("unsaturated");if(T1.idle())Z1("drain");T1.process()}}function mI(b0){if(b0.length===0&&T1.idle())return w(()=>Z1("drain")),!0;return!1}let s7=(b0)=>(C0)=>{if(!C0)return new Promise((n0,O1)=>{L0(b0,(H4,a4)=>{if(H4)return O1(H4);n0(a4)})});u0(b0),H0(b0,C0)};var MY=!1,T1={_tasks:new a7,_createTaskItem(b0,C0){return{data:b0,callback:C0}},*[Symbol.iterator](){yield*T1._tasks[Symbol.iterator]()},concurrency:C,payload:y,buffer:C/4,started:!1,paused:!1,push(b0,C0){if(Array.isArray(b0)){if(mI(b0))return;return b0.map((n0)=>D1(n0,!1,!1,C0))}return D1(b0,!1,!1,C0)},pushAsync(b0,C0){if(Array.isArray(b0)){if(mI(b0))return;return b0.map((n0)=>D1(n0,!1,!0,C0))}return D1(b0,!1,!0,C0)},kill(){u0(),T1._tasks.empty()},unshift(b0,C0){if(Array.isArray(b0)){if(mI(b0))return;return b0.map((n0)=>D1(n0,!0,!1,C0))}return D1(b0,!0,!1,C0)},unshiftAsync(b0,C0){if(Array.isArray(b0)){if(mI(b0))return;return b0.map((n0)=>D1(n0,!0,!0,C0))}return D1(b0,!0,!0,C0)},remove(b0){T1._tasks.remove(b0)},process(){if(MY)return;MY=!0;while(!T1.paused&&I0<T1.concurrency&&T1._tasks.length){var b0=[],C0=[],n0=T1._tasks.length;if(T1.payload)n0=Math.min(n0,T1.payload);for(var O1=0;O1<n0;O1++){var H4=T1._tasks.shift();b0.push(H4),Y0.push(H4),C0.push(H4.data)}if(I0+=1,T1._tasks.length===0)Z1("empty");if(I0===T1.concurrency)Z1("saturated");var a4=g(i$(b0));d(C0,a4)}MY=!1},length(){return T1._tasks.length},running(){return I0},workersList(){return Y0},idle(){return T1._tasks.length+I0===0},pause(){T1.paused=!0},resume(){if(T1.paused===!1)return;T1.paused=!1,w(T1.process)}};return Object.defineProperties(T1,{saturated:{writable:!1,value:s7("saturated")},unsaturated:{writable:!1,value:s7("unsaturated")},empty:{writable:!1,value:s7("empty")},drain:{writable:!1,value:s7("drain")},error:{writable:!1,value:s7("error")}}),T1}function R0(B,C){return N9(B,1,C)}function a(B,C,y){return N9(B,C,y)}function N(B,C,y,d){d=x(d);var I0=D(y);return S0(B,(Y0,w0,H0)=>{I0(C,Y0,(L0,u0)=>{C=u0,H0(L0)})},(Y0)=>d(Y0,C))}var P=O(N,4);function S(...B){var C=B.map(D);return function(...y){var d=this,I0=y[y.length-1];if(typeof I0=="function")y.pop();else I0=I1();return P(C,y,(Y0,w0,H0)=>{w0.apply(d,Y0.concat((L0,...u0)=>{H0(L0,u0)}))},(Y0,w0)=>I0(Y0,...w0)),I0[v0]}}function i(...B){return S(...B.reverse())}function s(B,C,y,d){return T(p(C),B,y,d)}var o=O(s,4);function $0 Line truncated
GFS4: `),console.error($)};if(!F4[O6]){if(oC=global[O6]||[],LY0(F4,oC),F4.close=function($){function I(z,q){return $.call(F4,z,function(U){if(!U)XY0();if(typeof q==="function")q.apply(this,arguments)})}return Object.defineProperty(I,sX,{value:$}),I}(F4.close),F4.closeSync=function($){function I(z){$.apply(F4,arguments),XY0()}return Object.defineProperty(I,sX,{value:$}),I}(F4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){UI(F4[O6]),t("assert").equal(F4[O6].length,0)})}var oC;if(!global[O6])LY0(global,F4[O6]);aC.exports=rC(i81(F4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!F4.__patched)aC.exports=rC(F4),F4.__patched=!0;function rC($){b81($),$.gracefulify=rC,$.createReadStream=v,$.createWriteStream=x;var I=$.readFile;$.readFile=z;function z(E,f,n){if(typeof f==="function")n=f,f=null;return g(E,f,n);function g(b,p,q0,R){return I(b,p,function(u){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))wU([g,[b,p,q0],u,R||Date.now(),Date.now()]);else if(typeof q0==="function")q0.apply(this,arguments)})}}var q=$.writeFile;$.writeFile=U;function U(E,f,n,g){if(typeof n==="function")g=n,n=null;return b(E,f,n,g);function b(p,q0,R,u,c){return q(p,q0,R,function(m){if(m&&(m.code==="EMFILE"||m.code==="ENFILE"))wU([b,[p,q0,R,u],m,c||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var Y=$.appendFile;if(Y)$.appendFile=J;function J(E,f,n,g){if(typeof n==="function")g=n,n=null;return b(E,f,n,g);function b(p,q0,R,u,c){return Y(p,q0,R,function(m){if(m&&(m.code==="EMFILE"||m.code==="ENFILE"))wU([b,[p,q0,R,u],m,c||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var Q=$.copyFile;if(Q)$.copyFile=K;function K(E,f,n,g){if(typeof n==="function")g=n,n=0;return b(E,f,n,g);function b(p,q0,R,u,c){return Q(p,q0,R,function(m){if(m&&(m.code==="EMFILE"||m.code==="ENFILE"))wU([b,[p,q0,R,u],m,c||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(E,f,n){if(typeof f==="function")n=f,f=null;var g=G.test(process.version)?function(q0,R,u,c){return w(q0,b(q0,R,u,c))}:function(q0,R,u,c){return w(q0,R,b(q0,R,u,c))};return g(E,f,n);function b(p,q0,R,u){return function(c,m){if(c&&(c.code==="EMFILE"||c.code==="ENFILE"))wU([g,[p,q0,R],c,u||Date.now(),Date.now()]);else{if(m&&m.sort)m.sort();if(typeof R==="function")R.call(this,c,m)}}}}if(process.version.substr(0,4)==="v0.8"){var W=n81($);O=W.ReadStream,T=W.WriteStream}var V=$.ReadStream;if(V)O.prototype=Object.create(V.prototype),O.prototype.open=A;var X=$.WriteStream;if(X)T.prototype=Object.create(X.prototype),T.prototype.open=M;Object.defineProperty($,"ReadStream",{get:function(){return O},set:function(E){O=E},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return T},set:function(E){T=E},enumerable:!0,configurable:!0});var L=O;Object.defineProperty($,"FileReadStream",{get:function(){return L},set:function(E){L=E},enumerable:!0,configurable:!0});var D=T;Object.defineProperty($,"FileWriteStream",{get:function(){return D},set:function(E){D=E},enumerable:!0,configurable:!0});function O(E,f){if(this instanceof O)return V.apply(this,arguments),this;else return O.apply(Object.create(O.prototype),arguments)}function A(){var E=this;k(E.path,E.flags,E.mode,function(f,n){if(f){if(E.autoClose)E.destroy();E.emit("error",f)}else E.fd=n,E.emit("open",n),E.read()})}function T(E,f){if(this instanceof T)return X.apply(this,arguments),this;else return T.apply(Object.create(T.prototype),arguments)}function M(){var E=this;k(E.path,E.flags,E.mode,function(f,n){if(f)E.destroy(),E.emit("error",f);else E.fd=n,E.emit("open",n)})}function v(E,f){return new $.ReadStream(E,f)}function x(E,f){return new $.WriteStream(E,f)}var h=$.open;$.open=k;function k(E,f,n,g){if(typeof n==="function")g=n,n=null;return b(E,f,n,g);function b(p,q0,R,u,c){return h(p,q0,R,function(m,e){if(m&&(m.code==="EMFILE"||m.code==="ENFILE"))wU([b,[p,q0,R,u],m,c||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}return $}function wU($){UI("ENQUEUE",$[0].name,$[1]),F4[O6].push($),tC()}var aX;function XY0(){var $=Date.now();for(var I=0;I<F4[O6].length;++I)if(F4[O6][I].length>2)F4[O6][I][3]=$,F4[O6][I][4]=$;tC()}function tC(){if(clearTimeout(aX),aX=void 0,F4[O6].length===0)return;var $=F4[O6].shift(),I=$[0],z=$[1],q=$[2],U=$[3],Y=$[4];if(U===void 0)UI("RETRY",I.name,z),I.apply(null,z);else if(Date.now()-U>=60000){UI("TIMEOUT",I.name,z);var J=z.pop();if(typeof J==="function")J.call(null,q)}else{var Q=Date.now()-Y,K=Math.max(Y-U,1),w=Math.min(K*1.2,100);if(Q>=w)UI("RETRY",I.name,z),I.apply(null,z.concat([U]));else F4[O6].push($)}if(aX===void 0)aX=setTimeout(tC,0)}});var OY0=F((uh1,sC)=>{function c81($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var DY0=C4().Buffer,v2=t("util");function d81($,I,z){$.copy(I,z)}sC.exports=function(){function $(){c81(this,$),this.head=null,this.tail=null,thi Line truncated
`+S);let[,s]=f;return s.replace(/\s/g,"").split(r1).map((U0)=>U0.replace(F1,"").trim())}function U6(C,S){var f={};return Object.keys(C).forEach((s)=>{var U0=C[s],J0,Z0=X(U0),X0=!Z0&&U0.length===1||Z0&&U0.length===0;if(Array.isArray(U0))J0=[...U0],U0=J0.pop(),f[s]=J0.concat(J0.length>0?M0:U0);else if(X0)f[s]=U0;else{if(J0=$1(U0),U0.length===0&&!Z0&&J0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!Z0)J0.pop();f[s]=J0.concat(M0)}function M0(k0,A1){var S1=J0.map((T1)=>k0[T1]);S1.push(A1),F(U0)(...S1)}}),c0(f,S)}class a8{constructor(){this.head=this.tail=null,this.length=0}removeLink(C){if(C.prev)C.prev.next=C.next;else this.head=C.next;if(C.next)C.next.prev=C.prev;else this.tail=C.prev;return C.prev=C.next=null,this.length-=1,C}empty(){while(this.head)this.shift();return this}insertAfter(C,S){if(S.prev=C,S.next=C.next,C.next)C.next.prev=S;else this.tail=S;C.next=S,this.length+=1}insertBefore(C,S){if(S.prev=C.prev,S.next=C,C.prev)C.prev.next=S;else this.head=S;C.prev=S,this.length+=1}unshift(C){if(this.head)this.insertBefore(this.head,C);else I6(this,C)}push(C){if(this.tail)this.insertAfter(this.tail,C);else I6(this,C)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var C=this.head;while(C)yield C.data,C=C.next}remove(C){var S=this.head;while(S){var{next:f}=S;if(C(S))this.removeLink(S);S=f}return this}}function I6(C,S){C.length=1,C.head=C.tail=S}function e8(C,S,f){if(S==null)S=1;else if(S===0)throw RangeError("Concurrency must not be zero");var s=F(C),U0=0,J0=[];let Z0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function X0(p0,S0){Z0[p0].push(S0)}function M0(p0,S0){let d0=(...E1)=>{k0(p0,d0),S0(...E1)};Z0[p0].push(d0)}function k0(p0,S0){if(!p0)return Object.keys(Z0).forEach((d0)=>Z0[d0]=[]);if(!S0)return Z0[p0]=[];Z0[p0]=Z0[p0].filter((d0)=>d0!==S0)}function A1(p0,...S0){Z0[p0].forEach((d0)=>d0(...S0))}var S1=!1;function T1(p0,S0,d0,E1){if(E1!=null&&typeof E1!=="function")throw Error("task callback must be a function");y1.started=!0;var C4,T6;function F$(X2,...xJ){if(X2)return d0?T6(X2):C4();if(xJ.length<=1)return C4(xJ[0]);C4(xJ)}var CY=y1._createTaskItem(p0,d0?F$:E1||F$);if(S0)y1._tasks.unshift(CY);else y1._tasks.push(CY);if(!S1)S1=!0,H(()=>{S1=!1,y1.process()});if(d0||!E1)return new Promise((X2,xJ)=>{C4=X2,T6=xJ})}function L$(p0){return function(S0,...d0){U0-=1;for(var E1=0,C4=p0.length;E1<C4;E1++){var T6=p0[E1],F$=J0.indexOf(T6);if(F$===0)J0.shift();else if(F$>0)J0.splice(F$,1);if(T6.callback(S0,...d0),S0!=null)A1("error",S0,T6.data)}if(U0<=y1.concurrency-y1.buffer)A1("unsaturated");if(y1.idle())A1("drain");y1.process()}}function _Y(p0){if(p0.length===0&&y1.idle())return H(()=>A1("drain")),!0;return!1}let W2=(p0)=>(S0)=>{if(!S0)return new Promise((d0,E1)=>{M0(p0,(C4,T6)=>{if(C4)return E1(C4);d0(T6)})});k0(p0),X0(p0,S0)};var yJ=!1,y1={_tasks:new a8,_createTaskItem(p0,S0){return{data:p0,callback:S0}},*[Symbol.iterator](){yield*y1._tasks[Symbol.iterator]()},concurrency:S,payload:f,buffer:S/4,started:!1,paused:!1,push(p0,S0){if(Array.isArray(p0)){if(_Y(p0))return;return p0.map((d0)=>T1(d0,!1,!1,S0))}return T1(p0,!1,!1,S0)},pushAsync(p0,S0){if(Array.isArray(p0)){if(_Y(p0))return;return p0.map((d0)=>T1(d0,!1,!0,S0))}return T1(p0,!1,!0,S0)},kill(){k0(),y1._tasks.empty()},unshift(p0,S0){if(Array.isArray(p0)){if(_Y(p0))return;return p0.map((d0)=>T1(d0,!0,!1,S0))}return T1(p0,!0,!1,S0)},unshiftAsync(p0,S0){if(Array.isArray(p0)){if(_Y(p0))return;return p0.map((d0)=>T1(d0,!0,!0,S0))}return T1(p0,!0,!0,S0)},remove(p0){y1._tasks.remove(p0)},process(){if(yJ)return;yJ=!0;while(!y1.paused&&U0<y1.concurrency&&y1._tasks.length){var p0=[],S0=[],d0=y1._tasks.length;if(y1.payload)d0=Math.min(d0,y1.payload);for(var E1=0;E1<d0;E1++){var C4=y1._tasks.shift();p0.push(C4),J0.push(C4),S0.push(C4.data)}if(U0+=1,y1._tasks.length===0)A1("empty");if(U0===y1.concurrency)A1("saturated");var T6=g(L$(p0));s(S0,T6)}yJ=!1},length(){return y1._tasks.length},running(){return U0},workersList(){return J0},idle(){return y1._tasks.length+U0===0},pause(){y1.paused=!0},resume(){if(y1.paused===!1)return;y1.paused=!1,H(y1.process)}};return Object.defineProperties(y1,{saturated:{writable:!1,value:W2("saturated")},unsaturated:{writable:!1,value:W2("unsaturated")},empty:{writable:!1,value:W2("empty")},drain:{writable:!1,value:W2("drain")},error:{writable:!1,value:W2("error")}}),y1}function L0(C,S){return e8(C,1,S)}function o(C,S,f){return e8(C,S,f)}function N(C,S,f,s){s=y(s);var U0=F(f);return R0(C,(J0,Z0,X0)=>{U0(S,J0,(M0,k0)=>{S=k0,X0(M0)})},(J0)=>s(J0,S))}var D=O(N,4);function h(...C){var S=C.map(F);return function(...f){var s=this,U0=f[f.length-1];if(typeof U0=="function")f.pop();else U0=f0();return D(S,f,(J0,Z0,X0)=>{Z0.apply(s,J0.concat((M0,...k0)=>{X0(M0,k0)}))},(J0,Z0)=>U0(J0,...Z0)),U0[v0]}}function x(...C){return h(...C.reverse())}function q0(C,S,f,s){return B(i(S),C,f,s)}var r=O(q0,4);function Line truncated
GFS4: `),console.error($)};if(!f4[m6]){if(sx=global[m6]||[],lG0(f4,sx),f4.close=function($){function q(Y,z){return $.call(f4,Y,function(U){if(!U)mG0();if(typeof z==="function")z.apply(this,arguments)})}return Object.defineProperty(q,mO,{value:$}),q}(f4.close),f4.closeSync=function($){function q(Y){$.apply(f4,arguments),mG0()}return Object.defineProperty(q,mO,{value:$}),q}(f4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){Lq(f4[m6]),m("assert").equal(f4[m6].length,0)})}var sx;if(!global[m6])lG0(global,f4[m6]);ex.exports=tx(AH1(f4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!f4.__patched)ex.exports=tx(f4),f4.__patched=!0;function tx($){NH1($),$.gracefulify=tx,$.createReadStream=T,$.createWriteStream=y;var q=$.readFile;$.readFile=Y;function Y(R,c,n){if(typeof c==="function")n=c,c=null;return g(R,c,n);function g(b,i,$0,j){return q(b,i,function(u){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))oU([g,[b,i,$0],u,j||Date.now(),Date.now()]);else if(typeof $0==="function")$0.apply(this,arguments)})}}var z=$.writeFile;$.writeFile=U;function U(R,c,n,g){if(typeof n==="function")g=n,n=null;return b(R,c,n,g);function b(i,$0,j,u,p){return z(i,$0,j,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oU([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var I=$.appendFile;if(I)$.appendFile=J;function J(R,c,n,g){if(typeof n==="function")g=n,n=null;return b(R,c,n,g);function b(i,$0,j,u,p){return I(i,$0,j,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oU([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var Q=$.copyFile;if(Q)$.copyFile=K;function K(R,c,n,g){if(typeof n==="function")g=n,n=0;return b(R,c,n,g);function b(i,$0,j,u,p){return Q(i,$0,j,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oU([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var H=$.readdir;$.readdir=Z;var G=/^v[0-5]\./;function Z(R,c,n){if(typeof c==="function")n=c,c=null;var g=G.test(process.version)?function($0,j,u,p){return H($0,b($0,j,u,p))}:function($0,j,u,p){return H($0,j,b($0,j,u,p))};return g(R,c,n);function b(i,$0,j,u){return function(p,d){if(p&&(p.code==="EMFILE"||p.code==="ENFILE"))oU([g,[i,$0,j],p,u||Date.now(),Date.now()]);else{if(d&&d.sort)d.sort();if(typeof j==="function")j.call(this,p,d)}}}}if(process.version.substr(0,4)==="v0.8"){var V=DH1($);O=V.ReadStream,B=V.WriteStream}var X=$.ReadStream;if(X)O.prototype=Object.create(X.prototype),O.prototype.open=A;var w=$.WriteStream;if(w)B.prototype=Object.create(w.prototype),B.prototype.open=P;Object.defineProperty($,"ReadStream",{get:function(){return O},set:function(R){O=R},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return B},set:function(R){B=R},enumerable:!0,configurable:!0});var L=O;Object.defineProperty($,"FileReadStream",{get:function(){return L},set:function(R){L=R},enumerable:!0,configurable:!0});var F=B;Object.defineProperty($,"FileWriteStream",{get:function(){return F},set:function(R){F=R},enumerable:!0,configurable:!0});function O(R,c){if(this instanceof O)return X.apply(this,arguments),this;else return O.apply(Object.create(O.prototype),arguments)}function A(){var R=this;k(R.path,R.flags,R.mode,function(c,n){if(c){if(R.autoClose)R.destroy();R.emit("error",c)}else R.fd=n,R.emit("open",n),R.read()})}function B(R,c){if(this instanceof B)return w.apply(this,arguments),this;else return B.apply(Object.create(B.prototype),arguments)}function P(){var R=this;k(R.path,R.flags,R.mode,function(c,n){if(c)R.destroy(),R.emit("error",c);else R.fd=n,R.emit("open",n)})}function T(R,c){return new $.ReadStream(R,c)}function y(R,c){return new $.WriteStream(R,c)}var v=$.open;$.open=k;function k(R,c,n,g){if(typeof n==="function")g=n,n=null;return b(R,c,n,g);function b(i,$0,j,u,p){return v(i,$0,j,function(d,Y0){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oU([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}return $}function oU($){Lq("ENQUEUE",$[0].name,$[1]),f4[m6].push($),ax()}var dO;function mG0(){var $=Date.now();for(var q=0;q<f4[m6].length;++q)if(f4[m6][q].length>2)f4[m6][q][3]=$,f4[m6][q][4]=$;ax()}function ax(){if(clearTimeout(dO),dO=void 0,f4[m6].length===0)return;var $=f4[m6].shift(),q=$[0],Y=$[1],z=$[2],U=$[3],I=$[4];if(U===void 0)Lq("RETRY",q.name,Y),q.apply(null,Y);else if(Date.now()-U>=60000){Lq("TIMEOUT",q.name,Y);var J=Y.pop();if(typeof J==="function")J.call(null,z)}else{var Q=Date.now()-I,K=Math.max(I-U,1),H=Math.min(K*1.2,100);if(Q>=H)Lq("RETRY",q.name,Y),q.apply(null,Y.concat([U]));else f4[m6].push($)}if(dO===void 0)dO=setTimeout(ax,0)}});var rG0=M((e84,$k)=>{function BH1($,q){if(!($ instanceof q))throw TypeError("Cannot call a class as a function")}var oG0=$6().Buffer,iH=m("util");function TH1($,q,Y){$.copy(q,Y)}$k.exports=function(){function $(){BH1(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.
*/UJ0.exports=function($,I){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var z=$.length;if(z<=1)return $;var q="";if(z>4&&$[3]==="\\"){var U=$[2];if((U==="?"||U===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),q="//"}var Y=$.split(/[/\\]+/);if(I!==!1&&Y[Y.length-1]==="")Y.pop();return q+Y.join("/")}});var Oh=F((oh1,HJ0)=>{var JJ0=9007199254740991,a51="[object Arguments]",s51="[object Function]",e51="[object GeneratorFunction]",$91=/^(?:0|[1-9]\d*)$/;function QJ0($,I,z){switch(z.length){case 0:return $.call(I);case 1:return $.call(I,z[0]);case 2:return $.call(I,z[0],z[1]);case 3:return $.call(I,z[0],z[1],z[2])}return $.apply(I,z)}function I91($,I){var z=-1,q=Array($);while(++z<$)q[z]=I(z);return q}var x2=Object.prototype,k2=x2.hasOwnProperty,KJ0=x2.toString,z91=x2.propertyIsEnumerable,YJ0=Math.max;function q91($,I){var z=V91($)||W91($)?I91($.length,String):[],q=z.length,U=!!q;for(var Y in $)if((I||k2.call($,Y))&&!(U&&(Y=="length"||GJ0(Y,q))))z.push(Y);return z}function U91($,I,z,q){if($===void 0||Xh($,x2[z])&&!k2.call(q,z))return I;return $}function Y91($,I,z){var q=$[I];if(!(k2.call($,I)&&Xh(q,z))||z===void 0&&!(I in $))$[I]=z}function J91($){if(!Dh($))return H91($);var I=G91($),z=[];for(var q in $)if(!(q=="constructor"&&(I||!k2.call($,q))))z.push(q);return z}function wJ0($,I){return I=YJ0(I===void 0?$.length-1:I,0),function(){var z=arguments,q=-1,U=YJ0(z.length-I,0),Y=Array(U);while(++q<U)Y[q]=z[I+q];q=-1;var J=Array(I+1);while(++q<I)J[q]=z[q];return J[I]=Y,QJ0($,this,J)}}function Q91($,I,z,q){z||(z={});var U=-1,Y=I.length;while(++U<Y){var J=I[U],Q=q?q(z[J],$[J],J,z,$):void 0;Y91(z,J,Q===void 0?$[J]:Q)}return z}function K91($){return wJ0(function(I,z){var q=-1,U=z.length,Y=U>1?z[U-1]:void 0,J=U>2?z[2]:void 0;if(Y=$.length>3&&typeof Y=="function"?(U--,Y):void 0,J&&w91(z[0],z[1],J))Y=U<3?void 0:Y,U=1;I=Object(I);while(++q<U){var Q=z[q];if(Q)$(I,Q,q,Y)}return I})}function GJ0($,I){return I=I==null?JJ0:I,!!I&&(typeof $=="number"||$91.test($))&&($>-1&&$%1==0&&$<I)}function w91($,I,z){if(!Dh(z))return!1;var q=typeof I;if(q=="number"?Lh(z)&&GJ0(I,z.length):q=="string"&&(I in z))return Xh(z[I],$);return!1}function G91($){var I=$&&$.constructor,z=typeof I=="function"&&I.prototype||x2;return $===z}function H91($){var I=[];if($!=null)for(var z in Object($))I.push(z);return I}function Xh($,I){return $===I||$!==$&&I!==I}function W91($){return Z91($)&&k2.call($,"callee")&&(!z91.call($,"callee")||KJ0.call($)==a51)}var V91=Array.isArray;function Lh($){return $!=null&&L91($.length)&&!X91($)}function Z91($){return D91($)&&Lh($)}function X91($){var I=Dh($)?KJ0.call($):"";return I==s51||I==e51}function L91($){return typeof $=="number"&&$>-1&&$%1==0&&$<=JJ0}function Dh($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function D91($){return!!$&&typeof $=="object"}var O91=K91(function($,I,z,q){Q91(I,N91(I),$,q)}),F91=wJ0(function($){return $.push(void 0,U91),QJ0(O91,void 0,$)});function N91($){return Lh($)?q91($,!0):J91($)}HJ0.exports=F91});var VJ0=F((rh1,Fh)=>{function M91($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var WJ0=C4().Buffer,f2=t("util");function A91($,I,z){$.copy(I,z)}Fh.exports=function(){function $(){M91(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(z){var q={data:z,next:null};if(this.length>0)this.tail.next=q;else this.head=q;this.tail=q,++this.length},$.prototype.unshift=function(z){var q={data:z,next:this.head};if(this.length===0)this.tail=q;this.head=q,++this.length},$.prototype.shift=function(){if(this.length===0)return;var z=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,z},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(z){if(this.length===0)return"";var q=this.head,U=""+q.data;while(q=q.next)U+=z+q.data;return U},$.prototype.concat=function(z){if(this.length===0)return WJ0.alloc(0);var q=WJ0.allocUnsafe(z>>>0),U=this.head,Y=0;while(U)A91(U.data,q,Y),Y+=U.data.length,U=U.next;return q},$}();if(f2&&f2.inspect&&f2.inspect.custom)Fh.exports.prototype[f2.inspect.custom]=function(){var $=f2.inspect({length:this.length});return this.constructor.name+" "+$}});var Nh=F((th1,ZJ0)=>{var HL=_4();function P91($,I){var z=this,q=this._readableState&&this._readableState.destroyed,U=this._writableState&&this._writableState.destroyed;if(q||U){if(I)I($);else if($){if(!this._writableState)HL.nextTick(WL,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,HL.nextTick(WL,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(Y){if(!I&&Y){if(!z._writableState)HL.nextTick(WL,z,Y);else if(!z._writableState.errorEmitted)z._writableState.errorEmitted=!0,HL.nextTick(WL,z,Y)}else if(I)I(Y)}),this}function T91(){if(this._readableState)this._readable Line truncated
%s`,v,v,A,q);var x=A.type==="*"?US:A.type==="?"?qS:"\\"+A.type;U=!0,q=q.slice(0,A.reStart)+x+"\\("+v}if(X(),Y)q+="\\\\";var h=!1;switch(q.charAt(0)){case"[":case".":case"(":h=!0}for(var k=Q.length-1;k>-1;k--){var E=Q[k],f=q.slice(0,E.reStart),n=q.slice(E.reStart,E.reEnd-8),g=q.slice(E.reEnd-8,E.reEnd),b=q.slice(E.reEnd);g+=b;var p=f.split("(").length-1,q0=b;for(L=0;L<p;L++)q0=q0.replace(/\)[+*?]?/,"");b=q0;var R="";if(b===""&&I!==vL)R="$";var u=f+n+b+R+g;q=u}if(q!==""&&U)q="(?=.)"+q;if(h)q=W+q;if(I===vL)return[q,U];if(!U)return pz1($);var c=z.nocase?"i":"";try{var m=new RegExp("^"+q+"$",c)}catch(e){return new RegExp("$.")}return m._glob=$,m._src=q,m}h$.makeRe=function($,I){return new k4($,I||{}).makeRe()};k4.prototype.makeRe=iz1;function iz1(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var I=this.options,z=I.noglobstar?US:I.dot?Sz1:yz1,q=I.nocase?"i":"",U=$.map(function(Y){return Y.map(function(J){return J===WI?z:typeof J==="string"?cz1(J):J._src}).join("\\/")}).join("|");if(U="^(?:"+U+")$",this.negate)U="^(?!"+U+").*$";try{this.regexp=new RegExp(U,q)}catch(Y){this.regexp=!1}return this.regexp}h$.match=function($,I,z){z=z||{};var q=new k4(I,z);if($=$.filter(function(U){return q.match(U)}),q.options.nonull&&!$.length)$.push(I);return $};k4.prototype.match=function(I,z){if(typeof z>"u")z=this.partial;if(this.debug("match",I,this.pattern),this.comment)return!1;if(this.empty)return I==="";if(I==="/"&&z)return!0;var q=this.options;if(a2.sep!=="/")I=I.split(a2.sep).join("/");I=I.split(iQ0),this.debug(this.pattern,"split",I);var U=this.set;this.debug(this.pattern,"set",U);var Y,J;for(J=I.length-1;J>=0;J--)if(Y=I[J],Y)break;for(J=0;J<U.length;J++){var Q=U[J],K=I;if(q.matchBase&&Q.length===1)K=[Y];var w=this.matchOne(K,Q,z);if(w){if(q.flipNegate)return!0;return!this.negate}}if(q.flipNegate)return!1;return this.negate};k4.prototype.matchOne=function($,I,z){if(I.indexOf(WI)!==-1)return this._matchGlobstar($,I,z,0,0);return this._matchOne($,I,z,0,0)};k4.prototype._matchGlobstar=function($,I,z,q,U){var Y,J=-1;for(Y=U;Y<I.length;Y++)if(I[Y]===WI){J=Y;break}var Q=-1;for(Y=I.length-1;Y>=0;Y--)if(I[Y]===WI){Q=Y;break}var K=I.slice(U,J),w=z?I.slice(J+1):I.slice(J+1,Q),G=z?[]:I.slice(Q+1);if(K.length){var H=$.slice(q,q+K.length);if(!this._matchOne(H,K,z,0,0))return!1;q+=K.length}var W=0;if(G.length){if(G.length+q>$.length)return!1;var V=$.length-G.length;if(this._matchOne($,G,z,V,0))W=G.length;else{if($[$.length-1]!==""||q+G.length===$.length)return!1;if(V--,!this._matchOne($,G,z,V,0))return!1;W=G.length+1}}if(!w.length){var X=!!W;for(Y=q;Y<$.length-W;Y++){var L=String($[Y]);if(X=!0,L==="."||L===".."||!this.options.dot&&L.charAt(0)===".")return!1}return z||X}var D=[[[],0]],O=D[0],A=0,T=[0];for(var M=0;M<w.length;M++){var v=w[M];if(v===WI)T.push(A),O=[[],0],D.push(O);else O[0].push(v),A++}var x=D.length-1,h=$.length-W;for(var k=0;k<D.length;k++)D[k][1]=h-(T[x--]+D[k][0].length);return!!this._matchGlobStarBodySections($,D,q,0,z,0,!!W)};k4.prototype._matchGlobStarBodySections=function($,I,z,q,U,Y,J){var Q=I[q];if(!Q){for(var K=z;K<$.length;K++){J=!0;var w=$[K];if(w==="."||w===".."||!this.options.dot&&w.charAt(0)===".")return!1}return J}var G=Q[0],H=Q[1];while(z<=H){var W=this._matchOne($.slice(0,z+G.length),G,U,z,0);if(W&&Y<this.maxGlobstarRecursion){var V=this._matchGlobStarBodySections($,I,z+G.length,q+1,U,Y+1,J);if(V!==!1)return V}var w=$[z];if(w==="."||w===".."||!this.options.dot&&w.charAt(0)===".")return!1;z++}return U||null};k4.prototype._matchOne=function($,I,z,q,U){var Y,J,Q,K;for(Y=q,J=U,Q=$.length,K=I.length;Y<Q&&J<K;Y++,J++){this.debug("matchOne loop");var w=I[J],G=$[Y];if(this.debug(I,w,G),w===!1||w===WI)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(Y===Q&&J===K)return!0;else if(Y===Q)return z;else if(J===K)return Y===Q-1&&$[Y]==="";throw Error("wtf?")};function pz1($){return $.replace(/\\(.)/g,"$1")}function cz1($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var CL=F((XS1,_L)=>{function dQ0($){return $.charAt(0)==="/"}function mQ0($){var I=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,z=I.exec($),q=z[1]||"",U=Boolean(q&&q.charAt(1)!==":");return Boolean(z[2]||U)}_L.exports=process.platform==="win32"?mQ0:dQ0;_L.exports.posix=dQ0;_L.exports.win32=mQ0});var JS=F(($q1)=>{$q1.setopts=tz1;$q1.ownProp=lQ0;$q1.makeAbs=s2;$q1.finish=az1;$q1.mark=sz1;$q1.isIgnored=rQ0;$q1.childrenIgnored=ez1;function lQ0($,I){return Object.prototype.hasOwnProperty.call($,I)}var dz1=t("fs"),AU=t("path"),mz1=gL(),oQ0=CL(),YS=mz1.Minimatch;function lz1($,I){return $.localeCompare(I,"en")}function oz1($,I){if($.ignore=I.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(rz1)}function rz1($){var I=null;if($.slice(-3)==="/**"){var z=$.replace(/(\/\*\*)+$/,"");I=new YS(z,{dot:!0})}return{matcher: Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new l4($,I).found}function l4($,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 l4))return new l4($,I);if(wq1(this,$,I),this.noprocess)return this;var z=this.minimatch.set.length;this.matches=Array(z);for(var q=0;q<z;q++)this._process(this.minimatch.set[q],q,!1);this._finish()}l4.prototype._finish=function(){if(aQ0.ok(this instanceof l4),this.realpath){var $=this;this.matches.forEach(function(I,z){var q=$.matches[z]=Object.create(null);for(var U in I)try{U=$._makeAbs(U);var Y=Kq1.realpathSync(U,$.realpathCache);q[Y]=!0}catch(J){if(J.syscall==="stat")q[$._makeAbs(U)]=!0;else throw J}})}VI.finish(this)};l4.prototype._process=function($,I,z){aQ0.ok(this instanceof l4);var q=0;while(typeof $[q]==="string")q++;var U;switch(q){case $.length:this._processSimple($.join("/"),I);return;case 0:U=null;break;default:U=$.slice(0,q).join("/");break}var Y=$.slice(q),J;if(U===null)J=".";else if(hL(U)||hL($.map(function(w){return typeof w==="string"?w:"[*]"}).join("/"))){if(!U||!hL(U))U="/"+U;J=U}else J=U;var Q=this._makeAbs(J);if(Gq1(this,J))return;var K=Y[0]===tQ0.GLOBSTAR;if(K)this._processGlobStar(U,J,Q,Y,I,z);else this._processReaddir(U,J,Q,Y,I,z)};l4.prototype._processReaddir=function($,I,z,q,U,Y){var J=this._readdir(z,Y);if(!J)return;var Q=q[0],K=!!this.minimatch.negate,w=Q._glob,G=this.dot||w.charAt(0)===".",H=[];for(var W=0;W<J.length;W++){var V=J[W];if(V.charAt(0)!=="."||G){var X;if(K&&!$)X=!V.match(Q);else X=V.match(Q);if(X)H.push(V)}}var L=H.length;if(L===0)return;if(q.length===1&&!this.mark&&!this.stat){if(!this.matches[U])this.matches[U]=Object.create(null);for(var W=0;W<L;W++){var V=H[W];if($)if($.slice(-1)!=="/")V=$+"/"+V;else V=$+V;if(V.charAt(0)==="/"&&!this.nomount)V=QS.join(this.root,V);this._emitMatch(U,V)}return}q.shift();for(var W=0;W<L;W++){var V=H[W],D;if($)D=[$,V];else D=[V];this._process(D.concat(q),U,Y)}};l4.prototype._emitMatch=function($,I){if(Hq1(this,I))return;var z=this._makeAbs(I);if(this.mark)I=this._mark(I);if(this.absolute)I=z;if(this.matches[$][I])return;if(this.nodir){var q=this.cache[z];if(q==="DIR"||Array.isArray(q))return}if(this.matches[$][I]=!0,this.stat)this._stat(I)};l4.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var I,z,q;try{z=this.fs.lstatSync($)}catch(Y){if(Y.code==="ENOENT")return null}var U=z&&z.isSymbolicLink();if(this.symlinks[$]=U,!U&&z&&!z.isDirectory())this.cache[$]="FILE";else I=this._readdir($,!1);return I};l4.prototype._readdir=function($,I){var z;if(I&&!KS(this.symlinks,$))return this._readdirInGlobStar($);if(KS(this.cache,$)){var q=this.cache[$];if(!q||q==="FILE")return null;if(Array.isArray(q))return q}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(U){return this._readdirError($,U),null}};l4.prototype._readdirEntries=function($,I){if(!this.mark&&!this.stat)for(var z=0;z<I.length;z++){var q=I[z];if($==="/")q=$+q;else q=$+"/"+q;this.cache[q]=!0}return this.cache[$]=I,I};l4.prototype._readdirError=function($,I){switch(I.code){case"ENOTSUP":case"ENOTDIR":var z=this._makeAbs($);if(this.cache[z]="FILE",z===this.cwdAbs){var q=Error(I.code+" invalid cwd "+this.cwd);throw q.path=this.cwd,q.code=I.code,q}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}};l4.prototype._processGlobStar=function($,I,z,q,U,Y){var J=this._readdir(z,Y);if(!J)return;var Q=q.slice(1),K=$?[$]:[],w=K.concat(Q);this._process(w,U,!1);var G=J.length,H=this.symlinks[z];if(H&&Y)return;for(var W=0;W<G;W++){var V=J[W];if(V.charAt(0)==="."&&!this.dot)continue;var X=K.concat(J[W],Q);this._process(X,U,!0);var L=K.concat(J[W],q);this._process(L,U,!0)}};l4.prototype._processSimple=function($,I){var z=this._stat($);if(!this.matches[I])this.matches[I]=Object.create(null);if(!z)return;if($&&hL($)&&!this.nomount){var q=/[\/\\]$/.test($);if($.charAt(0)==="/")$=QS.join(this.root,$);else if($=QS.resolve(this.root,$),q)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(I,$)};l4.prototype._stat=function($){var I=this._makeAbs($),z=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&KS(this.cache,I)){var J=this.cache[I];if(Array.isArray(J))J="DIR";if(!z||J==="DIR")return J;if(z&&J==="FILE")return!1}var q,U=this.statCache[I];if(!U){var Y;try{Y=this.fs.lstatSync(I)}catch(Q){if(Q&&(Q.code==="ENOENT"||Q.code==="ENOTDIR"))return this.statCache[I]=!1,!1}if(Y&&Y.isSymbolicLink())try{U=this.fs.statSync(I)}catch(Q){U=Y}else U=Y}this.statCache[I]=U;var J=!0;if(U)J=U.isDirectory()?"DIR":"FILE";if(this.cache[I]=this.cache[I]||J,z&&J==="FILE")return!1;return J};l4.prototype._mark=function($){return VI.mark(this,$)};l4.prototype._makeAbs=function($){return VI.makeAbs(this,$)}});var wS=F((MS1,z20)=>{z20.exports=I20;function I20($,I){if($&&I)return I20($)(I);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(q){z[q]=$[q]}),z;f Line truncated
`);if($.linkname)I+=nS(" linkpath="+$.linkname+`
`);var z=$.pax;if(z)for(var q in z)I+=nS(" "+q+"="+z[q]+`
`);return Buffer.from(I)};jU1.decodePax=function($){var I={};while($.length){var z=0;while(z<$.length&&$[z]!==32)z++;var q=parseInt($.slice(0,z).toString(),10);if(!q)return I;var U=$.slice(z+1,q-1).toString(),Y=U.indexOf("=");if(Y===-1)return I;I[U.slice(0,Y)]=U.slice(Y+1),$=$.slice(q)}return I};jU1.encode=function($){var I=LU1(512),z=$.name,q="";if($.typeflag===5&&z[z.length-1]!=="/")z+="/";if(Buffer.byteLength(z)!==z.length)return null;while(Buffer.byteLength(z)>100){var U=z.indexOf("/");if(U===-1)return null;q+=q?"/"+z.slice(0,U):z.slice(0,U),z=z.slice(U+1)}if(Buffer.byteLength(z)>100||Buffer.byteLength(q)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(I.write(z),I.write(g7($.mode&AU1,6),100),I.write(g7($.uid,6),108),I.write(g7($.gid,6),116),I.write(g7($.size,11),124),I.write(g7($.mtime.getTime()/1000|0,11),136),I[156]=NK0+EU1($.type),$.linkname)I.write($.linkname,157);if(MK0.copy(I,UK),FU1.copy(I,iS),$.uname)I.write($.uname,265);if($.gname)I.write($.gname,297);if(I.write(g7($.devmajor||0,6),329),I.write(g7($.devminor||0,6),337),q)I.write(q,345);return I.write(g7(PK0(I),6),148),I};jU1.decode=function($,I,z){var q=$[156]===0?0:$[156]-NK0,U=BU($,0,100,I),Y=_7($,100,8),J=_7($,108,8),Q=_7($,116,8),K=_7($,124,12),w=_7($,136,12),G=TU1(q),H=$[157]===0?null:BU($,157,100,I),W=BU($,265,32),V=BU($,297,32),X=_7($,329,8),L=_7($,337,8),D=PK0($);if(D===256)return null;if(D!==_7($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(MK0.compare($,UK,UK+6)===0){if($[345])U=BU($,345,155,I)+"/"+U}else if(NU1.compare($,UK,UK+6)===0&&MU1.compare($,iS,iS+2)===0);else if(!z)throw Error("Invalid tar header: unknown format.");if(q===0&&U&&U[U.length-1]==="/")q=5;return{name:U,mode:Y,uid:J,gid:Q,size:K,mtime:new Date(1000*w),type:G,linkname:H,uname:W,gname:V,devmajor:X,devminor:L}}});var gK0=F((zy1,RK0)=>{var EK0=t("util"),hU1=FK0(),YK=pS(),BK0=g6().Writable,jK0=g6().PassThrough,vK0=function(){},TK0=function($){return $&=511,$&&512-$},SU1=function($,I){var z=new bL($,I);return z.end(),z},yU1=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,$},bL=function($,I){this._parent=$,this.offset=I,jK0.call(this,{autoDestroy:!1})};EK0.inherits(bL,jK0);bL.prototype.destroy=function($){this._parent.destroy($)};var $9=function($){if(!(this instanceof $9))return new $9($);BK0.call(this,$),$=$||{},this._offset=0,this._buffer=hU1(),this._missing=0,this._partial=!1,this._onparse=vK0,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,z=I._buffer,q=function(){I._continue()},U=function(W){if(I._locked=!1,W)return I.destroy(W);if(!I._stream)q()},Y=function(){I._stream=null;var W=TK0(I._header.size);if(W)I._parse(W,J);else I._parse(512,H);if(!I._locked)q()},J=function(){I._buffer.consume(TK0(I._header.size)),I._parse(512,H),q()},Q=function(){var W=I._header.size;I._paxGlobal=YK.decodePax(z.slice(0,W)),z.consume(W),Y()},K=function(){var W=I._header.size;if(I._pax=YK.decodePax(z.slice(0,W)),I._paxGlobal)I._pax=Object.assign({},I._paxGlobal,I._pax);z.consume(W),Y()},w=function(){var W=I._header.size;this._gnuLongPath=YK.decodeLongPath(z.slice(0,W),$.filenameEncoding),z.consume(W),Y()},G=function(){var W=I._header.size;this._gnuLongLinkPath=YK.decodeLongPath(z.slice(0,W),$.filenameEncoding),z.consume(W),Y()},H=function(){var W=I._offset,V;try{V=I._header=YK.decode(z.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(X){I.emit("error",X)}if(z.consume(512),!V){I._parse(512,H),q();return}if(V.type==="gnu-long-path"){I._parse(V.size,w),q();return}if(V.type==="gnu-long-link-path"){I._parse(V.size,G),q();return}if(V.type==="pax-global-header"){I._parse(V.size,Q),q();return}if(V.type==="pax-header"){I._parse(V.size,K),q();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=yU1(V,I._pax),I._pax=null;if(I._locked=!0,!V.size||V.type==="directory"){I._parse(512,H),I.emit("entry",V,SU1(I,W),U);return}I._stream=new bL(I,W),I.emit("entry",V,I._stream,U),I._parse(V.size,Y),q()};this._onheader=H,this._parse(512,H)};EK0.inherits($9,BK0);$9.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};$9.prototype._parse=function($,I){if(this._destroyed)return;if(this._offset+=$,this._missing=$,I===this._onheader)this._partial=!1;this._onparse=I};$9.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=vK0,this._overflow)this._write(this._overflow,void 0,$);else $()};$9.prototype._write=function($,I,z){if(this._destroyed)return;var q=this._stream,U=this._buffer,Y=this._missing;if($.length)this._partial=!0;if($.length<Y){ 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="${$Y1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${$.Target}"/>`);return I}_writeClose(){this.stream.write("</Relationships>")}}zw0.exports=Iw0});var Kw0=F((Wy1,Qw0)=>{var Uw0=X6(),Yw0=V7(),zY1=L4(),qY1=A_(),UY1=T_();class Jw0{constructor($,I,z){this.id=z.id,this.count=0,this._worksheet=$,this._workbook=z.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:Yw0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let I={Type:Yw0.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 z=new qY1,q=new Uw0;z.render(q,$),this.commentsStream.write(q.xml);let U=new UY1,Y=new Uw0;U.render(Y,$,I),this.vmlStream.write(Y.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=zY1.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()}}Qw0.exports=Jw0});var Zw0=F((Vy1,Vw0)=>{var YY1=B4(),JY1=V7(),mS=L4(),ww0=bj(),Gw0=C5(),QY1=Ig(),Hw0=UV(),lS=JV(),KY1=qw0(),wY1=Kw0(),GY1=kj(),$6=new QY1,oS=G7(),HY1=tg(),WY1=ag(),VY1=sg(),ZY1=mg(),XY1=cg(),LY1=lg(),DY1=eg(),OY1=$_(),FY1=I_(),NY1=z_(),MY1=q_(),AY1=U_(),PY1=w_(),TY1=J_(),EY1=Y_(),I6={dataValidations:new HY1,sheetProperties:new WY1,sheetFormatProperties:new VY1,columns:new oS({tag:"cols",length:!1,childXform:new ZY1}),row:new XY1,hyperlinks:new oS({tag:"hyperlinks",length:!1,childXform:new LY1}),sheetViews:new oS({tag:"sheetViews",length:!1,childXform:new DY1}),sheetProtection:new OY1,pageMargins:new FY1,pageSeteup:new NY1,autoFilter:new MY1,picture:new AY1,conditionalFormattings:new PY1,headerFooter:new TY1,rowBreaks:new EY1};class Ww0{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 KY1($),this._sheetCommentsWriter=new wY1(this,this._sheetRelsWriter,$),this._dimensions=new Gw0,this._rowZero=1,this.committed=!1,this.dataValidations=new GY1,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
*/yZ0.exports=function($,q){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var Y=$.length;if(Y<=1)return $;var z="";if(Y>4&&$[3]==="\\"){var U=$[2];if((U==="?"||U===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),z="//"}var I=$.split(/[/\\]+/);if(q!==!1&&I[I.length-1]==="")I.pop();return z+I.join("/")}});var Mk=M((Z$4,nZ0)=>{var kZ0=9007199254740991,vG1="[object Arguments]",hG1="[object Function]",gG1="[object GeneratorFunction]",SG1=/^(?:0|[1-9]\d*)$/;function uZ0($,q,Y){switch(Y.length){case 0:return $.call(q);case 1:return $.call(q,Y[0]);case 2:return $.call(q,Y[0],Y[1]);case 3:return $.call(q,Y[0],Y[1],Y[2])}return $.apply(q,Y)}function yG1($,q){var Y=-1,z=Array($);while(++Y<$)z[Y]=q(Y);return z}var sH=Object.prototype,tH=sH.hasOwnProperty,fZ0=sH.toString,xG1=sH.propertyIsEnumerable,xZ0=Math.max;function kG1($,q){var Y=lG1($)||mG1($)?yG1($.length,String):[],z=Y.length,U=!!z;for(var I in $)if((q||tH.call($,I))&&!(U&&(I=="length"||iZ0(I,z))))Y.push(I);return Y}function uG1($,q,Y,z){if($===void 0||Lk($,sH[Y])&&!tH.call(z,Y))return q;return $}function fG1($,q,Y){var z=$[q];if(!(tH.call($,q)&&Lk(z,Y))||Y===void 0&&!(q in $))$[q]=Y}function bG1($){if(!Ok($))return dG1($);var q=pG1($),Y=[];for(var z in $)if(!(z=="constructor"&&(q||!tH.call($,z))))Y.push(z);return Y}function bZ0($,q){return q=xZ0(q===void 0?$.length-1:q,0),function(){var Y=arguments,z=-1,U=xZ0(Y.length-q,0),I=Array(U);while(++z<U)I[z]=Y[q+z];z=-1;var J=Array(q+1);while(++z<q)J[z]=Y[z];return J[q]=I,uZ0($,this,J)}}function iG1($,q,Y,z){Y||(Y={});var U=-1,I=q.length;while(++U<I){var J=q[U],Q=z?z(Y[J],$[J],J,Y,$):void 0;fG1(Y,J,Q===void 0?$[J]:Q)}return Y}function nG1($){return bZ0(function(q,Y){var z=-1,U=Y.length,I=U>1?Y[U-1]:void 0,J=U>2?Y[2]:void 0;if(I=$.length>3&&typeof I=="function"?(U--,I):void 0,J&&cG1(Y[0],Y[1],J))I=U<3?void 0:I,U=1;q=Object(q);while(++z<U){var Q=Y[z];if(Q)$(q,Q,z,I)}return q})}function iZ0($,q){return q=q==null?kZ0:q,!!q&&(typeof $=="number"||SG1.test($))&&($>-1&&$%1==0&&$<q)}function cG1($,q,Y){if(!Ok(Y))return!1;var z=typeof q;if(z=="number"?Fk(Y)&&iZ0(q,Y.length):z=="string"&&(q in Y))return Lk(Y[q],$);return!1}function pG1($){var q=$&&$.constructor,Y=typeof q=="function"&&q.prototype||sH;return $===Y}function dG1($){var q=[];if($!=null)for(var Y in Object($))q.push(Y);return q}function Lk($,q){return $===q||$!==$&&q!==q}function mG1($){return oG1($)&&tH.call($,"callee")&&(!xG1.call($,"callee")||fZ0.call($)==vG1)}var lG1=Array.isArray;function Fk($){return $!=null&&sG1($.length)&&!rG1($)}function oG1($){return tG1($)&&Fk($)}function rG1($){var q=Ok($)?fZ0.call($):"";return q==hG1||q==gG1}function sG1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=kZ0}function Ok($){var q=typeof $;return!!$&&(q=="object"||q=="function")}function tG1($){return!!$&&typeof $=="object"}var aG1=nG1(function($,q,Y,z){iG1(q,$Z1(q),$,z)}),eG1=bZ0(function($){return $.push(void 0,uG1),uZ0(aG1,void 0,$)});function $Z1($){return Fk($)?kG1($,!0):bG1($)}nZ0.exports=eG1});var pZ0=M((W$4,Nk)=>{function qZ1($,q){if(!($ instanceof q))throw TypeError("Cannot call a class as a function")}var cZ0=$6().Buffer,aH=m("util");function YZ1($,q,Y){$.copy(q,Y)}Nk.exports=function(){function $(){qZ1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(Y){var z={data:Y,next:null};if(this.length>0)this.tail.next=z;else this.head=z;this.tail=z,++this.length},$.prototype.unshift=function(Y){var z={data:Y,next:this.head};if(this.length===0)this.tail=z;this.head=z,++this.length},$.prototype.shift=function(){if(this.length===0)return;var Y=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,Y},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(Y){if(this.length===0)return"";var z=this.head,U=""+z.data;while(z=z.next)U+=Y+z.data;return U},$.prototype.concat=function(Y){if(this.length===0)return cZ0.alloc(0);var z=cZ0.allocUnsafe(Y>>>0),U=this.head,I=0;while(U)YZ1(U.data,z,I),I+=U.data.length,U=U.next;return z},$}();if(aH&&aH.inspect&&aH.inspect.custom)Nk.exports.prototype[aH.inspect.custom]=function(){var $=aH.inspect({length:this.length});return this.constructor.name+" "+$}});var Dk=M((X$4,dZ0)=>{var IM=e4();function zZ1($,q){var Y=this,z=this._readableState&&this._readableState.destroyed,U=this._writableState&&this._writableState.destroyed;if(z||U){if(q)q($);else if($){if(!this._writableState)IM.nextTick(JM,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,IM.nextTick(JM,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(I){if(!q&&I){if(!Y._writableState)IM.nextTick(JM,Y,I);else if(!Y._writableState.errorEmitted)Y._writableState.errorEmitted=!0,IM.nextTick(JM,Y,I)}else if(q)q(I)}),this}function UZ1(){if(this._readableState)this._readable Line truncated
%s`,T,T,A,z);var y=A.type==="*"?Iu:A.type==="?"?Uu:"\\"+A.type;U=!0,z=z.slice(0,A.reStart)+y+"\\("+T}if(w(),I)z+="\\\\";var v=!1;switch(z.charAt(0)){case"[":case".":case"(":v=!0}for(var k=Q.length-1;k>-1;k--){var R=Q[k],c=z.slice(0,R.reStart),n=z.slice(R.reStart,R.reEnd-8),g=z.slice(R.reEnd-8,R.reEnd),b=z.slice(R.reEnd);g+=b;var i=c.split("(").length-1,$0=b;for(L=0;L<i;L++)$0=$0.replace(/\)[+*?]?/,"");b=$0;var j="";if(b===""&&q!==AM)j="$";var u=c+n+b+j+g;z=u}if(z!==""&&U)z="(?=.)"+z;if(v)z=V+z;if(q===AM)return[z,U];if(!U)return Pw1($);var p=Y.nocase?"i":"";try{var d=new RegExp("^"+z+"$",p)}catch(Y0){return new RegExp("$.")}return d._glob=$,d._src=z,d}H$.makeRe=function($,q){return new G6($,q||{}).makeRe()};G6.prototype.makeRe=Aw1;function Aw1(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var q=this.options,Y=q.noglobstar?Iu:q.dot?Vw1:ww1,z=q.nocase?"i":"",U=$.map(function(I){return I.map(function(J){return J===Tq?Y:typeof J==="string"?Bw1(J):J._src}).join("\\/")}).join("|");if(U="^(?:"+U+")$",this.negate)U="^(?!"+U+").*$";try{this.regexp=new RegExp(U,z)}catch(I){this.regexp=!1}return this.regexp}H$.match=function($,q,Y){Y=Y||{};var z=new G6(q,Y);if($=$.filter(function(U){return z.match(U)}),z.options.nonull&&!$.length)$.push(q);return $};G6.prototype.match=function(q,Y){if(typeof Y>"u")Y=this.partial;if(this.debug("match",q,this.pattern),this.comment)return!1;if(this.empty)return q==="";if(q==="/"&&Y)return!0;var z=this.options;if(GG.sep!=="/")q=q.split(GG.sep).join("/");q=q.split(BX0),this.debug(this.pattern,"split",q);var U=this.set;this.debug(this.pattern,"set",U);var I,J;for(J=q.length-1;J>=0;J--)if(I=q[J],I)break;for(J=0;J<U.length;J++){var Q=U[J],K=q;if(z.matchBase&&Q.length===1)K=[I];var H=this.matchOne(K,Q,Y);if(H){if(z.flipNegate)return!0;return!this.negate}}if(z.flipNegate)return!1;return this.negate};G6.prototype.matchOne=function($,q,Y){if(q.indexOf(Tq)!==-1)return this._matchGlobstar($,q,Y,0,0);return this._matchOne($,q,Y,0,0)};G6.prototype._matchGlobstar=function($,q,Y,z,U){var I,J=-1;for(I=U;I<q.length;I++)if(q[I]===Tq){J=I;break}var Q=-1;for(I=q.length-1;I>=0;I--)if(q[I]===Tq){Q=I;break}var K=q.slice(U,J),H=Y?q.slice(J+1):q.slice(J+1,Q),G=Y?[]:q.slice(Q+1);if(K.length){var Z=$.slice(z,z+K.length);if(!this._matchOne(Z,K,Y,0,0))return!1;z+=K.length}var V=0;if(G.length){if(G.length+z>$.length)return!1;var X=$.length-G.length;if(this._matchOne($,G,Y,X,0))V=G.length;else{if($[$.length-1]!==""||z+G.length===$.length)return!1;if(X--,!this._matchOne($,G,Y,X,0))return!1;V=G.length+1}}if(!H.length){var w=!!V;for(I=z;I<$.length-V;I++){var L=String($[I]);if(w=!0,L==="."||L===".."||!this.options.dot&&L.charAt(0)===".")return!1}return Y||w}var F=[[[],0]],O=F[0],A=0,B=[0];for(var P=0;P<H.length;P++){var T=H[P];if(T===Tq)B.push(A),O=[[],0],F.push(O);else O[0].push(T),A++}var y=F.length-1,v=$.length-V;for(var k=0;k<F.length;k++)F[k][1]=v-(B[y--]+F[k][0].length);return!!this._matchGlobStarBodySections($,F,z,0,Y,0,!!V)};G6.prototype._matchGlobStarBodySections=function($,q,Y,z,U,I,J){var Q=q[z];if(!Q){for(var K=Y;K<$.length;K++){J=!0;var H=$[K];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1}return J}var G=Q[0],Z=Q[1];while(Y<=Z){var V=this._matchOne($.slice(0,Y+G.length),G,U,Y,0);if(V&&I<this.maxGlobstarRecursion){var X=this._matchGlobStarBodySections($,q,Y+G.length,z+1,U,I+1,J);if(X!==!1)return X}var H=$[Y];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1;Y++}return U||null};G6.prototype._matchOne=function($,q,Y,z,U){var I,J,Q,K;for(I=z,J=U,Q=$.length,K=q.length;I<Q&&J<K;I++,J++){this.debug("matchOne loop");var H=q[J],G=$[I];if(this.debug(q,H,G),H===!1||H===Tq)return!1;var Z;if(typeof H==="string")Z=G===H,this.debug("string match",H,G,Z);else Z=G.match(H),this.debug("pattern match",H,G,Z);if(!Z)return!1}if(I===Q&&J===K)return!0;else if(I===Q)return Y;else if(J===K)return I===Q-1&&$[I]==="";throw Error("wtf?")};function Pw1($){return $.replace(/\\(.)/g,"$1")}function Bw1($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var EM=M((g$4,TM)=>{function jX0($){return $.charAt(0)==="/"}function _X0($){var q=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,Y=q.exec($),z=Y[1]||"",U=Boolean(z&&z.charAt(1)!==":");return Boolean(Y[2]||U)}TM.exports=process.platform==="win32"?_X0:jX0;TM.exports.posix=jX0;TM.exports.win32=_X0});var Qu=M((Sw1)=>{Sw1.setopts=Rw1;Sw1.ownProp=CX0;Sw1.makeAbs=ZG;Sw1.finish=vw1;Sw1.mark=hw1;Sw1.isIgnored=vX0;Sw1.childrenIgnored=gw1;function CX0($,q){return Object.prototype.hasOwnProperty.call($,q)}var Tw1=m("fs"),QI=m("path"),Ew1=BM(),RX0=EM(),Ju=Ew1.Minimatch;function jw1($,q){return $.localeCompare(q,"en")}function _w1($,q){if($.ignore=q.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(Cw1)}function Cw1($){var q=null;if($.slice(-3)==="/**"){var Y=$.replace(/(\/\*\*)+$/,"");q=new Ju(Y,{dot:!0})}return{matcher Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new M6($,q).found}function M6($,q){if(!$)throw Error("must provide pattern");if(typeof q==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof M6))return new M6($,q);if(cw1(this,$,q),this.noprocess)return this;var Y=this.minimatch.set.length;this.matches=Array(Y);for(var z=0;z<Y;z++)this._process(this.minimatch.set[z],z,!1);this._finish()}M6.prototype._finish=function(){if(gX0.ok(this instanceof M6),this.realpath){var $=this;this.matches.forEach(function(q,Y){var z=$.matches[Y]=Object.create(null);for(var U in q)try{U=$._makeAbs(U);var I=nw1.realpathSync(U,$.realpathCache);z[I]=!0}catch(J){if(J.syscall==="stat")z[$._makeAbs(U)]=!0;else throw J}})}Eq.finish(this)};M6.prototype._process=function($,q,Y){gX0.ok(this instanceof M6);var z=0;while(typeof $[z]==="string")z++;var U;switch(z){case $.length:this._processSimple($.join("/"),q);return;case 0:U=null;break;default:U=$.slice(0,z).join("/");break}var I=$.slice(z),J;if(U===null)J=".";else if(jM(U)||jM($.map(function(H){return typeof H==="string"?H:"[*]"}).join("/"))){if(!U||!jM(U))U="/"+U;J=U}else J=U;var Q=this._makeAbs(J);if(pw1(this,J))return;var K=I[0]===hX0.GLOBSTAR;if(K)this._processGlobStar(U,J,Q,I,q,Y);else this._processReaddir(U,J,Q,I,q,Y)};M6.prototype._processReaddir=function($,q,Y,z,U,I){var J=this._readdir(Y,I);if(!J)return;var Q=z[0],K=!!this.minimatch.negate,H=Q._glob,G=this.dot||H.charAt(0)===".",Z=[];for(var V=0;V<J.length;V++){var X=J[V];if(X.charAt(0)!=="."||G){var w;if(K&&!$)w=!X.match(Q);else w=X.match(Q);if(w)Z.push(X)}}var L=Z.length;if(L===0)return;if(z.length===1&&!this.mark&&!this.stat){if(!this.matches[U])this.matches[U]=Object.create(null);for(var V=0;V<L;V++){var X=Z[V];if($)if($.slice(-1)!=="/")X=$+"/"+X;else X=$+X;if(X.charAt(0)==="/"&&!this.nomount)X=Ku.join(this.root,X);this._emitMatch(U,X)}return}z.shift();for(var V=0;V<L;V++){var X=Z[V],F;if($)F=[$,X];else F=[X];this._process(F.concat(z),U,I)}};M6.prototype._emitMatch=function($,q){if(dw1(this,q))return;var Y=this._makeAbs(q);if(this.mark)q=this._mark(q);if(this.absolute)q=Y;if(this.matches[$][q])return;if(this.nodir){var z=this.cache[Y];if(z==="DIR"||Array.isArray(z))return}if(this.matches[$][q]=!0,this.stat)this._stat(q)};M6.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var q,Y,z;try{Y=this.fs.lstatSync($)}catch(I){if(I.code==="ENOENT")return null}var U=Y&&Y.isSymbolicLink();if(this.symlinks[$]=U,!U&&Y&&!Y.isDirectory())this.cache[$]="FILE";else q=this._readdir($,!1);return q};M6.prototype._readdir=function($,q){var Y;if(q&&!Hu(this.symlinks,$))return this._readdirInGlobStar($);if(Hu(this.cache,$)){var z=this.cache[$];if(!z||z==="FILE")return null;if(Array.isArray(z))return z}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(U){return this._readdirError($,U),null}};M6.prototype._readdirEntries=function($,q){if(!this.mark&&!this.stat)for(var Y=0;Y<q.length;Y++){var z=q[Y];if($==="/")z=$+z;else z=$+"/"+z;this.cache[z]=!0}return this.cache[$]=q,q};M6.prototype._readdirError=function($,q){switch(q.code){case"ENOTSUP":case"ENOTDIR":var Y=this._makeAbs($);if(this.cache[Y]="FILE",Y===this.cwdAbs){var z=Error(q.code+" invalid cwd "+this.cwd);throw z.path=this.cwd,z.code=q.code,z}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 q;if(!this.silent)console.error("glob error",q);break}};M6.prototype._processGlobStar=function($,q,Y,z,U,I){var J=this._readdir(Y,I);if(!J)return;var Q=z.slice(1),K=$?[$]:[],H=K.concat(Q);this._process(H,U,!1);var G=J.length,Z=this.symlinks[Y];if(Z&&I)return;for(var V=0;V<G;V++){var X=J[V];if(X.charAt(0)==="."&&!this.dot)continue;var w=K.concat(J[V],Q);this._process(w,U,!0);var L=K.concat(J[V],z);this._process(L,U,!0)}};M6.prototype._processSimple=function($,q){var Y=this._stat($);if(!this.matches[q])this.matches[q]=Object.create(null);if(!Y)return;if($&&jM($)&&!this.nomount){var z=/[\/\\]$/.test($);if($.charAt(0)==="/")$=Ku.join(this.root,$);else if($=Ku.resolve(this.root,$),z)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(q,$)};M6.prototype._stat=function($){var q=this._makeAbs($),Y=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&Hu(this.cache,q)){var J=this.cache[q];if(Array.isArray(J))J="DIR";if(!Y||J==="DIR")return J;if(Y&&J==="FILE")return!1}var z,U=this.statCache[q];if(!U){var I;try{I=this.fs.lstatSync(q)}catch(Q){if(Q&&(Q.code==="ENOENT"||Q.code==="ENOTDIR"))return this.statCache[q]=!1,!1}if(I&&I.isSymbolicLink())try{U=this.fs.statSync(q)}catch(Q){U=I}else U=I}this.statCache[q]=U;var J=!0;if(U)J=U.isDirectory()?"DIR":"FILE";if(this.cache[q]=this.cache[q]||J,Y&&J==="FILE")return!1;return J};M6.prototype._mark=function($){return Eq.mark(this,$)};M6.prototype._makeAbs=function($){return Eq.makeAbs(this,$)}});var Gu=M((f$4,uX0)=>{uX0.exports=kX0;function kX0($,q){if($&&q)return kX0($)(q);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(z){Y[z]=$[z]}),Y;f Line truncated
`);if($.linkname)q+=Kf(" linkpath="+$.linkname+`
`);var Y=$.pax;if(Y)for(var z in Y)q+=Kf(" "+z+"="+Y[z]+`
`);return Buffer.from(q)};qM1.decodePax=function($){var q={};while($.length){var Y=0;while(Y<$.length&&$[Y]!==32)Y++;var z=parseInt($.slice(0,Y).toString(),10);if(!z)return q;var U=$.slice(Y+1,z-1).toString(),I=U.indexOf("=");if(I===-1)return q;q[U.slice(0,I)]=U.slice(I+1),$=$.slice(z)}return q};qM1.encode=function($){var q=pO1(512),Y=$.name,z="";if($.typeflag===5&&Y[Y.length-1]!=="/")Y+="/";if(Buffer.byteLength(Y)!==Y.length)return null;while(Buffer.byteLength(Y)>100){var U=Y.indexOf("/");if(U===-1)return null;z+=z?"/"+Y.slice(0,U):Y.slice(0,U),Y=Y.slice(U+1)}if(Buffer.byteLength(Y)>100||Buffer.byteLength(z)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(q.write(Y),q.write(x7($.mode&sO1,6),100),q.write(x7($.uid,6),108),q.write(x7($.gid,6),116),q.write(x7($.size,11),124),q.write(x7($.mtime.getTime()/1000|0,11),136),q[156]=aw0+eO1($.type),$.linkname)q.write($.linkname,157);if(ew0.copy(q,jG),lO1.copy(q,Hf),$.uname)q.write($.uname,265);if($.gname)q.write($.gname,297);if(q.write(x7($.devmajor||0,6),329),q.write(x7($.devminor||0,6),337),z)q.write(z,345);return q.write(x7(qL0(q),6),148),q};qM1.decode=function($,q,Y){var z=$[156]===0?0:$[156]-aw0,U=LI($,0,100,q),I=k7($,100,8),J=k7($,108,8),Q=k7($,116,8),K=k7($,124,12),H=k7($,136,12),G=aO1(z),Z=$[157]===0?null:LI($,157,100,q),V=LI($,265,32),X=LI($,297,32),w=k7($,329,8),L=k7($,337,8),F=qL0($);if(F===256)return null;if(F!==k7($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(ew0.compare($,jG,jG+6)===0){if($[345])U=LI($,345,155,q)+"/"+U}else if(oO1.compare($,jG,jG+6)===0&&rO1.compare($,Hf,Hf+2)===0);else if(!Y)throw Error("Invalid tar header: unknown format.");if(z===0&&U&&U[U.length-1]==="/")z=5;return{name:U,mode:I,uid:J,gid:Q,size:K,mtime:new Date(1000*H),type:G,linkname:Z,uname:V,gname:X,devmajor:w,devminor:L}}});var KL0=M((g54,QL0)=>{var zL0=m("util"),QM1=tw0(),_G=Gf(),UL0=A8().Writable,IL0=A8().PassThrough,JL0=function(){},YL0=function($){return $&=511,$&&512-$},KM1=function($,q){var Y=new lM($,q);return Y.end(),Y},HM1=function($,q){if(q.path)$.name=q.path;if(q.linkpath)$.linkname=q.linkpath;if(q.size)$.size=parseInt(q.size,10);return $.pax=q,$},lM=function($,q){this._parent=$,this.offset=q,IL0.call(this,{autoDestroy:!1})};zL0.inherits(lM,IL0);lM.prototype.destroy=function($){this._parent.destroy($)};var t9=function($){if(!(this instanceof t9))return new t9($);UL0.call(this,$),$=$||{},this._offset=0,this._buffer=QM1(),this._missing=0,this._partial=!1,this._onparse=JL0,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 q=this,Y=q._buffer,z=function(){q._continue()},U=function(V){if(q._locked=!1,V)return q.destroy(V);if(!q._stream)z()},I=function(){q._stream=null;var V=YL0(q._header.size);if(V)q._parse(V,J);else q._parse(512,Z);if(!q._locked)z()},J=function(){q._buffer.consume(YL0(q._header.size)),q._parse(512,Z),z()},Q=function(){var V=q._header.size;q._paxGlobal=_G.decodePax(Y.slice(0,V)),Y.consume(V),I()},K=function(){var V=q._header.size;if(q._pax=_G.decodePax(Y.slice(0,V)),q._paxGlobal)q._pax=Object.assign({},q._paxGlobal,q._pax);Y.consume(V),I()},H=function(){var V=q._header.size;this._gnuLongPath=_G.decodeLongPath(Y.slice(0,V),$.filenameEncoding),Y.consume(V),I()},G=function(){var V=q._header.size;this._gnuLongLinkPath=_G.decodeLongPath(Y.slice(0,V),$.filenameEncoding),Y.consume(V),I()},Z=function(){var V=q._offset,X;try{X=q._header=_G.decode(Y.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(w){q.emit("error",w)}if(Y.consume(512),!X){q._parse(512,Z),z();return}if(X.type==="gnu-long-path"){q._parse(X.size,H),z();return}if(X.type==="gnu-long-link-path"){q._parse(X.size,G),z();return}if(X.type==="pax-global-header"){q._parse(X.size,Q),z();return}if(X.type==="pax-header"){q._parse(X.size,K),z();return}if(q._gnuLongPath)X.name=q._gnuLongPath,q._gnuLongPath=null;if(q._gnuLongLinkPath)X.linkname=q._gnuLongLinkPath,q._gnuLongLinkPath=null;if(q._pax)q._header=X=HM1(X,q._pax),q._pax=null;if(q._locked=!0,!X.size||X.type==="directory"){q._parse(512,Z),q.emit("entry",X,KM1(q,V),U);return}q._stream=new lM(q,V),q.emit("entry",X,q._stream,U),q._parse(X.size,I),z()};this._onheader=Z,this._parse(512,Z)};zL0.inherits(t9,UL0);t9.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};t9.prototype._parse=function($,q){if(this._destroyed)return;if(this._offset+=$,this._missing=$,q===this._onheader)this._partial=!1;this._onparse=q};t9.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=JL0,this._overflow)this._write(this._overflow,void 0,$);else $()};t9.prototype._write=function($,q,Y){if(this._destroyed)return;var z=this._stream,U=this._buffer,I=this._missing;if($.length)this._partial=!0;if($.length<I){ Line truncated
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`)}_writeRelationship($){if(!this.count)this._writeOpen();let q=`rId${++this.count}`;if($.TargetMode)this.stream.write(`<Relationship Id="${q}" Type="${$.Type}" Target="${_M1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${q}" Type="${$.Type}" Target="${$.Target}"/>`);return q}_writeClose(){this.stream.write("</Relationships>")}}SL0.exports=gL0});var bL0=M((c54,fL0)=>{var xL0=c6(),kL0=V7(),RM1=x4(),vM1=By(),hM1=Ey();class uL0{constructor($,q,Y){this.id=Y.id,this.count=0,this._worksheet=$,this._workbook=Y.workbook,this._sheetRelsWriter=q}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:kL0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let q={Type:kL0.VmlDrawing,Target:`../drawings/vmlDrawing${this.id}.vml`};this.vmlRelId=this._sheetRelsWriter.addRelationship(q)}_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($,q){let Y=new vM1,z=new xL0;Y.render(z,$),this.commentsStream.write(z.xml);let U=new hM1,I=new xL0;U.render(I,$,q),this.vmlStream.write(I.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((q)=>{q.refAddress=RM1.decodeAddress(q.ref)}),$.forEach((q)=>{this._writeComment(q,this.count),this.count+=1})}}commit(){if(this.count)this._writeClose(),this.commentsStream.end(),this.vmlStream.end()}}fL0.exports=uL0});var mL0=M((p54,dL0)=>{var gM1=l4(),SM1=V7(),Xf=x4(),iL0=cv(),nL0=_9(),yM1=zS(),cL0=aw(),Vf=$L(),xM1=yL0(),kM1=bL0(),uM1=iv(),j6=new yM1,wf=Z7(),fM1=aS(),bM1=eS(),iM1=$y(),nM1=oS(),cM1=mS(),pM1=rS(),dM1=qy(),mM1=Yy(),lM1=zy(),oM1=Uy(),rM1=Iy(),sM1=Jy(),tM1=Zy(),aM1=Ky(),eM1=Qy(),_6={dataValidations:new fM1,sheetProperties:new bM1,sheetFormatProperties:new iM1,columns:new wf({tag:"cols",length:!1,childXform:new nM1}),row:new cM1,hyperlinks:new wf({tag:"hyperlinks",length:!1,childXform:new pM1}),sheetViews:new wf({tag:"sheetViews",length:!1,childXform:new dM1}),sheetProtection:new mM1,pageMargins:new lM1,pageSeteup:new oM1,autoFilter:new rM1,picture:new sM1,conditionalFormattings:new tM1,headerFooter:new aM1,rowBreaks:new eM1};class pL0{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 xM1($),this._sheetCommentsWriter=new kM1(this,this._sheetRelsWriter,$),this._dimensions=new nL0,this._rowZero=1,this.committed=!1,this.dataValidations=new uM1,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
`)},Wy=Vy.getNativePromise();if(Vy.isNode&&typeof MutationObserver>"u")Zy=global.setImmediate,Xy=process.nextTick,MI=Vy.isRecentNode?function($){Zy.call(global,$)}:function($){Xy.call(process,$)};else if(typeof Wy==="function"&&typeof Wy.resolve==="function")Ly=Wy.resolve(),MI=function($){Ly.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))MI=function(){var $=document.createElement("div"),I={attributes:!0},z=!1,q=document.createElement("div"),U=new MutationObserver(function(){$.classList.toggle("foo"),z=!1});U.observe(q,I);var Y=function(){if(z)return;z=!0,q.classList.toggle("foo")};return function(Q){var K=new MutationObserver(function(){K.disconnect(),Q()});K.observe($,I),Y()}}();else if(typeof setImmediate<"u")MI=function($){setImmediate($)};else if(typeof setTimeout<"u")MI=function($){setTimeout($,0)};else MI=LJ1;var Zy,Xy,Ly;lw0.exports=MI});var tw0=F((Ey1,rw0)=>{function DJ1($,I,z,q,U){for(var Y=0;Y<U;++Y)z[Y+q]=$[Y+I],$[Y+I]=void 0}function S7($){this._capacity=$,this._length=0,this._front=0}S7.prototype._willBeOverCapacity=function($){return this._capacity<$};S7.prototype._pushOne=function($){var I=this.length();this._checkCapacity(I+1);var z=this._front+I&this._capacity-1;this[z]=$,this._length=I+1};S7.prototype.push=function($,I,z){var q=this.length()+3;if(this._willBeOverCapacity(q)){this._pushOne($),this._pushOne(I),this._pushOne(z);return}var U=this._front+q-3;this._checkCapacity(q);var Y=this._capacity-1;this[U+0&Y]=$,this[U+1&Y]=I,this[U+2&Y]=z,this._length=q};S7.prototype.shift=function(){var $=this._front,I=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,I};S7.prototype.length=function(){return this._length};S7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};S7.prototype._resizeTo=function($){var I=this._capacity;this._capacity=$;var z=this._front,q=this._length,U=z+q&I-1;DJ1(this,0,this,I,U)};rw0.exports=S7});var qG0=F((By1,Dy)=>{var IG0;try{throw Error()}catch($){IG0=$}var OJ1=ow0(),aw0=tw0(),zG0=r1();function z6(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new aw0(16),this._normalQueue=new aw0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=OJ1}z6.prototype.setScheduler=function($){var I=this._schedule;return this._schedule=$,this._customScheduler=!0,I};z6.prototype.hasCustomScheduler=function(){return this._customScheduler};z6.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};z6.prototype.disableTrampolineIfNecessary=function(){if(zG0.hasDevTools)this._trampolineEnabled=!1};z6.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};z6.prototype.fatalError=function($,I){if(I)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};z6.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(z){throw Error(`No async scheduler available
`)},gf=Sf.getNativePromise();if(Sf.isNode&&typeof MutationObserver>"u")yf=global.setImmediate,xf=process.nextTick,uq=Sf.isRecentNode?function($){yf.call(global,$)}:function($){xf.call(process,$)};else if(typeof gf==="function"&&typeof gf.resolve==="function")kf=gf.resolve(),uq=function($){kf.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))uq=function(){var $=document.createElement("div"),q={attributes:!0},Y=!1,z=document.createElement("div"),U=new MutationObserver(function(){$.classList.toggle("foo"),Y=!1});U.observe(z,q);var I=function(){if(Y)return;Y=!0,z.classList.toggle("foo")};return function(Q){var K=new MutationObserver(function(){K.disconnect(),Q()});K.observe($,q),I()}}();else if(typeof setImmediate<"u")uq=function($){setImmediate($)};else if(typeof setTimeout<"u")uq=function($){setTimeout($,0)};else uq=pN1;var yf,xf,kf;TF0.exports=uq});var _F0=M((Y94,jF0)=>{function dN1($,q,Y,z,U){for(var I=0;I<U;++I)Y[I+z]=$[I+q],$[I+q]=void 0}function b7($){this._capacity=$,this._length=0,this._front=0}b7.prototype._willBeOverCapacity=function($){return this._capacity<$};b7.prototype._pushOne=function($){var q=this.length();this._checkCapacity(q+1);var Y=this._front+q&this._capacity-1;this[Y]=$,this._length=q+1};b7.prototype.push=function($,q,Y){var z=this.length()+3;if(this._willBeOverCapacity(z)){this._pushOne($),this._pushOne(q),this._pushOne(Y);return}var U=this._front+z-3;this._checkCapacity(z);var I=this._capacity-1;this[U+0&I]=$,this[U+1&I]=q,this[U+2&I]=Y,this._length=z};b7.prototype.shift=function(){var $=this._front,q=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,q};b7.prototype.length=function(){return this._length};b7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};b7.prototype._resizeTo=function($){var q=this._capacity;this._capacity=$;var Y=this._front,z=this._length,U=Y+z&q-1;dN1(this,0,this,q,U)};jF0.exports=b7});var yF0=M((z94,uf)=>{var gF0;try{throw Error()}catch($){gF0=$}var mN1=EF0(),CF0=_F0(),SF0=G4();function C6(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new CF0(16),this._normalQueue=new CF0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=mN1}C6.prototype.setScheduler=function($){var q=this._schedule;return this._schedule=$,this._customScheduler=!0,q};C6.prototype.hasCustomScheduler=function(){return this._customScheduler};C6.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};C6.prototype.disableTrampolineIfNecessary=function(){if(SF0.hasDevTools)this._trampolineEnabled=!1};C6.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};C6.prototype.fatalError=function($,q){if(q)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};C6.prototype.throwLater=function($,q){if(arguments.length===1)q=$,$=function(){throw q};if(typeof setTimeout<"u")setTimeout(function(){$(q)},0);else try{this._schedule(function(){$(q)})}catch(Y){throw Error(`No async scheduler available
See http://goo.gl/MqrFmX
`)}};function sw0($,I,z){this._lateQueue.push($,I,z),this._queueTick()}function ew0($,I,z){this._normalQueue.push($,I,z),this._queueTick()}function $G0($){this._normalQueue._pushOne($),this._queueTick()}if(!zG0.hasDevTools)z6.prototype.invokeLater=sw0,z6.prototype.invoke=ew0,z6.prototype.settlePromises=$G0;else z6.prototype.invokeLater=function($,I,z){if(this._trampolineEnabled)sw0.call(this,$,I,z);else this._schedule(function(){setTimeout(function(){$.call(I,z)},100)})},z6.prototype.invoke=function($,I,z){if(this._trampolineEnabled)ew0.call(this,$,I,z);else this._schedule(function(){$.call(I,z)})},z6.prototype.settlePromises=function($){if(this._trampolineEnabled)$G0.call(this,$);else this._schedule(function(){$._settlePromises()})};z6.prototype._drainQueue=function($){while($.length()>0){var I=$.shift();if(typeof I!=="function"){I._settlePromises();continue}var z=$.shift(),q=$.shift();I.call(z,q)}};z6.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};z6.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};z6.prototype._reset=function(){this._isTickUsed=!1};Dy.exports=z6;Dy.exports.firstLineError=IG0});var z9=F((jy1,JG0)=>{var Ny=NI(),FJ1=Ny.freeze,UG0=r1(),YG0=UG0.inherits,_U=UG0.notEnumerableProp;function CU($,I){function z(q){if(!(this instanceof z))return new z(q);if(_U(this,"message",typeof q==="string"?q:I),_U(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return YG0(z,Error),z}var Oy,Fy,NJ1=CU("Warning","warning"),MJ1=CU("CancellationError","cancellation error"),AJ1=CU("TimeoutError","timeout error"),HK=CU("AggregateError","aggregate error");try{Oy=TypeError,Fy=RangeError}catch($){Oy=CU("TypeError","type error"),Fy=CU("RangeError","range error")}var rL="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(AI=0;AI<rL.length;++AI)if(typeof Array.prototype[rL[AI]]==="function")HK.prototype[rL[AI]]=Array.prototype[rL[AI]];var AI;Ny.defineProperty(HK.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});HK.prototype.isOperational=!0;var tL=0;HK.prototype.toString=function(){var $=Array(tL*4+1).join(" "),I=`
`)}};function RF0($,q,Y){this._lateQueue.push($,q,Y),this._queueTick()}function vF0($,q,Y){this._normalQueue.push($,q,Y),this._queueTick()}function hF0($){this._normalQueue._pushOne($),this._queueTick()}if(!SF0.hasDevTools)C6.prototype.invokeLater=RF0,C6.prototype.invoke=vF0,C6.prototype.settlePromises=hF0;else C6.prototype.invokeLater=function($,q,Y){if(this._trampolineEnabled)RF0.call(this,$,q,Y);else this._schedule(function(){setTimeout(function(){$.call(q,Y)},100)})},C6.prototype.invoke=function($,q,Y){if(this._trampolineEnabled)vF0.call(this,$,q,Y);else this._schedule(function(){$.call(q,Y)})},C6.prototype.settlePromises=function($){if(this._trampolineEnabled)hF0.call(this,$);else this._schedule(function(){$._settlePromises()})};C6.prototype._drainQueue=function($){while($.length()>0){var q=$.shift();if(typeof q!=="function"){q._settlePromises();continue}var Y=$.shift(),z=$.shift();q.call(Y,z)}};C6.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};C6.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};C6.prototype._reset=function(){this._isTickUsed=!1};uf.exports=C6;uf.exports.firstLineError=gF0});var e9=M((U94,uF0)=>{var nf=kq(),lN1=nf.freeze,xF0=G4(),kF0=xF0.inherits,DI=xF0.notEnumerableProp;function AI($,q){function Y(z){if(!(this instanceof Y))return new Y(z);if(DI(this,"message",typeof z==="string"?z:q),DI(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return kF0(Y,Error),Y}var ff,bf,oN1=AI("Warning","warning"),rN1=AI("CancellationError","cancellation error"),sN1=AI("TimeoutError","timeout error"),SG=AI("AggregateError","aggregate error");try{ff=TypeError,bf=RangeError}catch($){ff=AI("TypeError","type error"),bf=AI("RangeError","range error")}var YN="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(fq=0;fq<YN.length;++fq)if(typeof Array.prototype[YN[fq]]==="function")SG.prototype[YN[fq]]=Array.prototype[YN[fq]];var fq;nf.defineProperty(SG.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});SG.prototype.isOperational=!0;var zN=0;SG.prototype.toString=function(){var $=Array(zN*4+1).join(" "),q=`
`+$+`AggregateError of:
`;tL++,$=Array(tL*4+1).join(" ");for(var z=0;z<this.length;++z){var q=this[z]===this?"[Circular AggregateError]":this[z]+"",U=q.split(`
`);for(var Y=0;Y<U.length;++Y)U[Y]=$+U[Y];q=U.join(`
`),I+=q+`
`}return tL--,I};function GK($){if(!(this instanceof GK))return new GK($);if(_U(this,"name","OperationalError"),_U(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)_U(this,"message",$.message),_U(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}YG0(GK,Error);var PI=Error.__BluebirdErrorTypes__;if(!PI)PI=FJ1({CancellationError:MJ1,TimeoutError:AJ1,OperationalError:GK,RejectionError:GK,AggregateError:HK}),Ny.defineProperty(Error,"__BluebirdErrorTypes__",{value:PI,writable:!1,enumerable:!1,configurable:!1});JG0.exports={Error,TypeError:Oy,RangeError:Fy,CancellationError:PI.CancellationError,OperationalError:PI.OperationalError,TimeoutError:PI.TimeoutError,AggregateError:PI.AggregateError,Warning:NJ1}});var KG0=F((vy1,QG0)=>{QG0.exports=function($,I){var z=r1(),q=z.errorObj,U=z.isObject;function Y(H,W){if(U(H)){if(H instanceof $)return H;var V=Q(H);if(V===q){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 J(H){return H.then}function Q(H){try{return J(H)}catch(W){return q.e=W,q}}var K={}.hasOwnProperty;function w(H){try{return K.call(H,"_promise0")}catch(W){return!1}}function G(H,W,V){var X=new $(I),L=X;if(V)V._pushContext();if(X._captureStackTrace(),V)V._popContext();var D=!0,O=z.tryCatch(W).call(H,A,T);if(D=!1,X&&O===q)X._rejectCallback(O.e,!0,!0),X=null;function A(M){if(!X)return;X._resolveCallback(M),X=null}function T(M){if(!X)return;X._rejectCallback(M,D,!0),X=null}return L}return Y}});var GG0=F((Ry1,wG0)=>{wG0.exports=function($,I,z,q,U){var Y=r1(),J=Y.isArray;function Q(w){switch(w){case-2:return[];case-3:return{}}}function K(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 Y.inherits(K,U),K.prototype.length=function(){return this._length},K.prototype.promise=function(){return this._promise},K.prototype._init=function w(G,H){var W=z(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=Y.asArray(W),W===null){var X=q("expecting an array or an iterable object but got "+Y.classString(W)).reason();this._promise._rejectCallback(X,!1);return}if(W.length===0){if(H===-5)this._resolveEmptyArray();else this._resolve(Q(H));return}this._iterate(W)},K.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 L=z(w[X],H);if(L instanceof $)L=L._target(),V=L._bitField;else V=null;if(W){if(V!==null)L.suppressUnhandledRejections()}else if(V!==null)if((V&50397184)===0)L._proxy(this,X),this._values[X]=L;else if((V&33554432)!==0)W=this._promiseFulfilled(L._value(),X);else if((V&16777216)!==0)W=this._promiseRejected(L._reason(),X);else W=this._promiseCancelled(X);else W=this._promiseFulfilled(L,X)}if(!W)H._setAsyncGuaranteed()},K.prototype._isResolved=function(){return this._values===null},K.prototype._resolve=function(w){this._values=null,this._promise._fulfill(w)},K.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},K.prototype._reject=function(w){this._values=null,this._promise._rejectCallback(w,!1)},K.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},K.prototype._promiseCancelled=function(){return this._cancel(),!0},K.prototype._promiseRejected=function(w){return this._totalResolved++,this._reject(w),!0},K.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()},K.prototype.shouldCopyValues=function(){return!0},K.prototype.getActualLength=function(w){return w},K}});var WG0=F((gy1,HG0)=>{HG0.exports=function($){var I=!1,z=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function q(){this._trace=new q.CapturedTrace(Y())}q.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,z.push(this._trace)},q.prototype._popContext=function(){if(this._trace!==void 0){var J=z.pop(),Q=J._promiseCreated;return J._promiseCreated=null,Q}return null};function U(){if(I)return new q}function Y(){var J=z.length-1;if(J>=0)return z[J];return}return q.CapturedTrace=null,q.create=U,q.deactivateLong Line truncated
`;zN++,$=Array(zN*4+1).join(" ");for(var Y=0;Y<this.length;++Y){var z=this[Y]===this?"[Circular AggregateError]":this[Y]+"",U=z.split(`
`);for(var I=0;I<U.length;++I)U[I]=$+U[I];z=U.join(`
`),q+=z+`
`}return zN--,q};function gG($){if(!(this instanceof gG))return new gG($);if(DI(this,"name","OperationalError"),DI(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)DI(this,"message",$.message),DI(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}kF0(gG,Error);var bq=Error.__BluebirdErrorTypes__;if(!bq)bq=lN1({CancellationError:rN1,TimeoutError:sN1,OperationalError:gG,RejectionError:gG,AggregateError:SG}),nf.defineProperty(Error,"__BluebirdErrorTypes__",{value:bq,writable:!1,enumerable:!1,configurable:!1});uF0.exports={Error,TypeError:ff,RangeError:bf,CancellationError:bq.CancellationError,OperationalError:bq.OperationalError,TimeoutError:bq.TimeoutError,AggregateError:bq.AggregateError,Warning:oN1}});var bF0=M((I94,fF0)=>{fF0.exports=function($,q){var Y=G4(),z=Y.errorObj,U=Y.isObject;function I(Z,V){if(U(Z)){if(Z instanceof $)return Z;var X=Q(Z);if(X===z){if(V)V._pushContext();var w=$.reject(X.e);if(V)V._popContext();return w}else if(typeof X==="function"){if(H(Z)){var w=new $(q);return Z._then(w._fulfill,w._reject,void 0,w,null),w}return G(Z,X,V)}}return Z}function J(Z){return Z.then}function Q(Z){try{return J(Z)}catch(V){return z.e=V,z}}var K={}.hasOwnProperty;function H(Z){try{return K.call(Z,"_promise0")}catch(V){return!1}}function G(Z,V,X){var w=new $(q),L=w;if(X)X._pushContext();if(w._captureStackTrace(),X)X._popContext();var F=!0,O=Y.tryCatch(V).call(Z,A,B);if(F=!1,w&&O===z)w._rejectCallback(O.e,!0,!0),w=null;function A(P){if(!w)return;w._resolveCallback(P),w=null}function B(P){if(!w)return;w._rejectCallback(P,F,!0),w=null}return L}return I}});var nF0=M((J94,iF0)=>{iF0.exports=function($,q,Y,z,U){var I=G4(),J=I.isArray;function Q(H){switch(H){case-2:return[];case-3:return{}}}function K(H){var G=this._promise=new $(q);if(H instanceof $)G._propagateFrom(H,3);G._setOnCancel(this),this._values=H,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return I.inherits(K,U),K.prototype.length=function(){return this._length},K.prototype.promise=function(){return this._promise},K.prototype._init=function H(G,Z){var V=Y(this._values,this._promise);if(V instanceof $){V=V._target();var X=V._bitField;if(this._values=V,(X&50397184)===0)return this._promise._setAsyncGuaranteed(),V._then(H,this._reject,void 0,this,Z);else if((X&33554432)!==0)V=V._value();else if((X&16777216)!==0)return this._reject(V._reason());else return this._cancel()}if(V=I.asArray(V),V===null){var w=z("expecting an array or an iterable object but got "+I.classString(V)).reason();this._promise._rejectCallback(w,!1);return}if(V.length===0){if(Z===-5)this._resolveEmptyArray();else this._resolve(Q(Z));return}this._iterate(V)},K.prototype._iterate=function(H){var G=this.getActualLength(H.length);this._length=G,this._values=this.shouldCopyValues()?Array(G):this._values;var Z=this._promise,V=!1,X=null;for(var w=0;w<G;++w){var L=Y(H[w],Z);if(L instanceof $)L=L._target(),X=L._bitField;else X=null;if(V){if(X!==null)L.suppressUnhandledRejections()}else if(X!==null)if((X&50397184)===0)L._proxy(this,w),this._values[w]=L;else if((X&33554432)!==0)V=this._promiseFulfilled(L._value(),w);else if((X&16777216)!==0)V=this._promiseRejected(L._reason(),w);else V=this._promiseCancelled(w);else V=this._promiseFulfilled(L,w)}if(!V)Z._setAsyncGuaranteed()},K.prototype._isResolved=function(){return this._values===null},K.prototype._resolve=function(H){this._values=null,this._promise._fulfill(H)},K.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},K.prototype._reject=function(H){this._values=null,this._promise._rejectCallback(H,!1)},K.prototype._promiseFulfilled=function(H,G){this._values[G]=H;var Z=++this._totalResolved;if(Z>=this._length)return this._resolve(this._values),!0;return!1},K.prototype._promiseCancelled=function(){return this._cancel(),!0},K.prototype._promiseRejected=function(H){return this._totalResolved++,this._reject(H),!0},K.prototype._resultCancelled=function(){if(this._isResolved())return;var H=this._values;if(this._cancel(),H instanceof $)H.cancel();else for(var G=0;G<H.length;++G)if(H[G]instanceof $)H[G].cancel()},K.prototype.shouldCopyValues=function(){return!0},K.prototype.getActualLength=function(H){return H},K}});var pF0=M((Q94,cF0)=>{cF0.exports=function($){var q=!1,Y=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function z(){this._trace=new z.CapturedTrace(I())}z.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,Y.push(this._trace)},z.prototype._popContext=function(){if(this._trace!==void 0){var J=Y.pop(),Q=J._promiseCreated;return J._promiseCreated=null,Q}return null};function U(){if(q)return new z}function I(){var J=Y.length-1;if(J>=0)return Y[J];return}return z.CapturedTrace=null,z.create=U,z.deactivateLong Line truncated
See http://goo.gl/MqrFmX
`);if(!R0.longStackTraces&&$$()){var a=$.prototype._captureStackTrace,N=$.prototype._attachExtraTrace;R0.longStackTraces=!0,M=function(){if(q.haveItemsQueued()&&!R0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
`);if(!L0.longStackTraces&&F1()){var o=$.prototype._captureStackTrace,N=$.prototype._attachExtraTrace;L0.longStackTraces=!0,P=function(){if(z.haveItemsQueued()&&!L0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
See http://goo.gl/MqrFmX
`);$.prototype._captureStackTrace=a,$.prototype._attachExtraTrace=N,I.deactivateLongStackTraces(),q.enableTrampoline(),R0.longStackTraces=!1},$.prototype._captureStackTrace=e,$.prototype._attachExtraTrace=G0,I.activateLongStackTraces(),q.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return R0.longStackTraces&&$$()};var v=function(){try{if(typeof CustomEvent==="function"){var a=new CustomEvent("CustomEvent");return Y.global.dispatchEvent(a),function(N,P){var S=new CustomEvent(N.toLowerCase(),{detail:P,cancelable:!0});return!Y.global.dispatchEvent(S)}}else if(typeof Event==="function"){var a=new Event("CustomEvent");return Y.global.dispatchEvent(a),function(P,S){var i=new Event(P.toLowerCase(),{cancelable:!0});return i.detail=S,!Y.global.dispatchEvent(i)}}else{var a=document.createEvent("CustomEvent");return a.initCustomEvent("testingtheevent",!1,!0,{}),Y.global.dispatchEvent(a),function(P,S){var i=document.createEvent("CustomEvent");return i.initCustomEvent(P.toLowerCase(),!1,!0,S),!Y.global.dispatchEvent(i)}}}catch(N){}return function(){return!1}}(),x=function(){if(Y.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!Y.global)return function(){return!1};return function(a){var N="on"+a.toLowerCase(),P=Y.global[N];if(!P)return!1;return P.apply(Y.global,[].slice.call(arguments,1)),!0}}}();function h(a,N){return{promise:N}}var k={promiseCreated:h,promiseFulfilled:h,promiseRejected:h,promiseResolved:h,promiseCancelled:h,promiseChained:function(a,N,P){return{promise:N,child:P}},warning:function(a,N){return{warning:N}},unhandledRejection:function(a,N,P){return{reason:N,promise:P}},rejectionHandled:h},E=function(a){var N=!1;try{N=x.apply(null,arguments)}catch(S){q.throwLater(S),N=!0}var P=!1;try{P=v(a,k[a].apply(null,arguments))}catch(S){q.throwLater(S),P=!0}return P||N};$.config=function(a){if(a=Object(a),"longStackTraces"in a){if(a.longStackTraces)$.longStackTraces();else if(!a.longStackTraces&&$.hasLongStackTraces())M()}if("warnings"in a){var N=a.warnings;if(R0.warnings=!!N,T=R0.warnings,Y.isObject(N)){if("wForgottenReturn"in N)T=!!N.wForgottenReturn}}if("cancellation"in a&&a.cancellation&&!R0.cancellation){if(q.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=q0,$.prototype._propagateFrom=R,$.prototype._onCancel=b,$.prototype._setOnCancel=p,$.prototype._attachCancellationCallback=g,$.prototype._execute=n,c=R,R0.cancellation=!0}if("monitoring"in a){if(a.monitoring&&!R0.monitoring)R0.monitoring=!0,$.prototype._fireEvent=E;else if(!a.monitoring&&R0.monitoring)R0.monitoring=!1,$.prototype._fireEvent=f}return $};function f(){return!1}$.prototype._fireEvent=f,$.prototype._execute=function(a,N,P){try{a(N,P)}catch(S){return S}},$.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,P){var S=this;try{a(N,P,function(i){if(typeof i!=="function")throw TypeError("onCancel must be a function, got: "+Y.toString(i));S._attachCancellationCallback(i)})}catch(i){return i}}function g(a){if(!this._isCancellable())return this;var N=this._onCancel();if(N!==void 0)if(Y.isArray(N))N.push(a);else this._setOnCancel([N,a]);else this._setOnCancel(a)}function b(){return this._onCancelField}function p(a){this._onCancelField=a}function q0(){this._cancellationParent=void 0,this._onCancelField=void 0}function R(a,N){if((N&1)!==0){this._cancellationParent=a;var P=a._branchesRemainingToCancel;if(P===void 0)P=0;a._branchesRemainingToCancel=P+1}if((N&2)!==0&&a._isBound())this._setBoundTo(a._boundTo)}function u(a,N){if((N&2)!==0&&a._isBound())this._setBoundTo(a._boundTo)}var c=u;function m(){var a=this._boundTo;if(a!==void 0){if(a instanceof $)if(a.isFulfilled())return a.value();else return}return a}function e(){this._trace=new M$(this._peekContext())}function G0(a,N){if(J(a)){var P=this._trace;if(P!==void 0){if(N)P=P._parent}if(P!==void 0)P.attachExtraTrace(a);else if(!a.__stackCleaned__){var S=I1(a);Y.notEnumerableProp(a,"stack",S.message+`
`+S.stack.join(`
`)),Y.notEnumerableProp(a,"__stackCleaned__",!0)}}}function M0(a,N,P,S,i){if(a===void 0&&N!==null&&T){if(i!==void 0&&i._returnedNonUndefined())return;if((S._bitField&65535)===0)return;if(P)P=P+" ";var s="",o="";if(N._trace){var $0=N._trace.stack.split(`
`),J0=U0($0);for(var W0=J0.length-1;W0>=0;--W0){var y0=J0[W0];if(!G.test(y0)){var c0=y0.match(H);if(c0)s="at "+c0[1]+":"+c0[2]+":"+c0[3]+" ";break}}if(J0.length>0){var i0=J0[0];for(var W0=0;W0<$0.length;++W0)if($0[W0]===i0){if(W0>0)o=`
`+$0[W0-1];break}}}var V1="a promise was created in a "+P+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+o;S._warn(V1,!0,N)}}function g0(a,N){var P=a+" is deprecated and will be removed in a future version.";if(N)P+=" Use "+N+" instead.";return G1(P)}function G1(a,N,P){if(!R0.warnings)return;var S=new U(a),i;if(N)P._attachExtraTrace(S);else if(R0.longStackTraces&&(i=$._peekContext()))i.attachExtraTrace(S);else{var s=I1(S);S.stack=s.message+`
`+s.stack.join(`
`)}if(!E("warning",S))W1(S,"",!0)}function S0(a,N){for(var P=0;P<N.length-1;++P)N[P].push("From previous event:"),N[P]=N[P].join(`
`);if(P<N.length)N[P]=N[P].join(`
`);return a+`
`);$.prototype._captureStackTrace=o,$.prototype._attachExtraTrace=N,q.deactivateLongStackTraces(),z.enableTrampoline(),L0.longStackTraces=!1},$.prototype._captureStackTrace=Y0,$.prototype._attachExtraTrace=t,q.activateLongStackTraces(),z.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return L0.longStackTraces&&F1()};var T=function(){try{if(typeof CustomEvent==="function"){var o=new CustomEvent("CustomEvent");return I.global.dispatchEvent(o),function(N,D){var h=new CustomEvent(N.toLowerCase(),{detail:D,cancelable:!0});return!I.global.dispatchEvent(h)}}else if(typeof Event==="function"){var o=new Event("CustomEvent");return I.global.dispatchEvent(o),function(D,h){var x=new Event(D.toLowerCase(),{cancelable:!0});return x.detail=h,!I.global.dispatchEvent(x)}}else{var o=document.createEvent("CustomEvent");return o.initCustomEvent("testingtheevent",!1,!0,{}),I.global.dispatchEvent(o),function(D,h){var x=document.createEvent("CustomEvent");return x.initCustomEvent(D.toLowerCase(),!1,!0,h),!I.global.dispatchEvent(x)}}}catch(N){}return function(){return!1}}(),y=function(){if(I.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!I.global)return function(){return!1};return function(o){var N="on"+o.toLowerCase(),D=I.global[N];if(!D)return!1;return D.apply(I.global,[].slice.call(arguments,1)),!0}}}();function v(o,N){return{promise:N}}var k={promiseCreated:v,promiseFulfilled:v,promiseRejected:v,promiseResolved:v,promiseCancelled:v,promiseChained:function(o,N,D){return{promise:N,child:D}},warning:function(o,N){return{warning:N}},unhandledRejection:function(o,N,D){return{reason:N,promise:D}},rejectionHandled:v},R=function(o){var N=!1;try{N=y.apply(null,arguments)}catch(h){z.throwLater(h),N=!0}var D=!1;try{D=T(o,k[o].apply(null,arguments))}catch(h){z.throwLater(h),D=!0}return D||N};$.config=function(o){if(o=Object(o),"longStackTraces"in o){if(o.longStackTraces)$.longStackTraces();else if(!o.longStackTraces&&$.hasLongStackTraces())P()}if("warnings"in o){var N=o.warnings;if(L0.warnings=!!N,B=L0.warnings,I.isObject(N)){if("wForgottenReturn"in N)B=!!N.wForgottenReturn}}if("cancellation"in o&&o.cancellation&&!L0.cancellation){if(z.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=$0,$.prototype._propagateFrom=j,$.prototype._onCancel=b,$.prototype._setOnCancel=i,$.prototype._attachCancellationCallback=g,$.prototype._execute=n,p=j,L0.cancellation=!0}if("monitoring"in o){if(o.monitoring&&!L0.monitoring)L0.monitoring=!0,$.prototype._fireEvent=R;else if(!o.monitoring&&L0.monitoring)L0.monitoring=!1,$.prototype._fireEvent=c}return $};function c(){return!1}$.prototype._fireEvent=c,$.prototype._execute=function(o,N,D){try{o(N,D)}catch(h){return h}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(o){},$.prototype._attachCancellationCallback=function(o){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(o,N){};function n(o,N,D){var h=this;try{o(N,D,function(x){if(typeof x!=="function")throw TypeError("onCancel must be a function, got: "+I.toString(x));h._attachCancellationCallback(x)})}catch(x){return x}}function g(o){if(!this._isCancellable())return this;var N=this._onCancel();if(N!==void 0)if(I.isArray(N))N.push(o);else this._setOnCancel([N,o]);else this._setOnCancel(o)}function b(){return this._onCancelField}function i(o){this._onCancelField=o}function $0(){this._cancellationParent=void 0,this._onCancelField=void 0}function j(o,N){if((N&1)!==0){this._cancellationParent=o;var D=o._branchesRemainingToCancel;if(D===void 0)D=0;o._branchesRemainingToCancel=D+1}if((N&2)!==0&&o._isBound())this._setBoundTo(o._boundTo)}function u(o,N){if((N&2)!==0&&o._isBound())this._setBoundTo(o._boundTo)}var p=u;function d(){var o=this._boundTo;if(o!==void 0){if(o instanceof $)if(o.isFulfilled())return o.value();else return}return o}function Y0(){this._trace=new I6(this._peekContext())}function t(o,N){if(J(o)){var D=this._trace;if(D!==void 0){if(N)D=D._parent}if(D!==void 0)D.attachExtraTrace(o);else if(!o.__stackCleaned__){var h=f0(o);I.notEnumerableProp(o,"stack",h.message+`
`+h.stack.join(`
`)),I.notEnumerableProp(o,"__stackCleaned__",!0)}}}function H0(o,N,D,h,x){if(o===void 0&&N!==null&&B){if(x!==void 0&&x._returnedNonUndefined())return;if((h._bitField&65535)===0)return;if(D)D=D+" ";var q0="",r="";if(N._trace){var z0=N._trace.stack.split(`
`),K0=Q0(z0);for(var V0=K0.length-1;V0>=0;--V0){var x0=K0[V0];if(!G.test(x0)){var r0=x0.match(Z);if(r0)q0="at "+r0[1]+":"+r0[2]+":"+r0[3]+" ";break}}if(K0.length>0){var l0=K0[0];for(var V0=0;V0<z0.length;++V0)if(z0[V0]===l0){if(V0>0)r=`
`+z0[V0-1];break}}}var D1="a promise was created in a "+D+"handler "+q0+"but was not returned from it, see http://goo.gl/rRqMUw"+r;h._warn(D1,!0,N)}}function w0(o,N){var D=o+" is deprecated and will be removed in a future version.";if(N)D+=" Use "+N+" instead.";return T0(D)}function T0(o,N,D){if(!L0.warnings)return;var h=new U(o),x;if(N)D._attachExtraTrace(h);else if(L0.longStackTraces&&(x=$._peekContext()))x.attachExtraTrace(h);else{var q0=f0(h);h.stack=q0.message+`
`+q0.stack.join(`
`)}if(!R("warning",h))c0(h,"",!0)}function R0(o,N){for(var D=0;D<N.length-1;++D)N[D].push("From previous event:"),N[D]=N[D].join(`
`);if(D<N.length)N[D]=N[D].join(`
`);return o+`
`+N.join(`
`)}function $1(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 A0(a){var N=a[0];for(var P=1;P<a.length;++P){var S=a[P],i=N.length-1,s=N[i],o=-1;for(var $0=S.length-1;$0>=0;--$0)if(S[$0]===s){o=$0;break}for(var $0=o;$0>=0;--$0){var J0=S[$0];if(N[i]===J0)N.pop(),i--;else break}N=S}}function U0(a){var N=[];for(var P=0;P<a.length;++P){var S=a[P],i=S===" (No stack trace)"||W.test(S),s=i&&k6(S);if(i&&!s){if(X&&S.charAt(0)!==" ")S=" "+S;N.push(S)}}return N}function v0(a){var N=a.stack.replace(/\s+$/g,"").split(`
`);for(var P=0;P<N.length;++P){var S=N[P];if(S===" (No stack trace)"||W.test(S))break}if(P>0&&a.name!="SyntaxError")N=N.slice(P);return N}function I1(a){var N=a.stack,P=a.toString();return N=typeof N==="string"&&N.length>0?v0(a):[" (No stack trace)"],{message:P,stack:a.name=="SyntaxError"?N:U0(N)}}function W1(a,N,P){if(typeof console<"u"){var S;if(Y.isObject(a)){var i=a.stack;S=N+V(i,a)}else S=N+String(a);if(typeof L==="function")L(S,P);else if(typeof console.log==="function"||typeof console.log==="object")console.log(S)}}function T4(a,N,P,S){var i=!1;try{if(typeof N==="function")if(i=!0,a==="rejectionHandled")N(S);else N(P,S)}catch(s){q.throwLater(s)}if(a==="unhandledRejection"){if(!E(a,P,S)&&!i)W1(P,"Unhandled rejection ")}else E(a,S)}function S4(a){var N;if(typeof a==="function")N="[function "+(a.name||"anonymous")+"]";else{N=a&&typeof a.toString==="function"?a.toString():Y.toString(a);var P=/\[object [a-zA-Z0-9$_]+\]/;if(P.test(N))try{var S=JSON.stringify(a);N=S}catch(i){}if(N.length===0)N="(empty array)"}return"(<"+b$(N)+">, no stack trace)"}function b$(a){var N=41;if(a.length<N)return a;return a.substr(0,N-3)+"..."}function $$(){return typeof N9==="function"}var k6=function(){return!1},n$=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function N$(a){var N=a.match(n$);if(N)return{fileName:N[1],line:parseInt(N[2],10)}}function a7(a,N){if(!$$())return;var P=a.stack.split(`
`),S=N.stack.split(`
`),i=-1,s=-1,o,$0;for(var J0=0;J0<P.length;++J0){var W0=N$(P[J0]);if(W0){o=W0.fileName,i=W0.line;break}}for(var J0=0;J0<S.length;++J0){var W0=N$(S[J0]);if(W0){$0=W0.fileName,s=W0.line;break}}if(i<0||s<0||!o||!$0||o!==$0||i>=s)return;k6=function(y0){if(w.test(y0))return!0;var c0=N$(y0);if(c0){if(c0.fileName===o&&(i<=c0.line&&c0.line<=s))return!0}return!1}}function M$(a){this._parent=a,this._promisesCreated=0;var N=this._length=1+(a===void 0?0:a._length);if(N9(this,M$),N>32)this.uncycle()}Y.inherits(M$,Error),I.CapturedTrace=M$,M$.prototype.uncycle=function(){var a=this._length;if(a<2)return;var N=[],P={};for(var S=0,i=this;i!==void 0;++S)N.push(i),i=i._parent;a=this._length=S;for(var S=a-1;S>=0;--S){var s=N[S].stack;if(P[s]===void 0)P[s]=S}for(var S=0;S<a;++S){var o=N[S].stack,$0=P[o];if($0!==void 0&&$0!==S){if($0>0)N[$0-1]._parent=void 0,N[$0-1]._length=1;N[S]._parent=void 0,N[S]._length=1;var J0=S>0?N[S-1]:this;if($0<a-1)J0._parent=N[$0+1],J0._parent.uncycle(),J0._length=J0._parent._length+1;else J0._parent=void 0,J0._length=1;var W0=J0._length+1;for(var y0=S-2;y0>=0;--y0)N[y0]._length=W0,W0++;return}}},M$.prototype.attachExtraTrace=function(a){if(a.__stackCleaned__)return;this.uncycle();var N=I1(a),P=N.message,S=[N.stack],i=this;while(i!==void 0)S.push(U0(i.stack.split(`
`))),i=i._parent;A0(S),$1(S),Y.notEnumerableProp(a,"stack",S0(P,S)),Y.notEnumerableProp(a,"__stackCleaned__",!0)};var N9=function(){var N=/^\s*at\s*/,P=function(o,$0){if(typeof o==="string")return o;if($0.name!==void 0&&$0.message!==void 0)return $0.toString();return S4($0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,W=N,V=P;var S=Error.captureStackTrace;return k6=function(o){return w.test(o)},function(o,$0){Error.stackTraceLimit+=6,S(o,$0),Error.stackTraceLimit-=6}}var i=Error();if(typeof i.stack==="string"&&i.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return W=/@/,V=P,X=!0,function($0){$0.stack=Error().stack};var s;try{throw Error()}catch(o){s="stack"in o}if(!("stack"in i)&&s&&typeof Error.stackTraceLimit==="number")return W=N,V=P,function($0){Error.stackTraceLimit+=6;try{throw Error()}catch(J0){$0.stack=J0.stack}Error.stackTraceLimit-=6};return V=function(o,$0){if(typeof o==="string")return o;if((typeof $0==="object"||typeof $0==="function")&&$0.name!==void 0&&$0.message!==void 0)return $0.toString();return S4($0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(L=function(a){console.warn(a)},Y.isNode&&process.stderr.isTTY)L=function(a,N){var P=N?"\x1B[33m":"\x1B[31m";console.warn(P+a+`\x1B[0m
`)};else if(!Y.isNode&&typeof Error().stack==="string")L=function(a,N){console.warn("%c"+a,N?"color: darkorange":"color: red")}}var R0={warnings:O,longStackTraces:!1,cancellation:!1,monitoring:!1};if(A)$.longStackTraces();return{longStackTraces:function(){return R0.longStackTraces},warnings:function(){return R0.warnings},cancellation:function(){return R0.cancellation},monitoring:function(){return R0.monitoring},propagateFromFunction:function(){return c},boundValueFunction:function(){return m},checkForgottenReturns:M0,setBounds:a7,warn:G1,deprecated:g0,CapturedTrace:M$,fireDomEvent:v,fireGlobalEvent:x}}});var LG0=F((Cy1,XG0)=>{XG0.exports=function($,I){var z=r1(),q=$.CancellationError,U=z.errorObj;function Y(H,W,V){this.promise=H,this.type=W,this.handler=V,this.called=!1,this.cancelPromise=null}Y.prototype.isFinallyHandler=function(){return this.type===0};function J(H){this.finallyHandler=H}J.prototype._resultCancelled=function(){Q(this.finallyHandler)};function Q(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 K(){return G.call(this,this.promise._target()._settledValue())}function w(H){if(Q(this,H))return;return U.e=H,U}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 L=I(X,W);if(L instanceof $){if(this.cancelPromise!=null){if(L._isCancelled()){var D=new q("late cancellation observer");return W._attachExtraTrace(D),U.e=D,U}else if(L.isPending())L._attachCancellationCallback(new J(this))}return L._then(K,w,void 0,this,void 0)}}}if(W.isRejected())return Q(this),U.e=H,U;else return Q(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 Y(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)},Y}});var OG0=F((hy1,DG0)=>{DG0.exports=function($){var I=r1(),z=NI().keys,q=I.tryCatch,U=I.errorObj;function Y(J,Q,K){return function(w){var G=K._boundValue();$:for(var H=0;H<J.length;++H){var W=J[H];if(W===Error||W!=null&&W.prototype instanceof Error){if(w instanceof W)return q(Q).call(G,w)}else if(typeof W==="function"){var V=q(W).call(G,w);if(V===U)return V;else if(V)return q(Q).call(G,w)}else if(I.isObject(w)){var X=z(W);for(var L=0;L<X.length;++L){var D=X[L];if(W[D]!=w[D])continue $}return q(Q).call(G,w)}}return $}}return Y}});var My=F((Sy1,MG0)=>{var FG0=r1(),PJ1=FG0.maybeWrapAsError,TJ1=z9(),EJ1=TJ1.OperationalError,NG0=NI();function BJ1($){return $ instanceof Error&&NG0.getPrototypeOf($)===Error.prototype}var jJ1=/^(?:name|message|stack|cause)$/;function vJ1($){var I;if(BJ1($)){I=new EJ1($),I.name=$.name,I.message=$.message,I.stack=$.stack;var z=NG0.keys($);for(var q=0;q<z.length;++q){var U=z[q];if(!jJ1.test(U))I[U]=$[U]}return I}return FG0.markAsOriginatingFromRejection($),$}function RJ1($,I){return function(z,q){if($===null)return;if(z){var U=vJ1(PJ1(z));$._attachExtraTrace(U),$._reject(U)}else if(!I)$._fulfill(q);else{var Y=arguments.length,J=Array(Math.max(Y-1,0));for(var Q=1;Q<Y;++Q)J[Q-1]=arguments[Q];$._fulfill(J)}$=null}}MG0.exports=RJ1});var PG0=F((yy1,AG0)=>{AG0.exports=function($,I,z,q,U){var Y=r1(),J=Y.tryCatch;$.method=function(Q){if(typeof Q!=="function")throw new $.TypeError("expecting a function but got "+Y.classString(Q));return function(){var K=new $(I);K._captureStackTrace(),K._pushContext();var w=J(Q).apply(this,arguments),G=K._popContext();return U.checkForgottenReturns(w,G,"Promise.method",K),K._resolveFromSyncValue(w),K}},$.attempt=$.try=function(Q){if(typeof Q!=="function")return q("expecting a function but got "+Y.classString(Q));var K=new $(I);K._captureStackTrace(),K._pushContext();var w;if(arguments.length>1){U.deprecated("calling Promise.try with more than 1 argument");var G=arguments[1],H=arguments[2];w=Y.isArray(G)?J(Q).apply(H,G):J(Q).call(H,G)}else w=J(Q)();var W=K._popContext();return U.checkForgottenReturns(w,W,"Promise.try",K),K._resolveFromSyncValue(w),K},$.prototype._resolveFromSyncValue=function(Q){if(Q===Y.errorObj)this._rejectCallback(Q.e,!1);else this._resolveCallback(Q,!0)}}});var EG0=F((uy1,TG0)=>{TG0.exports=function($,I,z,q){var U=!1,Y=function(w,G){this._reject(G)},J=function(w,G){G.promiseRejectionQueued=!0,G.bindingPromise._then(Y,Y,null,this,w)},Q=function(w,G){if((this._bitField&50397184)===0)this._resolveCallback(G.target)},K=function(w,G){if(!G.promiseRejectionQueued)this._reject(w)};$.prototype.bind=function(w){if(!U)U=!0,$.prototype._propagateFrom=q.propagateFromFunction(),$.prototype._boundValue=q.boundValueFunction();var G=z(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,J,voi Line truncated
`)}function E0(o){for(var N=0;N<o.length;++N)if(o[N].length===0||N+1<o.length&&o[N][0]===o[N+1][0])o.splice(N,1),N--}function i0(o){var N=o[0];for(var D=1;D<o.length;++D){var h=o[D],x=N.length-1,q0=N[x],r=-1;for(var z0=h.length-1;z0>=0;--z0)if(h[z0]===q0){r=z0;break}for(var z0=r;z0>=0;--z0){var K0=h[z0];if(N[x]===K0)N.pop(),x--;else break}N=h}}function Q0(o){var N=[];for(var D=0;D<o.length;++D){var h=o[D],x=h===" (No stack trace)"||V.test(h),q0=x&&b1(h);if(x&&!q0){if(w&&h.charAt(0)!==" ")h=" "+h;N.push(h)}}return N}function v0(o){var N=o.stack.replace(/\s+$/g,"").split(`
`);for(var D=0;D<N.length;++D){var h=N[D];if(h===" (No stack trace)"||V.test(h))break}if(D>0&&o.name!="SyntaxError")N=N.slice(D);return N}function f0(o){var N=o.stack,D=o.toString();return N=typeof N==="string"&&N.length>0?v0(o):[" (No stack trace)"],{message:D,stack:o.name=="SyntaxError"?N:Q0(N)}}function c0(o,N,D){if(typeof console<"u"){var h;if(I.isObject(o)){var x=o.stack;h=N+X(x,o)}else h=N+String(o);if(typeof L==="function")L(h,D);else if(typeof console.log==="function"||typeof console.log==="object")console.log(h)}}function R1(o,N,D,h){var x=!1;try{if(typeof N==="function")if(x=!0,o==="rejectionHandled")N(h);else N(D,h)}catch(q0){z.throwLater(q0)}if(o==="unhandledRejection"){if(!R(o,D,h)&&!x)c0(D,"Unhandled rejection ")}else R(o,h)}function a0(o){var N;if(typeof o==="function")N="[function "+(o.name||"anonymous")+"]";else{N=o&&typeof o.toString==="function"?o.toString():I.toString(o);var D=/\[object [a-zA-Z0-9$_]+\]/;if(D.test(N))try{var h=JSON.stringify(o);N=h}catch(x){}if(N.length===0)N="(empty array)"}return"(<"+r1(N)+">, no stack trace)"}function r1(o){var N=41;if(o.length<N)return o;return o.substr(0,N-3)+"..."}function F1(){return typeof e8==="function"}var b1=function(){return!1},$1=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function U6(o){var N=o.match($1);if(N)return{fileName:N[1],line:parseInt(N[2],10)}}function a8(o,N){if(!F1())return;var D=o.stack.split(`
`),h=N.stack.split(`
`),x=-1,q0=-1,r,z0;for(var K0=0;K0<D.length;++K0){var V0=U6(D[K0]);if(V0){r=V0.fileName,x=V0.line;break}}for(var K0=0;K0<h.length;++K0){var V0=U6(h[K0]);if(V0){z0=V0.fileName,q0=V0.line;break}}if(x<0||q0<0||!r||!z0||r!==z0||x>=q0)return;b1=function(x0){if(H.test(x0))return!0;var r0=U6(x0);if(r0){if(r0.fileName===r&&(x<=r0.line&&r0.line<=q0))return!0}return!1}}function I6(o){this._parent=o,this._promisesCreated=0;var N=this._length=1+(o===void 0?0:o._length);if(e8(this,I6),N>32)this.uncycle()}I.inherits(I6,Error),q.CapturedTrace=I6,I6.prototype.uncycle=function(){var o=this._length;if(o<2)return;var N=[],D={};for(var h=0,x=this;x!==void 0;++h)N.push(x),x=x._parent;o=this._length=h;for(var h=o-1;h>=0;--h){var q0=N[h].stack;if(D[q0]===void 0)D[q0]=h}for(var h=0;h<o;++h){var r=N[h].stack,z0=D[r];if(z0!==void 0&&z0!==h){if(z0>0)N[z0-1]._parent=void 0,N[z0-1]._length=1;N[h]._parent=void 0,N[h]._length=1;var K0=h>0?N[h-1]:this;if(z0<o-1)K0._parent=N[z0+1],K0._parent.uncycle(),K0._length=K0._parent._length+1;else K0._parent=void 0,K0._length=1;var V0=K0._length+1;for(var x0=h-2;x0>=0;--x0)N[x0]._length=V0,V0++;return}}},I6.prototype.attachExtraTrace=function(o){if(o.__stackCleaned__)return;this.uncycle();var N=f0(o),D=N.message,h=[N.stack],x=this;while(x!==void 0)h.push(Q0(x.stack.split(`
`))),x=x._parent;i0(h),E0(h),I.notEnumerableProp(o,"stack",R0(D,h)),I.notEnumerableProp(o,"__stackCleaned__",!0)};var e8=function(){var N=/^\s*at\s*/,D=function(r,z0){if(typeof r==="string")return r;if(z0.name!==void 0&&z0.message!==void 0)return z0.toString();return a0(z0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,V=N,X=D;var h=Error.captureStackTrace;return b1=function(r){return H.test(r)},function(r,z0){Error.stackTraceLimit+=6,h(r,z0),Error.stackTraceLimit-=6}}var x=Error();if(typeof x.stack==="string"&&x.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return V=/@/,X=D,w=!0,function(z0){z0.stack=Error().stack};var q0;try{throw Error()}catch(r){q0="stack"in r}if(!("stack"in x)&&q0&&typeof Error.stackTraceLimit==="number")return V=N,X=D,function(z0){Error.stackTraceLimit+=6;try{throw Error()}catch(K0){z0.stack=K0.stack}Error.stackTraceLimit-=6};return X=function(r,z0){if(typeof r==="string")return r;if((typeof z0==="object"||typeof z0==="function")&&z0.name!==void 0&&z0.message!==void 0)return z0.toString();return a0(z0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(L=function(o){console.warn(o)},I.isNode&&process.stderr.isTTY)L=function(o,N){var D=N?"\x1B[33m":"\x1B[31m";console.warn(D+o+`\x1B[0m
`)};else if(!I.isNode&&typeof Error().stack==="string")L=function(o,N){console.warn("%c"+o,N?"color: darkorange":"color: red")}}var L0={warnings:O,longStackTraces:!1,cancellation:!1,monitoring:!1};if(A)$.longStackTraces();return{longStackTraces:function(){return L0.longStackTraces},warnings:function(){return L0.warnings},cancellation:function(){return L0.cancellation},monitoring:function(){return L0.monitoring},propagateFromFunction:function(){return p},boundValueFunction:function(){return d},checkForgottenReturns:H0,setBounds:a8,warn:T0,deprecated:w0,CapturedTrace:I6,fireDomEvent:T,fireGlobalEvent:y}}});var oF0=M((H94,lF0)=>{lF0.exports=function($,q){var Y=G4(),z=$.CancellationError,U=Y.errorObj;function I(Z,V,X){this.promise=Z,this.type=V,this.handler=X,this.called=!1,this.cancelPromise=null}I.prototype.isFinallyHandler=function(){return this.type===0};function J(Z){this.finallyHandler=Z}J.prototype._resultCancelled=function(){Q(this.finallyHandler)};function Q(Z,V){if(Z.cancelPromise!=null){if(arguments.length>1)Z.cancelPromise._reject(V);else Z.cancelPromise._cancel();return Z.cancelPromise=null,!0}return!1}function K(){return G.call(this,this.promise._target()._settledValue())}function H(Z){if(Q(this,Z))return;return U.e=Z,U}function G(Z){var V=this.promise,X=this.handler;if(!this.called){this.called=!0;var w=this.isFinallyHandler()?X.call(V._boundValue()):X.call(V._boundValue(),Z);if(w!==void 0){V._setReturnedNonUndefined();var L=q(w,V);if(L instanceof $){if(this.cancelPromise!=null){if(L._isCancelled()){var F=new z("late cancellation observer");return V._attachExtraTrace(F),U.e=F,U}else if(L.isPending())L._attachCancellationCallback(new J(this))}return L._then(K,H,void 0,this,void 0)}}}if(V.isRejected())return Q(this),U.e=Z,U;else return Q(this),Z}return $.prototype._passThrough=function(Z,V,X,w){if(typeof Z!=="function")return this.then();return this._then(X,w,void 0,new I(this,V,Z),void 0)},$.prototype.lastly=$.prototype.finally=function(Z){return this._passThrough(Z,0,G,G)},$.prototype.tap=function(Z){return this._passThrough(Z,1,G)},I}});var sF0=M((G94,rF0)=>{rF0.exports=function($){var q=G4(),Y=kq().keys,z=q.tryCatch,U=q.errorObj;function I(J,Q,K){return function(H){var G=K._boundValue();$:for(var Z=0;Z<J.length;++Z){var V=J[Z];if(V===Error||V!=null&&V.prototype instanceof Error){if(H instanceof V)return z(Q).call(G,H)}else if(typeof V==="function"){var X=z(V).call(G,H);if(X===U)return X;else if(X)return z(Q).call(G,H)}else if(q.isObject(H)){var w=Y(V);for(var L=0;L<w.length;++L){var F=w[L];if(V[F]!=H[F])continue $}return z(Q).call(G,H)}}return $}}return I}});var cf=M((Z94,eF0)=>{var tF0=G4(),tN1=tF0.maybeWrapAsError,aN1=e9(),eN1=aN1.OperationalError,aF0=kq();function $D1($){return $ instanceof Error&&aF0.getPrototypeOf($)===Error.prototype}var qD1=/^(?:name|message|stack|cause)$/;function YD1($){var q;if($D1($)){q=new eN1($),q.name=$.name,q.message=$.message,q.stack=$.stack;var Y=aF0.keys($);for(var z=0;z<Y.length;++z){var U=Y[z];if(!qD1.test(U))q[U]=$[U]}return q}return tF0.markAsOriginatingFromRejection($),$}function zD1($,q){return function(Y,z){if($===null)return;if(Y){var U=YD1(tN1(Y));$._attachExtraTrace(U),$._reject(U)}else if(!q)$._fulfill(z);else{var I=arguments.length,J=Array(Math.max(I-1,0));for(var Q=1;Q<I;++Q)J[Q-1]=arguments[Q];$._fulfill(J)}$=null}}eF0.exports=zD1});var qO0=M((W94,$O0)=>{$O0.exports=function($,q,Y,z,U){var I=G4(),J=I.tryCatch;$.method=function(Q){if(typeof Q!=="function")throw new $.TypeError("expecting a function but got "+I.classString(Q));return function(){var K=new $(q);K._captureStackTrace(),K._pushContext();var H=J(Q).apply(this,arguments),G=K._popContext();return U.checkForgottenReturns(H,G,"Promise.method",K),K._resolveFromSyncValue(H),K}},$.attempt=$.try=function(Q){if(typeof Q!=="function")return z("expecting a function but got "+I.classString(Q));var K=new $(q);K._captureStackTrace(),K._pushContext();var H;if(arguments.length>1){U.deprecated("calling Promise.try with more than 1 argument");var G=arguments[1],Z=arguments[2];H=I.isArray(G)?J(Q).apply(Z,G):J(Q).call(Z,G)}else H=J(Q)();var V=K._popContext();return U.checkForgottenReturns(H,V,"Promise.try",K),K._resolveFromSyncValue(H),K},$.prototype._resolveFromSyncValue=function(Q){if(Q===I.errorObj)this._rejectCallback(Q.e,!1);else this._resolveCallback(Q,!0)}}});var zO0=M((X94,YO0)=>{YO0.exports=function($,q,Y,z){var U=!1,I=function(H,G){this._reject(G)},J=function(H,G){G.promiseRejectionQueued=!0,G.bindingPromise._then(I,I,null,this,H)},Q=function(H,G){if((this._bitField&50397184)===0)this._resolveCallback(G.target)},K=function(H,G){if(!G.promiseRejectionQueued)this._reject(H)};$.prototype.bind=function(H){if(!U)U=!0,$.prototype._propagateFrom=z.propagateFromFunction(),$.prototype._boundValue=z.boundValueFunction();var G=Y(H),Z=new $(q);Z._propagateFrom(this,1);var V=this._target();if(Z._setBoundTo(G),G instanceof $){var X={promiseRejectionQueued:!1,promise:Z,target:V,bindingPromise:G};V._then(q,J,voi Line truncated
See http://goo.gl/MqrFmX
`);return this._settledValue()},q=I.prototype.error=I.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
`);return this._settledValue()},z=q.prototype.error=q.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()},U=I.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},Y=I.prototype.isRejected=function(){return(this._bitField&16777216)!==0},J=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 J.call(this._target())},$.prototype.isRejected=function(){return Y.call(this._target())},$.prototype.isFulfilled=function(){return U.call(this._target())},$.prototype.isResolved=function(){return Q.call(this._target())},$.prototype.value=function(){return z.call(this._target())},$.prototype.reason=function(){var K=this._target();return K._unsetRejectionIsUnhandled(),q.call(K)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=I}});var hG0=F((by1,CG0)=>{CG0.exports=function($,I,z,q,U,Y){var J=r1(),Q=J.canEvaluate,K=J.tryCatch,w=J.errorObj,G;if(Q){var H=function(A){return Function("value","holder",`
`);return this._settledValue()},U=q.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},I=q.prototype.isRejected=function(){return(this._bitField&16777216)!==0},J=q.prototype.isPending=function(){return(this._bitField&50397184)===0},Q=q.prototype.isResolved=function(){return(this._bitField&50331648)!==0};q.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 J.call(this._target())},$.prototype.isRejected=function(){return I.call(this._target())},$.prototype.isFulfilled=function(){return U.call(this._target())},$.prototype.isResolved=function(){return Q.call(this._target())},$.prototype.value=function(){return Y.call(this._target())},$.prototype.reason=function(){var K=this._target();return K._unsetRejectionIsUnhandled(),z.call(K)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=q}});var ZO0=M((F94,GO0)=>{GO0.exports=function($,q,Y,z,U,I){var J=G4(),Q=J.canEvaluate,K=J.tryCatch,H=J.errorObj,G;if(Q){var Z=function(A){return Function("value","holder",`
'use strict';
holder.pIndex = value;
holder.checkFulfillment(this);
`.replace(/Index/g,A))},W=function(A){return Function("promise","holder",`
`.replace(/Index/g,A))},V=function(A){return Function("promise","holder",`
'use strict';
holder.pIndex = promise;
`.replace(/Index/g,A))},V=function(A){var T=Array(A);for(var M=0;M<T.length;++M)T[M]="this.p"+(M+1);var v=T.join(" = ")+" = null;",x=`var promise;
`+T.map(function(f){return`
promise = `+f+`;
`.replace(/Index/g,A))},X=function(A){var B=Array(A);for(var P=0;P<B.length;++P)B[P]="this.p"+(P+1);var T=B.join(" = ")+" = null;",y=`var promise;
`+B.map(function(c){return`
promise = `+c+`;
if (promise instanceof Promise) {
promise.cancel();
}
`}).join(`
`),h=T.join(", "),k="Holder$"+A,E=`return function(tryCatch, errorObj, Promise, async) {
`),v=B.join(", "),k="Holder$"+A,R=`return function(tryCatch, errorObj, Promise, async) {
'use strict';
function [TheName](fn) {
[TheProperties]
@@ -193,7 +193,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof l4))r
return [TheName];
}(tryCatch, errorObj, Promise, async);
`;return E=E.replace(/\[TheName\]/g,k).replace(/\[TheTotal\]/g,A).replace(/\[ThePassedArguments\]/g,h).replace(/\[TheProperties\]/g,v).replace(/\[CancellationCode\]/g,x),Function("tryCatch","errorObj","Promise","async",E)(K,w,$,U)},X=[],L=[],D=[];for(var O=0;O<8;++O)X.push(V(O+1)),L.push(H(O+1)),D.push(W(O+1));G=function(A){this._reject(A)}}$.join=function(){var A=arguments.length-1,T;if(A>0&&typeof arguments[A]==="function"){if(T=arguments[A],A<=8&&Q){var p=new $(q);p._captureStackTrace();var M=X[A-1],v=new M(T),x=L;for(var h=0;h<A;++h){var k=z(arguments[h],p);if(k instanceof $){k=k._target();var E=k._bitField;if((E&50397184)===0)k._then(x[h],G,void 0,p,v),D[h](k,v),v.asyncNeeded=!1;else if((E&33554432)!==0)x[h].call(p,k._value(),v);else if((E&16777216)!==0)p._reject(k._reason());else p._cancel()}else x[h].call(p,k,v)}if(!p._isFateSealed()){if(v.asyncNeeded){var f=Y();if(f!==null)v.fn=J.domainBind(f,v.fn)}p._setAsyncGuaranteed(),p._setOnCancel(v)}return p}}var n=arguments.length,g=Array(n);for(var b=0;b<n;++b)g[b]=arguments[b];if(T)g.pop();var p=new I(g).promise();return T!==void 0?p.spread(T):p}}});var yG0=F((ny1,SG0)=>{SG0.exports=function($,I,z,q,U,Y){var J=$._getDomain,Q=r1(),K=Q.tryCatch,w=Q.errorObj,G=$._async;function H(V,X,L,D){this.constructor$(V),this._promise._captureStackTrace();var O=J();this._callback=O===null?X:Q.domainBind(O,X),this._preservedValues=D===U?Array(this.length()):null,this._limit=L,this._inFlight=0,this._queue=[],G.invoke(this._asyncInit,this,void 0)}Q.inherits(H,I),H.prototype._asyncInit=function(){this._init$(void 0,-2)},H.prototype._init=function(){},H.prototype._promiseFulfilled=function(V,X){var L=this._values,D=this.length(),O=this._preservedValues,A=this._limit;if(X<0){if(X=X*-1-1,L[X]=V,A>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(A>=1&&this._inFlight>=A)return L[X]=V,this._queue.push(X),!1;if(O!==null)O[X]=V;var T=this._promise,M=this._callback,v=T._boundValue();T._pushContext();var x=K(M).call(v,V,X,D),h=T._popContext();if(Y.checkForgottenReturns(x,h,O!==null?"Promise.filter":"Promise.map",T),x===w)return this._reject(x.e),!0;var k=q(x,this._promise);if(k instanceof $){k=k._target();var E=k._bitField;if((E&50397184)===0){if(A>=1)this._inFlight++;return L[X]=k,k._proxy(this,(X+1)*-1),!1}else if((E&33554432)!==0)x=k._value();else if((E&16777216)!==0)return this._reject(k._reason()),!0;else return this._cancel(),!0}L[X]=x}var f=++this._totalResolved;if(f>=D){if(O!==null)this._filter(L,O);else this._resolve(L);return!0}return!1},H.prototype._drainQueue=function(){var V=this._queue,X=this._limit,L=this._values;while(V.length>0&&this._inFlight<X){if(this._isResolved())return;var D=V.pop();this._promiseFulfilled(L[D],D)}},H.prototype._filter=function(V,X){var L=X.length,D=Array(L),O=0;for(var A=0;A<L;++A)if(V[A])D[O++]=X[A];D.length=O,this._resolve(D)},H.prototype.preservedValues=function(){return this._preservedValues};function W(V,X,L,D){if(typeof X!=="function")return z("expecting a function but got "+Q.classString(X));var O=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)));O=L.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+Q.classString(L)));return O=typeof O==="number"&&isFinite(O)&&O>=1?O:0,new H(V,X,O,D).promise()}$.prototype.map=function(V,X){return W(this,V,X,null)},$.map=function(V,X,L,D){return W(V,X,L,D)}}});var xG0=F((iy1,uG0)=>{var Ay=Object.create;if(Ay)aL=Ay(null),sL=Ay(null),aL[" size"]=sL[" size"]=0;var aL,sL;uG0.exports=function($){var I=r1(),z=I.canEvaluate,q=I.isIdentifier,U,Y,J=function(V){return Function("ensureMethod",`
`;return R=R.replace(/\[TheName\]/g,k).replace(/\[TheTotal\]/g,A).replace(/\[ThePassedArguments\]/g,v).replace(/\[TheProperties\]/g,T).replace(/\[CancellationCode\]/g,y),Function("tryCatch","errorObj","Promise","async",R)(K,H,$,U)},w=[],L=[],F=[];for(var O=0;O<8;++O)w.push(X(O+1)),L.push(Z(O+1)),F.push(V(O+1));G=function(A){this._reject(A)}}$.join=function(){var A=arguments.length-1,B;if(A>0&&typeof arguments[A]==="function"){if(B=arguments[A],A<=8&&Q){var i=new $(z);i._captureStackTrace();var P=w[A-1],T=new P(B),y=L;for(var v=0;v<A;++v){var k=Y(arguments[v],i);if(k instanceof $){k=k._target();var R=k._bitField;if((R&50397184)===0)k._then(y[v],G,void 0,i,T),F[v](k,T),T.asyncNeeded=!1;else if((R&33554432)!==0)y[v].call(i,k._value(),T);else if((R&16777216)!==0)i._reject(k._reason());else i._cancel()}else y[v].call(i,k,T)}if(!i._isFateSealed()){if(T.asyncNeeded){var c=I();if(c!==null)T.fn=J.domainBind(c,T.fn)}i._setAsyncGuaranteed(),i._setOnCancel(T)}return i}}var n=arguments.length,g=Array(n);for(var b=0;b<n;++b)g[b]=arguments[b];if(B)g.pop();var i=new q(g).promise();return B!==void 0?i.spread(B):i}}});var XO0=M((O94,WO0)=>{WO0.exports=function($,q,Y,z,U,I){var J=$._getDomain,Q=G4(),K=Q.tryCatch,H=Q.errorObj,G=$._async;function Z(X,w,L,F){this.constructor$(X),this._promise._captureStackTrace();var O=J();this._callback=O===null?w:Q.domainBind(O,w),this._preservedValues=F===U?Array(this.length()):null,this._limit=L,this._inFlight=0,this._queue=[],G.invoke(this._asyncInit,this,void 0)}Q.inherits(Z,q),Z.prototype._asyncInit=function(){this._init$(void 0,-2)},Z.prototype._init=function(){},Z.prototype._promiseFulfilled=function(X,w){var L=this._values,F=this.length(),O=this._preservedValues,A=this._limit;if(w<0){if(w=w*-1-1,L[w]=X,A>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(A>=1&&this._inFlight>=A)return L[w]=X,this._queue.push(w),!1;if(O!==null)O[w]=X;var B=this._promise,P=this._callback,T=B._boundValue();B._pushContext();var y=K(P).call(T,X,w,F),v=B._popContext();if(I.checkForgottenReturns(y,v,O!==null?"Promise.filter":"Promise.map",B),y===H)return this._reject(y.e),!0;var k=z(y,this._promise);if(k instanceof $){k=k._target();var R=k._bitField;if((R&50397184)===0){if(A>=1)this._inFlight++;return L[w]=k,k._proxy(this,(w+1)*-1),!1}else if((R&33554432)!==0)y=k._value();else if((R&16777216)!==0)return this._reject(k._reason()),!0;else return this._cancel(),!0}L[w]=y}var c=++this._totalResolved;if(c>=F){if(O!==null)this._filter(L,O);else this._resolve(L);return!0}return!1},Z.prototype._drainQueue=function(){var X=this._queue,w=this._limit,L=this._values;while(X.length>0&&this._inFlight<w){if(this._isResolved())return;var F=X.pop();this._promiseFulfilled(L[F],F)}},Z.prototype._filter=function(X,w){var L=w.length,F=Array(L),O=0;for(var A=0;A<L;++A)if(X[A])F[O++]=w[A];F.length=O,this._resolve(F)},Z.prototype.preservedValues=function(){return this._preservedValues};function V(X,w,L,F){if(typeof w!=="function")return Y("expecting a function but got "+Q.classString(w));var O=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)));O=L.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+Q.classString(L)));return O=typeof O==="number"&&isFinite(O)&&O>=1?O:0,new Z(X,w,O,F).promise()}$.prototype.map=function(X,w){return V(this,X,w,null)},$.map=function(X,w,L,F){return V(X,w,L,F)}}});var wO0=M((M94,VO0)=>{var pf=Object.create;if(pf)UN=pf(null),IN=pf(null),UN[" size"]=IN[" size"]=0;var UN,IN;VO0.exports=function($){var q=G4(),Y=q.canEvaluate,z=q.isIdentifier,U,I,J=function(X){return Function("ensureMethod",`
return function(obj) {
'use strict'
var len = this.length;
@@ -207,29 +207,29 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof l4))r
return obj.methodName.apply(obj, this);
}
};
`.replace(/methodName/g,V))(w)},Q=function(V){return Function("obj",`
`.replace(/methodName/g,X))(H)},Q=function(X){return Function("obj",`
'use strict';
return obj.propertyName;
`.replace("propertyName",V))},K=function(V,X,L){var D=L[V];if(typeof D!=="function"){if(!q(V))return null;if(D=X(V),L[V]=D,L[" size"]++,L[" size"]>512){var O=Object.keys(L);for(var A=0;A<256;++A)delete L[O[A]];L[" size"]=O.length-256}}return D};U=function(V){return K(V,J,aL)},Y=function(V){return K(V,Q,sL)};function w(V,X){var L;if(V!=null)L=V[X];if(typeof L!=="function"){var D="Object "+I.classString(V)+" has no method '"+I.toString(X)+"'";throw new $.TypeError(D)}return L}function G(V){var X=this.pop(),L=w(V,X);return L.apply(V,this)}$.prototype.call=function(V){var X=arguments.length,L=Array(Math.max(X-1,0));for(var D=1;D<X;++D)L[D-1]=arguments[D];if(z){var O=U(V);if(O!==null)return this._then(O,void 0,void 0,L,void 0)}return L.push(V),this._then(G,void 0,void 0,L,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",L;if(!X)if(z){var D=Y(V);L=D!==null?D:H}else L=H;else L=W;return this._then(L,void 0,void 0,V,void 0)}}});var fG0=F((py1,kG0)=>{kG0.exports=function($,I,z,q,U,Y){var J=r1(),Q=z9().TypeError,K=r1().inherits,w=J.errorObj,G=J.tryCatch,H={};function W(T){setTimeout(function(){throw T},0)}function V(T){var M=z(T);if(M!==T&&typeof T._isDisposable==="function"&&typeof T._getDisposer==="function"&&T._isDisposable())M._setDisposable(T._getDisposer());return M}function X(T,M){var v=0,x=T.length,h=new $(U);function k(){if(v>=x)return h._fulfill();var E=V(T[v++]);if(E instanceof $&&E._isDisposable()){try{E=z(E._getDisposer().tryDispose(M),T.promise)}catch(f){return W(f)}if(E instanceof $)return E._then(k,W,null,null,null)}k()}return k(),h}function L(T,M,v){this._data=T,this._promise=M,this._context=v}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 H},L.prototype.tryDispose=function(T){var M=this.resource(),v=this._context;if(v!==void 0)v._pushContext();var x=M!==H?this.doDispose(M,T):null;if(v!==void 0)v._popContext();return this._promise._unsetDisposable(),this._data=null,x},L.isDisposer=function(T){return T!=null&&typeof T.resource==="function"&&typeof T.tryDispose==="function"};function D(T,M,v){this.constructor$(T,M,v)}K(D,L),D.prototype.doDispose=function(T,M){var v=this.data();return v.call(T,T,M)};function O(T){if(L.isDisposer(T))return this.resources[this.index]._setDisposable(T),T.promise();return T}function A(T){this.length=T,this.promise=null,this[T-1]=null}A.prototype._resultCancelled=function(){var T=this.length;for(var M=0;M<T;++M){var v=this[M];if(v instanceof $)v.cancel()}},$.using=function(){var T=arguments.length;if(T<2)return I("you must pass at least 2 arguments to Promise.using");var M=arguments[T-1];if(typeof M!=="function")return I("expecting a function but got "+J.classString(M));var v,x=!0;if(T===2&&Array.isArray(arguments[0]))v=arguments[0],T=v.length,x=!1;else v=arguments,T--;var h=new A(T);for(var k=0;k<T;++k){var E=v[k];if(L.isDisposer(E)){var f=E;E=E.promise(),E._setDisposable(f)}else{var n=z(E);if(n instanceof $)E=n._then(O,null,null,{resources:h,index:k},void 0)}h[k]=E}var g=Array(h.length);for(var k=0;k<g.length;++k)g[k]=$.resolve(h[k]).reflect();var b=$.all(g).then(function(q0){for(var R=0;R<q0.length;++R){var u=q0[R];if(u.isRejected())return w.e=u.error(),w;else if(!u.isFulfilled()){b.cancel();return}q0[R]=u.value()}p._pushContext(),M=G(M);var c=x?M.apply(void 0,q0):M(q0),m=p._popContext();return Y.checkForgottenReturns(c,m,"Promise.using",p),c}),p=b.lastly(function(){var q0=new $.PromiseInspection(b);return X(h,q0)});return h.promise=p,p._setOnCancel(h),p},$.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,q());throw new Q}}});var nG0=F((cy1,bG0)=>{bG0.exports=function($,I,z){var q=r1(),U=$.TimeoutError;function Y(H){this.handle=H}Y.prototype._resultCancelled=function(){clearTimeout(this.handle)};var J=function(H){return Q(+this).thenReturn(H)},Q=$.delay=function(H,W){var V,X;if(W!==void 0){if(V=$.resolve(W)._then(J,null,null,H,void 0),z.cancellation()&&W instanceof $)V._setOnCancel(W)}else{if(V=new $(I),X=setTimeout(function(){V._fulfill()},+H),z.cancellation())V._setOnCancel(new Y(X));V._captureStackTrace()}return V._setAsyncGuaranteed(),V};$.prototype.delay=function(H){return Q(H,this)};var K=function(H,W,V){var X;if(typeof W!=="string")if(W instanceof Error)X=W;else X=new U("operation timed out");else X=new U(W);if(q.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",X))},K=function(X,w,L){var F=L[X];if(typeof F!=="function"){if(!z(X))return null;if(F=w(X),L[X]=F,L[" size"]++,L[" size"]>512){var O=Object.keys(L);for(var A=0;A<256;++A)delete L[O[A]];L[" size"]=O.length-256}}return F};U=function(X){return K(X,J,UN)},I=function(X){return K(X,Q,IN)};function H(X,w){var L;if(X!=null)L=X[w];if(typeof L!=="function"){var F="Object "+q.classString(X)+" has no method '"+q.toString(w)+"'";throw new $.TypeError(F)}return L}function G(X){var w=this.pop(),L=H(X,w);return L.apply(X,this)}$.prototype.call=function(X){var w=arguments.length,L=Array(Math.max(w-1,0));for(var F=1;F<w;++F)L[F-1]=arguments[F];if(Y){var O=U(X);if(O!==null)return this._then(O,void 0,void 0,L,void 0)}return L.push(X),this._then(G,void 0,void 0,L,void 0)};function Z(X){return X[this]}function V(X){var w=+this;if(w<0)w=Math.max(0,w+X.length);return X[w]}$.prototype.get=function(X){var w=typeof X==="number",L;if(!w)if(Y){var F=I(X);L=F!==null?F:Z}else L=Z;else L=V;return this._then(L,void 0,void 0,X,void 0)}}});var FO0=M((N94,LO0)=>{LO0.exports=function($,q,Y,z,U,I){var J=G4(),Q=e9().TypeError,K=G4().inherits,H=J.errorObj,G=J.tryCatch,Z={};function V(B){setTimeout(function(){throw B},0)}function X(B){var P=Y(B);if(P!==B&&typeof B._isDisposable==="function"&&typeof B._getDisposer==="function"&&B._isDisposable())P._setDisposable(B._getDisposer());return P}function w(B,P){var T=0,y=B.length,v=new $(U);function k(){if(T>=y)return v._fulfill();var R=X(B[T++]);if(R instanceof $&&R._isDisposable()){try{R=Y(R._getDisposer().tryDispose(P),B.promise)}catch(c){return V(c)}if(R instanceof $)return R._then(k,V,null,null,null)}k()}return k(),v}function L(B,P,T){this._data=B,this._promise=P,this._context=T}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 Z},L.prototype.tryDispose=function(B){var P=this.resource(),T=this._context;if(T!==void 0)T._pushContext();var y=P!==Z?this.doDispose(P,B):null;if(T!==void 0)T._popContext();return this._promise._unsetDisposable(),this._data=null,y},L.isDisposer=function(B){return B!=null&&typeof B.resource==="function"&&typeof B.tryDispose==="function"};function F(B,P,T){this.constructor$(B,P,T)}K(F,L),F.prototype.doDispose=function(B,P){var T=this.data();return T.call(B,B,P)};function O(B){if(L.isDisposer(B))return this.resources[this.index]._setDisposable(B),B.promise();return B}function A(B){this.length=B,this.promise=null,this[B-1]=null}A.prototype._resultCancelled=function(){var B=this.length;for(var P=0;P<B;++P){var T=this[P];if(T instanceof $)T.cancel()}},$.using=function(){var B=arguments.length;if(B<2)return q("you must pass at least 2 arguments to Promise.using");var P=arguments[B-1];if(typeof P!=="function")return q("expecting a function but got "+J.classString(P));var T,y=!0;if(B===2&&Array.isArray(arguments[0]))T=arguments[0],B=T.length,y=!1;else T=arguments,B--;var v=new A(B);for(var k=0;k<B;++k){var R=T[k];if(L.isDisposer(R)){var c=R;R=R.promise(),R._setDisposable(c)}else{var n=Y(R);if(n instanceof $)R=n._then(O,null,null,{resources:v,index:k},void 0)}v[k]=R}var g=Array(v.length);for(var k=0;k<g.length;++k)g[k]=$.resolve(v[k]).reflect();var b=$.all(g).then(function($0){for(var j=0;j<$0.length;++j){var u=$0[j];if(u.isRejected())return H.e=u.error(),H;else if(!u.isFulfilled()){b.cancel();return}$0[j]=u.value()}i._pushContext(),P=G(P);var p=y?P.apply(void 0,$0):P($0),d=i._popContext();return I.checkForgottenReturns(p,d,"Promise.using",i),p}),i=b.lastly(function(){var $0=new $.PromiseInspection(b);return w(v,$0)});return v.promise=i,i._setOnCancel(v),i},$.prototype._setDisposable=function(B){this._bitField=this._bitField|131072,this._disposer=B},$.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(B){if(typeof B==="function")return new F(B,this,z());throw new Q}}});var MO0=M((D94,OO0)=>{OO0.exports=function($,q,Y){var z=G4(),U=$.TimeoutError;function I(Z){this.handle=Z}I.prototype._resultCancelled=function(){clearTimeout(this.handle)};var J=function(Z){return Q(+this).thenReturn(Z)},Q=$.delay=function(Z,V){var X,w;if(V!==void 0){if(X=$.resolve(V)._then(J,null,null,Z,void 0),Y.cancellation()&&V instanceof $)X._setOnCancel(V)}else{if(X=new $(q),w=setTimeout(function(){X._fulfill()},+Z),Y.cancellation())X._setOnCancel(new I(w));X._captureStackTrace()}return X._setAsyncGuaranteed(),X};$.prototype.delay=function(Z){return Q(Z,this)};var K=function(Z,V,X){var w;if(typeof V!=="string")if(V instanceof Error)w=V;else w=new U("operation timed out");else w=new U(V);if(z.markAsOriginatingFromRejection(w),Z._attachExtraTrace(w),Z._reject(w),X!=null)X.cancel()};function H(Z){return clearTimeout(this.handle),Z}f Line truncated
See http://goo.gl/MqrFmX
`.replace("%s",D)+`From coroutine:
`.replace("%s",F)+`From coroutine:
`+this._stack.split(`
`).slice(1,-7).join(`
`)));return}}O=O._target();var A=O._bitField;if((A&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((A&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((A&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(X,L){if(typeof X!=="function")throw new Q(`generatorFunction must be a function
`)));return}}O=O._target();var A=O._bitField;if((A&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((A&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((A&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(w,L){if(typeof w!=="function")throw new Q(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var D=Object(L).yieldHandler,O=V,A=Error().stack;return function(){var T=X.apply(this,arguments),M=new O(void 0,void 0,D,A),v=M.promise();return M._generator=T,M._promiseFulfilled(void 0),v}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new Q("expecting a function but got "+K.classString(X));H.push(X)},$.spawn=function(X){if(Y.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunction must be a function
`);var F=Object(L).yieldHandler,O=X,A=Error().stack;return function(){var B=w.apply(this,arguments),P=new O(void 0,void 0,F,A),T=P.promise();return P._generator=B,P._promiseFulfilled(void 0),T}},$.coroutine.addYieldHandler=function(w){if(typeof w!=="function")throw new Q("expecting a function but got "+K.classString(w));Z.push(w)},$.spawn=function(w){if(I.deprecated("Promise.spawn()","Promise.coroutine()"),typeof w!=="function")return q(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var L=new V(X,this),D=L.promise();return L._run($.spawn),D}}});var dG0=F((my1,cG0)=>{cG0.exports=function($){var I=r1(),z=$._async,q=I.tryCatch,U=I.errorObj;function Y(K,w){var G=this;if(!I.isArray(K))return J.call(G,K,w);var H=q(w).apply(G._boundValue(),[null].concat(K));if(H===U)z.throwLater(H.e)}function J(K,w){var G=this,H=G._boundValue(),W=K===void 0?q(w).call(H,null):q(w).call(H,null,K);if(W===U)z.throwLater(W.e)}function Q(K,w){var G=this;if(!K){var H=Error(K+"");H.cause=K,K=H}var W=q(w).call(G._boundValue(),K);if(W===U)z.throwLater(W.e)}$.prototype.asCallback=$.prototype.nodeify=function(K,w){if(typeof K=="function"){var G=J;if(w!==void 0&&Object(w).spread)G=Y;this._then(G,Q,void 0,this,K)}return this}}});var lG0=F((ly1,mG0)=>{mG0.exports=function($,I){var z={},q=r1(),U=My(),Y=q.withAppended,J=q.maybeWrapAsError,Q=q.canEvaluate,K=z9().TypeError,w="Async",G={__isPromisified__:!0},H=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],W=new RegExp("^(?:"+H.join("|")+")$"),V=function(b){return q.isIdentifier(b)&&b.charAt(0)!=="_"&&b!=="constructor"};function X(b){return!W.test(b)}function L(b){try{return b.__isPromisified__===!0}catch(p){return!1}}function D(b,p,q0){var R=q.getDataPropertyOrDefault(b,p+q0,G);return R?L(R):!1}function O(b,p,q0){for(var R=0;R<b.length;R+=2){var u=b[R];if(q0.test(u)){var c=u.replace(q0,"");for(var m=0;m<b.length;m+=2)if(b[m]===c)throw new K(`Cannot promisify an API that has normal methods with '%s'-suffix
`);var L=new X(w,this),F=L.promise();return L._run($.spawn),F}}});var PO0=M((P94,AO0)=>{AO0.exports=function($){var q=G4(),Y=$._async,z=q.tryCatch,U=q.errorObj;function I(K,H){var G=this;if(!q.isArray(K))return J.call(G,K,H);var Z=z(H).apply(G._boundValue(),[null].concat(K));if(Z===U)Y.throwLater(Z.e)}function J(K,H){var G=this,Z=G._boundValue(),V=K===void 0?z(H).call(Z,null):z(H).call(Z,null,K);if(V===U)Y.throwLater(V.e)}function Q(K,H){var G=this;if(!K){var Z=Error(K+"");Z.cause=K,K=Z}var V=z(H).call(G._boundValue(),K);if(V===U)Y.throwLater(V.e)}$.prototype.asCallback=$.prototype.nodeify=function(K,H){if(typeof K=="function"){var G=J;if(H!==void 0&&Object(H).spread)G=I;this._then(G,Q,void 0,this,K)}return this}}});var TO0=M((B94,BO0)=>{BO0.exports=function($,q){var Y={},z=G4(),U=cf(),I=z.withAppended,J=z.maybeWrapAsError,Q=z.canEvaluate,K=e9().TypeError,H="Async",G={__isPromisified__:!0},Z=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],V=new RegExp("^(?:"+Z.join("|")+")$"),X=function(b){return z.isIdentifier(b)&&b.charAt(0)!=="_"&&b!=="constructor"};function w(b){return!V.test(b)}function L(b){try{return b.__isPromisified__===!0}catch(i){return!1}}function F(b,i,$0){var j=z.getDataPropertyOrDefault(b,i+$0,G);return j?L(j):!1}function O(b,i,$0){for(var j=0;j<b.length;j+=2){var u=b[j];if($0.test(u)){var p=u.replace($0,"");for(var d=0;d<b.length;d+=2)if(b[d]===p)throw new K(`Cannot promisify an API that has normal methods with '%s'-suffix
See http://goo.gl/MqrFmX
`.replace("%s",p))}}}function A(b,p,q0,R){var u=q.inheritedDataKeys(b),c=[];for(var m=0;m<u.length;++m){var e=u[m],G0=b[e],M0=R===V?!0:V(e,G0,b);if(typeof G0==="function"&&!L(G0)&&!D(b,e,p)&&R(e,G0,b,M0))c.push(e,G0)}return O(c,p,q0),c}var T=function(b){return b.replace(/([$])/,"\\$")},M,v=function(b){var p=[b],q0=Math.max(0,b-1-3);for(var R=b-1;R>=q0;--R)p.push(R);for(var R=b+1;R<=3;++R)p.push(R);return p},x=function(b){return q.filledRange(b,"_arg","")},h=function(b){return q.filledRange(Math.max(b,3),"_arg","")},k=function(b){if(typeof b.length==="number")return Math.max(Math.min(b.length,1024),0);return 0};M=function(b,p,q0,R,u,c){var m=Math.max(0,k(R)-1),e=v(m),G0=typeof b==="string"||p===z;function M0($1){var A0=x($1).join(", "),U0=$1>0?", ":"",v0;if(G0)v0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else v0=p===void 0?`ret = callback({{args}}, nodeback); break;
`.replace("%s",i))}}}function A(b,i,$0,j){var u=z.inheritedDataKeys(b),p=[];for(var d=0;d<u.length;++d){var Y0=u[d],t=b[Y0],H0=j===X?!0:X(Y0,t,b);if(typeof t==="function"&&!L(t)&&!F(b,Y0,i)&&j(Y0,t,b,H0))p.push(Y0,t)}return O(p,i,$0),p}var B=function(b){return b.replace(/([$])/,"\\$")},P,T=function(b){var i=[b],$0=Math.max(0,b-1-3);for(var j=b-1;j>=$0;--j)i.push(j);for(var j=b+1;j<=3;++j)i.push(j);return i},y=function(b){return z.filledRange(b,"_arg","")},v=function(b){return z.filledRange(Math.max(b,3),"_arg","")},k=function(b){if(typeof b.length==="number")return Math.max(Math.min(b.length,1024),0);return 0};P=function(b,i,$0,j,u,p){var d=Math.max(0,k(j)-1),Y0=T(d),t=typeof b==="string"||i===Y;function H0(E0){var i0=y(E0).join(", "),Q0=E0>0?", ":"",v0;if(t)v0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else v0=i===void 0?`ret = callback({{args}}, nodeback); break;
`:`ret = callback.call(receiver, {{args}}, nodeback); break;
`;return v0.replace("{{args}}",A0).replace(", ",U0)}function g0(){var $1="";for(var A0=0;A0<e.length;++A0)$1+="case "+e[A0]+":"+M0(e[A0]);return $1+=`
`;return v0.replace("{{args}}",i0).replace(", ",Q0)}function w0(){var E0="";for(var i0=0;i0<Y0.length;++i0)E0+="case "+Y0[i0]+":"+H0(Y0[i0]);return E0+=`
default:
var args = new Array(len + 1);
var i = 0;
@@ -239,15 +239,15 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof l4))r
args[i] = nodeback;
[CodeForCall]
break;
`.replace("[CodeForCall]",G0?`ret = callback.apply(this, args);
`.replace("[CodeForCall]",t?`ret = callback.apply(this, args);
`:`ret = callback.apply(receiver, args);
`),$1}var G1=typeof b==="string"?"this != null ? this['"+b+"'] : fn":"fn",S0=`'use strict';
`),E0}var T0=typeof b==="string"?"this != null ? this['"+b+"'] : fn":"fn",R0=`'use strict';
var ret = function (Parameters) {
'use strict';
var len = arguments.length;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var nodeback = nodebackForPromise(promise, `+c+`);
var nodeback = nodebackForPromise(promise, `+p+`);
var ret;
var callback = tryCatch([GetFunctionCode]);
switch(len) {
@@ -261,25 +261,25 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof l4))r
};
notEnumerableProp(ret, '__isPromisified__', true);
return ret;
`.replace("[CodeForSwitchCase]",g0()).replace("[GetFunctionCode]",G1);return S0=S0.replace("Parameters",h(m)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",S0)($,R,p,Y,J,U,q.tryCatch,q.errorObj,q.notEnumerableProp,I)};function E(b,p,q0,R,u,c){var m=function(){return this}(),e=b;if(typeof e==="string")b=R;function G0(){var M0=p;if(p===z)M0=this;var g0=new $(I);g0._captureStackTrace();var G1=typeof e==="string"&&this!==m?this[e]:b,S0=U(g0,c);try{G1.apply(M0,Y(arguments,S0))}catch($1){g0._rejectCallback(J($1),!0,!0)}if(!g0._isFateSealed())g0._setAsyncGuaranteed();return g0}return q.notEnumerableProp(G0,"__isPromisified__",!0),G0}var f=Q?M:E;function n(b,p,q0,R,u){var c=new RegExp(T(p)+"$"),m=A(b,p,c,q0);for(var e=0,G0=m.length;e<G0;e+=2){var M0=m[e],g0=m[e+1],G1=M0+p;if(R===f)b[G1]=f(M0,z,M0,g0,p,u);else{var S0=R(g0,function(){return f(M0,z,M0,g0,p,u)});q.notEnumerableProp(S0,"__isPromisified__",!0),b[G1]=S0}}return q.toFastProperties(b),b}function g(b,p,q0){return f(b,p,void 0,b,null,q0)}$.promisify=function(b,p){if(typeof b!=="function")throw new K("expecting a function but got "+q.classString(b));if(L(b))return b;p=Object(p);var q0=p.context===void 0?z:p.context,R=!!p.multiArgs,u=g(b,q0,R);return q.copyDescriptors(b,u,X),u},$.promisifyAll=function(b,p){if(typeof b!=="function"&&typeof b!=="object")throw new K(`the target of promisifyAll must be an object or a function
`.replace("[CodeForSwitchCase]",w0()).replace("[GetFunctionCode]",T0);return R0=R0.replace("Parameters",v(d)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",R0)($,j,i,I,J,U,z.tryCatch,z.errorObj,z.notEnumerableProp,q)};function R(b,i,$0,j,u,p){var d=function(){return this}(),Y0=b;if(typeof Y0==="string")b=j;function t(){var H0=i;if(i===Y)H0=this;var w0=new $(q);w0._captureStackTrace();var T0=typeof Y0==="string"&&this!==d?this[Y0]:b,R0=U(w0,p);try{T0.apply(H0,I(arguments,R0))}catch(E0){w0._rejectCallback(J(E0),!0,!0)}if(!w0._isFateSealed())w0._setAsyncGuaranteed();return w0}return z.notEnumerableProp(t,"__isPromisified__",!0),t}var c=Q?P:R;function n(b,i,$0,j,u){var p=new RegExp(B(i)+"$"),d=A(b,i,p,$0);for(var Y0=0,t=d.length;Y0<t;Y0+=2){var H0=d[Y0],w0=d[Y0+1],T0=H0+i;if(j===c)b[T0]=c(H0,Y,H0,w0,i,u);else{var R0=j(w0,function(){return c(H0,Y,H0,w0,i,u)});z.notEnumerableProp(R0,"__isPromisified__",!0),b[T0]=R0}}return z.toFastProperties(b),b}function g(b,i,$0){return c(b,i,void 0,b,null,$0)}$.promisify=function(b,i){if(typeof b!=="function")throw new K("expecting a function but got "+z.classString(b));if(L(b))return b;i=Object(i);var $0=i.context===void 0?Y:i.context,j=!!i.multiArgs,u=g(b,$0,j);return z.copyDescriptors(b,u,w),u},$.promisifyAll=function(b,i){if(typeof b!=="function"&&typeof b!=="object")throw new K(`the target of promisifyAll must be an object or a function
See http://goo.gl/MqrFmX
`);p=Object(p);var q0=!!p.multiArgs,R=p.suffix;if(typeof R!=="string")R=w;var u=p.filter;if(typeof u!=="function")u=V;var c=p.promisifier;if(typeof c!=="function")c=f;if(!q.isIdentifier(R))throw RangeError(`suffix must be a valid identifier
`);i=Object(i);var $0=!!i.multiArgs,j=i.suffix;if(typeof j!=="string")j=H;var u=i.filter;if(typeof u!=="function")u=X;var p=i.promisifier;if(typeof p!=="function")p=c;if(!z.isIdentifier(j))throw RangeError(`suffix must be a valid identifier
See http://goo.gl/MqrFmX
`);var m=q.inheritedDataKeys(b);for(var e=0;e<m.length;++e){var G0=b[m[e]];if(m[e]!=="constructor"&&q.isClass(G0))n(G0.prototype,R,u,c,q0),n(G0,R,u,c,q0)}return n(b,R,u,c,q0)}}});var rG0=F((oy1,oG0)=>{oG0.exports=function($,I,z,q){var U=r1(),Y=U.isObject,J=NI(),Q;if(typeof Map==="function")Q=Map;var K=function(){var W=0,V=0;function X(L,D){this[W]=L,this[W+V]=D,W++}return function(D){V=D.size,W=0;var O=Array(D.size*2);return D.forEach(X,O),O}}(),w=function(W){var V=new Q,X=W.length/2|0;for(var L=0;L<X;++L){var D=W[X+L],O=W[L];V.set(D,O)}return V};function G(W){var V=!1,X;if(Q!==void 0&&W instanceof Q)X=K(W),V=!0;else{var L=J.keys(W),D=L.length;X=Array(D*2);for(var O=0;O<D;++O){var A=L[O];X[O]=W[A],X[O+D]=A}}this.constructor$(X),this._isMap=V,this._init$(void 0,-3)}U.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 L;if(this._isMap)L=w(this._values);else{L={};var D=this.length();for(var O=0,A=this.length();O<A;++O)L[this._values[O+D]]=this._values[O]}return this._resolve(L),!0}return!1},G.prototype.shouldCopyValues=function(){return!1},G.prototype.getActualLength=function(W){return W>>1};function H(W){var V,X=z(W);if(!Y(X))return q(`cannot await properties of a non-object
`);var d=z.inheritedDataKeys(b);for(var Y0=0;Y0<d.length;++Y0){var t=b[d[Y0]];if(d[Y0]!=="constructor"&&z.isClass(t))n(t.prototype,j,u,p,$0),n(t,j,u,p,$0)}return n(b,j,u,p,$0)}}});var jO0=M((T94,EO0)=>{EO0.exports=function($,q,Y,z){var U=G4(),I=U.isObject,J=kq(),Q;if(typeof Map==="function")Q=Map;var K=function(){var V=0,X=0;function w(L,F){this[V]=L,this[V+X]=F,V++}return function(F){X=F.size,V=0;var O=Array(F.size*2);return F.forEach(w,O),O}}(),H=function(V){var X=new Q,w=V.length/2|0;for(var L=0;L<w;++L){var F=V[w+L],O=V[L];X.set(F,O)}return X};function G(V){var X=!1,w;if(Q!==void 0&&V instanceof Q)w=K(V),X=!0;else{var L=J.keys(V),F=L.length;w=Array(F*2);for(var O=0;O<F;++O){var A=L[O];w[O]=V[A],w[O+F]=A}}this.constructor$(w),this._isMap=X,this._init$(void 0,-3)}U.inherits(G,q),G.prototype._init=function(){},G.prototype._promiseFulfilled=function(V,X){this._values[X]=V;var w=++this._totalResolved;if(w>=this._length){var L;if(this._isMap)L=H(this._values);else{L={};var F=this.length();for(var O=0,A=this.length();O<A;++O)L[this._values[O+F]]=this._values[O]}return this._resolve(L),!0}return!1},G.prototype.shouldCopyValues=function(){return!1},G.prototype.getActualLength=function(V){return V>>1};function Z(V){var X,w=Y(V);if(!I(w))return z(`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 aG0=F((ry1,tG0)=>{tG0.exports=function($,I,z,q){var U=r1(),Y=function(Q){return Q.then(function(K){return J(K,Q)})};function J(Q,K){var w=z(Q);if(w instanceof $)return Y(w);else if(Q=U.asArray(Q),Q===null)return q("expecting an array or an iterable object but got "+U.classString(Q));var G=new $(I);if(K!==void 0)G._propagateFrom(K,3);var{_fulfill:H,_reject:W}=G;for(var V=0,X=Q.length;V<X;++V){var L=Q[V];if(L===void 0&&!(V in Q))continue;$.cast(L)._then(H,W,void 0,G,null)}return G}$.race=function(Q){return J(Q,void 0)},$.prototype.race=function(){return J(this,void 0)}}});var eG0=F((ty1,sG0)=>{sG0.exports=function($,I,z,q,U,Y){var J=$._getDomain,Q=r1(),K=Q.tryCatch;function w(X,L,D,O){this.constructor$(X);var A=J();if(this._fn=A===null?L:Q.domainBind(A,L),D!==void 0)D=$.resolve(D),D._attachCancellationCallback(this);if(this._initialValue=D,this._currentCancellable=null,O===U)this._eachValues=Array(this._length);else if(O===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}Q.inherits(w,I),w.prototype._gotAccum=function(X){if(this._eachValues!==void 0&&this._eachValues!==null&&X!==U)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 L,D,O=X.length;if(this._initialValue!==void 0)L=this._initialValue,D=0;else L=$.resolve(X[0]),D=1;if(this._currentCancellable=L,!L.isRejected())for(;D<O;++D){var A={accum:null,value:X[D],index:D,length:O,array:this};L=L._then(W,void 0,void 0,A,void 0)}if(this._eachValues!==void 0)L=L._then(this._eachComplete,void 0,void 0,this,void 0);L._then(G,G,void 0,L,this)},$.prototype.reduce=function(X,L){return H(this,X,L,null)},$.reduce=function(X,L,D,O){return H(X,L,D,O)};function G(X,L){if(this.isFulfilled())L._resolve(X);else L._reject(X)}function H(X,L,D,O){if(typeof L!=="function")return z("expecting a function but got "+Q.classString(L));var A=new w(X,L,D,O);return A.promise()}function W(X){this.accum=X,this.array._gotAccum(X);var L=q(this.value,this.array._promise);if(L instanceof $)return this.array._currentCancellable=L,L._then(V,void 0,void 0,this,void 0);else return V.call(this,L)}function V(X){var L=this.array,D=L._promise,O=K(L._fn);D._pushContext();var A;if(L._eachValues!==void 0)A=O.call(D._boundValue(),X,this.index,this.length);else A=O.call(D._boundValue(),this.accum,X,this.index,this.length);if(A instanceof $)L._currentCancellable=A;var T=D._popContext();return Y.checkForgottenReturns(A,T,L._eachValues!==void 0?"Promise.each":"Promise.reduce",D),A}}});var IH0=F((ay1,$H0)=>{$H0.exports=function($,I,z){var q=$.PromiseInspection,U=r1();function Y(J){this.constructor$(J)}U.inherits(Y,I),Y.prototype._promiseResolved=function(J,Q){this._values[J]=Q;var K=++this._totalResolved;if(K>=this._length)return this._resolve(this._values),!0;return!1},Y.prototype._promiseFulfilled=function(J,Q){var K=new q;return K._bitField=33554432,K._settledValueField=J,this._promiseResolved(Q,K)},Y.prototype._promiseRejected=function(J,Q){var K=new q;return K._bitField=16777216,K._settledValueField=J,this._promiseResolved(Q,K)},$.settle=function(J){return z.deprecated(".settle()",".reflect()"),new Y(J).promise()},$.prototype.settle=function(){return $.settle(this)}}});var qH0=F((sy1,zH0)=>{zH0.exports=function($,I,z){var q=r1(),U=z9().RangeError,Y=z9().AggregateError,J=q.isArray,Q={};function K(G){this.constructor$(G),this._howMany=0,this._unwrap=!1,this._initialized=!1}q.inherits(K,I),K.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var G=J(this._values);if(!this._isResolved()&&G&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},K.prototype.init=function(){this._initialized=!0,this._init()},K.prototype.setUnwrap=function(){this._unwrap=!0},K.prototype.howMany=function(){return this._howMany},K.prototype.setHowMany=function(G){this._howMany=G},K.prototype._promiseFulfilled=function(G){if(this._addFulfilled(G),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
`);else if(w instanceof $)X=w._then($.props,void 0,void 0,void 0,void 0);else X=new G(w).promise();if(w instanceof $)X._propagateFrom(w,2);return X}$.prototype.props=function(){return Z(this)},$.props=function(V){return Z(V)}}});var CO0=M((E94,_O0)=>{_O0.exports=function($,q,Y,z){var U=G4(),I=function(Q){return Q.then(function(K){return J(K,Q)})};function J(Q,K){var H=Y(Q);if(H instanceof $)return I(H);else if(Q=U.asArray(Q),Q===null)return z("expecting an array or an iterable object but got "+U.classString(Q));var G=new $(q);if(K!==void 0)G._propagateFrom(K,3);var{_fulfill:Z,_reject:V}=G;for(var X=0,w=Q.length;X<w;++X){var L=Q[X];if(L===void 0&&!(X in Q))continue;$.cast(L)._then(Z,V,void 0,G,null)}return G}$.race=function(Q){return J(Q,void 0)},$.prototype.race=function(){return J(this,void 0)}}});var vO0=M((j94,RO0)=>{RO0.exports=function($,q,Y,z,U,I){var J=$._getDomain,Q=G4(),K=Q.tryCatch;function H(w,L,F,O){this.constructor$(w);var A=J();if(this._fn=A===null?L:Q.domainBind(A,L),F!==void 0)F=$.resolve(F),F._attachCancellationCallback(this);if(this._initialValue=F,this._currentCancellable=null,O===U)this._eachValues=Array(this._length);else if(O===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}Q.inherits(H,q),H.prototype._gotAccum=function(w){if(this._eachValues!==void 0&&this._eachValues!==null&&w!==U)this._eachValues.push(w)},H.prototype._eachComplete=function(w){if(this._eachValues!==null)this._eachValues.push(w);return this._eachValues},H.prototype._init=function(){},H.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},H.prototype.shouldCopyValues=function(){return!1},H.prototype._resolve=function(w){this._promise._resolveCallback(w),this._values=null},H.prototype._resultCancelled=function(w){if(w===this._initialValue)return this._cancel();if(this._isResolved())return;if(this._resultCancelled$(),this._currentCancellable instanceof $)this._currentCancellable.cancel();if(this._initialValue instanceof $)this._initialValue.cancel()},H.prototype._iterate=function(w){this._values=w;var L,F,O=w.length;if(this._initialValue!==void 0)L=this._initialValue,F=0;else L=$.resolve(w[0]),F=1;if(this._currentCancellable=L,!L.isRejected())for(;F<O;++F){var A={accum:null,value:w[F],index:F,length:O,array:this};L=L._then(V,void 0,void 0,A,void 0)}if(this._eachValues!==void 0)L=L._then(this._eachComplete,void 0,void 0,this,void 0);L._then(G,G,void 0,L,this)},$.prototype.reduce=function(w,L){return Z(this,w,L,null)},$.reduce=function(w,L,F,O){return Z(w,L,F,O)};function G(w,L){if(this.isFulfilled())L._resolve(w);else L._reject(w)}function Z(w,L,F,O){if(typeof L!=="function")return Y("expecting a function but got "+Q.classString(L));var A=new H(w,L,F,O);return A.promise()}function V(w){this.accum=w,this.array._gotAccum(w);var L=z(this.value,this.array._promise);if(L instanceof $)return this.array._currentCancellable=L,L._then(X,void 0,void 0,this,void 0);else return X.call(this,L)}function X(w){var L=this.array,F=L._promise,O=K(L._fn);F._pushContext();var A;if(L._eachValues!==void 0)A=O.call(F._boundValue(),w,this.index,this.length);else A=O.call(F._boundValue(),this.accum,w,this.index,this.length);if(A instanceof $)L._currentCancellable=A;var B=F._popContext();return I.checkForgottenReturns(A,B,L._eachValues!==void 0?"Promise.each":"Promise.reduce",F),A}}});var gO0=M((_94,hO0)=>{hO0.exports=function($,q,Y){var z=$.PromiseInspection,U=G4();function I(J){this.constructor$(J)}U.inherits(I,q),I.prototype._promiseResolved=function(J,Q){this._values[J]=Q;var K=++this._totalResolved;if(K>=this._length)return this._resolve(this._values),!0;return!1},I.prototype._promiseFulfilled=function(J,Q){var K=new z;return K._bitField=33554432,K._settledValueField=J,this._promiseResolved(Q,K)},I.prototype._promiseRejected=function(J,Q){var K=new z;return K._bitField=16777216,K._settledValueField=J,this._promiseResolved(Q,K)},$.settle=function(J){return Y.deprecated(".settle()",".reflect()"),new I(J).promise()},$.prototype.settle=function(){return $.settle(this)}}});var yO0=M((C94,SO0)=>{SO0.exports=function($,q,Y){var z=G4(),U=e9().RangeError,I=e9().AggregateError,J=z.isArray,Q={};function K(G){this.constructor$(G),this._howMany=0,this._unwrap=!1,this._initialized=!1}z.inherits(K,q),K.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var G=J(this._values);if(!this._isResolved()&&G&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},K.prototype.init=function(){this._initialized=!0,this._init()},K.prototype.setUnwrap=function(){this._unwrap=!0},K.prototype.howMany=function(){return this._howMany},K.prototype.setHowMany=function(G){this._howMany=G},K.prototype._promiseFulfilled=function(G){if(this._addFulfilled(G),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
See http://goo.gl/MqrFmX
`);var W=new K(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=K}});var YH0=F((ey1,UH0)=>{UH0.exports=function($,I){var z=$.map;$.prototype.filter=function(q,U){return z(this,q,U,I)},$.filter=function(q,U,Y){return z(q,U,Y,I)}}});var QH0=F(($u1,JH0)=>{JH0.exports=function($,I){var{reduce:z,all:q}=$;function U(){return q(this)}function Y(J,Q){return z(J,Q,I,I)}$.prototype.each=function(J){return z(this,J,I,0)._then(U,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(J){return z(this,J,I,I)},$.each=function(J,Q){return z(J,Q,I,0)._then(U,void 0,void 0,J,void 0)},$.mapSeries=Y}});var wH0=F((Iu1,KH0)=>{KH0.exports=function($){var I=$._SomePromiseArray;function z(q){var U=new I(q),Y=U.promise();return U.setHowMany(1),U.setUnwrap(),U.init(),Y}$.any=function(q){return z(q)},$.prototype.any=function(){return z(this)}}});var GH0=F((zu1,Py)=>{Py.exports=function(){var $=function(){return new H(`circular promise resolution chain
`);var V=new K(G),X=V.promise();return V.setHowMany(Z),V.init(),X}$.some=function(G,Z){return H(G,Z)},$.prototype.some=function(G){return H(this,G)},$._SomePromiseArray=K}});var kO0=M((R94,xO0)=>{xO0.exports=function($,q){var Y=$.map;$.prototype.filter=function(z,U){return Y(this,z,U,q)},$.filter=function(z,U,I){return Y(z,U,I,q)}}});var fO0=M((v94,uO0)=>{uO0.exports=function($,q){var{reduce:Y,all:z}=$;function U(){return z(this)}function I(J,Q){return Y(J,Q,q,q)}$.prototype.each=function(J){return Y(this,J,q,0)._then(U,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(J){return Y(this,J,q,q)},$.each=function(J,Q){return Y(J,Q,q,0)._then(U,void 0,void 0,J,void 0)},$.mapSeries=I}});var iO0=M((h94,bO0)=>{bO0.exports=function($){var q=$._SomePromiseArray;function Y(z){var U=new q(z),I=U.promise();return U.setHowMany(1),U.setUnwrap(),U.init(),I}$.any=function(z){return Y(z)},$.prototype.any=function(){return Y(this)}}});var nO0=M((g94,df)=>{df.exports=function(){var $=function(){return new Z(`circular promise resolution chain
See http://goo.gl/MqrFmX
`)},I=function(){return new g.PromiseInspection(this._target())},z=function(R){return g.reject(new H(R))};function q(){}var U={},Y=r1(),J;if(Y.isNode)J=function(){var R=process.domain;if(R===void 0)R=null;return R};else J=function(){return null};Y.notEnumerableProp(g,"_getDomain",J);var Q=NI(),K=qG0(),w=new K;Q.defineProperty(g,"_async",{value:w});var G=z9(),H=g.TypeError=G.TypeError;g.RangeError=G.RangeError;var W=g.CancellationError=G.CancellationError;g.TimeoutError=G.TimeoutError,g.OperationalError=G.OperationalError,g.RejectionError=G.OperationalError,g.AggregateError=G.AggregateError;var V=function(){},X={},L={},D=KG0()(g,V),O=GG0()(g,V,D,z,q),A=WG0()(g),T=A.create,M=ZG0()(g,A),v=M.CapturedTrace,x=LG0()(g,D),h=OG0()(L),k=My(),E=Y.errorObj,f=Y.tryCatch;function n(R,u){if(typeof u!=="function")throw new H("expecting a function but got "+Y.classString(u));if(R.constructor!==g)throw new H(`the promise constructor cannot be invoked directly
`)},q=function(){return new g.PromiseInspection(this._target())},Y=function(j){return g.reject(new Z(j))};function z(){}var U={},I=G4(),J;if(I.isNode)J=function(){var j=process.domain;if(j===void 0)j=null;return j};else J=function(){return null};I.notEnumerableProp(g,"_getDomain",J);var Q=kq(),K=yF0(),H=new K;Q.defineProperty(g,"_async",{value:H});var G=e9(),Z=g.TypeError=G.TypeError;g.RangeError=G.RangeError;var V=g.CancellationError=G.CancellationError;g.TimeoutError=G.TimeoutError,g.OperationalError=G.OperationalError,g.RejectionError=G.OperationalError,g.AggregateError=G.AggregateError;var X=function(){},w={},L={},F=bF0()(g,X),O=nF0()(g,X,F,Y,z),A=pF0()(g),B=A.create,P=mF0()(g,A),T=P.CapturedTrace,y=oF0()(g,F),v=sF0()(L),k=cf(),R=I.errorObj,c=I.tryCatch;function n(j,u){if(typeof u!=="function")throw new Z("expecting a function but got "+I.classString(u));if(j.constructor!==g)throw new Z(`the promise constructor cannot be invoked directly
See http://goo.gl/MqrFmX
`)}function g(R){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,R!==V)n(this,R),this._resolveFromExecutor(R);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(R){var u=arguments.length;if(u>1){var c=Array(u-1),m=0,e;for(e=0;e<u-1;++e){var G0=arguments[e];if(Y.isObject(G0))c[m++]=G0;else return z("expecting an object but got A catch statement predicate "+Y.classString(G0))}return c.length=m,R=arguments[e],this.then(void 0,h(c,R,this))}return this.then(void 0,R)},g.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},g.prototype.then=function(R,u){if(M.warnings()&&arguments.length>0&&typeof R!=="function"&&typeof u!=="function"){var c=".then() only accepts functions but was passed: "+Y.classString(R);if(arguments.length>1)c+=", "+Y.classString(u);this._warn(c)}return this._then(R,u,void 0,void 0,void 0)},g.prototype.done=function(R,u){var c=this._then(R,u,void 0,void 0,void 0);c._setIsFinal()},g.prototype.spread=function(R){if(typeof R!=="function")return z("expecting a function but got "+Y.classString(R));return this.all()._then(R,void 0,void 0,X,void 0)},g.prototype.toJSON=function(){var R={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())R.fulfillmentValue=this.value(),R.isFulfilled=!0;else if(this.isRejected())R.rejectionReason=this.reason(),R.isRejected=!0;return R},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},g.prototype.error=function(R){return this.caught(Y.originatesFromRejection,R)},g.getNewLibraryCopy=Py.exports,g.is=function(R){return R instanceof g},g.fromNode=g.fromCallback=function(R){var u=new g(V);u._captureStackTrace();var c=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,m=f(R)(k(u,c));if(m===E)u._rejectCallback(m.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},g.all=function(R){return new O(R).promise()},g.cast=function(R){var u=D(R);if(!(u instanceof g))u=new g(V),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=R;return u},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(R){var u=new g(V);return u._captureStackTrace(),u._rejectCallback(R,!0),u},g.setScheduler=function(R){if(typeof R!=="function")throw new H("expecting a function but got "+Y.classString(R));return w.setScheduler(R)},g.prototype._then=function(R,u,c,m,e){var G0=e!==void 0,M0=G0?e:new g(V),g0=this._target(),G1=g0._bitField;if(!G0){if(M0._propagateFrom(this,3),M0._captureStackTrace(),m===void 0&&(this._bitField&2097152)!==0)if((G1&50397184)!==0)m=this._boundValue();else m=g0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,M0)}var S0=J();if((G1&50397184)!==0){var $1,A0,U0=g0._settlePromiseCtx;if((G1&33554432)!==0)A0=g0._rejectionHandler0,$1=R;else if((G1&16777216)!==0)A0=g0._fulfillmentHandler0,$1=u,g0._unsetRejectionIsUnhandled();else U0=g0._settlePromiseLateCancellationObserver,A0=new W("late cancellation observer"),g0._attachExtraTrace(A0),$1=u;w.invoke(U0,g0,{handler:S0===null?$1:typeof $1==="function"&&Y.domainBind(S0,$1),promise:M0,receiver:m,value:A0})}else g0._addCallbacks(R,u,M0,m,S0);return M0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(R){this._bitField=this._bitField&-65536|R&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(w.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(R){var u=R===0?this._receiver0:this[R*4-4+3];if(u===U)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},g.prototype._promiseAt=function(R){return this[R*4-4+2]},g.prototype._fulfillmentHandlerAt=function(R){return this[R*4-4+0]},g.prototype._rejectionHandlerAt=function(R){return this[R*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(R){var{_bitField:u,_ Line truncated
`)}function g(j){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,j!==X)n(this,j),this._resolveFromExecutor(j);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(j){var u=arguments.length;if(u>1){var p=Array(u-1),d=0,Y0;for(Y0=0;Y0<u-1;++Y0){var t=arguments[Y0];if(I.isObject(t))p[d++]=t;else return Y("expecting an object but got A catch statement predicate "+I.classString(t))}return p.length=d,j=arguments[Y0],this.then(void 0,v(p,j,this))}return this.then(void 0,j)},g.prototype.reflect=function(){return this._then(q,q,void 0,this,void 0)},g.prototype.then=function(j,u){if(P.warnings()&&arguments.length>0&&typeof j!=="function"&&typeof u!=="function"){var p=".then() only accepts functions but was passed: "+I.classString(j);if(arguments.length>1)p+=", "+I.classString(u);this._warn(p)}return this._then(j,u,void 0,void 0,void 0)},g.prototype.done=function(j,u){var p=this._then(j,u,void 0,void 0,void 0);p._setIsFinal()},g.prototype.spread=function(j){if(typeof j!=="function")return Y("expecting a function but got "+I.classString(j));return this.all()._then(j,void 0,void 0,w,void 0)},g.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},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},g.prototype.error=function(j){return this.caught(I.originatesFromRejection,j)},g.getNewLibraryCopy=df.exports,g.is=function(j){return j instanceof g},g.fromNode=g.fromCallback=function(j){var u=new g(X);u._captureStackTrace();var p=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,d=c(j)(k(u,p));if(d===R)u._rejectCallback(d.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},g.all=function(j){return new O(j).promise()},g.cast=function(j){var u=F(j);if(!(u instanceof g))u=new g(X),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=j;return u},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(j){var u=new g(X);return u._captureStackTrace(),u._rejectCallback(j,!0),u},g.setScheduler=function(j){if(typeof j!=="function")throw new Z("expecting a function but got "+I.classString(j));return H.setScheduler(j)},g.prototype._then=function(j,u,p,d,Y0){var t=Y0!==void 0,H0=t?Y0:new g(X),w0=this._target(),T0=w0._bitField;if(!t){if(H0._propagateFrom(this,3),H0._captureStackTrace(),d===void 0&&(this._bitField&2097152)!==0)if((T0&50397184)!==0)d=this._boundValue();else d=w0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,H0)}var R0=J();if((T0&50397184)!==0){var E0,i0,Q0=w0._settlePromiseCtx;if((T0&33554432)!==0)i0=w0._rejectionHandler0,E0=j;else if((T0&16777216)!==0)i0=w0._fulfillmentHandler0,E0=u,w0._unsetRejectionIsUnhandled();else Q0=w0._settlePromiseLateCancellationObserver,i0=new V("late cancellation observer"),w0._attachExtraTrace(i0),E0=u;H.invoke(Q0,w0,{handler:R0===null?E0:typeof E0==="function"&&I.domainBind(R0,E0),promise:H0,receiver:d,value:i0})}else w0._addCallbacks(j,u,H0,d,R0);return H0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(j){this._bitField=this._bitField&-65536|j&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(j){var u=j===0?this._receiver0:this[j*4-4+3];if(u===U)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},g.prototype._promiseAt=function(j){return this[j*4-4+2]},g.prototype._fulfillmentHandlerAt=function(j){return this[j*4-4+0]},g.prototype._rejectionHandlerAt=function(j){return this[j*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(j){var{_bitField:u Line truncated
path = %s
syscall = %s
fstream_type = %s
@@ -288,22 +288,26 @@ fstream_unc_path = %s
fstream_class = %s
fstream_stack =
%s
`,I||"UNKNOWN",q.stack,q.path,q.syscall,q.fstream_type,q.fstream_path,q.fstream_unc_path,q.fstream_class,q.fstream_stack.join(`
`));else z.emit("warn",q)};x7.prototype.info=function($,I){this.emit("info",$,I)};x7.prototype.error=function($,I,z){var q=pW0($,I,this);if(z)throw q;else this.emit("error",q)};function pW0($,I,z){if(!($ instanceof Error))$=Error($);if($.code=$.code||I,$.path=$.path||z.path,$.fstream_type=$.fstream_type||z.type,$.fstream_path=$.fstream_path||z.path,z._path!==z.path)$.fstream_unc_path=$.fstream_unc_path||z._path;if(z.linkpath)$.fstream_linkpath=$.fstream_linkpath||z.linkpath;return $.fstream_class=$.fstream_class||z.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(q){return q.replace(/^ {4}at /,"")}),$}});var SK=F((Cu1,dW0)=>{dW0.exports=KK1;function KK1($){var I=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],z;if($.type&&I.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var q=0,U=I.length;q<U;q++){z=I[q];var Y=$[z]||$["is"+z];if(typeof Y==="function")Y=Y.call($);if(Y)return $[z]=!0,$.type=z,z}return null}});var wu=F((hu1,mW0)=>{mW0.exports=yK;var wK1=X$(),GK1=l0(),Ku=RI();GK1(yK,Ku);function yK($){var I=this;if(!(I instanceof yK))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Ku.call(I,$)}yK.prototype._stat=function($){var I=this;wK1.readlink(I._path,function(z,q){if(z)return I.error(z);I.linkpath=I.props.linkpath=q,I.emit("linkpath",q),Ku.prototype._stat.call(I,$)})};yK.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Hu=F((Su1,rW0)=>{rW0.exports=W5;var oW0=X$(),HK1=l0(),uK=t("path"),Gu=RI(),lW0=t("assert").ok;HK1(W5,Gu);function W5($){var I=this;if(!(I instanceof W5))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;Gu.call(this,$)}W5.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,oW0.readdir($._path,function(I,z){if(I)return $.error(I);if($.entries=z,$.emit("entries",z),$._paused)$.once("resume",q);else q();function q(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};W5.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=uK.resolve($._path,$.entries[$._index]);lW0(I!==$._path),lW0($.entries[$._index]),$._currentEntry=I,oW0[$.props.follow?"stat":"lstat"](I,function(z,q){if(z)return $.error(z);var U=$._proxy||$;q.path=I,q.basename=uK.basename(I),q.dirname=uK.dirname(I);var Y=$.getChildProps.call(U,q);Y.path=I,Y.basename=uK.basename(I),Y.dirname=uK.dirname(I);var J=Gu(Y,q);$._currentEntry=J,J.on("pause",function(w){if(!$._paused&&!J._disowned)$.pause(w)}),J.on("resume",function(w){if($._paused&&!J._disowned)$.resume(w)}),J.on("stat",function(w){if($.emit("_entryStat",J,w),J._aborted)return;if(J._paused)J.once("resume",function(){$.emit("entryStat",J,w)});else $.emit("entryStat",J,w)}),J.on("ready",function w(){if($._paused)return J.pause($),$.once("resume",w);if(J.type==="Socket")$.emit("socket",J);else $.emitEntry(J)});var Q=!1;J.on("close",K),J.on("disown",K);function K(){if(Q)return;if(Q=!0,$.emit("childEnd",J),$.emit("entryEnd",J),$._currentEntry=null,!$._paused)$._read()}J.on("error",function(w){if(J._swallowErrors)$.warn(w),J.emit("end"),J.emit("close");else $.emit("error",w)}),["child","childEnd","warn"].forEach(function(w){J.on(w,$.emit.bind($,w))})})};W5.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};W5.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}};W5.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",$)};W5.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()};W5.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var Wu=F((yu1,eW0)=>{eW0.exports=gI;var WK1=X$(),VK1=l0(),tW0=RI(),aW0={EOF:!0},sW0={CLOSE:!0};VK1(gI,tW0);function gI($){var I=this;if(!(I instanceof gI))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,tW0.call(I,$)}gI.prototype._getStream=function(){var $=this,I=$._stream=WK1.createReadStream($._path,$.pro Line truncated
`,q||"UNKNOWN",z.stack,z.path,z.syscall,z.fstream_type,z.fstream_path,z.fstream_unc_path,z.fstream_class,z.fstream_stack.join(`
`));else Y.emit("warn",z)};c7.prototype.info=function($,q){this.emit("info",$,q)};c7.prototype.error=function($,q,Y){var z=DN0($,q,this);if(Y)throw z;else this.emit("error",z)};function DN0($,q,Y){if(!($ instanceof Error))$=Error($);if($.code=$.code||q,$.path=$.path||Y.path,$.fstream_type=$.fstream_type||Y.type,$.fstream_path=$.fstream_path||Y.path,Y._path!==Y.path)$.fstream_unc_path=$.fstream_unc_path||Y._path;if(Y.linkpath)$.fstream_linkpath=$.fstream_linkpath||Y.linkpath;return $.fstream_class=$.fstream_class||Y.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(z){return z.replace(/^ {4}at /,"")}),$}});var zZ=M((H34,PN0)=>{PN0.exports=xP1;function xP1($){var q=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],Y;if($.type&&q.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var z=0,U=q.length;z<U;z++){Y=q[z];var I=$[Y]||$["is"+Y];if(typeof I==="function")I=I.call($);if(I)return $[Y]=!0,$.type=Y,Y}return null}});var vb=M((G34,BN0)=>{BN0.exports=UZ;var kP1=m8(),uP1=m0(),Rb=mq();uP1(UZ,Rb);function UZ($){var q=this;if(!(q instanceof UZ))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Rb.call(q,$)}UZ.prototype._stat=function($){var q=this;kP1.readlink(q._path,function(Y,z){if(Y)return q.error(Y);q.linkpath=q.props.linkpath=z,q.emit("linkpath",z),Rb.prototype._stat.call(q,$)})};UZ.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var gb=M((Z34,jN0)=>{jN0.exports=z9;var EN0=m8(),fP1=m0(),IZ=m("path"),hb=mq(),TN0=m("assert").ok;fP1(z9,hb);function z9($){var q=this;if(!(q instanceof z9))throw Error("DirReader must be called as constructor.");if($.type!=="Directory"||!$.Directory)throw Error("Non-directory type "+$.type);if(q.entries=null,q._index=-1,q._paused=!1,q._length=-1,$.sort)this.sort=$.sort;hb.call(this,$)}z9.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,EN0.readdir($._path,function(q,Y){if(q)return $.error(q);if($.entries=Y,$.emit("entries",Y),$._paused)$.once("resume",z);else z();function z(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};z9.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 q=IZ.resolve($._path,$.entries[$._index]);TN0(q!==$._path),TN0($.entries[$._index]),$._currentEntry=q,EN0[$.props.follow?"stat":"lstat"](q,function(Y,z){if(Y)return $.error(Y);var U=$._proxy||$;z.path=q,z.basename=IZ.basename(q),z.dirname=IZ.dirname(q);var I=$.getChildProps.call(U,z);I.path=q,I.basename=IZ.basename(q),I.dirname=IZ.dirname(q);var J=hb(I,z);$._currentEntry=J,J.on("pause",function(H){if(!$._paused&&!J._disowned)$.pause(H)}),J.on("resume",function(H){if($._paused&&!J._disowned)$.resume(H)}),J.on("stat",function(H){if($.emit("_entryStat",J,H),J._aborted)return;if(J._paused)J.once("resume",function(){$.emit("entryStat",J,H)});else $.emit("entryStat",J,H)}),J.on("ready",function H(){if($._paused)return J.pause($),$.once("resume",H);if(J.type==="Socket")$.emit("socket",J);else $.emitEntry(J)});var Q=!1;J.on("close",K),J.on("disown",K);function K(){if(Q)return;if(Q=!0,$.emit("childEnd",J),$.emit("entryEnd",J),$._currentEntry=null,!$._paused)$._read()}J.on("error",function(H){if(J._swallowErrors)$.warn(H),J.emit("end"),J.emit("close");else $.emit("error",H)}),["child","childEnd","warn"].forEach(function(H){J.on(H,$.emit.bind($,H))})})};z9.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};z9.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}};z9.prototype.pause=function($){var q=this;if(q._paused)return;if($=$||q,q._paused=!0,q._currentEntry&&q._currentEntry.pause)q._currentEntry.pause($);q.emit("pause",$)};z9.prototype.resume=function($){var q=this;if(!q._paused)return;if($=$||q,q._paused=!1,q.emit("resume",$),q._paused)return;if(q._currentEntry){if(q._currentEntry.resume)q._currentEntry.resume($)}else q._read()};z9.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var Sb=M((W34,vN0)=>{vN0.exports=lq;var bP1=m8(),iP1=m0(),_N0=mq(),CN0={EOF:!0},RN0={CLOSE:!0};iP1(lq,_N0);function lq($){var q=this;if(!(q instanceof lq))throw Error("FileReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="File"&&$.File))throw Error("Non-file type "+$.type);q._buffer=[],q._bytesEmitted=0,_N0.call(q,$)}lq.prototype._getStream=function(){var $=this,q=$._stream=bP1.createReadStream($._path,$.pro Line truncated
expect: `+$.props.size+`
actual: `+$._bytesEmitted)}),I.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(sW0),$._read();else $.emit("close")}),I.on("error",function(z){$.emit("error",z)}),$._read()};gI.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var I=$._buffer;for(var z=0,q=I.length;z<q;z++){var U=I[z];if(U===aW0)$.emit("end");else if(U===sW0)$.emit("close");else $.emit("data",U);if($._paused){$._buffer=I.slice(z);return}}$._buffer.length=0}};gI.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._stream)I._stream.pause();I.emit("pause",$)};gI.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 zV0=F((uu1,IV0)=>{IV0.exports=TD;var ZK1=l0(),$V0=RI();ZK1(TD,$V0);function TD($){var I=this;if(!(I instanceof TD))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);$V0.call(I,$)}TD.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Zu=F((xu1,qV0)=>{qV0.exports=_I;var Vu=RI(),XK1=SK(),LK1=l0(),DK1=X$();LK1(_I,Vu);function _I($){var I=this;if(!(I instanceof _I))throw Error("ProxyReader must be called as constructor.");I.props=$,I._buffer=[],I.ready=!1,Vu.call(I,$)}_I.prototype._stat=function(){var $=this,I=$.props,z=I.follow?"stat":"lstat";DK1[z](I.path,function(q,U){var Y;if(q||!U)Y="File";else Y=XK1(U);I[Y]=!0,I.type=$.type=Y,$._old=U,$._addProxy(Vu(I,U))})};_I.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(q){$.on(q,I.emit.bind(I,q))}),I.emit("proxy",$),$.on("ready",function(){I.ready=!0,I.emit("ready")});var z=I._buffer;I._buffer.length=0,z.forEach(function(q){$[q[0]].apply($,q[1])})};_I.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};_I.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var RI=F((ku1,JV0)=>{JV0.exports=C8;var OK1=X$(),FK1=t("stream").Stream,NK1=l0(),Xu=t("path"),Lu=SK(),ED=C8.hardLinks={},UV0=PD();NK1(C8,UV0);var YV0=wu();function C8($,I){var z=this;if(!(z instanceof C8))return new C8($,I);if(typeof $==="string")$={path:$};var q,U;if($.type&&typeof $.type==="function")q=$.type,U=q;else q=Lu($),U=C8;if(I&&!q)q=Lu(I),$[q]=!0,$.type=q;switch(q){case"Directory":U=Hu();break;case"Link":case"File":U=Wu();break;case"SymbolicLink":U=YV0;break;case"Socket":U=zV0();break;case null:U=Zu();break}if(!(z instanceof U))return new U($);if(UV0.call(z),!$.path)z.error("Must provide a path",null,!0);if(z.readable=!0,z.writable=!1,z.type=q,z.props=$,z.depth=$.depth=$.depth||0,z.parent=$.parent||null,z.root=$.root||$.parent&&$.parent.root||z,z._path=z.path=Xu.resolve($.path),process.platform==="win32"){if(z.path=z._path=z.path.replace(/\?/g,"_"),z._path.length>=260)z._swallowErrors=!0,z._path="\\\\?\\"+z.path.replace(/\//g,"\\")}if(z.basename=$.basename=Xu.basename(z.path),z.dirname=$.dirname=Xu.dirname(z.path),$.parent=$.root=null,z.size=$.size,z.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=MK1;z._stat(I)}function MK1($,I){return $===I?0:$.toLowerCase()>I.toLowerCase()?1:$.toLowerCase()<I.toLowerCase()?-1:$>I?1:-1}C8.prototype._stat=function($){var I=this,z=I.props,q=z.follow?"stat":"lstat";if($)process.nextTick(U.bind(null,null,$));else OK1[q](I._path,U);function U(Y,J){if(Y)return I.error(Y);if(Object.keys(J).forEach(function(V){z[V]=J[V]}),I.size!==void 0&&z.size!==I.size)return I.error("incorrect size");I.size=z.size;var Q=Lu(z),K=z.hardlinks!==!1;if(K&&Q!=="Directory"&&z.nlink&&z.nlink>1){var w=z.dev+":"+z.ino;if(ED[w]===I._path||!ED[w])ED[w]=I._path;else Q=I.type=I.props.type="Link",I.Link=I.props.Link=!0,I.linkpath=I.props.linkpath=ED[w],I._stat=I._read=YV0.prototype._read}if(I.type&&I.type!==Q)I.error("Unexpected type: "+Q);if(I.filter){var G=I._proxy||I;if(!I.filter.call(G,G,z)){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,z),V()})()}};C8.prototype.pipe=function($){var I=this;if(typeof $.add==="function")I.on("entry",function(z){var q=$.add(z);if(q===!1)I.pause()});return FK1.prototype.pipe.apply(this,arguments)};C8.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};C8.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};C8.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var Nu=F((fu1,ZV0)=>{Z Line truncated
actual: `+$._bytesEmitted)}),q.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(RN0),$._read();else $.emit("close")}),q.on("error",function(Y){$.emit("error",Y)}),$._read()};lq.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var q=$._buffer;for(var Y=0,z=q.length;Y<z;Y++){var U=q[Y];if(U===CN0)$.emit("end");else if(U===RN0)$.emit("close");else $.emit("data",U);if($._paused){$._buffer=q.slice(Y);return}}$._buffer.length=0}};lq.prototype.pause=function($){var q=this;if(q._paused)return;if($=$||q,q._paused=!0,q._stream)q._stream.pause();q.emit("pause",$)};lq.prototype.resume=function($){var q=this;if(!q._paused)return;if($=$||q,q.emit("resume",$),q._paused=!1,q._stream)q._stream.resume();q._read()}});var SN0=M((X34,gN0)=>{gN0.exports=vN;var nP1=m0(),hN0=mq();nP1(vN,hN0);function vN($){var q=this;if(!(q instanceof vN))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);hN0.call(q,$)}vN.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var xb=M((V34,yN0)=>{yN0.exports=oq;var yb=mq(),cP1=zZ(),pP1=m0(),dP1=m8();pP1(oq,yb);function oq($){var q=this;if(!(q instanceof oq))throw Error("ProxyReader must be called as constructor.");q.props=$,q._buffer=[],q.ready=!1,yb.call(q,$)}oq.prototype._stat=function(){var $=this,q=$.props,Y=q.follow?"stat":"lstat";dP1[Y](q.path,function(z,U){var I;if(z||!U)I="File";else I=cP1(U);q[I]=!0,q.type=$.type=I,$._old=U,$._addProxy(yb(q,U))})};oq.prototype._addProxy=function($){var q=this;if(q._proxyTarget)return q.error("proxy already set");q._proxyTarget=$,$._proxy=q,["error","data","end","close","linkpath","entry","entryEnd","child","childEnd","warn","stat"].forEach(function(z){$.on(z,q.emit.bind(q,z))}),q.emit("proxy",$),$.on("ready",function(){q.ready=!0,q.emit("ready")});var Y=q._buffer;q._buffer.length=0,Y.forEach(function(z){$[z[0]].apply($,z[1])})};oq.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};oq.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var mq=M((w34,uN0)=>{uN0.exports=F5;var mP1=m8(),lP1=m("stream").Stream,oP1=m0(),kb=m("path"),ub=zZ(),hN=F5.hardLinks={},xN0=RN();oP1(F5,xN0);var kN0=vb();function F5($,q){var Y=this;if(!(Y instanceof F5))return new F5($,q);if(typeof $==="string")$={path:$};var z,U;if($.type&&typeof $.type==="function")z=$.type,U=z;else z=ub($),U=F5;if(q&&!z)z=ub(q),$[z]=!0,$.type=z;switch(z){case"Directory":U=gb();break;case"Link":case"File":U=Sb();break;case"SymbolicLink":U=kN0;break;case"Socket":U=SN0();break;case null:U=xb();break}if(!(Y instanceof U))return new U($);if(xN0.call(Y),!$.path)Y.error("Must provide a path",null,!0);if(Y.readable=!0,Y.writable=!1,Y.type=z,Y.props=$,Y.depth=$.depth=$.depth||0,Y.parent=$.parent||null,Y.root=$.root||$.parent&&$.parent.root||Y,Y._path=Y.path=kb.resolve($.path),process.platform==="win32"){if(Y.path=Y._path=Y.path.replace(/\?/g,"_"),Y._path.length>=260)Y._swallowErrors=!0,Y._path="\\\\?\\"+Y.path.replace(/\//g,"\\")}if(Y.basename=$.basename=kb.basename(Y.path),Y.dirname=$.dirname=kb.dirname(Y.path),$.parent=$.root=null,Y.size=$.size,Y.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=rP1;Y._stat(q)}function rP1($,q){return $===q?0:$.toLowerCase()>q.toLowerCase()?1:$.toLowerCase()<q.toLowerCase()?-1:$>q?1:-1}F5.prototype._stat=function($){var q=this,Y=q.props,z=Y.follow?"stat":"lstat";if($)process.nextTick(U.bind(null,null,$));else mP1[z](q._path,U);function U(I,J){if(I)return q.error(I);if(Object.keys(J).forEach(function(X){Y[X]=J[X]}),q.size!==void 0&&Y.size!==q.size)return q.error("incorrect size");q.size=Y.size;var Q=ub(Y),K=Y.hardlinks!==!1;if(K&&Q!=="Directory"&&Y.nlink&&Y.nlink>1){var H=Y.dev+":"+Y.ino;if(hN[H]===q._path||!hN[H])hN[H]=q._path;else Q=q.type=q.props.type="Link",q.Link=q.props.Link=!0,q.linkpath=q.props.linkpath=hN[H],q._stat=q._read=kN0.prototype._read}if(q.type&&q.type!==Q)q.error("Unexpected type: "+Q);if(q.filter){var G=q._proxy||q;if(!q.filter.call(G,G,Y)){if(!q._disowned)q.abort(),q.emit("end"),q.emit("close");return}}var Z=["_stat","stat","ready"],V=0;(function X(){if(q._aborted){q.emit("end"),q.emit("close");return}if(q._paused&&q.type!=="Directory"){q.once("resume",X);return}var w=Z[V++];if(!w)return q._read();q.emit(w,Y),X()})()}};F5.prototype.pipe=function($){var q=this;if(typeof $.add==="function")q.on("entry",function(Y){var z=$.add(Y);if(z===!1)q.pause()});return lP1.prototype.pipe.apply(this,arguments)};F5.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};F5.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};F5.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var nb=M((L34,mN0)=>{m Line truncated
expect: `+$.size+`
actual: `+$._bytesWritten);uD.prototype._finish.call($)}});var _u=F((qx1,qZ0)=>{qZ0.exports=i7;var gu=cU(),oK1=SK(),rK1=l0(),tK1=SD(),aK1=t("fs");rK1(i7,gu);function i7($){var I=this;if(!(I instanceof i7))throw Error("ProxyWriter must be called as constructor.");I.props=$,I._needDrain=!1,gu.call(I,$)}i7.prototype._stat=function(){var $=this,I=$.props,z=I.follow?"stat":"lstat";aK1[z](I.path,function(q,U){var Y;if(q||!U)Y="File";else Y=oK1(U);I[Y]=!0,I.type=$.type=Y,$._old=U,$._addProxy(gu(I,U))})};i7.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(q){$.on(q,I.emit.bind(I,q))}),I.emit("proxy",$);var z=I._buffer;if(z.forEach(function(q){$[q[0]].apply($,q[1])}),I._buffer.length=0,I._needsDrain)I.emit("drain")};i7.prototype.add=function($){if(tK1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};i7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};i7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var cU=F((Ux1,WZ0)=>{WZ0.exports=J8;var Y8=X$(),sK1=l0(),eK1=Nu(),$w1=Eu(),bK=t("path"),YZ0=process.platform==="win32"?0:process.umask(),JZ0=SK(),QZ0=PD();sK1(J8,QZ0);J8.dirmode=parseInt("0777",8)&~YZ0;J8.filemode=parseInt("0666",8)&~YZ0;var Iw1=ju(),zw1=vu(),qw1=Ru(),Uw1=_u();function J8($,I){var z=this;if(typeof $==="string")$={path:$};var q=JZ0($),U=J8;switch(q){case"Directory":U=Iw1;break;case"File":U=qw1;break;case"Link":case"SymbolicLink":U=zw1;break;case null:default:U=Uw1;break}if(!(z instanceof U))return new U($);if(QZ0.call(z),!$.path)z.error("Must provide a path",null,!0);if(z.type=$.type,z.props=$,z.depth=$.depth||0,z.clobber=$.clobber===!1?$.clobber:!0,z.parent=$.parent||null,z.root=$.root||$.parent&&$.parent.root||z,z._path=z.path=bK.resolve($.path),process.platform==="win32"){if(z.path=z._path=z.path.replace(/\?/g,"_"),z._path.length>=260)z._swallowErrors=!0,z._path="\\\\?\\"+z.path.replace(/\//g,"\\")}if(z.basename=bK.basename($.path),z.dirname=bK.dirname($.path),z.linkpath=$.linkpath||null,$.parent=$.root=null,z.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);z.readable=!1,z.writable=!0,z._buffer=[],z.ready=!1,z.filter=typeof $.filter==="function"?$.filter:null,z._stat(I)}J8.prototype._create=function(){var $=this;Y8[$.props.follow?"stat":"lstat"]($._path,function(I){if(I)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};J8.prototype._stat=function($){var I=this,z=I.props,q=z.follow?"stat":"lstat",U=I._proxy||I;if($)Y(null,$);else Y8[q](I._path,Y);function Y(J,Q){if(I.filter&&!I.filter.call(U,U,Q)){I._aborted=!0,I.emit("end"),I.emit("close");return}if(J||!Q)return Cu(I);I._old=Q;var K=JZ0(Q);if(K!==I.type||I.type==="File"&&Q.nlink>1)return eK1(I._path,function(w){if(w)return I.error(w);I._old=null,Cu(I)});Cu(I)}};function Cu($){$w1(bK.dirname($._path),J8.dirmode,function(I,z){if(I)return $.error(I);return $._madeDir=z,$._create()})}function KZ0($,I,z,q,U){var Y=I.mode,J=I.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!Y8[J])return U();if(typeof Y!=="number")return U();var Q=z.mode&parseInt("0777",8);if(Y=Y&parseInt("0777",8),Y===Q)return U();Y8[J](q,Y,U)}function wZ0($,I,z,q,U){if(process.platform==="win32")return U();if(!process.getuid||process.getuid()!==0)return U();if(typeof I.uid!=="number"&&typeof I.gid!=="number")return U();if(z.uid===I.uid&&z.gid===I.gid)return U();var Y=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!Y8[Y])return U();if(typeof I.uid!=="number")I.uid=z.uid;if(typeof I.gid!=="number")I.gid=z.gid;Y8[Y](q,I.uid,I.gid,U)}function GZ0($,I,z,q,U){if(!Y8.utimes||process.platform==="win32")return U();var Y=I.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(Y==="lutimes"&&!Y8[Y])Y="utimes";if(!Y8[Y])return U();var{atime:J,mtime:Q}=z,K=I.atime,w=I.mtime;if(K===void 0)K=J;if(w===void 0)w=Q;if(!UZ0(K))K=new Date(K);if(!UZ0(w))K=new Date(w);if(K.getTime()===J.getTime()&&w.getTime()===Q.getTime())return U();Y8[Y](q,K,w,U)}J8.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var I=0,z=null,q=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),Y($._old);else{var U=$.props.follow?"stat":"lstat";Y8[U]($._path,function(Q,K){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);Y($._old=K)})}return;function Y(Q){I+=3,KZ0($,$.props,Q,$._path,J("chmod")),wZ0($,$.props,Q,$._path,J("chown")),GZ0($,$.props,Q,$._path,J("utimes"))}function J(Q){return function(K){if(z)return;if(K)return K.fstream_finish_call=Q,$.error(z=K);if(--I>0)return;if(q)return;if(q=!0,!$._madeDir)return w();else HZ0($,$._path,w);function w(G){if(G)return G.fstream_finish_call="setupMadeDir",$.error(G);$.emit("end"),$.emit("close")}}}};function HZ0($,I,z){var q=$._madeDir,U=bK.dirname(I);Yw1($,U,function(Y){if(Y)return z(Y);if(U===q)return z();HZ0($,U,z)})}function Yw1($,I,z){var q={};Object.keys($.props).forEach(function(Q){if(q[Q]=$.props[Q],Q==="mode"&&$.type!=="Directory")q[Q]=q[Q]|parseInt("0111",8)});var U=3,Y=null;Y8.stat(I,function(Q,K){if(Q)return z(Y=Q);KZ0($,q,K,I,J),wZ0($,q,K,I,J),GZ0($,q,K,I,J)});function J(Q){if(Y)return;if(Q)return z(Y=Q);if(--U===0)return z()}}J8.prototype.pipe=function(){this.error("Can't pipe from writable stream")};J8.prototype.add=function(){this.error("Can't add to non-Directory type")};J8.prototype.write=function(){return!0};function Jw1($){return Object.prototype.toString.call($)}function UZ0($){return typeof $==="object"&&Jw1($)==="[object Date]"}});var xu=F((Qw1)=>{Qw1.Abstract=PD();Qw1.Reader=RI();Qw1.Writer=cU();Qw1.File={Reader:Wu(),Writer:Ru()};Qw1.Dir={Reader:Hu(),Writer:ju()};Qw1.Link={Reader:wu(),Writer:vu()};Qw1.Proxy={Reader:Zu(),Writer:_u()};Qw1.Reader.Dir=Qw1.DirReader=Qw1.Dir.Reader;Qw1.Reader.File=Qw1.FileReader=Qw1.File.Reader;Qw1.Reader.Link=Qw1.LinkReader=Qw1.Link.Reader;Qw1.Reader.Proxy=Qw1.ProxyReader=Qw1.Proxy.Reader;Qw1.Writer.Dir=Qw1.DirWriter=Qw1.Dir.Writer;Qw1.Writer.File=Qw1.FileWriter=Qw1.File.Writer;Qw1.Writer.Link=Qw1.LinkWriter=Qw1.Link.Writer;Qw1.Writer.Proxy=Qw1.ProxyWriter=Qw1.Proxy.Writer;Qw1.collect=SD()});var ZZ0=F((Zx1,VZ0)=>{VZ0.exports=Xw1;var Gw1=ZD(),Hw1=xu().Writer,ku=t("path"),Ww1=t("stream"),Vw1=Ju(),Zw1=y7();function Xw1($){$.path=ku.resolve(ku.normalize($.path));var I=new Gw1($),z=new Ww1.Writable({objectMode:!0});z._write=function(U,Y,J){if(U.type=="Directory")return J();var Q=ku.join($.path,U.path);if(Q.indexOf($.path)!=0)return J();let K=$.getWriter?$.getWriter({path:Q}):Hw1({path:Q});U.pipe(K).on("error",J).on("close",J)};var q=Vw1(I,z);return I.once("crx-header",function(U){q.crxHeader=U}),I.pipe(z).on("finish",function(){q.emit("close")}),q.promise=function(){return new Zw1(function(U,Y){q.on("close",U),q.on("error",Y)})},q}});var XZ0=F((Xx1,xD)=>{var o4=function($){var I=1e7,z=7,q=9007199254740992,U=W(q),Y="0123456789abcdefghijklmnopqrstuvwxyz",J=typeof BigInt==="function";function Q(N,P,S,i){if(typeof N>"u")return Q[0];if(typeof P<"u")return+P===10&&!S?R0(N):$$(N,P,S,i);return R0(N)}function K(N,P){this.value=N,this.sign=P,this.isSmall=!1}K.prototype=Object.create(Q.prototype);function w(N){this.value=N,this.sign=N<0,this.isSmall=!0}w.prototype=Object.create(Q.prototype);function G(N){th Line truncated
actual: `+$._bytesWritten);cN.prototype._finish.call($)}});var eb=M((S34,yD0)=>{yD0.exports=o7;var ab=SI(),AB1=zZ(),PB1=m0(),BB1=iN(),TB1=m("fs");PB1(o7,ab);function o7($){var q=this;if(!(q instanceof o7))throw Error("ProxyWriter must be called as constructor.");q.props=$,q._needDrain=!1,ab.call(q,$)}o7.prototype._stat=function(){var $=this,q=$.props,Y=q.follow?"stat":"lstat";TB1[Y](q.path,function(z,U){var I;if(z||!U)I="File";else I=AB1(U);q[I]=!0,q.type=$.type=I,$._old=U,$._addProxy(ab(q,U))})};o7.prototype._addProxy=function($){var q=this;if(q._proxy)return q.error("proxy already set");q._proxy=$,["ready","error","close","pipe","drain","warn"].forEach(function(z){$.on(z,q.emit.bind(q,z))}),q.emit("proxy",$);var Y=q._buffer;if(Y.forEach(function(z){$[z[0]].apply($,z[1])}),q._buffer.length=0,q._needsDrain)q.emit("drain")};o7.prototype.add=function($){if(BB1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};o7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};o7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var SI=M((y34,pD0)=>{pD0.exports=u$;var k$=m8(),EB1=m0(),jB1=nb(),_B1=lb(),HZ=m("path"),kD0=process.platform==="win32"?0:process.umask(),uD0=zZ(),fD0=RN();EB1(u$,fD0);u$.dirmode=parseInt("0777",8)&~kD0;u$.filemode=parseInt("0666",8)&~kD0;var CB1=rb(),RB1=sb(),vB1=tb(),hB1=eb();function u$($,q){var Y=this;if(typeof $==="string")$={path:$};var z=uD0($),U=u$;switch(z){case"Directory":U=CB1;break;case"File":U=vB1;break;case"Link":case"SymbolicLink":U=RB1;break;case null:default:U=hB1;break}if(!(Y instanceof U))return new U($);if(fD0.call(Y),!$.path)Y.error("Must provide a path",null,!0);if(Y.type=$.type,Y.props=$,Y.depth=$.depth||0,Y.clobber=$.clobber===!1?$.clobber:!0,Y.parent=$.parent||null,Y.root=$.root||$.parent&&$.parent.root||Y,Y._path=Y.path=HZ.resolve($.path),process.platform==="win32"){if(Y.path=Y._path=Y.path.replace(/\?/g,"_"),Y._path.length>=260)Y._swallowErrors=!0,Y._path="\\\\?\\"+Y.path.replace(/\//g,"\\")}if(Y.basename=HZ.basename($.path),Y.dirname=HZ.dirname($.path),Y.linkpath=$.linkpath||null,$.parent=$.root=null,Y.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);Y.readable=!1,Y.writable=!0,Y._buffer=[],Y.ready=!1,Y.filter=typeof $.filter==="function"?$.filter:null,Y._stat(q)}u$.prototype._create=function(){var $=this;k$[$.props.follow?"stat":"lstat"]($._path,function(q){if(q)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};u$.prototype._stat=function($){var q=this,Y=q.props,z=Y.follow?"stat":"lstat",U=q._proxy||q;if($)I(null,$);else k$[z](q._path,I);function I(J,Q){if(q.filter&&!q.filter.call(U,U,Q)){q._aborted=!0,q.emit("end"),q.emit("close");return}if(J||!Q)return $i(q);q._old=Q;var K=uD0(Q);if(K!==q.type||q.type==="File"&&Q.nlink>1)return jB1(q._path,function(H){if(H)return q.error(H);q._old=null,$i(q)});$i(q)}};function $i($){_B1(HZ.dirname($._path),u$.dirmode,function(q,Y){if(q)return $.error(q);return $._madeDir=Y,$._create()})}function bD0($,q,Y,z,U){var I=q.mode,J=q.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!k$[J])return U();if(typeof I!=="number")return U();var Q=Y.mode&parseInt("0777",8);if(I=I&parseInt("0777",8),I===Q)return U();k$[J](z,I,U)}function iD0($,q,Y,z,U){if(process.platform==="win32")return U();if(!process.getuid||process.getuid()!==0)return U();if(typeof q.uid!=="number"&&typeof q.gid!=="number")return U();if(Y.uid===q.uid&&Y.gid===q.gid)return U();var I=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!k$[I])return U();if(typeof q.uid!=="number")q.uid=Y.uid;if(typeof q.gid!=="number")q.gid=Y.gid;k$[I](z,q.uid,q.gid,U)}function nD0($,q,Y,z,U){if(!k$.utimes||process.platform==="win32")return U();var I=q.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(I==="lutimes"&&!k$[I])I="utimes";if(!k$[I])return U();var{atime:J,mtime:Q}=Y,K=q.atime,H=q.mtime;if(K===void 0)K=J;if(H===void 0)H=Q;if(!xD0(K))K=new Date(K);if(!xD0(H))K=new Date(H);if(K.getTime()===J.getTime()&&H.getTime()===Q.getTime())return U();k$[I](z,K,H,U)}u$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var q=0,Y=null,z=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),I($._old);else{var U=$.props.follow?"stat":"lstat";k$[U]($._path,function(Q,K){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);I($._old=K)})}return;function I(Q){q+=3,bD0($,$.props,Q,$._path,J("chmod")),iD0($,$.props,Q,$._path,J("chown")),nD0($,$.props,Q,$._path,J("utimes"))}function J(Q){return function(K){if(Y)return;if(K)return K.fstream_finish_call=Q,$.error(Y=K);if(--q>0)return;if(z)return;if(z=!0,!$._madeDir)return H();else cD0($,$._path,H);function H(G){if(G)return G.fstream_finish_call="setupMadeDir",$.error(G);$.emit("end"),$.emit("close")}}}};function cD0($,q,Y){var z=$._madeDir,U=HZ.dirname(q);gB1($,U,function(I){if(I)return Y(I);if(U===z)return Y();cD0($,U,Y)})}function gB1($,q,Y){var z={};Object.keys($.props).forEach(function(Q){if(z[Q]=$.props[Q],Q==="mode"&&$.type!=="Directory")z[Q]=z[Q]|parseInt("0111",8)});var U=3,I=null;k$.stat(q,function(Q,K){if(Q)return Y(I=Q);bD0($,z,K,q,J),iD0($,z,K,q,J),nD0($,z,K,q,J)});function J(Q){if(I)return;if(Q)return Y(I=Q);if(--U===0)return Y()}}u$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};u$.prototype.add=function(){this.error("Can't add to non-Directory type")};u$.prototype.write=function(){return!0};function SB1($){return Object.prototype.toString.call($)}function xD0($){return typeof $==="object"&&SB1($)==="[object Date]"}});var Ii=M((yB1)=>{yB1.Abstract=RN();yB1.Reader=mq();yB1.Writer=SI();yB1.File={Reader:Sb(),Writer:tb()};yB1.Dir={Reader:gb(),Writer:rb()};yB1.Link={Reader:vb(),Writer:sb()};yB1.Proxy={Reader:xb(),Writer:eb()};yB1.Reader.Dir=yB1.DirReader=yB1.Dir.Reader;yB1.Reader.File=yB1.FileReader=yB1.File.Reader;yB1.Reader.Link=yB1.LinkReader=yB1.Link.Reader;yB1.Reader.Proxy=yB1.ProxyReader=yB1.Proxy.Reader;yB1.Writer.Dir=yB1.DirWriter=yB1.Dir.Writer;yB1.Writer.File=yB1.FileWriter=yB1.File.Writer;yB1.Writer.Link=yB1.LinkWriter=yB1.Link.Writer;yB1.Writer.Proxy=yB1.ProxyWriter=yB1.Proxy.Writer;yB1.collect=iN()});var mD0=M((d34,dD0)=>{dD0.exports=cB1;var uB1=DN(),fB1=Ii().Writer,Ji=m("path"),bB1=m("stream"),iB1=_b(),nB1=i7();function cB1($){$.path=Ji.resolve(Ji.normalize($.path));var q=new uB1($),Y=new bB1.Writable({objectMode:!0});Y._write=function(U,I,J){if(U.type=="Directory")return J();var Q=Ji.join($.path,U.path);if(Q.indexOf($.path)!=0)return J();let K=$.getWriter?$.getWriter({path:Q}):fB1({path:Q});U.pipe(K).on("error",J).on("close",J)};var z=iB1(q,Y);return q.once("crx-header",function(U){z.crxHeader=U}),q.pipe(Y).on("finish",function(){z.emit("close")}),z.promise=function(){return new nB1(function(U,I){z.on("close",U),z.on("error",I)})},z}});var lD0=M((m34,pN)=>{var N6=function($){var q=1e7,Y=7,z=9007199254740992,U=V(z),I="0123456789abcdefghijklmnopqrstuvwxyz",J=typeof BigInt==="function";function Q(N,D,h,x){if(typeof N>"u")return Q[0];if(typeof D<"u")return+D===10&&!h?L0(N):F1(N,D,h,x);return L0(N)}function K(N,D){this.value=N,this.sign=D,this.isSmall=!1}K.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 G(N){th Line truncated
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/var d1=t("fs"),pD=t("os"),r4=t("path"),vZ0=t("crypto"),V5={fs:d1.constants,os:pD.constants},CZ0=/XXXXXX/,hZ0=(V5.O_CREAT||V5.fs.O_CREAT)|(V5.O_EXCL||V5.fs.O_EXCL)|(V5.O_RDWR||V5.fs.O_RDWR),fw1=pD.platform()==="win32",bw1=V5.EBADF||V5.os.errno.EBADF,nw1=V5.ENOENT||V5.os.errno.ENOENT,mU=[],SZ0=d1.rmdirSync.bind(d1),yZ0=!1;function iw1($,I){return d1.rm($,{recursive:!0},I)}function uZ0($){return d1.rmSync($,{recursive:!0})}function pu($,I){let z=lU($,I),q=z[0],U=z[1];sw1(q,function(Y,J){if(Y)return U(Y);let Q=J.tries;(function K(){try{let w=kZ0(J);d1.stat(w,function(G){if(!G){if(Q-- >0)return K();return U(Error("Could not get a unique tmp filename, max tries reached "+w))}U(null,w)})}catch(w){U(w)}})()})}function cu($){let I=lU($),z=I[0],q=ew1(z),U=q.tries;do{let Y=kZ0(q);try{d1.statSync(Y)}catch(J){return Y}}while(U-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function pw1($,I){let z=lU($,I),q=z[0],U=z[1];pu(q,function(J,Q){if(J)return U(J);d1.open(Q,hZ0,q.mode||384,function(w,G){if(w)return U(w);if(q.discardDescriptor)return d1.close(G,function(W){return U(W,Q,void 0,nu(Q,-1,q,!1))});else{let H=q.discardDescriptor||q.detachDescriptor;U(null,Q,G,nu(Q,H?-1:G,q,!1))}})})}function cw1($){let I=lU($),z=I[0],q=z.discardDescriptor||z.detachDescriptor,U=cu(z),Y=d1.openSync(U,hZ0,z.mode||384);if(z.discardDescriptor)d1.closeSync(Y),Y=void 0;return{name:U,fd:Y,removeCallback:nu(U,q?-1:Y,z,!0)}}function dw1($,I){let z=lU($,I),q=z[0],U=z[1];pu(q,function(J,Q){if(J)return U(J);d1.mkdir(Q,q.mode||448,function(w){if(w)return U(w);U(null,Q,xZ0(Q,q,!1))})})}function mw1($){let I=lU($),z=I[0],q=cu(z);return d1.mkdirSync(q,z.mode||448),{name:q,removeCallback:xZ0(q,z,!0)}}function lw1($,I){let z=function(q){if(q&&!iu(q))return I(q);I()};if(0<=$[0])d1.close($[0],function(){d1.unlink($[1],z)});else d1.unlink($[1],z)}function ow1($){let I=null;try{if(0<=$[0])d1.closeSync($[0])}catch(z){if(!$G1(z)&&!iu(z))throw z}finally{try{d1.unlinkSync($[1])}catch(z){if(!iu(z))I=z}}if(I!==null)throw I}function nu($,I,z,q){let U=iD(ow1,[I,$],q),Y=iD(lw1,[I,$],q,U);if(!z.keep)mU.unshift(U);return q?U:Y}function xZ0($,I,z){let q=I.unsafeCleanup?iw1:d1.rmdir.bind(d1),U=I.unsafeCleanup?uZ0:SZ0,Y=iD(U,$,z),J=iD(q,$,z,Y);if(!I.keep)mU.unshift(Y);return z?Y:J}function iD($,I,z,q){let U=!1;return function Y(J){if(!U){let Q=q||Y,K=mU.indexOf(Q);if(K>=0)mU.splice(K,1);if(U=!0,z||$===SZ0||$===uZ0)return $(I);else return $(I,J||function(){})}}}function rw1(){if(!yZ0)return;while(mU.length)try{mU[0]()}catch($){}}function RZ0($){let I=[],z=null;try{z=vZ0.randomBytes($)}catch(q){z=vZ0.pseudoRandomBytes($)}for(let q=0;q<$;q++)I.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[z[q]%62]);return I.join("")}function D$($){return typeof $>"u"}function lU($,I){if(typeof $==="function")return[{},$];if(D$($))return[{},I];let z={};for(let q of Object.getOwnPropertyNames($))z[q]=$[q];return[z,I]}function tw1($,I,z){let q=r4.isAbsolute($)?$:r4.join(I,$);d1.stat(q,function(U){if(U)d1.realpath(r4.dirname(q),function(Y,J){if(Y)return z(Y);z(null,r4.join(J,r4.basename(q)))});else d1.realpath(q,z)})}function aw1($,I){let z=r4.isAbsolute($)?$:r4.join(I,$);try{return d1.statSync(z),d1.realpathSync(z)}catch(q){let U=d1.realpathSync(r4.dirname(z));return r4.join(U,r4.basename(z))}}function kZ0($){let I=$.tmpdir;if(!D$($.name))return r4.join(I,$.dir,$.name);if(!D$($.template))return r4.join(I,$.dir,$.template).replace(CZ0,RZ0(6));let z=[$.prefix?$.prefix:"tmp","-",process.pid,"-",RZ0(12),$.postfix?"-"+$.postfix:""].join("");return r4.join(I,$.dir,z)}function bu($,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 fZ0($){if(!D$($.name)){let I=$.name;if(r4.isAbsolute(I))throw Error(`name option must not contain an absolute path, found "${I}".`);let z=r4.basename(I);if(z===".."||z==="."||z!==I)throw Error(`name option must not contain a path, found "${I}".`)}if(!D$($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(CZ0))throw Error(`Invalid template, found "${$.template}".`)}if(!D$($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=D$($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=D$($.prefix)?"":bu("prefix",$.prefix),$.postfix=D$($.postfix)?"":bu("postfix",$.postfix),$.template=D$($.template)?void 0:bu("template",$.template)}function gZ0($,I,z,q){if(D$(I))return q(null);tw1(I,z,function(U,Y){if(U)return q(U);let J=r4.relative(z,Y);if(J.startsWith("..")||r4.isAbsolute(J))return q(Error(`${$} option must be relative to "${z}", found "${J}".`));q(null,J)})}function _Z0($,I,z){if(D$(I))return;let q=aw1(I,z),U=r4.relative(z,q);if(U.startsWith("..")||r4.isAbsolute(U))throw ELine truncated
`,{mode:384}),I}function qx($){let I=TX0();for(let z of I){if(!x$(z))continue;for(let q of aD(z).filter((U)=>U.endsWith(".json")).filter((U)=>!U.startsWith("example."))){let U=Z5(z,q);try{let Y=eD(U,"utf-8"),J=JSON.parse(Y);if(J&&typeof J==="object"&&J.id===$)return U}catch{}}}return}function c7($,I){let z=qx($);if(!z)throw Error(`Enterprise config not found: ${$}`);let U={...JSON.parse(eD(z,"utf-8")),...I};for(let J of Object.keys(I))if(I[J]===void 0)delete U[J];let Y=eu.parse(U);return OX0(z,`${JSON.stringify(Y,null,2)}
`,"utf-8"),Y}var Ix="SEAL_USE_ENTERPRISES_DIR",FX0="SEAL_HOME_ENTERPRISES_DIR",NX0="SEAL_USE_USER_ENTERPRISES_DIR",MX0="SEAL_HOME_USER_ENTERPRISES_DIR",AX0="SEAL_USE_CONFIG_FILE",PX0="SEAL_HOME_CONFIG_FILE",rU,sD,tD,LX0;var G9=K0(()=>{$x();rU=Z5($O(),".config","seal-use","enterprises"),sD=Z5($O(),".config","seal-home","enterprises"),tD=Z5($O(),".config","seal-use","config.json"),LX0=Z5($O(),".config","seal-home","config.json")});function d7($,I,z=[]){let q=I.corpId?.trim()||void 0,U=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,Y=q??U;if(Y){let Q=$.find((G)=>G.id===Y);if(Q)return Q;let K=$.find((G)=>G.id.toLowerCase()===Y.toLowerCase());if(K)return K;let w=$.find((G)=>G.name.toLowerCase()===Y.toLowerCase());if(w)return w;throw Error(`No enterprise config found for ${Y}`)}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 J=$[0];if(J)return J;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(z.length?z.join(", "):"the configured enterprise directories"))}function $H1($,I){return $.map((z)=>z.trim()).filter(Boolean).map((z)=>I?z:z.toLowerCase())}function IH1($,I){return I?$:$.toLowerCase()}function zH1($,I,z,q){let U=IH1($,q),Y=I.filter((J)=>U.includes(J));if(z==="all"&&Y.length!==I.length)return[];return Y}function qH1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function UH1($,I){if(I.fields&&!I.fields.has($.field))return[];let z=qH1($.value),q=[];return z.forEach((U,Y)=>{let J=zH1(U,I.keywords,I.matchMode,I.caseSensitive);if(J.length===0)return;let Q=Math.max(0,Y-I.contextLines),K=Math.min(z.length,Y+I.contextLines+1),w={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Y+1,matchedKeywords:J,matchedText:IO(U,I.maxChars),context:{before:I.snippetOnly?[]:z.slice(Q,Y).map((G)=>IO(G,I.maxChars)),line:IO(U,I.maxChars),after:I.snippetOnly?[]:z.slice(Y+1,K).map((G)=>IO(G,I.maxChars))},metadata:$.metadata};if(I.snippetOnly)w.context={before:[],line:w.context.line,after:[]};q.push(w)}),q}function IO($,I){if(!I||$.length<=I)return $;return`${$.slice(0,Math.max(0,I))}...`}function YH1($){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 BX0($){return $.rules.flatMap((I,z)=>{let q=`${$.id}:${I.description.slice(0,32)}`,U={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:z};return[{area:"rules",entityType:"rule",entityId:q,title:`${$.versionName} / ${I.scope}`,field:"history.description",value:I.description,metadata:U},{area:"rules",entityType:"rule",entityId:q,title:`${$.versionName} / ${I.scope}`,field:"history.scope",value:I.scope,metadata:U}]})}function JH1($){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 QH1($){let I=[];if($.decisionPreferences)for(let[z,q]of Object.entries($.decisionPreferences))I.push({area:"preferences",entityType:"preference",field:`decisionPreferences.${z}`,value:q,metadata:{integrationSystem:$.integrationSystem}});return $.integrations.forEach((z,q)=>{I.push({area:"preferences",entityType:"integration",title:z.outboundName,field:`integrations[${q}]`,value:z,metadata:{type:z.type,outboundName:z.outboundName,mode:z.mode,corporationId:z.corporationId}})}),I}async function KH1($,I,z){let q=z.ruleVersionScope??"current",U=[I.id,`ruleVersionScope=${q}`,`ruleVersionId=${z.ruleVersionId??""}`,`ruleVersionNumber=${z.ruleVersionNumber??""}`,`latestRuleVersion=${z.latestRuleVersion??!1}`,`documentLimit=${z.documentLimit??100}`].join("|"),Y=EX0.get(U);if(!z.refresh&&Y&&Date.now()<Y.expiresAt)return Y;let[J,Q,K]=await Promise.all([wH1($,{scope:q,versionId:z.ruleVersionId,versionNumber:z.ruleVersionNumber,latest:z.latestRuleVersion}),d9($,{limit:z.documentLimit??100}),E1($,I.seal.endpoints.approvalStylePreferences)]),w=Date.now(),G={entries:[...J,...Q.articles.flatMap(JH1),...QH1(K)],fetchedAt:w,expiresAt:w+jX0};return EX0.set(U,G),G}async function wH1($,I){if(I.scope==="current")return(await W6($)).rules.flatMap(YH1);if(I.scope==="version"){let q=await GH1($,I);return BX0(q)}r Line truncated
`+"为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。",1,`seal-use webhook replay --target-corp <testCorpId>${z.id!==q.id?` --source-corp ${z.id}`:""}`);return{sourceCorp:z,targetCorp:q}}async function Jx($,I,z){let q=I.seal?.endpoints?.approvalStylePreferences??"api/v1/agent/ai-approval/config",U=await v$($,q);if(z||U.length>0)return _X0(U,z,I.id);if(I.environment==="test"||I.id.toLowerCase().includes("test")){console.error(`[webhook-replay] 测试企业「${I.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);let Y=(I.seal.url??I.source?.sealUrl??`https://${I.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,"");return await oW($,Y,{name:"(Seal测-回放通道)",mode:"assisted",outgoingResultWebhook:`${Y}/api/v1/integrations/webhook/replay-mock-callback`},I.seal.endpoints.approvalStylePreferences)}throw new N4(`当前租户「${I.name}」未配置任何 Webhook 集成通道。`,1,`seal-use webhook add --name <name> --result-url <url> --corp ${I.id}`)}async function tU($){let{query:I,sourceClient:z,targetClient:q,sourceCorp:U,targetCorp:Y,webhookSelector:J,snPrefix:Q,snSuffix:K,docIdPrefix:w,docIdSuffix:G,dryRun:H,fetchFn:W=fetch}=$,V=[];if(I.recordId){let v=await X4(z,I.recordId);V.push(v)}else if(I.recordIds&&I.recordIds.length>0)for(let v of I.recordIds)V.push(await X4(z,v));else if(I.sn){let v=await s4(z,{sourceDocumentSN:I.sn,limit:1});if(!v.records.length)throw Error(`在企业「${U.name}」中未找到单据编号为「${I.sn}」的审批记录。`);V.push(v.records[0])}else if(I.sns&&I.sns.length>0)for(let v of I.sns){let x=await s4(z,{sourceDocumentSN:v,limit:1});if(!x.records.length)throw Error(`在企业「${U.name}」中未找到单据编号为「${v}」的审批记录。`);V.push(x.records[0])}else if(I.limit!==void 0){let v=await s4(z,{limit:I.limit,status:I.status,startDate:I.startDate,endDate:I.endDate});if(!v.records.length)throw Error(`在企业「${U.name}」中未检索到符合条件的审批记录。`);V=v.records}else throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let X=V.map((v)=>({run:v,doc:Ux(v,{snPrefix:Q,snSuffix:K,docIdPrefix:w,docIdSuffix:G})}));if(H){let v={id:"preview-webhook",name:J??"预览目标通道",mode:"assisted",incomingDocumentWebhookUrl:`${Y.seal.url}/api/v1/integrations/webhook/preview`};try{let k=await v$(q,Y.seal.endpoints.approvalStylePreferences);if(k.length>0){let E=_X0(k,J,Y.id);v={id:E.id,name:E.name,mode:E.mode,incomingDocumentWebhookUrl:E.incomingDocumentWebhook.url}}}catch{}let x=X.map(({run:k,doc:E})=>({originalRecord:{id:k.id,sourceSystem:k.sourceSystem,sourceDocumentSN:k.sourceDocumentSN,sourceDocumentId:k.sourceDocumentId},document:E,success:!0})),h=x.length===1;return{dryRun:!0,success:!0,sourceCorp:{id:U.id,name:U.name,environment:U.environment},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment},targetWebhook:v,totalCount:x.length,successCount:x.length,failureCount:0,originalRecord:h?x[0].originalRecord:void 0,document:h?x[0].document:void 0,records:x}}let L=await Jx(q,Y,J),D={id:L.id,name:L.name,mode:L.mode,incomingDocumentWebhookUrl:L.incomingDocumentWebhook.url},O=[],A=0,T=0;for(let{run:v,doc:x}of X){console.error(`[webhook-replay] 正在向 Webhook 通道「${L.name}」推送单据: ${x.documentSN}...`);try{let h=await Yx(L.incomingDocumentWebhook.url,L.secret,x,W,p4(Y.seal));O.push({originalRecord:{id:v.id,sourceSystem:v.sourceSystem,sourceDocumentSN:v.sourceDocumentSN,sourceDocumentId:v.sourceDocumentId},replayedDocument:{documentSN:x.documentSN,documentId:x.documentId,fieldCount:x.fields.length},pushResult:h,success:!0}),A+=1}catch(h){let k=h instanceof Error?h.message:String(h);O.push({originalRecord:{id:v.id,sourceSystem:v.sourceSystem,sourceDocumentSN:v.sourceDocumentSN,sourceDocumentId:v.sourceDocumentId},replayedDocument:{documentSN:x.documentSN,documentId:x.documentId,fieldCount:x.fields.length},error:k,success:!1}),T+=1}}let M=O.length===1;return{success:T===0,dryRun:!1,sourceCorp:{id:U.id,name:U.name,environment:U.environment},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment},targetWebhook:D,totalCount:O.length,successCount:A,failureCount:T,originalRecord:M?O[0].originalRecord:void 0,replayedDocument:M?O[0].replayedDocument:void 0,pushResult:M?O[0].pushResult:void 0,records:O}}var XH1;var tK=K0(()=>{zO();k$();c4();XH1=new Set(["TEXT","NUMBER","DATE","AMOUNT","PERSON","ATTACHMENT","DATE_RANGE","DEPARTMENT","LIST","CITY","OBJECT"])});var CX0,Ik1,DH1,zk1;var hX0=K0(()=>{p9();CX0=Z.object({level:Z.enum(["error","warning","info"]),code:Z.string(),message:Z.string(),snippet:Z.string().optional(),suggestion:Z.string().optional()}),Ik1=Z.object({score:Z.number().min(0).max(100),passed:Z.boolean(),issues:Z.array(CX0)}),DH1=Z.object({ruleId:Z.stri Line truncated
*/var J4=m("fs"),sN=m("os"),D6=m("path"),JA0=m("crypto"),U9={fs:J4.constants,os:sN.constants},GA0=/XXXXXX/,ZA0=(U9.O_CREAT||U9.fs.O_CREAT)|(U9.O_EXCL||U9.fs.O_EXCL)|(U9.O_RDWR||U9.fs.O_RDWR),XT1=sN.platform()==="win32",VT1=U9.EBADF||U9.os.errno.EBADF,wT1=U9.ENOENT||U9.os.errno.ENOENT,xI=[],WA0=J4.rmdirSync.bind(J4),XA0=!1;function LT1($,q){return J4.rm($,{recursive:!0},q)}function VA0($){return J4.rmSync($,{recursive:!0})}function Zi($,q){let Y=kI($,q),z=Y[0],U=Y[1];ET1(z,function(I,J){if(I)return U(I);let Q=J.tries;(function K(){try{let H=LA0(J);J4.stat(H,function(G){if(!G){if(Q-- >0)return K();return U(Error("Could not get a unique tmp filename, max tries reached "+H))}U(null,H)})}catch(H){U(H)}})()})}function Wi($){let q=kI($),Y=q[0],z=jT1(Y),U=z.tries;do{let I=LA0(z);try{J4.statSync(I)}catch(J){return I}}while(U-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function FT1($,q){let Y=kI($,q),z=Y[0],U=Y[1];Zi(z,function(J,Q){if(J)return U(J);J4.open(Q,ZA0,z.mode||384,function(H,G){if(H)return U(H);if(z.discardDescriptor)return J4.close(G,function(V){return U(V,Q,void 0,Hi(Q,-1,z,!1))});else{let Z=z.discardDescriptor||z.detachDescriptor;U(null,Q,G,Hi(Q,Z?-1:G,z,!1))}})})}function OT1($){let q=kI($),Y=q[0],z=Y.discardDescriptor||Y.detachDescriptor,U=Wi(Y),I=J4.openSync(U,ZA0,Y.mode||384);if(Y.discardDescriptor)J4.closeSync(I),I=void 0;return{name:U,fd:I,removeCallback:Hi(U,z?-1:I,Y,!0)}}function MT1($,q){let Y=kI($,q),z=Y[0],U=Y[1];Zi(z,function(J,Q){if(J)return U(J);J4.mkdir(Q,z.mode||448,function(H){if(H)return U(H);U(null,Q,wA0(Q,z,!1))})})}function NT1($){let q=kI($),Y=q[0],z=Wi(Y);return J4.mkdirSync(z,Y.mode||448),{name:z,removeCallback:wA0(z,Y,!0)}}function DT1($,q){let Y=function(z){if(z&&!Gi(z))return q(z);q()};if(0<=$[0])J4.close($[0],function(){J4.unlink($[1],Y)});else J4.unlink($[1],Y)}function AT1($){let q=null;try{if(0<=$[0])J4.closeSync($[0])}catch(Y){if(!_T1(Y)&&!Gi(Y))throw Y}finally{try{J4.unlinkSync($[1])}catch(Y){if(!Gi(Y))q=Y}}if(q!==null)throw q}function Hi($,q,Y,z){let U=rN(AT1,[q,$],z),I=rN(DT1,[q,$],z,U);if(!Y.keep)xI.unshift(U);return z?U:I}function wA0($,q,Y){let z=q.unsafeCleanup?LT1:J4.rmdir.bind(J4),U=q.unsafeCleanup?VA0:WA0,I=rN(U,$,Y),J=rN(z,$,Y,I);if(!q.keep)xI.unshift(I);return Y?I:J}function rN($,q,Y,z){let U=!1;return function I(J){if(!U){let Q=z||I,K=xI.indexOf(Q);if(K>=0)xI.splice(K,1);if(U=!0,Y||$===WA0||$===VA0)return $(q);else return $(q,J||function(){})}}}function PT1(){if(!XA0)return;while(xI.length)try{xI[0]()}catch($){}}function QA0($){let q=[],Y=null;try{Y=JA0.randomBytes($)}catch(z){Y=JA0.pseudoRandomBytes($)}for(let z=0;z<$;z++)q.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Y[z]%62]);return q.join("")}function o8($){return typeof $>"u"}function kI($,q){if(typeof $==="function")return[{},$];if(o8($))return[{},q];let Y={};for(let z of Object.getOwnPropertyNames($))Y[z]=$[z];return[Y,q]}function BT1($,q,Y){let z=D6.isAbsolute($)?$:D6.join(q,$);J4.stat(z,function(U){if(U)J4.realpath(D6.dirname(z),function(I,J){if(I)return Y(I);Y(null,D6.join(J,D6.basename(z)))});else J4.realpath(z,Y)})}function TT1($,q){let Y=D6.isAbsolute($)?$:D6.join(q,$);try{return J4.statSync(Y),J4.realpathSync(Y)}catch(z){let U=J4.realpathSync(D6.dirname(Y));return D6.join(U,D6.basename(Y))}}function LA0($){let q=$.tmpdir;if(!o8($.name))return D6.join(q,$.dir,$.name);if(!o8($.template))return D6.join(q,$.dir,$.template).replace(GA0,QA0(6));let Y=[$.prefix?$.prefix:"tmp","-",process.pid,"-",QA0(12),$.postfix?"-"+$.postfix:""].join("");return D6.join(q,$.dir,Y)}function Ki($,q){if(typeof q!=="string")throw Error(`${$} option must be a string, got "${typeof q}".`);if(q.includes(".."))throw Error("Relative value not allowed");return q}function FA0($){if(!o8($.name)){let q=$.name;if(D6.isAbsolute(q))throw Error(`name option must not contain an absolute path, found "${q}".`);let Y=D6.basename(q);if(Y===".."||Y==="."||Y!==q)throw Error(`name option must not contain a path, found "${q}".`)}if(!o8($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(GA0))throw Error(`Invalid template, found "${$.template}".`)}if(!o8($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=o8($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=o8($.prefix)?"":Ki("prefix",$.prefix),$.postfix=o8($.postfix)?"":Ki("postfix",$.postfix),$.template=o8($.template)?void 0:Ki("template",$.template)}function KA0($,q,Y,z){if(o8(q))return z(null);BT1(q,Y,function(U,I){if(U)return z(U);let J=D6.relative(Y,I);if(J.startsWith("..")||D6.isAbsolute(J))return z(Error(`${$} option must be relative to "${Y}", found "${J}".`));z(null,J)})}function HA0($,q,Y){if(o8(q))return;let z=TT1(q,Y),U=D6.relative(Y,z);if(U.startsWith("..")||D6.isAbsolute(U))throw ELine truncated
`)}let z=[];q.forEach((U,I)=>{let J=$.length+I+1,Q=I===0?"⏳ ":"";z.push(`${Q}${J}. ${U}`)});for(let U=$.length-1;U>=0;U--){let I=U+1;z.push(`${I}. ${$[U]}`)}return z.join(`
`)}function Pi($,q,Y,z,U){let I=$?.operator||q?.operator||Y?.operator,J=I?.name||I?.id||Y?.operatorName||"",Q=($?.nodeName||q?.fromNodeName||q?.nodeName||Y?.nodeName||"").trim();if(Q==="合思审批节点"||Q==="外部审批节点"||Q.includes("合思审批")||Q.includes("外部审批"))Q="";if((!Q||Q==="提交人"||Q==="审批节点")&&J&&z){let F=z.find((O)=>O.operator?.name===J&&O.nodeName&&O.nodeName.trim()!=="提交人"&&!O.isEbot&&O.rawAction!=="freeflow.reject");if(F?.nodeName)Q=F.nodeName.trim()}let H=$?.comment||q?.reason||Y?.rejectComment||"修改";if(H.includes(":")){let F=H.split(":");if(F.length>1)H=F.slice(1).join(":").trim()}let G=H;if(Q&&J)G=`${Q}(${J}) ❌: ${H}`;else if(J)G=`${J} ❌: ${H}`;else if(Q)G=`${Q} ❌: ${H}`;else G=H;let Z=$?.rejectTargetNodeName||q?.targetNodeName||"提交人",V=$?.rejectTargetOperator?.name||q?.targetOperator?.name||U?.submitter?.name,X=V?`${Z}(${V})`:Z,w=$?.resubmitRuleText||q?.resubmitRuleText||(J?`重新提交后由${J}继续审批`:"重新提交后继续审批");return{comment:`${G}
↳ 驳回至: ${X}
↳ ${w}`,operator:I}}function $P0($){if(!$)return[];let q=$.pending||[],Y=String($.rawState||"").toUpperCase(),z=String($.state||"").toUpperCase(),U=[];if(q.length>0)for(let I of q){let J=I.approver?.name||I.approver?.id||"待定",Q=(I.name||$.currentNode||"").trim(),K=Q?`${Q}(${J})`:J,G=I.type?.toUpperCase()==="PAYING"||Q.includes("支付")||Y==="PAYING"||z==="支付中"?"待支付":"待审批";U.push(`${K}: ${G}`)}else if($.currentNode?.trim()){let J=$.currentNode.includes("支付")||Y==="PAYING"||z==="支付中"?"待支付":"待审批";U.push(`${$.currentNode.trim()}: ${J}`)}return U}function tq($,q){let Y=new Map;if(!$||$.length===0)return Y;if(!q){for(let X of $){let L=(X.result||{}).decision||X.aiDecision||"-";Y.set(X.id,{recordId:X.id,sourceDocumentSN:X.sourceDocumentSN,taskMode:X.taskMode,aiDecision:eA0(typeof L==="string"?L:"-"),aiAction:"-",eHumanAction:"-",eHumanComment:"-",auditDrift:!1})}return Y}let z=[...$].sort((X,w)=>(Number(X.createdAt)||0)-(Number(w.createdAt)||0)),U=q.history||[],I=String(q.rawState||"").toUpperCase(),J=String(q.state||"").toUpperCase(),Q=I==="DRAFT"||I==="REVOKED"||I==="CANCELED"||I==="CANCELLED"||J==="草稿"||J==="已撤回"||J==="已取消",K=I==="REJECTED"||I==="TERMINATED"||J==="审批驳回"||J==="已驳回",H=!Q&&!K&&(I==="PAID"||J==="已支付"||U.some((X)=>!X.isEbot&&(X.rawAction==="freeflow.pay"||X.action==="支付成功"||X.action==="支付完成"))),G=!Q&&!K&&!H&&(I==="PAYING"||J==="支付中"||(q.pending||[]).some((X)=>X.isCurrent&&(X.type?.toUpperCase()==="PAYING"||X.name?.includes("支付")))||q.currentNode?.includes("支付")===!0),V=H||!Q&&!K&&!G&&(I==="COMPLETED"||I==="APPROVED"||J==="已完成"||J==="审批通过");for(let X=0;X<z.length;X++){let w=z[X];if(!w)continue;let L=Number(w.createdAt)||0,F=w.document||{},O=w.manualApprovalRecord||w.result?.manualApprovalRecord||F.manualApprovalRecord||{},A=typeof w.sourceExtendData?.nodeId==="string"?String(w.sourceExtendData.nodeId):void 0,B=typeof O.nodeId==="string"?String(O.nodeId):void 0,P=B?decodeURIComponent(B).replace(/^hcnode_/,"").replace(/_r\d+$/,""):void 0,T=A||P,y=T?U.find((L0)=>L0.nodeId&&(L0.nodeId===T||T.includes(L0.nodeId))):void 0,v=y?.time??L,k=z[X+1],R=k?Number(k.createdAt)||1/0:1/0,c=X===z.length-1,n=U.find((L0)=>(L0.time??0)>v+5000&&L0.isEbot&&(L0.nodeName?.includes("智能")||L0.nodeName?.includes("AI")||L0.action?.includes("智能")||L0.comment?.includes("AI")||L0.comment?.includes("approval-result"))&&!L0.nodeName?.includes("费用标准检查")&&!L0.nodeName?.includes("标准检查")&&!L0.nodeName?.includes("预算"));if(n){if(c=!1,(n.time??1/0)<R)R=n.time}let g=w.result||{},b=g.decision||w.aiDecision||"-",i=typeof b==="string"?b:"-",$0=i.toUpperCase(),j=$0==="REJECT"||$0==="驳回",u=$0==="APPROVE"||$0==="通过",p=$0==="EXEMPT_APPROVE"||$0==="免审通过"||$0==="备注通过",d=w.taskMode||w.finalExecutionMode||"",t=String(d).toLowerCase().includes("auto")||w.finalExecutionMode==="automatic"||d==="automatic"||d==="fully_automatic",H0="-";if(u||p)H0="添加评论";else if(j)H0=t?"驳回":"添加评论";else if($0==="REVIEW"||$0==="转交复核")H0="转交复核";let w0=typeof O.status==="object"&&O.status!==null?String(O.status.type||O.status.label||"").toUpperCase():"",T0=typeof O.status==="object"&&O.status!==null?String(O.status.sourceStatus||""):"",R0=F.manualApprovalStatus||g.manualApprovalStatus||w.manualApprovalStatus,E0=typeof R0==="string"?R0.toUpperCase():"",i0=E0==="CANCELLED"||E0==="CANCELED"||E0==="已取消"||E0==="已撤回"||E0==="REVOKED"||w0==="CANCELLED"||w0==="CANCELED"||T0.includes("撤回")||T0.includes("取消"),Q0=E0==="APPROVED"||E0==="已支付/审批完成"||E0==="已通过"||E0==="已完成"||E0==="已支付"||w0==="APPROVED",f0=!(T0.includes("补偿")||T0.includes("已支付"))&&(E0==="TERMINATED"||E0==="REJECTED"||E0==="REJECT"||E0==="已驳回"||E0==="被驳回"||w0==="TERMINATED"||w0==="REJECTED"||w0==="已驳回"||w0==="被驳回"),c0=y?1000:60000,R1=U.filter((L0)=>{let o=L0.time??0;return o>=v-c0&&o<R}),a0="-",r1="-",F1=!1,b1,$1,U6=u||p,a8=U.filter((L0)=>(L0.time??0)>v+5000),I6=a8.some((L0)=>L0.rawAction==="freeflow.retract"||L0.action==="单据撤回"),e8=a8.some((L0)=>L0.rawAction==="freeflow.submit"||L0.action==="提交送审");if(U6&&c&&(I6||e8))F1=!0,b1="AI通过后单据发生撤回/修改重提,后续未经AI复审";if(t&&j)a0="无操作",r1="-";else{let L0=R1.filter((D)=>(D.time??0)>=v-1000&&!D.isEbot&&D.rawAction!=="freeflow.submit"&&D.action!=="提交送审"&&!((D.rawAction==="freeflow.comment"||D.action==="发表评论")&&!D.comment)&&!((D.rawAction==="freeflow.print"||D.action==="打印提醒")&&!D.comment)&&!(D.rawAction==="freeflow.carbonCopy"||D.rawAction==="freeflow.cc"||D.action==="抄送通知")),o=L0.find((D)=>D.rawAction==="freeflow.retract"||D.action==="单据撤回"),N=L0.find((D)=>D.rawAction==="freeflow.reject"||D.action==="审批驳回");if(!c)if(N||!q&&f0){a0="审批驳回",F1=!1,b1=void 0;let D=Pi(N,void 0,O,U,q); Line truncated
`,{mode:384}),q}function ki($){let q=MP0();for(let Y of q){if(!X$(Y))continue;for(let z of HD(Y).filter((U)=>U.endsWith(".json")).filter((U)=>!U.startsWith("example."))){let U=J9(Y,z);try{let I=ZD(U,"utf-8"),J=JSON.parse(I);if(J&&typeof J==="object"&&J.id===$)return U}catch{}}}return}function a7($,q){let Y=ki($);if(!Y)throw Error(`Enterprise config not found: ${$}`);let U={...JSON.parse(ZD(Y,"utf-8")),...q};for(let J of Object.keys(q))if(q[J]===void 0)delete U[J];let I=gi.parse(U);return XP0(Y,`${JSON.stringify(I,null,2)}
`,"utf-8"),I}var yi="SEAL_USE_ENTERPRISES_DIR",VP0="SEAL_HOME_ENTERPRISES_DIR",wP0="SEAL_USE_USER_ENTERPRISES_DIR",LP0="SEAL_HOME_USER_ENTERPRISES_DIR",FP0="SEAL_USE_CONFIG_FILE",OP0="SEAL_HOME_CONFIG_FILE",iI,GD,KD,ZP0;var Q3=e(()=>{Si();iI=J9(WD(),".config","seal-use","enterprises"),GD=J9(WD(),".config","seal-home","enterprises"),KD=J9(WD(),".config","seal-use","config.json"),ZP0=J9(WD(),".config","seal-home","config.json")});function e7($,q,Y=[]){let z=q.corpId?.trim()||void 0,U=q.stateful?q.defaultCorpId?.trim()||void 0:void 0,I=z??U;if(I){let Q=$.find((G)=>G.id===I);if(Q)return Q;let K=$.find((G)=>G.id.toLowerCase()===I.toLowerCase());if(K)return K;let H=$.find((G)=>G.name.toLowerCase()===I.toLowerCase());if(H)return H;throw Error(`No enterprise config found for ${I}`)}if(!q.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 J=$[0];if(J)return J;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(Y.length?Y.join(", "):"the configured enterprise directories"))}import{existsSync as ui,mkdirSync as Qj1,readFileSync as Kj1,renameSync as Hj1,unlinkSync as Gj1,writeFileSync as Zj1}from"node:fs";import{homedir as Wj1}from"node:os";import{dirname as Xj1,join as Vj1}from"node:path";function bi(){let $=process.env[wj1]?.trim();if($)return $;return Lj1}function NP0($=new Date){return $.toISOString().slice(0,10)}function DP0($=fi,q=new Date){let Y=q.getTime()-Math.max(0,$-1)*86400000;return new Date(Y).toISOString().slice(0,10)}function AP0($=bi()){if(!ui($))return{};try{let q=Kj1($,"utf-8"),Y=JSON.parse(q);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y;return{}}catch{return{}}}function Fj1($,q){let Y={};for(let[z,U]of Object.entries($)){if(!U||typeof U!=="object")continue;let I={},J=!1;for(let[Q,K]of Object.entries(U))if(typeof K==="number"&&K>0&&Q>=q)I[Q]=K,J=!0;if(J)Y[z]=I}return Y}function Oj1($,q=bi()){let Y=Xj1(q);if(!ui(Y))Qj1(Y,{recursive:!0,mode:448});let z=`${q}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{Zj1(z,JSON.stringify($,null,2),"utf-8"),Hj1(z,q)}catch(U){try{if(ui(z))Gj1(z)}catch{}throw U}}function PP0($,q=new Date){if(!$||typeof $!=="string")return;try{let Y=bi(),z=AP0(Y),U=NP0(q),I=DP0(fi,q),J=Fj1(z,I);J[$]=J[$]||{},J[$][U]=(J[$][U]??0)+1,Oj1(J,Y)}catch{}}function Mj1($,q=fi,Y=new Date){let z=new Map;try{let U=AP0(),I=DP0(q,Y),J=NP0(Y),Q=$??Object.keys(U);for(let K of Q){let H=U[K];if(!H){z.set(K,0);continue}let G=0;for(let[Z,V]of Object.entries(H))if(Z>=I&&Z<=J&&typeof V==="number")G+=V;z.set(K,G)}}catch{if($)for(let U of $)z.set(U,0)}return z}function BP0($,q,Y){let z=Y??Mj1($.map((U)=>U.id));return[...$].sort((U,I)=>{if(q){if(U.id===q&&I.id!==q)return-1;if(I.id===q&&U.id!==q)return 1}let J=z.get(U.id)??0,Q=z.get(I.id)??0;if(J!==Q)return Q-J;let K=U.name??U.id,H=I.name??I.id,G=K.localeCompare(H,"zh-CN");if(G!==0)return G;return U.id.localeCompare(I.id)})}var wj1="SEAL_USE_USAGE_FILE",Lj1,fi=7;var ii=e(()=>{Lj1=Vj1(Wj1(),".config","seal-use","usage.json")});function Nj1($,q){return $.map((Y)=>Y.trim()).filter(Boolean).map((Y)=>q?Y:Y.toLowerCase())}function Dj1($,q){return q?$:$.toLowerCase()}function Aj1($,q,Y,z){let U=Dj1($,z),I=q.filter((J)=>U.includes(J));if(Y==="all"&&I.length!==q.length)return[];return I}function Pj1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function Bj1($,q){if(q.fields&&!q.fields.has($.field))return[];let Y=Pj1($.value),z=[];return Y.forEach((U,I)=>{let J=Aj1(U,q.keywords,q.matchMode,q.caseSensitive);if(J.length===0)return;let Q=Math.max(0,I-q.contextLines),K=Math.min(Y.length,I+q.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:I+1,matchedKeywords:J,matchedText:XD(U,q.maxChars),context:{before:q.snippetOnly?[]:Y.slice(Q,I).map((G)=>XD(G,q.maxChars)),line:XD(U,q.maxChars),after:q.snippetOnly?[]:Y.slice(I+1,K).map((G)=>XD(G,q.maxChars))},metadata:$.metadata};if(q.snippetOnly)H.context={before:[],line:H.context.line,after:[]};z.push(H)}),z}function XD($,q){if(!q||$.length<=q)return $;return`${$.slice(0,Math.max(0,q))}...`}function Tj1($){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 EP0($){return $.rules.flatMap((q,Y)=>{let z=`${$.id}:${q.description.slice(0,32)}`,U={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:q.scope,strictness:q.strictness,code:"code"in q?q.code:void 0,index:Y};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName} / ${q.scope}`,field:"history.description", Line truncated
`+"为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。",1,`seal-use webhook replay --target-corp <testCorpId>${Y.id!==z.id?` --source-corp ${Y.id}`:""}`);return{sourceCorp:Y,targetCorp:z}}async function pi($,q,Y){let z=q.seal?.endpoints?.approvalStylePreferences??"api/v1/agent/ai-approval/config",U=await U$($,z);if(Y||U.length>0)return vP0(U,Y,q.id);if(q.environment==="test"||q.id.toLowerCase().includes("test")){console.error(`[webhook-replay] 测试企业「${q.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);let I=(q.seal.url??q.source?.sealUrl??`https://${q.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,"");return await nw($,I,{name:"(Seal测-回放通道)",mode:"assisted",outgoingResultWebhook:`${I}/api/v1/integrations/webhook/replay-mock-callback`},q.seal.endpoints.approvalStylePreferences)}throw new b4(`当前租户「${q.name}」未配置任何 Webhook 集成通道。`,1,`seal-use webhook add --name <name> --result-url <url> --corp ${q.id}`)}async function nI($){let{query:q,sourceClient:Y,targetClient:z,sourceCorp:U,targetCorp:I,webhookSelector:J,snPrefix:Q,snSuffix:K,docIdPrefix:H,docIdSuffix:G,dryRun:Z,fetchFn:V=fetch}=$,X=[];if(q.recordId){let T=await e1(Y,q.recordId);X.push(T)}else if(q.recordIds&&q.recordIds.length>0)for(let T of q.recordIds)X.push(await e1(Y,T));else if(q.sn){let T=await y4(Y,{sourceDocumentSN:q.sn,limit:1});if(!T.records.length)throw Error(`在企业「${U.name}」中未找到单据编号为「${q.sn}」的审批记录。`);X.push(T.records[0])}else if(q.sns&&q.sns.length>0)for(let T of q.sns){let y=await y4(Y,{sourceDocumentSN:T,limit:1});if(!y.records.length)throw Error(`在企业「${U.name}」中未找到单据编号为「${T}」的审批记录。`);X.push(y.records[0])}else if(q.limit!==void 0){let T=await y4(Y,{limit:q.limit,status:q.status,startDate:q.startDate,endDate:q.endDate});if(!T.records.length)throw Error(`在企业「${U.name}」中未检索到符合条件的审批记录。`);X=T.records}else throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=X.map((T)=>({run:T,doc:ni(T,{snPrefix:Q,snSuffix:K,docIdPrefix:H,docIdSuffix:G})}));if(Z){let T={id:"preview-webhook",name:J??"预览目标通道",mode:"assisted",incomingDocumentWebhookUrl:`${I.seal.url}/api/v1/integrations/webhook/preview`};try{let k=await U$(z,I.seal.endpoints.approvalStylePreferences);if(k.length>0){let R=vP0(k,J,I.id);T={id:R.id,name:R.name,mode:R.mode,incomingDocumentWebhookUrl:R.incomingDocumentWebhook.url}}}catch{}let y=w.map(({run:k,doc:R})=>({originalRecord:{id:k.id,sourceSystem:k.sourceSystem,sourceDocumentSN:k.sourceDocumentSN,sourceDocumentId:k.sourceDocumentId},document:R,success:!0})),v=y.length===1;return{dryRun:!0,success:!0,sourceCorp:{id:U.id,name:U.name,environment:U.environment},targetCorp:{id:I.id,name:I.name,environment:I.environment},targetWebhook:T,totalCount:y.length,successCount:y.length,failureCount:0,originalRecord:v?y[0].originalRecord:void 0,document:v?y[0].document:void 0,records:y}}let L=await pi(z,I,J),F={id:L.id,name:L.name,mode:L.mode,incomingDocumentWebhookUrl:L.incomingDocumentWebhook.url},O=[],A=0,B=0;for(let{run:T,doc:y}of w){console.error(`[webhook-replay] 正在向 Webhook 通道「${L.name}」推送单据: ${y.documentSN}...`);try{let v=await ci(L.incomingDocumentWebhook.url,L.secret,y,V,L6(I.seal));O.push({originalRecord:{id:T.id,sourceSystem:T.sourceSystem,sourceDocumentSN:T.sourceDocumentSN,sourceDocumentId:T.sourceDocumentId},replayedDocument:{documentSN:y.documentSN,documentId:y.documentId,fieldCount:y.fields.length},pushResult:v,success:!0}),A+=1}catch(v){let k=v instanceof Error?v.message:String(v);O.push({originalRecord:{id:T.id,sourceSystem:T.sourceSystem,sourceDocumentSN:T.sourceDocumentSN,sourceDocumentId:T.sourceDocumentId},replayedDocument:{documentSN:y.documentSN,documentId:y.documentId,fieldCount:y.fields.length},error:k,success:!1}),B+=1}}let P=O.length===1;return{success:B===0,dryRun:!1,sourceCorp:{id:U.id,name:U.name,environment:U.environment},targetCorp:{id:I.id,name:I.name,environment:I.environment},targetWebhook:F,totalCount:O.length,successCount:A,failureCount:B,originalRecord:P?O[0].originalRecord:void 0,replayedDocument:P?O[0].replayedDocument:void 0,pushResult:P?O[0].pushResult:void 0,records:O}}var yj1;var DZ=e(()=>{VD();V$();J6();yj1=new Set(["TEXT","NUMBER","DATE","AMOUNT","PERSON","ATTACHMENT","DATE_RANGE","DEPARTMENT","LIST","CITY","OBJECT"])});var hP0,g24,kj1,S24;var gP0=e(()=>{I5();hP0=W.object({level:W.enum(["error","warning","info"]),code:W.string(),message:W.string(),snippet:W.string().optional(),suggestion:W.string().optional()}),g24=W.object({score:W.number().min(0).max(100),passed:W.boolean(),issues:W.array(hP0)}),kj1=W.object({ruleId:W.string Line truncated
* ==============================================================================
* Seal 官方标准规则校验器 (Official Standard Rule Linter)
* ==============================================================================
@@ -626,41 +630,295 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
export default lintRule;
`}});import{existsSync as uI,mkdirSync as BH1,readFileSync as jH1,readdirSync as xX0,rmSync as vH1,unlinkSync as RH1,writeFileSync as gH1}from"node:fs";import{homedir as _H1}from"node:os";import{isAbsolute as CH1,join as u6,resolve as hH1}from"node:path";import{pathToFileURL as yX0}from"node:url";function kX0($=L5){let I=[],z=[];try{if(!uI($))BH1($,{recursive:!0});let q=Object.keys(wx);for(let[Y,J]of Object.entries(wx)){let Q=u6($,Y),K=!0;if(uI(Q))try{if(jH1(Q,"utf8")===J)K=!1}catch{K=!0}if(K)gH1(Q,J,"utf8");I.push(Y)}let U=xX0($,{withFileTypes:!0});for(let Y of U)if(!q.includes(Y.name)){let J=u6($,Y.name);try{if(Y.isDirectory())vH1(J,{recursive:!0,force:!0});else RH1(J);z.push(Y.name)}catch{}}}catch{}return{synced:I,pruned:z}}function fX0($={syncOfficial:!0}){if($.syncOfficial!==!1)kX0();let I=[{name:"builtin",type:"builtin",path:u6(L5,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:u6(L5,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"}],z=[Q8,JO];for(let q of z)if(uI(q))try{let U=xX0(q,{withFileTypes:!0});for(let Y of U){if(Y.isDirectory())continue;let J=Y.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let Q=J.replace(/\.(ts|js|mjs)$/,"");if(!I.some((K)=>K.name===Q))I.push({name:Q,type:"custom",path:u6(q,J),description:`用户自定义规则校验器 (${J})`})}}}catch{}return I}function yH1($){let I=($||"").trim();if(!I||I==="builtin"||I==="default"||I==="official/builtin"||I==="official/builtin.ts")return{path:u6(L5,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(I==="strict"||I==="official/strict"||I==="official/strict.ts")return{path:u6(L5,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(CH1(I)||I.startsWith("./")||I.startsWith("../")){let q=hH1(I);if(uI(q))return{path:q};for(let U of[".ts",".js",".mjs"])if(uI(`${q}${U}`))return{path:`${q}${U}`}}let z=[u6(Q8,`${I}.ts`),u6(Q8,`${I}.js`),u6(Q8,`${I}.mjs`),u6(JO,`${I}.ts`),u6(JO,`${I}.js`),u6(JO,`${I}.mjs`)];for(let q of z)if(uI(q))return{path:q};return{}}async function Hx($){kX0();let I=yH1($??"builtin");if(I.isOfficial){let q=I.officialKind==="strict"?SX0:aU,U=I.officialKind==="strict"?"official":"builtin",Y=I.path;if(Y&&uI(Y))try{let Q=await import(yX0(Y).href),K=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof K==="function")return{name:I.officialKind??"builtin",type:U,filePath:Y,linter:uX0(K,q)}}catch{}return{name:I.officialKind??"builtin",type:U,filePath:Y,linter:q}}let z=I.path;if(!z)return console.error(`⚠️ [linter] 未找到自定义校验器 "${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:aU};try{let U=await import(yX0(z).href),Y=U.default??U.lintRule??U.linter??U.lint;if(typeof Y!=="function")return console.error(`⚠️ [linter] 自定义校验器 "${z}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:aU};return{name:$??"custom",type:"custom",filePath:z,linter:uX0(Y,aU)}}catch(q){return console.error(`⚠️ [linter] 加载自定义校验器脚本 "${z}" 失败(语法错误或依赖缺失: ${q?.message??q}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:aU}}}function uX0($,I){return async(z,q)=>{try{let U=await $(z,q);if(U&&typeof U==="object"&&typeof U.score==="number"&&Array.isArray(U.issues))return U;return console.error("⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。"),I(z,q)}catch(U){return console.error("⚠️ [linter] 自定义校验器执行异常:",U),I(z,q)}}}var Q8,SH1="official",L5,JO;var Wx=K0(()=>{Qx();Gx();Kx();Q8=u6(_H1(),".config","seal-use","linters"),L5=u6(Q8,SH1),JO=u6(process.cwd(),"linters")});async function Vx($,I,z){let q=await I.linter($,z);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:q.score,passed:q.passed,issues:q.issues,description:$.description}}async function bX0($,I,z,q){let U=q?.minScore??0,Y=q?.level??"all",J=[],Q=0;for(let V of $){let X=await Vx(V,I,z);Q+=X.score;let L=X.issues;if(Y==="error")L=X.issues.filter((O)=>O.level==="error");else if(Y==="warning")L=X.issues.filter((O)=>O.level==="warning"||O.level==="error");let D=L.every((O)=>O.level!=="error");if(q?.summary){if(L.length>0)J.push({...X,passed:D,issues:L})}else J.push({...X,passed:D,issues:L})}let K=$.length,w=K===0?100:Math.round(Q/K),G=J.filter((V)=>V.issues.length>0).length,H=K-G,W=w>=U&&J.every((V)=>V.passed);return{linter:I.name,linterType:I.type,totalRules:K,healthyCount:H,issueCount:G,overallScore:w,passed:W,issues:J}}var Zx=K0(()=>{hX0();Qx();Kx();Gx();Wx()});import{existsSync as uH1,readFileSync as xH1,writeFileSync as kH1,mkdirSync as fH1}from"node:fs";import{dirname as bH1,resolve as iX0}from"node:path";function nH1($){let I;try{I=JSON.parse($)}catch(z){throw ErroLine truncated
`,"utf8"),z}function cX0($){return $.map((I,z)=>{let q;if(typeof I.code==="number")q=`#${String(I.code).padStart(4,"0")}`;else if(typeof I.code==="string")q=I.code.startsWith("#")?I.code:`#${I.code}`;else q=`#${String(z+1).padStart(4,"0")}`;return{id:I.id,code:q,name:I.name,description:I.description,scope:I.scope,strictness:I.strictness}})}var dX0=()=>{};var K8;var sU=K0(()=>{K8=class K8 extends Error{errors;warnings;constructor($,I=[]){super([`材料包校验失败:${$.length} 个错误`,...$.map((z)=>`- ${z}`)].join(`
`));this.errors=$;this.warnings=I;this.name="MaterialPackValidationError"}}});var rX0=F((jk1,oX0)=>{oX0.exports=QO;function QO(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}QO.prototype.go=function($){if(this.pending<this.max)lX0(this,$);else this.waiting.push($)};QO.prototype.wait=function($){if(this.pending===0)$(this.error);else this.listeners.push($)};QO.prototype.hold=function(){return mX0(this)};function mX0($){$.pending+=1;var I=!1;return z;function z(U){if(I)throw Error("callback called twice");if(I=!0,$.error=$.error||U,$.pending-=1,$.waiting.length>0&&$.pending<$.max)lX0($,$.waiting.shift());else if($.pending===0){var Y=$.listeners;$.listeners=[],Y.forEach(q)}}function q(U){U($.error)}}function lX0($,I){I(mX0($))}});var sX0=F((cH1)=>{var Lx=t("fs"),Dx=t("util"),tX0=t("stream"),aX0=tX0.Readable,iH1=tX0.PassThrough,pH1=rX0(),KO=t("events").EventEmitter;cH1.BufferSlicer=$Y;cH1.FdSlicer=eU;Dx.inherits(eU,KO);function eU($){KO.call(this),this.fd=$,this.pend=new pH1,this.pend.max=1,this.refCount=0}eU.prototype.read=function($,I,z,q,U){var Y=this;Y.pend.go(function(J){Lx.read(Y.fd,$,I,z,q,function(Q,K,w){J(),U(Q,K,w)})})};eU.prototype.createReadStream=function($){return new aK(this,$)};eU.prototype.ref=function(){this.refCount+=1};eU.prototype.unref=function(){var $=this;if($.refCount-=1,$.refCount<0)throw Error("invalid unref");if($.refCount>0)return;Lx.close($.fd,I);function I(z){if(z)$.emit("error",z);else $.emit("close")}};Dx.inherits(aK,aX0);function aK($,I){I=I||{},aX0.call(this,I),this.context=$,this.context.ref(),this.start=I.start||0,this.endOffset=I.end,this.pos=this.start}aK.prototype._read=function($){var I=this,z=Math.min(I._readableState.highWaterMark,$);if(I.endOffset!=null)z=Math.min(z,I.endOffset-I.pos);if(z<=0){I.push(null),this._cleanup();return}I.context.pend.go(function(q){var U=Buffer.allocUnsafe(z);Lx.read(I.context.fd,U,0,z,I.pos,function(Y,J){if(Y)I.destroy(Y);else if(J===0)I.push(null),I._cleanup();else I.pos+=J,I.push(U.slice(0,J));q()})})};aK.prototype._destroy=function($,I){this._cleanup(),I($)};aK.prototype._cleanup=function(){if(this.context!=null)this.context.unref(),this.context=null};Dx.inherits($Y,KO);function $Y($){KO.call(this),this.refCount=0,this.buffer=$}$Y.prototype.read=function($,I,z,q,U){if(!(0<=I&&I<=$.length))throw RangeError("offset outside buffer: 0 <= "+I+" <= "+$.length);if(q<0)throw RangeError("position is negative: "+q);if(I+z>$.length)z=$.length-I;if(q+z>this.buffer.length)z=this.buffer.length-q;if(z<=0){setImmediate(function(){U(null,0)});return}this.buffer.copy($,I,q,q+z),setImmediate(function(){U(null,z)})};$Y.prototype.createReadStream=function($){$=$||{};var I=new iH1($);I.start=$.start||0,I.endOffset=$.end,I.pos=I.endOffset||this.buffer.length;var z=this.buffer.slice(I.start,I.pos),q=65536,U=0;while(!0){var Y=U+q;if(Y>=z.length){if(U<z.length)I.write(z.slice(U,z.length));break}I.write(z.slice(U,Y)),U=Y}return I.end(),I};$Y.prototype.ref=function(){this.refCount+=1};$Y.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")}});var $L0=F((Rk1,eX0)=>{var lH1=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512, Line truncated
`,"hlab.ts":`/**
* ==============================================================================
* 合思实验室 (HLab) 结构化规则校验器 (HLab Structured SOP Rule Linter)
* ==============================================================================
*
* 存放路径: ~/.config/seal-use/linters/official/hlab.ts
* 维护说明: 本文件由 seal-use 官方自动同步并保护。
* 每次运行时系统会自动重写本文件并清理 official/ 目录下的非官方文件。
* 若您需要编写企业私有规则校验器,请将自定义 .ts 文件放置在外层的用户目录:
* ~/.config/seal-use/linters/ 即可,系统将自动识别并加载。
*/
export interface RuleLintTarget {
id?: string;
code?: string;
name?: string;
description: string;
scope?: string;
strictness?: string;
}
export interface RuleLintIssue {
level: "error" | "warning";
code: string;
message: string;
snippet?: string;
suggestion?: string;
}
export interface RuleLintResult {
score: number;
passed: boolean;
issues: RuleLintIssue[];
}
export const HLAB_DISPOSAL_WORDS = [
"驳回单据",
"直接驳回",
"整单退回",
"退回单据",
"退单处理",
"进行提醒",
"请进行提醒",
"予以驳回",
"直接退回",
"无需人工关注",
"无需展示在最后的审核结论中"
];
export const HLAB_SCOPE_SKIP_WORDS = [
"若上传了",
"如上传了",
"若提供了",
"如提供了",
"附件需上传",
"上传了发票",
"提供了支付截图",
"提供了行程单",
"上传了行程单"
];
export const HLAB_RISK_SUPPRESSION_WORDS = [
"忽略行程冲突",
"忽略重复报销",
"忽略跨城一致性",
"不识别为风险",
"不作为风险事项",
"无需作为风险"
];
export const HLAB_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const HLAB_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票",
"流程"
];
export function lintRule(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const scopeText = (rule.scope || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则长度检查
if (text.length < 10) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 10 个字),无法承载 HLab 结构化规范所要求的判定逻辑",
suggestion: "请按照 HLab 工业化规范补充【检查方法】与【判定标准】"
});
} else if (text.length < 30 && !text.includes("**") && !text.includes("检查方法")) {
issues.push({
level: "warning",
code: "SHORT_DESCRIPTION",
message: "规则正文偏短且缺少结构化要素,可能缺少执行细节或证据边界",
suggestion: "建议扩充核验场景、限制标准或异常处理方式"
});
}
// 2. 结构完备性检查
const hasMethod = /\\*\\*检查方法\\*\\*|检查方法[::]/.test(text);
if (!hasMethod) {
issues.push({
level: "error",
code: "MISSING_CHECK_METHOD",
message: "规则正文缺少【检查方法】结构块,大模型难以确定数据提取来源与对齐逻辑",
suggestion: "建议在正文前部增加 **检查方法**:明确 SealAI 应读取的凭证类型、字段名称、归一化方式或前置规则依赖"
});
}
const hasStandard = /\\*\\*判定标准\\*\\*|判定标准[::]/.test(text);
if (!hasStandard) {
issues.push({
level: "error",
code: "MISSING_EVAL_STANDARD",
message: "规则正文缺少【判定标准】结构块,缺乏标准化判定边界",
suggestion: "建议在正文后部增加 **判定标准**:包含清晰的 PASS、FAIL 以及证据不足分支"
});
}
// 3. 三元闭环判定检查
const hasPass = /[-*•]?\\s*PASS[::]/i.test(text);
const hasFail = /[-*•]?\\s*FAIL[::]/i.test(text);
const hasInsufficient = /[-*•]?\\s*证据不足[::]/.test(text);
if (!hasPass || !hasFail || !hasInsufficient) {
const missing: string[] = [];
if (!hasPass) missing.push("PASS");
if (!hasFail) missing.push("FAIL");
if (!hasInsufficient) missing.push("证据不足");
issues.push({
level: "error",
code: "INCOMPLETE_TERNARY_BRANCH",
message: \`判定标准未形成三元闭环,缺少分支:\${missing.join("、")}\`,
suggestion: "HLab 规范要求必须提供完整的三元分支:- PASS(充分合规条件)、- FAIL(明确违规条件)、- 证据不足(容错与复核条件)"
});
}
// 4. 证据不足分支人工复核兜底检查
if (hasInsufficient) {
const snippet = text.split("证据不足")?.[1]?.slice(0, 100) || "";
const hasManualReview = /人工复核|人工核对|人工审核|转人工/.test(snippet);
if (!hasManualReview) {
issues.push({
level: "warning",
code: "INSUFFICIENT_WITHOUT_MANUAL_REVIEW",
message: "【证据不足】分支未明确指定转【人工复核】兜底,大模型在材料模糊或冲突时可能失控",
suggestion: "建议在【证据不足】分支末尾补充标准处置话术:'转人工复核',确保容错降级路径统一"
});
}
}
// 5. 整单处置动作越界拦截
for (const word of HLAB_DISPOSAL_WORDS) {
if (text.includes(word)) {
issues.push({
level: "warning",
code: "DISPOSAL_ACTION_LEAK",
snippet: word,
message: \`规则正文包含整单处置动作话术 "\${word}",违反 HLab 规则事实判定与处置动作解耦规范\`,
suggestion: \`请移除正文中的 "\${word}";单据处置动作(驳回/提醒)应交由平台严格程度(必须遵守/仅建议)或业务工作流定义\`
});
break;
}
}
// 6. 适用场景防静默漏判检查
if (scopeText) {
for (const word of HLAB_SCOPE_SKIP_WORDS) {
if (scopeText.includes(word)) {
issues.push({
level: "warning",
code: "SCOPE_FALSE_SKIP_PRONE",
snippet: word,
message: \`适用场景包含材料上传前置判断 "\${word}",当材料未上传时可能导致该规则被静默跳过(SKIP)而非报违规(FAIL)\`,
suggestion: "建议适用场景仅保留业务与单据触发条件(如单据模板、费用类型);材料缺失的检查应显式置于【判定标准】的 FAIL 分支中"
});
break;
}
}
}
// 7. 消极风险压制拦截
for (const word of HLAB_RISK_SUPPRESSION_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "RISK_SUPPRESSION",
snippet: word,
message: \`规则正文包含消极风险压制话术 "\${word}",可能破坏模型正常审计底线或压制有效违规\`,
suggestion: "请移除该规则或改写为正向合规要求;若需豁免特定场景,请在 **例外** 结构块中封闭说明豁免条件与凭证依据"
});
break;
}
}
// 8. 悬空例外与凭据检查
const matchedTrigger = HLAB_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = HLAB_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "error",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: \`包含例外条款 "\${matchedTrigger}",但未指定 AI 从何处核验该例外成立的凭据来源\`,
suggestion: "HLab 规范要求例外条款必须明确凭据载体(如:在【**例外**】块中注明需提供专项 OA 审批 PDF 附件或商家盖章证明)"
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 25 - warningCount * 10);
return {
score,
passed: errorCount === 0,
issues
};
}
export default lintRule;
`}});import{existsSync as $Y,mkdirSync as tj1,readFileSync as aj1,readdirSync as uP0,rmSync as ej1,unlinkSync as $_1,writeFileSync as q_1}from"node:fs";import{homedir as Y_1}from"node:os";import{isAbsolute as z_1,join as R6,resolve as U_1}from"node:path";import{pathToFileURL as xP0}from"node:url";function fP0($=i$){let q=[],Y=[];try{if(!$Y($))tj1($,{recursive:!0});let z=Object.keys(oi);for(let[I,J]of Object.entries(oi)){let Q=R6($,I),K=!0;if($Y(Q))try{if(aj1(Q,"utf8")===J)K=!1}catch{K=!0}if(K)q_1(Q,J,"utf8");q.push(I)}let U=uP0($,{withFileTypes:!0});for(let I of U)if(!z.includes(I.name)){let J=R6($,I.name);try{if(I.isDirectory())ej1(J,{recursive:!0,force:!0});else $_1(J);Y.push(I.name)}catch{}}}catch{}return{synced:q,pruned:Y}}function bP0($={syncOfficial:!0}){if($.syncOfficial!==!1)fP0();let q=[{name:"builtin",type:"builtin",path:R6(i$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:R6(i$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:R6(i$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],Y=[b$,OD];for(let z of Y)if($Y(z))try{let U=uP0(z,{withFileTypes:!0});for(let I of U){if(I.isDirectory())continue;let J=I.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let Q=J.replace(/\.(ts|js|mjs)$/,"");if(!q.some((K)=>K.name===Q))q.push({name:Q,type:"custom",path:R6(z,J),description:`用户自定义规则校验器 (${J})`})}}}catch{}return q}function J_1($){let q=($||"").trim();if(!q||q==="builtin"||q==="default"||q==="official/builtin"||q==="official/builtin.ts")return{path:R6(i$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(q==="strict"||q==="official/strict"||q==="official/strict.ts")return{path:R6(i$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(q==="hlab"||q==="hlab-sop"||q==="hlab-rules"||q==="hlab-standard"||q==="official/hlab"||q==="official/hlab.ts")return{path:R6(i$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(z_1(q)||q.startsWith("./")||q.startsWith("../")){let z=U_1(q);if($Y(z))return{path:z};for(let U of[".ts",".js",".mjs"])if($Y(`${z}${U}`))return{path:`${z}${U}`}}let Y=[R6(b$,`${q}.ts`),R6(b$,`${q}.js`),R6(b$,`${q}.mjs`),R6(OD,`${q}.ts`),R6(OD,`${q}.js`),R6(OD,`${q}.mjs`)];for(let z of Y)if($Y(z))return{path:z};return{}}async function si($){fP0();let q=J_1($??"builtin");if(q.isOfficial){let z=q.officialKind==="strict"?SP0:q.officialKind==="hlab"?yP0:cI,U=q.officialKind==="builtin"?"builtin":"official",I=q.path;if(I&&$Y(I))try{let Q=await import(xP0(I).href),K=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof K==="function")return{name:q.officialKind??"builtin",type:U,filePath:I,linter:kP0(K,z)}}catch{}return{name:q.officialKind??"builtin",type:U,filePath:I,linter:z}}let Y=q.path;if(!Y)return console.error(`⚠️ [linter] 未找到自定义校验器 "${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cI};try{let U=await import(xP0(Y).href),I=U.default??U.lintRule??U.linter??U.lint;if(typeof I!=="function")return console.error(`⚠️ [linter] 自定义校验器 "${Y}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cI};return{name:$??"custom",type:"custom",filePath:Y,linter:kP0(I,cI)}}catch(z){return console.error(`⚠️ [linter] 加载自定义校验器脚本 "${Y}" 失败(语法错误或依赖缺失: ${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cI}}}function kP0($,q){return async(Y,z)=>{try{let U=await $(Y,z);if(U&&typeof U==="object"&&typeof U.score==="number"&&Array.isArray(U.issues))return U;return console.error("⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。"),q(Y,z)}catch(U){return console.error("⚠️ [linter] 自定义校验器执行异常:",U),q(Y,z)}}}var b$,I_1="official",i$,OD;var ti=e(()=>{di();li();ri();mi();b$=R6(Y_1(),".config","seal-use","linters"),i$=R6(b$,I_1),OD=R6(process.cwd(),"linters")});async function ai($,q,Y){let z=await q.linter($,Y);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}async function iP0($,q,Y,z){let U=z?.minScore??0,I=z?.level??"all",J=[],Q=0;for(let X of $){let w=await ai(X,q,Y);Q+=w.score;let L=w.issues;if(I==="error")L=w.issues.filter((O)=>O.level==="error");else if(I==="warning")L=w.issues.filter((O)=>O.level==="warning"||O.level==="error");let F=L.every((O)=>O.level!=="error");if(z?.summary){if(L.length>0)J.push({...w,passed:F,issues:L})}else J.push({...w,passed:F,issues:L})}let K=$.length,H=K===0?100:Math.round(Q/K),G=J.filter((X)=>X.issues.length>0).length,Z=K-Line truncated
`,"utf8"),Y}function dP0($){return $.map((q,Y)=>{let z;if(typeof q.code==="number")z=`#${String(q.code).padStart(4,"0")}`;else if(typeof q.code==="string")z=q.code.startsWith("#")?q.code:`#${q.code}`;else z=`#${String(Y+1).padStart(4,"0")}`;return{id:q.id,code:z,name:q.name,description:q.description,scope:q.scope,strictness:q.strictness}})}var mP0=()=>{};var lP0,M5;var pI=e(()=>{lP0=class lP0 extends Error{errors;warnings;constructor($,q=[]){super([`webhook 资源包校验失败:${$.length} 个错误`,...$.map((Y)=>`- ${Y}`)].join(`
`));this.errors=$;this.warnings=q;this.name="ResourcePackValidationError"}};M5=lP0});var tP0=M((Kq4,sP0)=>{sP0.exports=MD;function MD(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}MD.prototype.go=function($){if(this.pending<this.max)rP0(this,$);else this.waiting.push($)};MD.prototype.wait=function($){if(this.pending===0)$(this.error);else this.listeners.push($)};MD.prototype.hold=function(){return oP0(this)};function oP0($){$.pending+=1;var q=!1;return Y;function Y(U){if(q)throw Error("callback called twice");if(q=!0,$.error=$.error||U,$.pending-=1,$.waiting.length>0&&$.pending<$.max)rP0($,$.waiting.shift());else if($.pending===0){var I=$.listeners;$.listeners=[],I.forEach(z)}}function z(U){U($.error)}}function rP0($,q){q(oP0($))}});var $B0=M((w_1)=>{var qn=m("fs"),Yn=m("util"),aP0=m("stream"),eP0=aP0.Readable,X_1=aP0.PassThrough,V_1=tP0(),ND=m("events").EventEmitter;w_1.BufferSlicer=mI;w_1.FdSlicer=dI;Yn.inherits(dI,ND);function dI($){ND.call(this),this.fd=$,this.pend=new V_1,this.pend.max=1,this.refCount=0}dI.prototype.read=function($,q,Y,z,U){var I=this;I.pend.go(function(J){qn.read(I.fd,$,q,Y,z,function(Q,K,H){J(),U(Q,K,H)})})};dI.prototype.createReadStream=function($){return new AZ(this,$)};dI.prototype.ref=function(){this.refCount+=1};dI.prototype.unref=function(){var $=this;if($.refCount-=1,$.refCount<0)throw Error("invalid unref");if($.refCount>0)return;qn.close($.fd,q);function q(Y){if(Y)$.emit("error",Y);else $.emit("close")}};Yn.inherits(AZ,eP0);function AZ($,q){q=q||{},eP0.call(this,q),this.context=$,this.context.ref(),this.start=q.start||0,this.endOffset=q.end,this.pos=this.start}AZ.prototype._read=function($){var q=this,Y=Math.min(q._readableState.highWaterMark,$);if(q.endOffset!=null)Y=Math.min(Y,q.endOffset-q.pos);if(Y<=0){q.push(null),this._cleanup();return}q.context.pend.go(function(z){var U=Buffer.allocUnsafe(Y);qn.read(q.context.fd,U,0,Y,q.pos,function(I,J){if(I)q.destroy(I);else if(J===0)q.push(null),q._cleanup();else q.pos+=J,q.push(U.slice(0,J));z()})})};AZ.prototype._destroy=function($,q){this._cleanup(),q($)};AZ.prototype._cleanup=function(){if(this.context!=null)this.context.unref(),this.context=null};Yn.inherits(mI,ND);function mI($){ND.call(this),this.refCount=0,this.buffer=$}mI.prototype.read=function($,q,Y,z,U){if(!(0<=q&&q<=$.length))throw RangeError("offset outside buffer: 0 <= "+q+" <= "+$.length);if(z<0)throw RangeError("position is negative: "+z);if(q+Y>$.length)Y=$.length-q;if(z+Y>this.buffer.length)Y=this.buffer.length-z;if(Y<=0){setImmediate(function(){U(null,0)});return}this.buffer.copy($,q,z,z+Y),setImmediate(function(){U(null,Y)})};mI.prototype.createReadStream=function($){$=$||{};var q=new X_1($);q.start=$.start||0,q.endOffset=$.end,q.pos=q.endOffset||this.buffer.length;var Y=this.buffer.slice(q.start,q.pos),z=65536,U=0;while(!0){var I=U+z;if(I>=Y.length){if(U<Y.length)q.write(Y.slice(U,Y.length));break}q.write(Y.slice(U,I)),U=I}return q.end(),q};mI.prototype.ref=function(){this.refCount+=1};mI.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")}});var YB0=M((Gq4,qB0)=>{var O_1=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090 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 CL0=F((dW1)=>{var ex=W9().Buffer;dW1._dbcs=Z9;var T6=-1,_L0=-2,H8=-10,a6=-1000,QY=Array(256),$w=-1;for(eK=0;eK<256;eK++)QY[eK]=T6;var eK;function Z9($,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 z=$.table();this.decodeTables=[],this.decodeTables[0]=QY.slice(0),this.decodeTableSeq=[];for(var q=0;q<z.length;q++)this._addDecodeChunk(z[q]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var U=this.decodeTables.length;this.decodeTables.push(QY.slice(0));var Y=this.decodeTables.length;this.decodeTables.push(QY.slice(0));var J=this.decodeTables[0];for(var q=129;q<=254;q++){var Q=this.decodeTables[a6-J[q]];for(var K=48;K<=57;K++){if(Q[K]===T6)Q[K]=a6-U;else if(Q[K]>a6)throw Error("gb18030 decode tables conflict at byte 2");var w=this.decodeTables[a6-Q[K]];for(var G=129;G<=254;G++){if(w[G]===T6)w[G]=a6-Y;else if(w[G]===a6-Y)continue;else if(w[G]>a6)throw Error("gb18030 decode tables conflict at byte 3");var H=this.decodeTables[a6-w[G]];for(var W=48;W<=57;W++)if(H[W]===T6)H[W]=_L0}}}}this.defaultCharUnicode=I.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var V={};if($.encodeSkipVals)for(var q=0;q<$.encodeSkipVals.length;q++){var X=$.encodeSkipVals[q];if(typeof X==="number")V[X]=!0;else for(var K=X.from;K<=X.to;K++)V[K]=!0}if(this._fillEncodeTable(0,0,V),$.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===T6)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===T6)this.defCharSB=63}Z9.prototype.encoder=MO;Z9.prototype.decoder=$k;Z9.prototype._getDecodeTrieNode=function($){var I=[];for(;$>0;$>>>=8)I.push($&255);if(I.length==0)I.push(0);var z=this.decodeTables[0];for(var q=I.length-1;q>0;q--){var U=z[I[q]];if(U==T6)z[I[q]]=a6-this.decodeTables.length,this.decodeTables.push(z=QY.slice(0));else if(U<=a6)z=this.decodeTables[a6-U];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return z};Z9.prototype._addDecodeChunk=function($){var I=parseInt($[0],16),z=this._getDecodeTrieNode(I);I=I&255;for(var q=1;q<$.length;q++){var U=$[q];if(typeof U==="string")for(var Y=0;Y<U.length;){var J=U.charCodeAt(Y++);if(J>=55296&&J<56320){var Q=U.charCodeAt(Y++);if(Q>=56320&&Q<57344)z[I++]=65536+(J-55296)*1024+(Q-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(J>4080&&J<=4095){var K=4095-J+2,w=[];for(var G=0;G<K;G++)w.push(U.charCodeAt(Y++));z[I++]=H8-this.decodeTableSeq.length,this.decodeTableSeq.push(w)}else z[I++]=J}else if(typeof U==="number"){var H=z[I-1]+1;for(var Y=0;Y<U;Y++)z[I++]=H++}else throw Error("Incorrect type '"+typeof U+"' given in "+this.encodingName+" at chunk "+$[0])}if(I>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`);let O=new FormData,A=await Jk(q.fileBuffer,D),T=L.split("/").pop()??L;O.append("files",new File([new Uint8Array(A)],T));let M=await fetch(`${U}/api/v1/integrations/webhook/${encodeURIComponent(Y)}/attachments`,{method:"POST",headers:{...z.customHeaders??{},...rK({},z.secret)},body:O});if(!M.ok)throw Error(`附件上传失败 ${M.status}: ${await M.text()}`);let v=await M.json();G.set(L,v.attachments?.map((x)=>x.data)??(v.data===void 0?[]:[v.data])),process.stderr.write(`✓ 附件上传成功: ${L}
\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 SB0=M((LC1)=>{var un=H3().Buffer;LC1._dbcs=Z3;var a6=-1,gB0=-2,p$=-10,j8=-1000,eI=Array(256),TZ=-1;for(BZ=0;BZ<256;BZ++)eI[BZ]=a6;var BZ;function Z3($,q){if(this.encodingName=$.encodingName,!$)throw Error("DBCS codec is called without the data.");if(!$.table)throw Error("Encoding '"+this.encodingName+"' has no data.");var Y=$.table();this.decodeTables=[],this.decodeTables[0]=eI.slice(0),this.decodeTableSeq=[];for(var z=0;z<Y.length;z++)this._addDecodeChunk(Y[z]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var U=this.decodeTables.length;this.decodeTables.push(eI.slice(0));var I=this.decodeTables.length;this.decodeTables.push(eI.slice(0));var J=this.decodeTables[0];for(var z=129;z<=254;z++){var Q=this.decodeTables[j8-J[z]];for(var K=48;K<=57;K++){if(Q[K]===a6)Q[K]=j8-U;else if(Q[K]>j8)throw Error("gb18030 decode tables conflict at byte 2");var H=this.decodeTables[j8-Q[K]];for(var G=129;G<=254;G++){if(H[G]===a6)H[G]=j8-I;else if(H[G]===j8-I)continue;else if(H[G]>j8)throw Error("gb18030 decode tables conflict at byte 3");var Z=this.decodeTables[j8-H[G]];for(var V=48;V<=57;V++)if(Z[V]===a6)Z[V]=gB0}}}}this.defaultCharUnicode=q.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var X={};if($.encodeSkipVals)for(var z=0;z<$.encodeSkipVals.length;z++){var w=$.encodeSkipVals[z];if(typeof w==="number")X[w]=!0;else for(var K=w.from;K<=w.to;K++)X[K]=!0}if(this._fillEncodeTable(0,0,X),$.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][q.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===a6)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===a6)this.defCharSB=63}Z3.prototype.encoder=gD;Z3.prototype.decoder=fn;Z3.prototype._getDecodeTrieNode=function($){var q=[];for(;$>0;$>>>=8)q.push($&255);if(q.length==0)q.push(0);var Y=this.decodeTables[0];for(var z=q.length-1;z>0;z--){var U=Y[q[z]];if(U==a6)Y[q[z]]=j8-this.decodeTables.length,this.decodeTables.push(Y=eI.slice(0));else if(U<=j8)Y=this.decodeTables[j8-U];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return Y};Z3.prototype._addDecodeChunk=function($){var q=parseInt($[0],16),Y=this._getDecodeTrieNode(q);q=q&255;for(var z=1;z<$.length;z++){var U=$[z];if(typeof U==="string")for(var I=0;I<U.length;){var J=U.charCodeAt(I++);if(J>=55296&&J<56320){var Q=U.charCodeAt(I++);if(Q>=56320&&Q<57344)Y[q++]=65536+(J-55296)*1024+(Q-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(J>4080&&J<=4095){var K=4095-J+2,H=[];for(var G=0;G<K;G++)H.push(U.charCodeAt(I++));Y[q++]=p$-this.decodeTableSeq.length,this.decodeTableSeq.push(H)}else Y[q++]=J}else if(typeof U==="number"){var Z=Y[q-1]+1;for(var I=0;I<U;I++)Y[q++]=Z++}else throw Error("Incorrect type '"+typeof U+"' given in "+this.encodingName+" at chunk "+$[0])}if(q>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`;super(q);this.name="AggregateError",this.errors=$}}cT0.exports={AggregateError:nT0,ArrayIsArray($){return Array.isArray($)},ArrayPrototypeIncludes($,q){return $.includes(q)},ArrayPrototypeIndexOf($,q){return $.indexOf(q)},ArrayPrototypeJoin($,q){return $.join(q)},ArrayPrototypeMap($,q){return $.map(q)},ArrayPrototypePop($,q){return $.pop(q)},ArrayPrototypePush($,q){return $.push(q)},ArrayPrototypeSlice($,q,Y){return $.slice(q,Y)},Error,FunctionPrototypeCall($,q,...Y){return $.call(q,...Y)},FunctionPrototypeSymbolHasInstance($,q){return Function.prototype[Symbol.hasInstance].call($,q)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties($,q){return Object.defineProperties($,q)},ObjectDefineProperty($,q,Y){return Object.defineProperty($,q,Y)},ObjectGetOwnPropertyDescriptor($,q){return Object.getOwnPropertyDescriptor($,q)},ObjectKeys($){return Object.keys($)},ObjectSetPrototypeOf($,q){return Object.setPrototypeOf($,q)},Promise,PromisePrototypeCatch($,q){return $.catch(q)},PromisePrototypeThen($,q,Y){return $.then(q,Y)},PromiseReject($){return Promise.reject($)},PromiseResolve($){return Promise.resolve($)},ReflectApply:Reflect.apply,RegExpPrototypeTest($,q){return $.test(q)},SafeSet:Set,String,StringPrototypeSlice($,q,Y){return $.slice(q,Y)},StringPrototypeToLowerCase($){return $.toLowerCase()},StringPrototypeToUpperCase($){return $.toUpperCase()},StringPrototypeTrim($){return $.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet($,q,Y){return $.set(q,Y)},Boolean,Uint8Array}});var Hc=M((VY4,pT0)=>{pT0.exports={format($,...q){return $.replace(/%([sdifj])/g,function(...[Y,z]){let U=q.shift();if(z==="f")return U.toFixed(6);else if(z==="j")return JSON.stringify(U);else if(z==="s"&&typeof U==="object")return`${U.constructor!==Object?U.constructor.name:""} {}`.trim();else return U.toString()})},inspect($){switch(typeof $){case"string":if($.includes("'")){if(!$.includes('"'))return`"${$}"`;else if(!$.includes("`")&&!$.includes("${"))return`\`${$}\``}return`'${$}'`;case"number":if(isNaN($))return"NaN";else if(Object.is($,-0))return String($);return $;case"bigint":return`${String($)}n`;case"boolean":case"undefined":return String($);case"object":return"{}"}}}});var Z8=M((wY4,oT0)=>{var{format:Hv1,inspect:fD}=Hc(),{AggregateError:Gv1}=h4(),Zv1=globalThis.AggregateError||Gv1,Wv1=Symbol("kIsNodeError"),Xv1=["string","function","number","object","Function","Object","boolean","bigint","symbol"],Vv1=/^([A-Z][a-z0-9]*)+$/,bD={};function zY($,q){if(!$)throw new bD.ERR_INTERNAL_ASSERTION(q)}function dT0($){let q="",Y=$.length,z=$[0]==="-"?1:0;for(;Y>=z+4;Y-=3)q=`_${$.slice(Y-3,Y)}${q}`;return`${$.slice(0,Y)}${q}`}function wv1($,q,Y){if(typeof q==="function")return zY(q.length<=Y.length,`Code: ${$}; The provided arguments length (${Y.length}) does not match the required ones (${q.length}).`),q(...Y);let z=(q.match(/%[dfijoOs]/g)||[]).length;if(zY(z===Y.length,`Code: ${$}; The provided arguments length (${Y.length}) does not match the required ones (${z}).`),Y.length===0)return q;return Hv1(q,...Y)}function e6($,q,Y){if(!Y)Y=Error;class z extends Y{constructor(...U){super(wv1($,q,U))}toString(){return`${this.name} [${$}]: ${this.message}`}}Object.defineProperties(z.prototype,{name:{value:Y.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${$}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),z.prototype.code=$,z.prototype[Wv1]=!0,bD[$]=z}function mT0($){let q="__node_internal_"+$.name;return Object.defineProperty($,"name",{value:q}),$}function Lv1($,q){if($&&q&&$!==q){if(Array.isArray(q.errors))return q.errors.push($),q;let Y=new Zv1([q,$],q.message);return Y.code=q.code,Y}return $||q}class lT0 extends Error{constructor($="The operation was aborted",q=void 0){if(q!==void 0&&typeof q!=="object")throw new bD.ERR_INVALID_ARG_TYPE("options","Object",q);super($,q);this.code="ABORT_ERR",this.name="AbortError"}}e6("ERR_ASSERTION","%s",Error);e6("ERR_INVALID_ARG_TYPE",($,q,Y)=>{if(zY(typeof $==="string","'name' must be a string"),!Array.isArray(q))q=[q];let z="The ";if($.endsWith(" argument"))z+=`${$} `;else z+=`"${$}" ${$.includes(".")?"property":"argument"} `;z+="must be ";let U=[],I=[],J=[];for(let K of q)if(zY(typeof K==="string","All expected entries have to be of type string"),Xv1.includes(K))U.push(K.toLowerCase());else if(Vv1.test(K))I.push(K);else zY(K!=="object",'The value "object" should be written as "Object"'),J.push(K);if(I.length>0){let K=U.indexOf("object");if(K!==-1)U.splice(U,K,1),I.push("Object")}if(U.length>0){switch(U.length){case 1:z+=`of type ${U[Line truncated
`);if(q.linkname)Y+=fp(" linkpath="+q.linkname+`
`);let z=q.pax;if(z)for(let U in z)Y+=fp(" "+U+"="+z[U]+`
`);return C1.from(Y)};Xu1.decodePax=function(q){let Y={};while(q.length){let z=0;while(z<q.length&&q[z]!==32)z++;let U=parseInt(C1.toString(q.subarray(0,z)),10);if(!U)return Y;let I=C1.toString(q.subarray(z+1,U-1)),J=I.indexOf("=");if(J===-1)return Y;Y[I.slice(0,J)]=I.slice(J+1),q=q.subarray(U)}return Y};Xu1.encode=function(q){let Y=C1.alloc(512),z=q.name,U="";if(q.typeflag===5&&z[z.length-1]!=="/")z+="/";if(C1.byteLength(z)!==z.length)return null;while(C1.byteLength(z)>100){let I=z.indexOf("/");if(I===-1)return null;U+=U?"/"+z.slice(0,I):z.slice(0,I),z=z.slice(I+1)}if(C1.byteLength(z)>100||C1.byteLength(U)>155)return null;if(q.linkname&&C1.byteLength(q.linkname)>100)return null;if(C1.write(Y,z),C1.write(Y,Q2(q.mode&4095,6),100),C1.write(Y,Q2(q.uid,6),108),C1.write(Y,Q2(q.gid,6),116),Zu1(q.size,Y,124),C1.write(Y,Q2(q.mtime.getTime()/1000|0,11),136),Y[156]=48+Hu1(q.type),q.linkname)C1.write(Y,q.linkname,157);if(C1.copy(OR0,Y,257),C1.copy(Yu1,Y,263),q.uname)C1.write(Y,q.uname,265);if(q.gname)C1.write(Y,q.gname,297);if(C1.write(Y,Q2(q.devmajor||0,6),329),C1.write(Y,Q2(q.devminor||0,6),337),U)C1.write(Y,U,345);return C1.write(Y,Q2(NR0(Y),6),148),Y};Xu1.decode=function(q,Y,z){let U=q[156]===0?0:q[156]-48,I=MJ(q,0,100,Y),J=J2(q,100,8),Q=J2(q,108,8),K=J2(q,116,8),H=J2(q,124,12),G=J2(q,136,12),Z=Ku1(U),V=q[157]===0?null:MJ(q,157,100,Y),X=MJ(q,265,32),w=MJ(q,297,32),L=J2(q,329,8),F=J2(q,337,8),O=NR0(q);if(O===256)return null;if(O!==J2(q,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(Iu1(q)){if(q[345])I=MJ(q,345,155,Y)+"/"+I}else if(Ju1(q));else if(!z)throw Error("Invalid tar header: unknown format.");if(U===0&&I&&I[I.length-1]==="/")U=5;return{name:I,mode:J,uid:Q,gid:K,size:H,byteOffset:0,mtime:new Date(1000*G),type:Z,linkname:V,uname:X,gname:w,devmajor:L,devminor:F,pax:null}};function Iu1($){return C1.equals(OR0,$.subarray(257,263))}function Ju1($){return C1.equals(zu1,$.subarray(257,263))&&C1.equals(Uu1,$.subarray(263,265))}function Qu1($,q,Y){if(typeof $!=="number")return Y;if($=~~$,$>=q)return q;if($>=0)return $;if($+=q,$>=0)return $;return 0}function Ku1($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function Hu1($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function MR0($,q,Y,z){for(;Y<z;Y++)if($[Y]===q)return Y;return z}function NR0($){let q=256;for(let Y=0;Y<148;Y++)q+=$[Y];for(let Y=156;Y<512;Y++)q+=$[Y];return q}function Q2($,q){if($=$.toString(8),$.length>q)return"7777777777777777777".slice(0,q)+" ";return"0000000000000000000".slice(0,q-$.length)+$+" "}function Gu1($,q,Y){q[Y]=128;for(let z=11;z>0;z--)q[Y+z]=$&255,$=Math.floor($/256)}function Zu1($,q,Y){if($.toString(8).length>11)Gu1($,q,Y);else C1.write(q,Q2($,11),Y)}function Wu1($){let q;if($[0]===128)q=!0;else if($[0]===255)q=!1;else return null;let Y=[],z;for(z=$.length-1;z>0;z--){let J=$[z];if(q)Y.push(J);else Y.push(255-J)}let U=0,I=Y.length;for(z=0;z<I;z++)U+=Y[z]*Math.pow(256,z);return q?U:-1*U}function J2($,q,Y){if($=$.subarray(q,q+Y),q=0,$[q]&128)return Wu1($);else{while(q<$.length&&$[q]===32)q++;let z=Qu1(MR0($,32,q,$.length),$.length,$.length);while(q<z&&$[q]===0)q++;if(z===q)return 0;return parseInt(C1.toString($.subarray(q,z)),8)}}function MJ($,q,Y,z){return C1.toString($.subarray(q,MR0($,0,q,q+Y)),z)}function fp($){let q=C1.byteLength($),Y=Math.floor(Math.log(q)/Math.log(10))+1;if(q+Y>=Math.pow(10,Y))Y++;return q+Y+$}});var _R0=M((IU4,jR0)=>{var{Writable:Mu1,Readable:Nu1,getStreamError:DR0}=up(),Du1=Rp(),AR0=OJ(),NJ=bp(),Au1=AR0.alloc(0);class PR0{constructor(){this.buffered=0,this.shifted=0,this.queue=new Du1,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this.buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return Au1;let q=this._next($);if($===q.byteLength)return q;let Y=[q];while(($-=q.byteLength)>0)q=this._next($),Y.push(q);return AR0.concat(Y)}_next($){let q=this.queue.peek(),Y=q.byteLength-this._offset;if($>=Y){let z=this._offset?q.subarray(this._offset,q.byteLength):q;return this.queue.shift(),this._offset=0,this.buffered-=Y,this.shifted+=Y,z}return this.buffered-=$,this.shifted+=$,q.subarray(this._offset,this._offset+=$)}}class BR0 extends Nu1{constructor($,q,Y){super();this.header=q,this.offset=Y,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(DR0(this))}_detach(){if(this._parent._stream= Line truncated
`),z=[await e1($,Y.recordId)];else if(Y.recordIds&&Y.recordIds.length>0)process.stderr.write(`\uD83D\uDD0D 批量查询 ${Y.recordIds.length} 条单据记录...
`),z=await Promise.all(Y.recordIds.map((O)=>e1($,O)));else{let O=Y.limit??10;process.stderr.write(`\uD83D\uDD0D 检索企业「${q.name}」(${q.id}) 的线上审核记录 (限制 ${O} 条)...
`);let B=(await y4($,{limit:O,status:Y.status,startDate:Y.startDate!==void 0?String(Y.startDate):void 0,endDate:Y.endDate!==void 0?String(Y.endDate):void 0})).records??[];if(B.length===0)throw Error("未检索到符合条件的线上审核记录,无法导出 webhook 资源包。");process.stderr.write(`\uD83D\uDCE5 正在拉取 ${B.length} 条审核记录完整详情...
`),z=await Promise.all(B.map((P)=>e1($,P.id)))}let U=new Map,I=0;for(let O of z){let A=O.document,B=O.sourceDocumentId??(typeof A?.id==="string"?A.id:void 0)??(typeof A?.sourceDocumentId==="string"?A.sourceDocumentId:void 0)??O.documentId??O.id,P=`${Y.docIdPrefix??""}${B}${Y.docIdSuffix??""}`,T=[];if(Y.includeAttachments!==!1){let v=t7(O,{summary:!1}).attachments,k=new Set;for(let R of v){let c=R.ossSignedUrl??R.url;if(!c)continue;let n=R.fileName??R.fileId??"attachment",g=Ri(n),b=g,i=g.lastIndexOf("."),$0=i>0?g.slice(0,i):g,j=i>0?g.slice(i):"",u=1;while(k.has(b.toLowerCase()))b=`${$0}_${u}${j}`,u++;k.add(b.toLowerCase());try{process.stderr.write(`⬇ 下载单据「${P}」附件: ${n}...
`);let p=await fetch(c);if(p.ok){let d=await p.arrayBuffer(),Y0=Buffer.from(d);T.push({fileName:b,zipPath:`${P}/${b}`,buffer:Y0,sourceField:R.sourceField??"附件"}),I++}}catch(p){process.stderr.write(`⚠️ [跳过附件] 下载失败 ${n}: ${p}
`)}}}U.set(P,T)}let J=new mR0.default.Workbook;J.creator="seal-use",J.created=new Date;let Q=new Set;for(let O of U.values())for(let A of O)Q.add(A.sourceField);if(Q.size===0)Q.add("附件");let K=new Set;for(let O of z){let A=O.document,B=Array.isArray(A?.fields)?A.fields:[];for(let P of B)if(P&&typeof P==="object"){let T=P,y=typeof T.label==="string"?T.label.trim():typeof T.key==="string"?T.key.trim():"",v=typeof T.type==="string"?T.type.toUpperCase():"";if(y&&v!=="ATTACHMENT"&&v!=="LIST")K.add(y)}}let H=["会议编号","会议名称","状态","总金额","报销事由","申请日期"],G=Array.from(K).filter((O)=>!H.includes(O)&&O!=="单据编号"&&O!=="单号"),Z=Array.from(Q).map((O)=>`[附件]${O}`),V=[...H,...G,...Z],X=J.addWorksheet("主表");X.addRow(V),X.getRow(1).font={bold:!0};for(let O of z){let A=O.document,B=O.sourceDocumentSN??(typeof A?.sn==="string"?A.sn:void 0)??(typeof A?.sourceDocumentSN==="string"?A.sourceDocumentSN:void 0)??O.id,P=O.sourceDocumentId??(typeof A?.id==="string"?A.id:void 0)??(typeof A?.sourceDocumentId==="string"?A.sourceDocumentId:void 0)??O.documentId??O.id,T=`${Y.docIdPrefix??""}${P}${Y.docIdSuffix??""}`,y=`${Y.docIdPrefix??""}${B}${Y.docIdSuffix??""}`,v=(typeof A?.title==="string"?A.title:void 0)??(typeof A?.name==="string"?A.name:void 0)??y,k="";if(typeof A?.sourceStartTime==="number")k=new Date(A.sourceStartTime*1000).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof O.createdAt==="number")k=new Date(O.createdAt).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof O.createdAt==="string")k=O.createdAt.slice(0,10);let R=new Map,c=Array.isArray(A?.fields)?A.fields:[];for(let $0 of c)if($0&&typeof $0==="object"){let j=$0,u=typeof j.label==="string"?j.label.trim():typeof j.key==="string"?j.key.trim():"";if(u)R.set(u,j.value)}let n,g=R.get("总金额")??R.get("报销金额")??R.get("total_amount");if(typeof g==="number")n=g;else if(g&&typeof g==="object"&&"amount"in g&&typeof g.amount==="number")n=g.amount;let b=[];b.push(T),b.push(v),b.push(O.status??"已审批"),b.push(n??""),b.push(R.get("报销事由")??R.get("事由")??v),b.push(k);for(let $0 of G){let j=R.get($0);if(j===void 0||j===null)b.push("");else if(typeof j==="object")if("amount"in j)b.push(j.amount);else b.push(JSON.stringify(j));else b.push(j)}let i=U.get(T)??[];for(let $0 of Q){let j=i.filter((u)=>u.sourceField===$0||Q.size===1);if(j.length>0)b.push(j.map((u)=>u.zipPath).join(`
`));else b.push("")}X.addRow(b)}let w=iu1(Y,q);xu1(fu1(w),{recursive:!0});let L=await J.xlsx.writeBuffer();process.stderr.write(`\uD83D\uDCE6 正在压缩生成 Webhook 资源包: ${w}...
`),await new Promise((O,A)=>{let B=yu1(w),P=new dp({zlib:{level:9}});B.on("close",()=>O()),P.on("error",(T)=>A(T)),P.pipe(B),P.append(Buffer.from(L),{name:"信息表.xlsx"});for(let T of U.values())for(let y of T)P.append(y.buffer,{name:y.zipPath});P.finalize()});let F=ku1(w);return{filePath:w,corpId:q.id,corpName:q.name,recordCount:z.length,attachmentCount:I,fileSizeBytes:F.size,exportedAt:new Date().toISOString(),nextAction:`seal-use webhook resource-pack push ${w} --corp <targetCorpId>`}}var mR0;var mp=e(()=>{pR0();J6();JD();mR0=S4(FZ(),1)});import{readFileSync as nu1}from"node:fs";function cu1($){let q=new URL($),Y=q.pathname.match(/\/webhook\/([^/]+)/);if(!Y)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${q.protocol}//${q.host}`,webhookId:Y[1]}}function pu1($,q){return q.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!q.toLowerCase().endsWith(".xlsx")}function du1($,q){if(!$.length)return;let Y=new Set($.map((I)=>{let J=I.fileName.split("/")[0],Q=J.indexOf("@");return Q>=0?J.slice(0,Q):J}).filter((I)=>I!=="信息表.xlsx")),z=[];for(let I of q){let J=I.document.documentId;if((I.documentAttachments.length>0||Object.values(I.expenseAttachments).some((K)=>K.length>0)||Object.values(I.personAttachments).some((K)=>K.length>0))&&!Y.has(J))z.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let U=new Set(q.map((I)=>I.document.documentId));for(let I of Y)if(!U.has(I))z.push(`ZIP 根目录对应的编号「${I}」在信息表中找不到对应的会议编号。`);if(z.length)throw new M5(z)}async function lR0($,q,Y){let z=[],U=$;if(pu1($,q)){z=await zT0($),IT0(z,Y);let K=z.find((H)=>H.fileName==="信息表.xlsx");if(!K)throw Error("ZIP 根目录缺少信息表.xlsx");U=await mn($,K)}let I=await WT0(U);du1(z,I);let J=XT0(z,I),Q=I.map((K)=>K.document);return{entries:z,parsed:I,plans:J,documents:Q,fileBuffer:$}}async function DY($,q,Y){let z=await lR0($,q,Y),U=z.parsed.map((I,J)=>an(I.document,z.plans[J],new Map));return{warnings:[],documents:U,attachmentPlan:z.plans}}async function CA($,q,Y){let z=await lR0($,q,Y.materialPackFilePolicy),{baseUrl:U,webhookId:I}=cu1(Y.webhookUrl),J=[];for(let Q=0;Q<z.parsed.length;Q+=1){let K=z.parsed[Q],H=z.plans[Q],G=new Map,Z=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let w of Z)for(let L of w.paths){if(G.has(L))continue;let F=z.entries.find((y)=>y.fileName===L);if(!F)continue;process.stderr.write(`⬆ 上传附件: ${L}
`);let O=new FormData,A=await mn(z.fileBuffer,F),B=L.split("/").pop()??L;O.append("files",new File([new Uint8Array(A)],B));let P=await fetch(`${U}/api/v1/integrations/webhook/${encodeURIComponent(I)}/attachments`,{method:"POST",headers:{...Y.customHeaders??{},...NZ({},Y.secret)},body:O});if(!P.ok)throw Error(`附件上传失败 ${P.status}: ${await P.text()}`);let T=await P.json();G.set(L,T.attachments?.map((y)=>y.data)??(T.data===void 0?[]:[T.data])),process.stderr.write(`✓ 附件上传成功: ${L}
`)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${K.document.documentId}
`);let W=Hk(K.document,w,G),V=await fetch(`${U}/api/v1/integrations/webhook/${encodeURIComponent(Y)}/document`,{method:"POST",headers:{...z.customHeaders??{},"Content-Type":"application/json",...rK({webhookId:Y,...W},z.secret)},body:JSON.stringify(W)});if(!V.ok)throw Error(`Webhook 单据推送失败 ${V.status}: ${await V.text()}`);J.push({documentId:W.documentId,document:W,pushResult:await V.json()}),process.stderr.write(`✓ 单据推送成功: ${W.documentId}
`)}return{warnings:[],results:J}}function bI($){return{fileBuffer:BV1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}var Vk=K0(()=>{zO();Wk();Gk();Qk();sU()});import{existsSync as gV1}from"node:fs";async function vO($,I,z={}){let U=K4().stateful?"stateful":"stateless",Y="ok",J,Q,K;try{let M=await v6($);K={id:M.user.id,name:M.user.name,isAdmin:M.user.isAdmin},Q={id:M.tenant.id,name:M.tenant.name,tenantSlug:M.tenant.tenantSlug,corporationName:M.tenant.hoseCorpConfig?.corporationName}}catch(M){Y="error",J=M instanceof Error?M.message:String(M)}let w=[];if(Y==="ok")try{w=await v$($,I.seal.endpoints.approvalStylePreferences)}catch(M){Y="error",J=`读取 Webhook 配置失败: ${M instanceof Error?M.message:String(M)}`}let G=w.length===1,H=w.map((M)=>({id:M.id,name:M.name,mode:M.mode,incomingDocumentWebhookUrl:M.incomingDocumentWebhook.url,outgoingResultWebhookUrl:M.outgoingResultWebhook,autoApprovalRate:M.autoApprovalRate,...G?{isDefault:!0}:{}})),W=G?{id:w[0].id,name:w[0].name,mode:w[0].mode}:null,V=z.webhook?m9(w,z.webhook):G?w[0]:void 0,X;if(z.filePath)if(!gV1(z.filePath))X={valid:!1,filePath:z.filePath,fileName:z.filePath.split(/[\\/]/).pop()??z.filePath,documentCount:0,errors:[`文件不存在: ${z.filePath}`]};else try{let M=bI(z.filePath),v=await fI(M.fileBuffer,M.fileName,V?.materialPackFilePolicy);X={valid:!0,filePath:z.filePath,fileName:M.fileName,documentCount:v.documents.length,warnings:v.warnings}}catch(M){X={valid:!1,filePath:z.filePath,fileName:z.filePath.split(/[\\/]/).pop()??z.filePath,documentCount:0,errors:[M instanceof Error?M.message:String(M)]}}let L=X?X.valid:!0,D=Y==="ok"&&H.length>0&&L,O=U==="stateful"?"":` --corp ${I.id}`,A="",T="";if(Y!=="ok")T=`凭证鉴权异常: ${J}`,A=`seal-use auth diagnose${O}`;else if(H.length===0)T="当前企业尚未配置任何 Webhook 集成通道",A=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${O}`;else if(X&&!X.valid)T=`材料包预检失败: ${X.errors?.join("; ")}`,A=`seal-use webhook material-pack preview ${X.filePath}${O}`;else{T=G?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${H.length} 个 Webhook 通道,等待载入`;let M=X?.filePath??"<材料包.zip>",v=G?"":` --webhook ${W?W.id:"<webhookIdOrName>"}`;A=`seal-use webhook material-pack push ${M}${v}${O}`}return{ready:D,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:Q,user:K},stateMode:U,authStatus:Y,authError:J,activeWebhooks:H,defaultWebhook:W,materialPack:X,statusMessage:T,nextAction:A}}var VD0=K0(()=>{G9();c4();Vk()});var Zk=K0(()=>{sU();sz();zO();Qk();Gk();Wk();Vk();VD0()});import{existsSync as ZD0,mkdirSync as XD0,statSync as _V1}from"node:fs";import{homedir as CV1}from"node:os";import{dirname as hV1,resolve as RO}from"node:path";function LD0($){if($.outputFile){let J=RO($.outputFile),Q=hV1(J);if(!ZD0(Q))XD0(Q,{recursive:!0});return J}let z=($.corpName||$.corpId||"企业").replace(/[/\\?%*:|"<>]/g,"_").trim()||"企业",q=$.dateTag||new Date().toISOString().slice(0,10),U=`${z}_智能洞察报告_${q}.xlsx`,Y;if($.toDownloads)Y=RO(CV1(),"Downloads");else Y=RO(process.cwd(),"exports");if(!ZD0(Y))XD0(Y,{recursive:!0});return RO(Y,U)}async function gO($,I,z={}){let q=I.name||I.id,U=LD0({outputFile:z.outputFile,toDownloads:z.toDownloads,corpName:q,corpId:I.id}),Y=new Date().toISOString(),[J,Q]=await Promise.all([eW($,{startDate:z.startDate?String(z.startDate):void 0,endDate:z.endDate?String(z.endDate):void 0,limit:z.limit??100}),IV($,{startDate:z.startDate,endDate:z.endDate}).catch(()=>({metrics:{},sankeyData:{nodes:[],links:[]}}))]),K=J.tagStats||[],w=[],G=Math.min(K.length,z.limit??50);for(let E=0;E<G;E++){let f=K[E];if(!f?.tagId)continue;try{let n=await $V($,{tagId:f.tagId,startDate:z.startDate?String(z.startDate):void 0,endDate:z.endDate?String(z.endDate):void 0});for(let g of n.risks||[])w.push({tagId:f.tagId,tagName:f.tagName||f.tagId,documentSN:g.documentSN||"-",documentType:g.documentType||"-",riskLevel:g.riskLevel||"warning",confidence:g.confidence??0,riskDetails:g.riskDetails||"-",reasoning:g.reasoning||"-",sourceDocumentURL:g.sourceDocumentURL,createdAt:g.createdAt})}catch{}}let H=new DD0.default.Workbook;H.creator="seal-use",H.lastModifiedBy="seal-use",H.created=new Date,H.modified=new Date;let W={type:"pattern",pattern:"solid",fgColor:{argb:"FF1E293B"}},V={name:"Microsoft YaHei",size:11,bold:!0,color:{argb:"FFFFFFFF"}},X={top:{style:"thin",color:{argb:"FFE2E8F0"}},bottom:{style:"thin",color:{argb:"FFE2E8F0"}},left:{style:"thin",color:{argb:"FFE2E8F0"}},right:{style:"thin",color:{argb:"FFE2E8F0"}}},L=H.addWorksheet("审核效能与决策流向",{views:[{showGridLines:!0}]});L.columns=[{header:"分类",key:"category",width:20},{header:"指标名称",key:"name",width:28},{header:"数值",key:"val",width:22},{header:"环比/趋势",key:"trend",width:18},{header:"说明",key:"desc",width:36}],L.getRow(1).height=28,L.getRow(1).font=V,L.getRow(1).fill=W,L.g Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:KY({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:uO(I,["template.name","templateName","form.name","formName","formTitle"]),amount:CO(z,["金额","报销金额","付款金额","合计","价税合计"])??uO(I,["amount","totalAmount","expenseAmount"]),expenseType:CO(z,["费用类型","费用类别","报销类型"]),costCompany:CO(z,["费用承担公司","承担公司","成本中心","费用归属"]),payee:CO(z,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:z.slice(0,30)}),invoices:tV1($),attachments:oU($,{summary:!0}).attachments,aiResult:kO($),manualResult:iI($)?.value,hints:KY({amountMentions:MD0(q,["金额","合计","税率"],8),partyMentions:MD0(q,["买方","卖方","甲方","乙方","收款"],8)})}}function mV1($){let I=[["result.citedRules",X9($,"result.citedRules")],["result.matchedRules",X9($,"result.matchedRules")],["result.ruleResults",X9($,"result.ruleResults")],["result.rules",X9($,"result.rules")],["pipelineData.citedRules",X9($,"pipelineData.citedRules")],["pipelineData.matchedRules",X9($,"pipelineData.matchedRules")]],z=[],q=new Set;for(let[U,Y]of I)(Array.isArray(Y)?Y:Y&&typeof Y==="object"?Object.values(Y):[]).forEach((Q,K)=>{let w=Qw(Q);if(!w)return;let G=w4(w.runtimeRuleId)??w4(w.runtimeId)??w4(w.id)??w4(w.ruleId),H=w4(w.ruleCode)??w4(w.code)??(G?eV1(G):void 0),W=KY({runtimeRuleId:G,ruleCode:H,versionNumber:oV1(w.versionNumber)??$.ruleSetVersionNumber,scope:w4(w.scope),strictness:w4(w.strictness),appliedAnalysis:w.appliedAnalysis??w.analysis??w.reasoning,checkResult:w.checkResult??w.result??w.decision,findings:w.findings??w.riskPoints??w.evidence,sourcePath:`${U}.${K}`}),V=JSON.stringify(W);if(!q.has(V))q.add(V),z.push(W)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:z.length,rules:z}}function uO($,I){if(!$)return;for(let z of I){let q=X9($,z);if(q!==void 0)return q}return}function ND0($,I){if(!$)return 0;for(let z of I){let q=X9($,z);if(Array.isArray(q))return q.length;if(q&&typeof q==="object")return Object.keys(q).length;if(typeof q==="number")return q}return 0}function X9($,I){return I.split(".").reduce((z,q)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){let U=Number(q);return Number.isInteger(U)?z[U]:void 0}if(typeof z==="object")return z[q];return},$)}function lV1($,I,z){let q=I.split("."),U=$;for(let Y of q.slice(0,-1)){let J=U[Y];if(!J||typeof J!=="object"||Array.isArray(J))U[Y]={};U=U[Y]}U[q[q.length-1]??I]=z}function KY($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function Qw($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function oV1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function rV1($){let I=[];return Ok($,"document",I),I}function Ok($,I,z){if(Array.isArray($)){$.forEach((J,Q)=>Ok(J,`${I}.${Q}`,z));return}let q=Qw($);if(!q)return;let U=w4(q.label)??w4(q.name)??w4(q.title)??w4(q.fieldName),Y=q.value??q.displayValue??q.text??q.content;if(U&&Y!==void 0&&typeof Y!=="object")z.push(KY({path:I,label:U,value:Y,type:w4(q.type)??w4(q.fieldType)}));for(let[J,Q]of Object.entries(q)){if(J==="attachments")continue;Ok(Q,`${I}.${J}`,z)}}function CO($,I){return $.find((q)=>{let U=w4(q.label)??"";return I.some((Y)=>U.includes(Y))})?.value}function tV1($){let I=[];return xO($.result,"result",I),xO($.document,"document",I),I.slice(0,20)}function xO($,I,z){if(Array.isArray($)){$.forEach((U,Y)=>xO(U,`${I}.${Y}`,z));return}let q=Qw($);if(!q)return;if(/invoice|发票/i.test(I))z.push(KY({path:I,fileName:w4(q.fileName)??w4(q.filename)??w4(q.name),buyer:q.buyer??q.buyerName??q.purchaserName,seller:q.seller??q.sellerName,amount:q.amount??q.totalAmount??q.total,taxRate:q.taxRate,category:q.category??q.type}));for(let[U,Y]of Object.entries(q))xO(Y,`${I}.${U}`,z)}function MD0($,I,z){return $.split(/\r?\n/).filter((q)=>I.some((U)=>q.includes(U))).slice(0,z)}function hO($){return $.map((I)=>{let z=nI(I);return{recordId:z.id,tenantId:z.tenantId,agentId:z.agentId,sourceDocumentSN:z.sourceDocumentSN,sourceDocumentId:z.sourceDocumentId,simulationBatchId:z.simulationBatchId,langfuseTraceId:z.langfuseTraceId,langfuseSessionFallback:z.langfuseSessionFallback,ruleSetVersionNumber:z.ruleSetVersionNumber,ruleSetPublishedAt:z.ruleSetPublishedAt,ruleSetPublishedByName:z.ruleSetPublishedByName,resolution:z.langfuseTraceId?"trace":z.langfuseSessionFallback?"session-fallback":"unresolved"}})}function Lk($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function aV1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let z=await X4($,I.recordId);if(!z.ruleSetVersionNumber)throw Er Line truncated
`);let V=an(K.document,H,G),X=await fetch(`${U}/api/v1/integrations/webhook/${encodeURIComponent(I)}/document`,{method:"POST",headers:{...Y.customHeaders??{},"Content-Type":"application/json",...NZ({webhookId:I,...V},Y.secret)},body:JSON.stringify(V)});if(!X.ok)throw Error(`Webhook 单据推送失败 ${X.status}: ${await X.text()}`);J.push({documentId:V.documentId,document:V,pushResult:await X.json()}),process.stderr.write(`✓ 单据推送成功: ${V.documentId}
`)}return{warnings:[],results:J}}function AY($){return{fileBuffer:nu1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}var lp=e(()=>{VD();en();tn();ln();pI();mp()});import{existsSync as mu1}from"node:fs";async function RA($,q,Y={}){let U=B4().stateful?"stateful":"stateless",I="ok",J,Q,K;try{let P=await z8($);K={id:P.user.id,name:P.user.name,isAdmin:P.user.isAdmin},Q={id:P.tenant.id,name:P.tenant.name,tenantSlug:P.tenant.tenantSlug,corporationName:P.tenant.hoseCorpConfig?.corporationName}}catch(P){I="error",J=P instanceof Error?P.message:String(P)}let H=[];if(I==="ok")try{H=await U$($,q.seal.endpoints.approvalStylePreferences)}catch(P){I="error",J=`读取 Webhook 配置失败: ${P instanceof Error?P.message:String(P)}`}let G=H.length===1,Z=H.map((P)=>({id:P.id,name:P.name,mode:P.mode,incomingDocumentWebhookUrl:P.incomingDocumentWebhook.url,outgoingResultWebhookUrl:P.outgoingResultWebhook,autoApprovalRate:P.autoApprovalRate,...G?{isDefault:!0}:{}})),V=G?{id:H[0].id,name:H[0].name,mode:H[0].mode}:null,X=Y.webhook?m3(H,Y.webhook):G?H[0]:void 0,w;if(Y.filePath)if(!mu1(Y.filePath))w={valid:!1,filePath:Y.filePath,fileName:Y.filePath.split(/[\\/]/).pop()??Y.filePath,documentCount:0,errors:[`文件不存在: ${Y.filePath}`]};else try{let P=AY(Y.filePath),T=await DY(P.fileBuffer,P.fileName,X?.materialPackFilePolicy);w={valid:!0,filePath:Y.filePath,fileName:P.fileName,documentCount:T.documents.length,warnings:T.warnings}}catch(P){w={valid:!1,filePath:Y.filePath,fileName:Y.filePath.split(/[\\/]/).pop()??Y.filePath,documentCount:0,errors:[P instanceof Error?P.message:String(P)]}}let L=w?w.valid:!0,F=I==="ok"&&Z.length>0&&L,O=U==="stateful"?"":` --corp ${q.id}`,A="",B="";if(I!=="ok")B=`凭证鉴权异常: ${J}`,A=`seal-use auth diagnose${O}`;else if(Z.length===0)B="当前企业尚未配置任何 Webhook 集成通道",A=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${O}`;else if(w&&!w.valid)B=`资源包预检失败: ${w.errors?.join("; ")}`,A=`seal-use webhook resource-pack preview ${w.filePath}${O}`;else{B=G?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${Z.length} 个 Webhook 通道,等待载入`;let P=w?.filePath??"<资源包.zip>",T=G?"":` --webhook ${V?V.id:"<webhookIdOrName>"}`;A=`seal-use webhook resource-pack push ${P}${T}${O}`}return{ready:F,corp:{id:q.id,name:q.name,sourceType:q.source.type,tenant:Q,user:K},stateMode:U,authStatus:I,authError:J,activeWebhooks:Z,defaultWebhook:V,resourcePack:w,materialPack:w,statusMessage:B,nextAction:A}}var oR0=e(()=>{Q3();J6();lp()});var op=e(()=>{pI();xz();VD();ln();tn();en();lp();oR0();mp()});import{existsSync as rR0,mkdirSync as sR0,statSync as lu1}from"node:fs";import{homedir as ou1}from"node:os";import{dirname as ru1,resolve as vA}from"node:path";function su1($){if($.outputFile){let J=vA($.outputFile),Q=ru1(J);if(!rR0(Q))sR0(Q,{recursive:!0});return J}let Y=($.corpName||$.corpId||"企业").replace(/[/\\?%*:|"<>]/g,"_").trim()||"企业",z=$.dateTag||new Date().toISOString().slice(0,10),U=`${Y}_智能洞察报告_${z}.xlsx`,I;if($.toDownloads)I=vA(ou1(),"Downloads");else I=vA(process.cwd(),"exports");if(!rR0(I))sR0(I,{recursive:!0});return vA(I,U)}async function hA($,q,Y={}){let z=q.name||q.id,U=ji({startDate:Y.startDate,endDate:Y.endDate,force:Y.force}),I=new Date().toISOString(),[J,Q]=await Promise.all([lw($,{startDate:U.startDateStr,endDate:U.endDateStr,limit:Y.limit??100}),rw($,{startDate:U.startDateStr,endDate:U.endDateStr}).catch(()=>({metrics:{},sankeyData:{nodes:[],links:[]}}))]),K=J.tagStats||[],H=[],G=Math.min(K.length,Y.limit??50);for(let R=0;R<G;R++){let c=K[R];if(!c?.tagId)continue;try{let n=await ow($,{tagId:c.tagId,startDate:U.startDateStr,endDate:U.endDateStr});for(let g of n.risks||[])H.push({tagId:c.tagId,tagName:c.tagName||c.tagId,documentSN:g.documentSN||"-",documentType:g.documentType||"-",riskLevel:g.riskLevel||"warning",confidence:g.confidence??0,riskDetails:g.riskDetails||"-",reasoning:g.reasoning||"-",sourceDocumentURL:g.sourceDocumentURL,createdAt:g.createdAt})}catch{}}let Z=new tR0.default.Workbook;Z.creator="seal-use",Z.lastModifiedBy="seal-use",Z.created=new Date,Z.modified=new Date;let V={type:"pattern",pattern:"solid",fgColor:{argb:"FF1E293B"}},X={name:"Microsoft YaHei",size:11,bold:!0,color:{argb:"FFFFFFFF"}},w={top:{style:"thin",color:{argb:"FFE2E8F0"}},bottom:{style:"thin",color:{argb:"FFE2E8F0"}},left:{style:"thin",color:{argb:"FFE2E8F0"}},right:{style:"thin",color:{argb:"FFE2E8F0"}}},L=Z.addWorksheet("审核效能与决策流向",{views:[{showGridLines:!0}]});L.columns=[{header:"分类",key:"category",width:20},{header:"指标名称",key:"name",width:28},{header:"数值",key:"val",width:22},{header:"环比/趋势",key:"trend",width:18},{header:"说明",key:"desc",width:36}],L.getRow(1).height=28,L.getRow(1).font=X,L.getRow(1).fill=V,L.getRow(1).alignment={vertical:"middle",horizontal:"center"};let F=Q.metrics||{},O=[{c Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:AJ({id:q?.id,sn:q?.sn??q?.sourceDocumentSN??$.sourceDocumentSN,title:q?.title??q?.name,template:uA(q,["template.name","templateName","form.name","formName","formTitle"]),amount:SA(Y,["金额","报销金额","付款金额","合计","价税合计"])??uA(q,["amount","totalAmount","expenseAmount"]),expenseType:SA(Y,["费用类型","费用类别","报销类型"]),costCompany:SA(Y,["费用承担公司","承担公司","成本中心","费用归属"]),payee:SA(Y,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:Y.slice(0,30)}),invoices:Xf1($),attachments:t7($,{summary:!0}).attachments,aiResult:bA($),manualResult:BY($)?.value,hints:AJ({amountMentions:qv0(z,["金额","合计","税率"],8),partyMentions:qv0(z,["买方","卖方","甲方","乙方","收款"],8)})}}function Hf1($){let q=[["result.citedRules",F3($,"result.citedRules")],["result.matchedRules",F3($,"result.matchedRules")],["result.ruleResults",F3($,"result.ruleResults")],["result.rules",F3($,"result.rules")],["pipelineData.citedRules",F3($,"pipelineData.citedRules")],["pipelineData.matchedRules",F3($,"pipelineData.matchedRules")]],Y=[],z=new Set;for(let[U,I]of q)(Array.isArray(I)?I:I&&typeof I==="object"?Object.values(I):[]).forEach((Q,K)=>{let H=zW(Q);if(!H)return;let G=j4(H.runtimeRuleId)??j4(H.runtimeId)??j4(H.id)??j4(H.ruleId),Z=j4(H.ruleCode)??j4(H.code)??(G?Lf1(G):void 0),V=AJ({runtimeRuleId:G,ruleCode:Z,versionNumber:Zf1(H.versionNumber)??$.ruleSetVersionNumber,scope:j4(H.scope),strictness:j4(H.strictness),appliedAnalysis:H.appliedAnalysis??H.analysis??H.reasoning,checkResult:H.checkResult??H.result??H.decision,findings:H.findings??H.riskPoints??H.evidence,sourcePath:`${U}.${K}`}),X=JSON.stringify(V);if(!z.has(X))z.add(X),Y.push(V)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:Y.length,rules:Y}}function uA($,q){if(!$)return;for(let Y of q){let z=F3($,Y);if(z!==void 0)return z}return}function $v0($,q){if(!$)return 0;for(let Y of q){let z=F3($,Y);if(Array.isArray(z))return z.length;if(z&&typeof z==="object")return Object.keys(z).length;if(typeof z==="number")return z}return 0}function F3($,q){return q.split(".").reduce((Y,z)=>{if(Y===void 0||Y===null)return;if(Array.isArray(Y)){let U=Number(z);return Number.isInteger(U)?Y[U]:void 0}if(typeof Y==="object")return Y[z];return},$)}function Gf1($,q,Y){let z=q.split("."),U=$;for(let I of z.slice(0,-1)){let J=U[I];if(!J||typeof J!=="object"||Array.isArray(J))U[I]={};U=U[I]}U[z[z.length-1]??q]=Y}function AJ($){return Object.fromEntries(Object.entries($).filter(([,q])=>q!==void 0))}function zW($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Zf1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Wf1($){let q=[];return ap($,"document",q),q}function ap($,q,Y){if(Array.isArray($)){$.forEach((J,Q)=>ap(J,`${q}.${Q}`,Y));return}let z=zW($);if(!z)return;let U=j4(z.label)??j4(z.name)??j4(z.title)??j4(z.fieldName),I=z.value??z.displayValue??z.text??z.content;if(U&&I!==void 0&&typeof I!=="object")Y.push(AJ({path:q,label:U,value:I,type:j4(z.type)??j4(z.fieldType)}));for(let[J,Q]of Object.entries(z)){if(J==="attachments")continue;ap(Q,`${q}.${J}`,Y)}}function SA($,q){return $.find((z)=>{let U=j4(z.label)??"";return q.some((I)=>U.includes(I))})?.value}function Xf1($){let q=[];return fA($.result,"result",q),fA($.document,"document",q),q.slice(0,20)}function fA($,q,Y){if(Array.isArray($)){$.forEach((U,I)=>fA(U,`${q}.${I}`,Y));return}let z=zW($);if(!z)return;if(/invoice|发票/i.test(q))Y.push(AJ({path:q,fileName:j4(z.fileName)??j4(z.filename)??j4(z.name),buyer:z.buyer??z.buyerName??z.purchaserName,seller:z.seller??z.sellerName,amount:z.amount??z.totalAmount??z.total,taxRate:z.taxRate,category:z.category??z.type}));for(let[U,I]of Object.entries(z))fA(I,`${q}.${U}`,Y)}function qv0($,q,Y){return $.split(/\r?\n/).filter((z)=>q.some((U)=>z.includes(U))).slice(0,Y)}function yA($){return $.map((q)=>{let Y=PY(q);return{recordId:Y.id,tenantId:Y.tenantId,agentId:Y.agentId,sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId,simulationBatchId:Y.simulationBatchId,langfuseTraceId:Y.langfuseTraceId,langfuseSessionFallback:Y.langfuseSessionFallback,ruleSetVersionNumber:Y.ruleSetVersionNumber,ruleSetPublishedAt:Y.ruleSetPublishedAt,ruleSetPublishedByName:Y.ruleSetPublishedByName,resolution:Y.langfuseTraceId?"trace":Y.langfuseSessionFallback?"session-fallback":"unresolved"}})}function sp($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function Vf1($,q){if(q.recordId&&!q.versionId&&!q.versionNumber&&!q.latest){let Y=await e1($,q.recordId);if(!Y.ruleSetVersionNumber)throw Er Line truncated
`+`• 身份主体:${O}${A}
`+`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)
`+`• 时效性:换票凭证有效时间 ${V} 秒(${Math.round(V/60)} 分钟),在浏览器打开后将保留 30 天会话
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:I.sso?G:w,sealResultUrl:w,ssoUrl:G,type:I.sso?"sso_link":"deep_link",expiresIn:I.sso?V:void 0,identity:H,warning:W,enterpriseAssistUrl:J,enterpriseUrl:J,hoseDomain:Y.type==="hose"?qZ1(Y.domain):void 0,documentUrl:Q,recordId:U?.id,sourceDocumentSN:U?.sourceDocumentSN,sourceDocumentId:U?.sourceDocumentId,sourceSystem:U?.sourceSystem,missing:{enterpriseAssistUrl:J?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:q&&!Q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:Z.object({query:Z.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:Z.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:Z.string().optional().describe("模拟批次 ID"),latest:Z.boolean().optional().describe("只返回最新一条匹配记录"),fields:Z.union([Z.string(),Z.array(Z.string())]).optional().describe("限制返回字段"),limit:Z.number().int().positive().max(100).optional(),maxScan:Z.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:Z.boolean().optional()}),handler:async($,I)=>{let z=I.sn??I.query;if(!z)throw Error("query or sn is required");let q=await UZ1($,{query:z,sn:I.sn,batchId:I.batchId,latest:I.latest,limit:I.latest?1:I.limit??20,maxScan:I.maxScan??1000}),U=await Promise.all(q.records.map((Q)=>X4($,Q.id))),Y=FD0(I.fields),J=U.map((Q)=>$Z1(Q,Y));return{query:z,sourceDocumentSN:I.sn,simulationBatchId:I.batchId,latest:I.latest??!1,total:q.total,scanned:q.scanned,matched:J.length,records:J,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-home tool seal_approval_context_get --json '{"ruleVersionNumber":14}'`},...I.includeBridge?{bridge:hO(U)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:Z.object({batchId:Z.string().describe("simulation batch ID"),query:Z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,I)=>{let z=Tk(await _j($,I.batchId),I.query);return{batchId:I.batchId,count:z.length,records:z.map(nI),bridge:hO(z)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:Z.object({mode:Z.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:Z.array(Z.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:Z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:Z.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:Z.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:Z.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:Z.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:Z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:Z.array(Z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:Z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:Z.record(Z.string(),Z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:Z.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:Z.record(Z.string(),Z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,I)=>{let z=I.mode??"hosecloud",q=I.signKey;if(z==="hosecloud"&&!q){if(q=(await hj($)).find((Q)=>Q.signKey)?.signKey,!q)throw Error("未找到合思集成 signKey, 请通过 signKey Line truncated
`)}function ZZ1($){let I=[];if(I.push(`seal-use ${$.area} - ${$.title}`),$.description)I.push($.description);I.push(""),I.push("Usage:");for(let z of $.commands)for(let q of z.usage)I.push(` ${q}`);if($.commands.some((z)=>z.name))I.push(""),I.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`);return I.join(`
`)}function kD0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let I of fD0)for(let z of I.commands)for(let q of z.usage)$.push(` ${q}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var fD0;var _k=K0(()=>{k$();fD0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",summary:"List all configured enterprises",usage:["seal-use corps list [query] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"bind-test",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",description:"Filter records by status (e.g. completed, failed, rejected)"},{flag:"--webhook <idOrName>",description:"Target Webhook integration on test enterprise"},{flag:"--sn-suffix <str>",description:"Optional suffix appended to documentSN"},{fla Line truncated
`+`• 时效性:换票凭证有效时间 ${X} 秒(${Math.round(X/60)} 分钟),在浏览器打开后将保留 30 天会话
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:q.sso?G:H,sealResultUrl:H,ssoUrl:G,type:q.sso?"sso_link":"deep_link",expiresIn:q.sso?X:void 0,identity:Z,warning:V,enterpriseAssistUrl:J,enterpriseUrl:J,hoseDomain:I.type==="hose"?Nf1(I.domain):void 0,documentUrl:Q,recordId:U?.id,sourceDocumentSN:U?.sourceDocumentSN,sourceDocumentId:U?.sourceDocumentId,sourceSystem:U?.sourceSystem,missing:{enterpriseAssistUrl:J?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:z&&!Q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:W.object({query:W.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:W.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:W.string().optional().describe("模拟批次 ID"),latest:W.boolean().optional().describe("只返回最新一条匹配记录"),fields:W.union([W.string(),W.array(W.string())]).optional().describe("限制返回字段"),limit:W.number().int().positive().max(100).optional(),maxScan:W.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:W.boolean().optional()}),handler:async($,q)=>{let Y=q.sn??q.query;if(!Y)throw Error("query or sn is required");let z=await Df1($,{query:Y,sn:q.sn,batchId:q.batchId,latest:q.latest,limit:q.latest?1:q.limit??20,maxScan:q.maxScan??1000}),U=await Promise.all(z.records.map((Q)=>e1($,Q.id))),I=eR0(q.fields),J=U.map((Q)=>Ff1(Q,I));return{query:Y,sourceDocumentSN:q.sn,simulationBatchId:q.batchId,latest:q.latest??!1,total:z.total,scanned:z.scanned,matched:J.length,records:J,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-home tool seal_approval_context_get --json '{"ruleVersionNumber":14}'`},...q.includeBridge?{bridge:yA(U)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:W.object({batchId:W.string().describe("simulation batch ID"),query:W.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,q)=>{let Y=Ud(await Sv($,q.batchId),q.query);return{batchId:q.batchId,count:Y.length,records:Y.map(PY),bridge:yA(Y)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:W.object({mode:W.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:W.array(W.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:W.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:W.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:W.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:W.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:W.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:W.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:W.array(W.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:W.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:W.record(W.string(),W.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:W.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:W.record(W.string(),W.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,q)=>{let Y=q.mode??"hosecloud",z=q.signKey;if(Y==="hosecloud"&&!z){if(z=(await xv($)).find((Q)=>Q.signKey)?.signKey,!z)throw Error("未找到合思集成 signKey, 请通过 signKey Line truncated
`)}function vf1($){let q=[];if(q.push(`seal-use ${$.area} - ${$.title}`),$.description)q.push($.description);q.push(""),q.push("Usage:");for(let Y of $.commands)for(let z of Y.usage)q.push(` ${z}`);if($.commands.some((Y)=>Y.name))q.push(""),q.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`);return q.join(`
`)}function Ov0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let q of Mv0)for(let Y of q.commands)for(let z of Y.usage)$.push(` ${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Mv0;var Zd=e(()=>{V$();Mv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"bind-test",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",descripti Line truncated
`)}
`}function ww($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function T0($,I={}){FZ1($,I);let z=`${JSON.stringify($,null,2)}
`;if(I.outputFile){XZ1(I.outputFile,z),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(z,"utf-8")},null,2));return}console.log(z.trimEnd())}function FZ1($,I={}){if(I.allowFull||I.outputFile)return;let z=Buffer.byteLength(JSON.stringify($),"utf-8");if(z>OZ1)throw new qO(`Output is large (${z} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function pD0($,I){if(I)return;let z=$&&typeof $==="object"?$:{},q=typeof z.count==="number"?z.count:void 0,U=Array.isArray(z.rules)?z.rules.length:void 0,Y=Buffer.byteLength(JSON.stringify($),"utf-8"),J=q??U??0;if(J>LZ1||Y>DZ1)throw new qO(`Rule list is large (${J} rules, ${Y} 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 Z0($){return{allowFull:V0($.full)===!0,outputFile:j($.outputFile)??j($["output-file"])}}function cD0($=[]){console.log(nD0($))}var LZ1=100,DZ1=120000,iD0,OZ1=200000;var u1=K0(()=>{G4();k$();_k();iD0=["id","code","status","strictness","scope","createdAt","updatedAt"]});var dD0={};A$(dD0,{selectCorp:()=>w1,runToolResult:()=>o7,runTool:()=>N0,globalConfigSummary:()=>l7});function w1($){let I=O$(),z=K4();return d7(I,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$},w9())}function l7($=K4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:SI()}}async function N0($,I,z,q,U={}){T0(await o7($,I,z,q),U)}async function o7($,I,z,q){let U=Jw.find((Q)=>Q.name===$);if(!U)throw Error(`Unknown Seal tool: ${$}`);let Y=Object.fromEntries(Object.entries(q).filter(([,Q])=>Q!==void 0)),J=U.handler;return J(I,Y,{corp:z})}var A4=K0(()=>{G9();fO();u1()});var iF0={};A$(iF0,{formatTenantDoctorDashboard:()=>BX1,diagnoseTenantContract:()=>EX1});async function EX1($,I){let z=[],q=I.environment==="test"?"test":"production",U=q==="test"?I.prodCorpId:I.testCorpId,Y=q==="test"?"prodParent":"testTarget",J=null,Q=null;try{let D=await v6($);if(J=D.user,Q=D.tenant,Boolean(J?.isAdmin||J?.permissions?.includes("*")))z.push({id:"auth_identity",name:"身份与权限契约",status:"pass",summary:`已认证为管理员「${J.name??"未知"}」(${J.id??""}),具备完整操作权限`,details:{userId:J.id,userName:J.name,isAdmin:!0,tenantSlug:Q?.tenantSlug,permissions:J.permissions}});else z.push({id:"auth_identity",name:"身份与权限契约",status:"warn",summary:`已认证为普通用户「${J.name??"未知"}」,非超级管理员,部分配置操作可能受限`,details:{userId:J.id,userName:J.name,isAdmin:!1,permissions:J.permissions},recommendation:"建议使用具有管理权限的企业主账号执行规则修改与集成发布"})}catch(D){z.push({id:"auth_identity",name:"身份与权限契约",status:"fail",summary:`鉴权握手失败:${D instanceof Error?D.message:String(D)}`,details:{error:String(D)},recommendation:`请执行 seal-use auth login --corp ${I.id} 重新登录或更新 Token`})}let K={featureCode:"ai-approval",balance:0,deductionAmount:120,estimatedRuns:0,status:"exhausted"},w={used:0,remaining:0};try{let D=await N3($),O=Array.isArray(D.features)?D.features:[],A=O.find((M)=>M?.code==="ai-approval");if(A){let M=typeof A.balance==="number"?A.balance:0,v=typeof A.deductionAmount==="number"&&A.deductionAmount>0?A.deductionAmount:120,x=Math.floor(M/v);if(K.balance=M,K.deductionAmount=v,K.estimatedRuns=x,M<=0)K.status="exhausted",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"fail",summary:"当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试",details:{balance:M,deductionAmount:v,estimatedRuns:x},recommendation:"请联系管理员为企业充值 AI 审批额度"});else if(x<10)K.status="low",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`额度偏低:剩余 ${M} 点 (单笔扣除 ${v} 点),仅可支持约 ${x} 笔审核`,details:{balance:M,deductionAmount:v,estimatedRuns:x},recommendation:"建议在发起大规模自动化回归前充值补充额度"});else K.status="sufficient",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"pass",summary:`额度充裕:剩余 ${M} 点,预估可支持 ${x} 笔审核单据`,details:{balance:M,deductionAmount:v,estimatedRuns:x}})}else z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:"未检索到「ai-approval」功能包额度明细,按默认通道运行",details:{features:O.map((M)=>M?.code)}});let T=O.find((M)=>M?.code==="approval-rules");if(T)w.used=typeof T.used==="number"?T.used:0,w.remaining=typeof T.remaining==="number"?T.remaining:0}catch(D){z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`读取计费状态失败:${D instanceof Error?D.message:String(D)}`,details:{error: Line truncated
`)}var pF0=K0(()=>{c4()});import{dirname as Fw,resolve as vN0}from"node:path";import{fileURLToPath as YL1}from"node:url";q$();function Oz($){return!!$._zod}function _9($,I){if(Oz($))return $z($,I);return $.safeParse(I)}function nG($){if(!$)return;let I;if(Oz($))I=$._zod?.def?.shape;else I=$.shape;if(!I)return;if(typeof I==="function")try{return I()}catch{return}return I}function bn($){if(Oz($)){let Y=$._zod?.def;if(Y){if(Y.value!==void 0)return Y.value;if(Array.isArray(Y.values)&&Y.values.length>0)return Y.values[0]}}let z=$._def;if(z){if(z.value!==void 0)return z.value;if(Array.isArray(z.values)&&z.values.length>0)return z.values[0]}let q=$.value;if(q!==void 0)return q;return}var ME="2025-11-25";var Up=[ME,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],h9="io.modelcontextprotocol/related-task",NH="2.0",i4=OH(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Yp=c1([Q0(),M1().int()]),Jp=Q0(),XF1=J6({ttl:M1().optional(),pollInterval:M1().optional()}),sP0=j0({ttl:M1().optional()}),eP0=j0({taskId:Q0()}),AE=J6({progressToken:Yp.optional(),[h9]:eP0.optional()}),B$=j0({_meta:AE.optional()}),VJ=B$.extend({task:sP0.optional()}),Qp=($)=>VJ.safeParse($).success,K6=j0({method:Q0(),params:B$.loose().optional()}),d$=j0({_meta:AE.optional()}),m$=j0({method:Q0(),params:d$.loose().optional()}),w6=J6({_meta:AE.optional()}),MH=c1([Q0(),M1().int()]),Kp=j0({jsonrpc:x0(NH),id:MH,...K6.shape}).strict(),PE=($)=>Kp.safeParse($).success,wp=j0({jsonrpc:x0(NH),...m$.shape}).strict(),Gp=($)=>wp.safeParse($).success,TE=j0({jsonrpc:x0(NH),id:MH,result:w6}).strict(),ZJ=($)=>TE.safeParse($).success;var H1;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(H1||(H1={}));var EE=j0({jsonrpc:x0(NH),id:MH.optional(),error:j0({code:M1().int(),message:Q0(),data:p1().optional()})}).strict();var Hp=($)=>EE.safeParse($).success;var Wp=c1([Kp,wp,TE,EE]),LF1=c1([TE,EE]),AH=w6.strict(),$T0=d$.extend({requestId:MH.optional(),reason:Q0().optional()}),PH=m$.extend({method:x0("notifications/cancelled"),params:$T0}),IT0=j0({src:Q0(),mimeType:Q0().optional(),sizes:Y1(Q0()).optional(),theme:Q6(["light","dark"]).optional()}),XJ=j0({icons:Y1(IT0).optional()}),jz=j0({name:Q0(),title:Q0().optional()}),Vp=jz.extend({...jz.shape,...XJ.shape,version:Q0(),websiteUrl:Q0().optional(),description:Q0().optional()}),zT0=Bz(j0({applyDefaults:R4().optional()}),f1(Q0(),p1())),qT0=WJ(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},Bz(j0({form:zT0.optional(),url:i4.optional()}),f1(Q0(),p1()).optional())),UT0=J6({list:i4.optional(),cancel:i4.optional(),requests:J6({sampling:J6({createMessage:i4.optional()}).optional(),elicitation:J6({create:i4.optional()}).optional()}).optional()}),YT0=J6({list:i4.optional(),cancel:i4.optional(),requests:J6({tools:J6({call:i4.optional()}).optional()}).optional()}),JT0=j0({experimental:f1(Q0(),i4).optional(),sampling:j0({context:i4.optional(),tools:i4.optional()}).optional(),elicitation:qT0.optional(),roots:j0({listChanged:R4().optional()}).optional(),tasks:UT0.optional(),extensions:f1(Q0(),i4).optional()}),QT0=B$.extend({protocolVersion:Q0(),capabilities:JT0,clientInfo:Vp}),BE=K6.extend({method:x0("initialize"),params:QT0});var KT0=j0({experimental:f1(Q0(),i4).optional(),logging:i4.optional(),completions:i4.optional(),prompts:j0({listChanged:R4().optional()}).optional(),resources:j0({subscribe:R4().optional(),listChanged:R4().optional()}).optional(),tools:j0({listChanged:R4().optional()}).optional(),tasks:YT0.optional(),extensions:f1(Q0(),i4).optional()}),wT0=w6.extend({protocolVersion:Q0(),capabilities:KT0,serverInfo:Vp,instructions:Q0().optional()}),jE=m$.extend({method:x0("notifications/initialized"),params:d$.optional()});var TH=K6.extend({method:x0("ping"),params:B$.optional()}),GT0=j0({progress:M1(),total:l1(M1()),message:l1(Q0())}),HT0=j0({...d$.shape,...GT0.shape,progressToken:Yp}),EH=m$.extend({method:x0("notifications/progress"),params:HT0}),WT0=B$.extend({cursor:Jp.optional()}),LJ=K6.extend({params:WT0.optional()}),DJ=w6.extend({nextCursor:Jp.optional()}),VT0=Q6(["working","input_required","completed","failed","cancelled"]),OJ=j0({taskId:Q0(),status:VT0,ttl:c1([M1(),UJ()]),createdAt:Q0(),lastUpdatedAt:Q0(),pollInterval:l1(M1()),statusMessage:l1(Q0())}),vz=w6.extend({task:OJ}),ZT0=d$.merge(OJ),FJ=m$.extend({method:x0("notifications/tasks/status"),params:ZT0}),BH=K6.extend({method:x0("tasks/get"),params:B$.extend({taskId:Q0()})}),jH=w6.merge(OJ),vH=K6.extend({method:x0("tasks/result"),params:B$.extend({taskId:Q0()})}),DF1=w6.loose(),RH=LJ.extend({method:x0("tasks/list")}),gH=DJ.extend({tasks:Y1(OJ)}),_H=K6.extend({method:x0("tasks/cancel"),par Line truncated
`);if($===-1)return null;let I=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),YS0(I)}clear(){this._buffer=void 0}}function YS0($){return Wp.parse(JSON.parse($))}function Ko($){return JSON.stringify($)+`
`}class rB{constructor($=wo.stdin,I=wo.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new oB,this._started=!1,this._ondata=(z)=>{this._readBuffer.append(z),this.processReadBuffer()},this._onerror=(z)=>{this.onerror?.(z)}}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 z=Ko($);if(this._stdout.write(z))I();else this._stdout.once("drain",I)})}}w$();import{dirname as Hf,join as eX1}from"node:path";import{fileURLToPath as $L1}from"node:url";import{spawnSync as Gr}from"node:child_process";var qQ={name:"seal-use",version:"0.10.20",type:"module",module:"src/server.ts",bin:{"seal-use":"src/cli.ts","seal-home":"src/cli.ts"},scripts:{dev:"bun run --watch src/server.ts",start:"bun run src/server.ts",probe:"bun run src/probe.ts",cli:"bun run src/cli.ts",check:"tsc --noEmit","build:binary":"node scripts/build-binary.mjs","build:plugin":"node scripts/build-plugin.mjs",bump:"bun run scripts/bump-version.ts","dev:override":"bun run scripts/dev-override.ts","dev:link":"bun run scripts/dev-override.ts","openapi:bundle":"bun run scripts/bundle-openapi.ts","openapi:raw":"bun run scripts/generate-raw-openapi.ts",test:"bun test"},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0",exceljs:"^4.4.0","iconv-lite":"^0.7.3",ky:"^2.0.2","pinyin-pro":"^3.29.3",yauzl:"^3.4.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@types/yauzl":"^3.4.0","bun-types":"^1.3.14",typescript:"^5.9.3",yaml:"^2.9.0"}};function oS0($,I=qQ.version){let z=$.trim();if(!z)return null;let q=z.endsWith("-dirty"),U=q?z.slice(0,-6):z,Y=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);if(Y&&Y[1]&&Y[2]&&Y[3])return{baseVersion:Y[1],commitsAhead:Number.parseInt(Y[2],10),commit:Y[3],dirty:q,describe:z};let J=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);if(J&&J[1])return{baseVersion:J[1],commitsAhead:0,commit:"",dirty:q,describe:z};let Q=U.match(/^([0-9a-f]{7,40})$/);if(Q&&Q[1])return{baseVersion:I,commitsAhead:0,commit:Q[1],dirty:q,describe:z};return null}function rS0($,I,z,q){let Y=z?`+g${z}${q?".dirty":""}`:q?"+dirty":"";return`${$}-dev.${I}${Y}`}function tS0($){let I=$?.env,z=I?.SEAL_BUILD_VERSION??process.env.SEAL_BUILD_VERSION,q=I?.SEAL_BUILD_IS_RELEASE??process.env.SEAL_BUILD_IS_RELEASE,U=I?.SEAL_BUILD_CHANNEL??process.env.SEAL_BUILD_CHANNEL,Y=I?.SEAL_BUILD_GIT_BASE??process.env.SEAL_BUILD_GIT_BASE,J=I?.SEAL_BUILD_GIT_COMMITS_AHEAD??process.env.SEAL_BUILD_GIT_COMMITS_AHEAD,Q=I?.SEAL_BUILD_GIT_COMMIT??process.env.SEAL_BUILD_GIT_COMMIT,K=I?.SEAL_BUILD_GIT_DIRTY??process.env.SEAL_BUILD_GIT_DIRTY,w=I?.SEAL_BUILD_GIT_DESCRIBE??process.env.SEAL_BUILD_GIT_DESCRIBE,G=I?.SEAL_FORCE_RELEASE??process.env.SEAL_FORCE_RELEASE,H=$?.cwd;if(z){let W=q==="true",X={name:"seal-use",version:z,channel:U||(W?"release":"dev"),isRelease:W};if(Y)X.git={baseVersion:Y,commitsAhead:Number.parseInt(J||"0",10),commit:Q||"",dirty:K==="true",describe:w||z};return X}if(q==="true"||G==="1")return{name:"seal-use",version:qQ.version,channel:"release",isRelease:!0};try{let W=Gr("git",["describe","--tags","--long","--dirty","--always"],{cwd:H,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(W.status===0&&W.stdout){let V=oS0(W.stdout.trim(),qQ.version);if(V){if(!V.commit){let L=Gr("git",["rev-parse","--short","HEAD"],{cwd:H,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(L.status===0&&L.stdout)V.commit=L.stdout.trim()}return{name:"seal-use",version:rS0(V.baseVersion,V.commitsAhead,V.commit,V.dirty),channel:"dev",isRelease:!1,git:V}}}}catch{}return{name:"seal-use",version:`${qQ.version}-dev.0+local`,channel:"dev",isRelease:!1}}var UQ=tS0(),q1=UQ.version,Dj=UQ.isRelease,uB1=UQ.channel;c4();lu();tu();A4();G4();u1();w$();A4();c4();c4();tK();Zk();G4();u1();k$();import{existsSync as mD0}from"node:fs";async function lD0($,I){if(!mD0($))throw Error(`File not found: ${$}`);let z=bI($);console.log(JSON.stringify(await fI(z.fileBuffer,z.fileName,I),null,2))}async function cO($,I,z,q,U){if($==="ready"||$==="status"){let Y=I??j(U.options.file)??j(U.options.input),J=await vO(z,q,{filePath:Y,webhook:j(U.options.webhook)??j(U.options.selector)});if(console.error(`[webhook-ready] 企业环境: ${J.corp.name} (${J.corp.id}) [${J.stateMode}]`),J.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${J.corp.tenant.name} (${J.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${J.authStatus==="ok"?"OK":`异常 (${J.authError})`}`),console.error(`[webhook-ready] Webhook 通道: ${J.activeWebhooLine truncated
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let Y=w1(q),J=w1(U);if(Y.id===J.id)throw M4(`Cannot bind enterprise '${Y.id}' to itself.`);if(Y.prodCorpId&&Y.prodCorpId!==J.id)throw M4(`Cannot use '${Y.id}' as a production enterprise because it is already registered as a test enterprise for '${Y.prodCorpId}'. Multi-tier chaining is not permitted.`);if(J.testCorpId&&J.testCorpId!==Y.id)throw M4(`Cannot bind '${J.id}' as a test enterprise because it already has a bound test enterprise '${J.testCorpId}'. Multi-tier chaining is not permitted.`);let Q=V0(z.options.force)===!0;if(Y.testCorpId&&Y.testCorpId!==J.id||J.prodCorpId&&J.prodCorpId!==Y.id){if(!Q)throw X5(`Enterprise binding conflict: production enterprise '${Y.id}' is bound to '${Y.testCorpId??"none"}', and test enterprise '${J.id}' is bound to '${J.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,`seal-use corps bind-test ${Y.id} ${J.id} --confirm --force`)}if(!(V0(z.options.confirm)===!0||V0(z.options.yes)===!0)){let H=Q?" --force":"";throw X5(`Refusing to bind test enterprise '${J.name}' (${J.id}) to production enterprise '${Y.name}' (${Y.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${J.id}' as a test environment.`,`seal-use corps bind-test ${Y.id} ${J.id} --confirm${H}`)}if(Y.testCorpId&&Y.testCorpId!==J.id)try{c7(Y.testCorpId,{prodCorpId:void 0})}catch{}if(J.prodCorpId&&J.prodCorpId!==Y.id)try{c7(J.prodCorpId,{testCorpId:void 0})}catch{}let w=c7(Y.id,{environment:"production",testCorpId:J.id}),G=c7(J.id,{environment:"test",prodCorpId:Y.id});T0({success:!0,productionEnterprise:{id:w.id,name:w.name,environment:w.environment,testCorpId:w.testCorpId},testEnterprise:{id:G.id,name:G.name,environment:G.environment,prodCorpId:G.prodCorpId}});return}if($==="unbind-test"){let q=I??j(z.options.corp),U=w1(q);if(!U.testCorpId&&!U.prodCorpId){T0({unbound:!1,message:`Enterprise '${U.name}' (${U.id}) does not have an active test enterprise binding.`});return}let Y=U.testCorpId?U.id:U.prodCorpId,J=U.testCorpId?U.testCorpId:U.id;if(!(V0(z.options.confirm)===!0||V0(z.options.yes)===!0))throw X5(`Refusing to unbind production enterprise '${Y}' and test enterprise '${J}' without --confirm.`,`seal-use corps unbind-test ${U.id} --confirm`);c7(Y,{testCorpId:void 0});try{c7(J,{prodCorpId:void 0})}catch{}T0({success:!0,unboundProduction:Y,unboundTest:J});return}if($==="sync-test"){let q=I??j(z.options.corp),U=w1(q);if(!U.testCorpId)throw M4(`Production enterprise '${U.name}' (${U.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${U.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let Y=w1(U.testCorpId);if(Y.environment!=="test")throw Error(`Target enterprise '${Y.name}' (${Y.id}) is marked as '${Y.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let J=await J1(U),Q=await J1(Y),[K,w,G,H,W,V,X,L]=await Promise.all([E1(J,U.seal.endpoints.approvalStylePreferences).catch(()=>({})),E1(Q,Y.seal.endpoints.approvalStylePreferences).catch(()=>({})),W6(J),W6(Q),r$(J).catch(()=>[]),r$(Q).catch(()=>[]),d9(J,{limit:100}).catch(()=>({articles:[]})),d9(Q,{limit:100}).catch(()=>({articles:[]}))]),D=(X.articles||[]).filter((U0)=>!U0.isDeleted),O=(L.articles||[]).filter((U0)=>!U0.isDeleted),A=new Map(O.map((U0)=>[U0.title.trim(),U0])),T=[],M=[],v=new Set(D.map((U0)=>U0.title.trim()));for(let U0 of D){let v0=U0.title.trim(),I1=A.get(v0);if(!I1)T.push(U0);else{let W1=I1.content!==U0.content,T4=(I1.purpose??"")!==(U0.purpose??""),S4=I1.enabled!==U0.enabled,b$=I1.contentType!==U0.contentType,$$=(I1.status??"")!==(U0.status??""),k6=JSON.stringify([...I1.scenarios??[]].sort())!==JSON.stringify([...U0.scenarios??[]].sort()),n$=JSON.stringify([...I1.tags??[]].sort())!==JSON.stringify([...U0.tags??[]].sort());if(W1||T4||S4||b$||$$||k6||n$)M.push({testId:I1.id,prodDoc:U0,reasons:[...W1?["content"]:[],...T4?["purpose"]:[],...S4?["enabled"]:[],...b$?["contentType"]:[],...$$?["status"]:[],...k6?["scenarios"]:[],...n$?["tags"]:[]]})}}let x=O.filter((U0)=>!v.has(U0.title.trim())),k=[...W].sort((U0,v0)=>v0.versionNumber-U0.versionNumber)[0],E=k?.versionNumber,n=([...V].sort((U0,v0)=>v0.versionNumber-U0.versionNumber)[0]?.versionNumber??0)+1,g=wF0(U.name,E,V),p=j(z.options["version-name"])??j(z.options.versionName)??GF0(U.name,E,g,n),q0={...w,tone:K.tone,language:K.language,detailLevel:K.detailLevel,outputFormat:K.outputFormat,examples:K.examples??[],prohibitedPhrases:K.prohibitedPhrases??[],customInstructions:K.customInstructions,decisionPreferences:K.decisionPreferences,thinkingDepthPreference:K.thinkingDepthPreference};if(V0(z.options["dry-run"])===!0||V0(z.options.dryRun)===!0){T0({dryRun:!0,source:{id:U.id,name:U.name,environment:U.environment,latestPublishedVersion:k?{versionNumber:k.versionNumber,versionName:k.versionName}:null,documentsCount:D.length},target:{id:Y.id,name:Y.name,environment:Y.environment},versionMappingPlan:{sourceProdVersionNumber:E??null,sourceProdVersionName:k?.versionName??null,targetTestExpectedVersionNumber:n,targetTestPublishVersionName:p,iteration:g},preferencesDiff:{decisionPreferences:{before:w.decisionPreferences,after:K.decisionPreferences},thinkingDepthPreference:{before:w.thinkingDepthPreference,after:K.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:G.rules.length,targetExistingDraftRuleCount:H.rules.length,toDeleteCount:H.rules.length,toCreateCount:G.rules.length,rulesToSync:G.rules.map((U0,v0)=>({index:v0+1,sourceRuleId:U0.id,sourceRuleCode:U0.code??v0+1,expectedTargetCode:`rule-${v0+1}`,description:U0.description,scope:U0.scope,strictness:U0.strictness}))},documentsPlan:{sourceDocumentCount:D.length,targetExistingDocumentCount:O.length,toCreateCount:T.length,toCreate:T.map((U0)=>({title:U0.title,purpose:U0.purpose,contentType:U0.contentType,scenarios:U0.scenarios})),toUpdateCount:M.length,toUpdate:M.map((U0)=>({targetDocumentId:U0.testId,title:U0.prodDoc.title,reasons:U0.reasons})),toDeleteCount:x.length,toDelete:x.map((U0)=>({targetDocumentId:U0.id,title:U0.title}))},publishingPlan:{targetCorpId:Y.id,publishVersionName:p,publishTarget:"test"},hosecloudSyncPlan:(()=>{if(U.source.type!=="hose")return{sourceType:U.source.type,skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let U0=(K.integrations??[]).filter((W1)=>W1.type==="hosecloud"),v0=new Set,I1=U0.filter((W1)=>{let T4=W1.corporationId??U.id;if(v0.has(T4))return!1;return v0.add(T4),!0});return{sourceType:"hose",outboundName:LF0(U.name),targetMode:"assisted",integrationsCount:I1.length,integrations:I1.map((W1)=>({corporationId:W1.corporationId,apiOrigin:W1.apiOrigin,customApiUrl:W1.customApiUrl}))}})(),productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(V0(z.options.yes)===!0||V0(z.options.confirm)===!0))throw X5(`Refusing to overwrite test enterprise '${Y.name}' (${Y.id}) with preferences, ${G.rules.length} draft rules, and ${D.length} knowledge documents from production enterprise '${U.name}' (${U.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,`seal-use corps sync-test ${U.id} --yes`);await i8(Q,q0,Y.seal.endpoints.approvalStylePreferences);let c=[];for(let U0 of x)await lW(Q,U0.id),c.push({id:U0.id,title:U0.title});let m=[];for(let U0 of M)await mW(Q,U0.testId,{title:U0.prodDoc.title,purpose:U0.prodDoc.purpose,content:U0.prodDoc.content,contentType:U0.prodDoc.contentType,status:U0.prodDoc.status,enabled:U0.prodDoc.ena Line truncated
`}function IW($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function j0($,q={}){xf1($,q);let Y=`${JSON.stringify($,null,2)}
`;if(q.outputFile){hf1(q.outputFile,Y),console.log(JSON.stringify({outputFile:q.outputFile,bytes:Buffer.byteLength(Y,"utf-8")},null,2));return}console.log(Y.trimEnd())}function xf1($,q={}){if(q.allowFull||q.outputFile)return;let Y=Buffer.byteLength(JSON.stringify($),"utf-8");if(Y>yf1)throw new wD(`Output is large (${Y} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function Pv0($,q){if(q)return;let Y=$&&typeof $==="object"?$:{},z=typeof Y.count==="number"?Y.count:void 0,U=Array.isArray(Y.rules)?Y.rules.length:void 0,I=Buffer.byteLength(JSON.stringify($),"utf-8"),J=z??U??0;if(J>gf1||I>Sf1)throw new wD(`Rule list is large (${J} rules, ${I} 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 F0($){return{allowFull:W0($.full)===!0,outputFile:E($.outputFile)??E($["output-file"])}}function Bv0($=[]){console.log(Dv0($))}var gf1=100,Sf1=120000,Av0,yf1=200000;var o1=e(()=>{_4();V$();Zd();Av0=["id","code","status","strictness","scope","createdAt","updatedAt"]});var Tv0={};$$(Tv0,{selectCorp:()=>w1,runToolResult:()=>H2,runTool:()=>P0,globalConfigSummary:()=>K2});function w1($){let q=r8(),Y=B4(),z=e7(q,{stateful:Y.stateful,defaultCorpId:Y.defaultCorpId,corpId:$},J3());return PP0(z.id),z}function K2($=B4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:aq()}}async function P0($,q,Y,z,U={}){j0(await H2($,q,Y,z),U)}async function H2($,q,Y,z){let U=YW.find((Q)=>Q.name===$);if(!U)throw Error(`Unknown Seal tool: ${$}`);let I=Object.fromEntries(Object.entries(z).filter(([,Q])=>Q!==void 0)),J=U.handler;return J(q,I,{corp:Y})}var p4=e(()=>{Q3();ii();iA();o1()});var Ag0={};$$(Ag0,{formatTenantDoctorDashboard:()=>cb1,diagnoseTenantContract:()=>nb1});async function nb1($,q){let Y=[],z=q.environment==="test"?"test":"production",U=z==="test"?q.prodCorpId:q.testCorpId,I=z==="test"?"prodParent":"testTarget",J=null,Q=null;try{let F=await z8($);if(J=F.user,Q=F.tenant,Boolean(J?.isAdmin||J?.permissions?.includes("*")))Y.push({id:"auth_identity",name:"身份与权限契约",status:"pass",summary:`已认证为管理员「${J.name??"未知"}」(${J.id??""}),具备完整操作权限`,details:{userId:J.id,userName:J.name,isAdmin:!0,tenantSlug:Q?.tenantSlug,permissions:J.permissions}});else Y.push({id:"auth_identity",name:"身份与权限契约",status:"warn",summary:`已认证为普通用户「${J.name??"未知"}」,非超级管理员,部分配置操作可能受限`,details:{userId:J.id,userName:J.name,isAdmin:!1,permissions:J.permissions},recommendation:"建议使用具有管理权限的企业主账号执行规则修改与集成发布"})}catch(F){Y.push({id:"auth_identity",name:"身份与权限契约",status:"fail",summary:`鉴权握手失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)},recommendation:`请执行 seal-use auth login --corp ${q.id} 重新登录或更新 Token`})}let K={featureCode:"ai-approval",balance:0,deductionAmount:120,estimatedRuns:0,status:"exhausted"},H={used:0,remaining:0};try{let F=await g2($),O=Array.isArray(F.features)?F.features:[],A=O.find((P)=>P?.code==="ai-approval");if(A){let P=typeof A.balance==="number"?A.balance:0,T=typeof A.deductionAmount==="number"&&A.deductionAmount>0?A.deductionAmount:120,y=Math.floor(P/T);if(K.balance=P,K.deductionAmount=T,K.estimatedRuns=y,P<=0)K.status="exhausted",Y.push({id:"billing_quota",name:"AI 审批额度余量",status:"fail",summary:"当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试",details:{balance:P,deductionAmount:T,estimatedRuns:y},recommendation:"请联系管理员为企业充值 AI 审批额度"});else if(y<10)K.status="low",Y.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`额度偏低:剩余 ${P} 点 (单笔扣除 ${T} 点),仅可支持约 ${y} 笔审核`,details:{balance:P,deductionAmount:T,estimatedRuns:y},recommendation:"建议在发起大规模自动化回归前充值补充额度"});else K.status="sufficient",Y.push({id:"billing_quota",name:"AI 审批额度余量",status:"pass",summary:`额度充裕:剩余 ${P} 点,预估可支持 ${y} 笔审核单据`,details:{balance:P,deductionAmount:T,estimatedRuns:y}})}else Y.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:"未检索到「ai-approval」功能包额度明细,按默认通道运行",details:{features:O.map((P)=>P?.code)}});let B=O.find((P)=>P?.code==="approval-rules");if(B)H.used=typeof B.used==="number"?B.used:0,H.remaining=typeof B.remaining==="number"?B.remaining:0}catch(F){Y.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`读取计费状态失败:${F instanceof Error?F.message:String(F)}Line truncated
`)}var Pg0=e(()=>{J6()});import{dirname as wW,resolve as KS0}from"node:path";import{fileURLToPath as Ai1}from"node:url";S8();function $z($){return!!$._zod}function h3($,q){if($z($))return xY($,q);return $.safeParse(q)}function kX($){if(!$)return;let q;if($z($))q=$._zod?.def?.shape;else q=$.shape;if(!q)return;if(typeof q==="function")try{return q()}catch{return}return q}function Mo($){if($z($)){let I=$._zod?.def;if(I){if(I.value!==void 0)return I.value;if(Array.isArray(I.values)&&I.values.length>0)return I.values[0]}}let Y=$._def;if(Y){if(Y.value!==void 0)return Y.value;if(Array.isArray(Y.values)&&Y.values.length>0)return Y.values[0]}let z=$.value;if(z!==void 0)return z;return}var PC="2025-11-25";var kr=[PC,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],S3="io.modelcontextprotocol/related-task",LV="2.0",V6=VV(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),ur=I4([G0(),v1().int()]),fr=G0(),hp1=S6({ttl:v1().optional(),pollInterval:v1().optional()}),hk0=h0({ttl:v1().optional()}),gk0=h0({taskId:G0()}),BC=S6({progressToken:ur.optional(),[S3]:gk0.optional()}),z$=h0({_meta:BC.optional()}),jQ=z$.extend({task:hk0.optional()}),br=($)=>jQ.safeParse($).success,x6=h0({method:G0(),params:z$.loose().optional()}),M$=h0({_meta:BC.optional()}),N$=h0({method:G0(),params:M$.loose().optional()}),k6=S6({_meta:BC.optional()}),FV=I4([G0(),v1().int()]),ir=h0({jsonrpc:u0(LV),id:FV,...x6.shape}).strict(),TC=($)=>ir.safeParse($).success,nr=h0({jsonrpc:u0(LV),...N$.shape}).strict(),cr=($)=>nr.safeParse($).success,EC=h0({jsonrpc:u0(LV),id:FV,result:k6}).strict(),_Q=($)=>EC.safeParse($).success;var O1;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(O1||(O1={}));var jC=h0({jsonrpc:u0(LV),id:FV.optional(),error:h0({code:v1().int(),message:G0(),data:U4().optional()})}).strict();var pr=($)=>jC.safeParse($).success;var dr=I4([ir,nr,EC,jC]),gp1=I4([EC,jC]),OV=k6.strict(),Sk0=M$.extend({requestId:FV.optional(),reason:G0().optional()}),MV=N$.extend({method:u0("notifications/cancelled"),params:Sk0}),yk0=h0({src:G0(),mimeType:G0().optional(),sizes:G1(G0()).optional(),theme:y6(["light","dark"]).optional()}),CQ=h0({icons:G1(yk0).optional()}),Hz=h0({name:G0(),title:G0().optional()}),mr=Hz.extend({...Hz.shape,...CQ.shape,version:G0(),websiteUrl:G0().optional(),description:G0().optional()}),xk0=Kz(h0({applyDefaults:t4().optional()}),a1(G0(),U4())),kk0=EQ(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},Kz(h0({form:xk0.optional(),url:V6.optional()}),a1(G0(),U4()).optional())),uk0=S6({list:V6.optional(),cancel:V6.optional(),requests:S6({sampling:S6({createMessage:V6.optional()}).optional(),elicitation:S6({create:V6.optional()}).optional()}).optional()}),fk0=S6({list:V6.optional(),cancel:V6.optional(),requests:S6({tools:S6({call:V6.optional()}).optional()}).optional()}),bk0=h0({experimental:a1(G0(),V6).optional(),sampling:h0({context:V6.optional(),tools:V6.optional()}).optional(),elicitation:kk0.optional(),roots:h0({listChanged:t4().optional()}).optional(),tasks:uk0.optional(),extensions:a1(G0(),V6).optional()}),ik0=z$.extend({protocolVersion:G0(),capabilities:bk0,clientInfo:mr}),_C=x6.extend({method:u0("initialize"),params:ik0});var nk0=h0({experimental:a1(G0(),V6).optional(),logging:V6.optional(),completions:V6.optional(),prompts:h0({listChanged:t4().optional()}).optional(),resources:h0({subscribe:t4().optional(),listChanged:t4().optional()}).optional(),tools:h0({listChanged:t4().optional()}).optional(),tasks:fk0.optional(),extensions:a1(G0(),V6).optional()}),ck0=k6.extend({protocolVersion:G0(),capabilities:nk0,serverInfo:mr,instructions:G0().optional()}),CC=N$.extend({method:u0("notifications/initialized"),params:M$.optional()});var NV=x6.extend({method:u0("ping"),params:z$.optional()}),pk0=h0({progress:v1(),total:K4(v1()),message:K4(G0())}),dk0=h0({...M$.shape,...pk0.shape,progressToken:ur}),DV=N$.extend({method:u0("notifications/progress"),params:dk0}),mk0=z$.extend({cursor:fr.optional()}),RQ=x6.extend({params:mk0.optional()}),vQ=k6.extend({nextCursor:fr.optional()}),lk0=y6(["working","input_required","completed","failed","cancelled"]),hQ=h0({taskId:G0(),status:lk0,ttl:I4([v1(),OQ()]),createdAt:G0(),lastUpdatedAt:G0(),pollInterval:K4(v1()),statusMessage:K4(G0())}),Gz=k6.extend({task:hQ}),ok0=M$.merge(hQ),gQ=N$.extend({method:u0("notifications/tasks/status"),params:ok0}),AV=x6.extend({method:u0("tasks/get"),params:z$.extend({taskId:G0()})}),PV=k6.merge(hQ),BV=x6.extend({method:u0("tasks/result"),params:z$.extend({taskId:G0()})}),Sp1=k6.loose(),TV=RQ.extend({method:u0("tasks/list")}),EV=vQ.extend({tasks:G1(hQ)}),jV=x6.extend({method:u0("tasks/cancel"),para Line truncated
`);if($===-1)return null;let q=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),fl0(q)}clear(){this._buffer=void 0}}function fl0($){return dr.parse(JSON.parse($))}function i00($){return JSON.stringify($)+`
`}class tR{constructor($=n00.stdin,q=n00.stdout){this._stdin=$,this._stdout=q,this._readBuffer=new sR,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}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((q)=>{let Y=i00($);if(this._stdout.write(Y))q();else this._stdout.once("drain",q)})}}b8();import{dirname as dd,join as Li1}from"node:path";import{fileURLToPath as Fi1}from"node:url";import{spawnSync as i10}from"node:child_process";var LK={name:"seal-use",version:"0.10.23",type:"module",module:"src/server.ts",bin:{"seal-use":"src/cli.ts","seal-home":"src/cli.ts"},scripts:{dev:"bun run --watch src/server.ts",start:"bun run src/server.ts",probe:"bun run src/probe.ts",cli:"bun run src/cli.ts",check:"tsc --noEmit","build:binary":"node scripts/build-binary.mjs","build:plugin":"node scripts/build-plugin.mjs",bump:"bun run scripts/bump-version.ts","dev:override":"bun run scripts/dev-override.ts","dev:link":"bun run scripts/dev-override.ts","openapi:bundle":"bun run scripts/bundle-openapi.ts","openapi:raw":"bun run scripts/generate-raw-openapi.ts",test:"bun test"},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0",archiver:"^8.0.0",exceljs:"^4.4.0","iconv-lite":"^0.7.3",ky:"^2.0.2","pinyin-pro":"^3.29.3",yauzl:"^3.4.0",zod:"^4.4.3"},devDependencies:{"@types/archiver":"^8.0.0","@types/bun":"^1.3.14","@types/yauzl":"^3.4.0","bun-types":"^1.3.14",typescript:"^5.9.3",yaml:"^2.9.0"}};function _o0($,q=LK.version){let Y=$.trim();if(!Y)return null;let z=Y.endsWith("-dirty"),U=z?Y.slice(0,-6):Y,I=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);if(I&&I[1]&&I[2]&&I[3])return{baseVersion:I[1],commitsAhead:Number.parseInt(I[2],10),commit:I[3],dirty:z,describe:Y};let J=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);if(J&&J[1])return{baseVersion:J[1],commitsAhead:0,commit:"",dirty:z,describe:Y};let Q=U.match(/^([0-9a-f]{7,40})$/);if(Q&&Q[1])return{baseVersion:q,commitsAhead:0,commit:Q[1],dirty:z,describe:Y};return null}function Co0($,q,Y,z){let I=Y?`+g${Y}${z?".dirty":""}`:z?"+dirty":"";return`${$}-dev.${q}${I}`}function Ro0($){let q=$?.env,Y=q?.SEAL_BUILD_VERSION??process.env.SEAL_BUILD_VERSION,z=q?.SEAL_BUILD_IS_RELEASE??process.env.SEAL_BUILD_IS_RELEASE,U=q?.SEAL_BUILD_CHANNEL??process.env.SEAL_BUILD_CHANNEL,I=q?.SEAL_BUILD_GIT_BASE??process.env.SEAL_BUILD_GIT_BASE,J=q?.SEAL_BUILD_GIT_COMMITS_AHEAD??process.env.SEAL_BUILD_GIT_COMMITS_AHEAD,Q=q?.SEAL_BUILD_GIT_COMMIT??process.env.SEAL_BUILD_GIT_COMMIT,K=q?.SEAL_BUILD_GIT_DIRTY??process.env.SEAL_BUILD_GIT_DIRTY,H=q?.SEAL_BUILD_GIT_DESCRIBE??process.env.SEAL_BUILD_GIT_DESCRIBE,G=q?.SEAL_FORCE_RELEASE??process.env.SEAL_FORCE_RELEASE,Z=$?.cwd;if(Y){let V=z==="true",w={name:"seal-use",version:Y,channel:U||(V?"release":"dev"),isRelease:V};if(I)w.git={baseVersion:I,commitsAhead:Number.parseInt(J||"0",10),commit:Q||"",dirty:K==="true",describe:H||Y};return w}if(z==="true"||G==="1")return{name:"seal-use",version:LK.version,channel:"release",isRelease:!0};try{let V=i10("git",["describe","--tags","--long","--dirty","--always"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(V.status===0&&V.stdout){let X=_o0(V.stdout.trim(),LK.version);if(X){if(!X.commit){let L=i10("git",["rev-parse","--short","HEAD"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(L.status===0&&L.stdout)X.commit=L.stdout.trim()}return{name:"seal-use",version:Co0(X.baseVersion,X.commitsAhead,X.commit,X.dirty),channel:"dev",isRelease:!1,git:X}}}}catch{}return{name:"seal-use",version:`${LK.version}-dev.0+local`,channel:"dev",isRelease:!1}}var FK=Ro0(),Q1=FK.version,Nv=FK.isRelease,et1=FK.channel;J6();UD();JD();p4();_4();o1();b8();p4();J6();J6();DZ();op();_4();o1();V$();import{existsSync as Ev0}from"node:fs";async function jv0($,q){if(!Ev0($))throw Error(`File not found: ${$}`);let Y=AY($);console.log(JSON.stringify(await DY(Y.fileBuffer,Y.fileName,q),null,2))}async function mA($,q,Y,z,U){if($==="ready"||$==="status"){let I=q??E(U.options.file)??E(U.options.input),J=await RA(Y,z,{filePath:I,webhook:E(U.options.webhook)??E(U.options.selector)});if(console.error(`[webhook-ready] 企业环境: ${J.corp.name} (${J.corp.id}) [${J.stateMode}]`),J.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${J.corp.tenant.name} (${J.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${J.authStatus==="ok"?"OK":`异常 (${J.authError})`}`),console.erro Line truncated
`+`\uD83D\uDC49 查看全部请添加: seal-use corps list --all
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}j0(O.map((A)=>({id:A.id,name:A.name,environment:A.environment??"production",sourceType:A.source.type,provider:A.source.provider??A.source.type,staffId:A.source.staffId,testCorpId:A.testCorpId,prodCorpId:A.prodCorpId,current:A.id===H})));return}if($==="get"||$==="show"){let z=q??E(Y.options.corp);if(!z)throw i4("Usage: seal-use corps get <corpId>");let U=w1(z),I=ki(U.id),J=Vb1(U);j0({id:U.id,name:U.name,environment:U.environment??"production",configFile:I,seal:{url:J,tenantSlug:U.seal.tenantSlug??U.source.tenantSlug,customHeaderNames:U.seal.headers?Object.keys(U.seal.headers):[],customCookieNames:U.seal.cookies?Object.keys(U.seal.cookies):[],endpoints:U.seal.endpoints},source:wb1(U.source),relations:{testCorpId:U.testCorpId,prodCorpId:U.prodCorpId},auth:{refreshTtl:U.auth.refreshTtl}});return}if($==="current"){let z=w1(E(Y.options.corp));j0({id:z.id,name:z.name,environment:z.environment??"production",sourceType:z.source.type,provider:z.source.provider??z.source.type,staffId:z.source.staffId,testCorpId:z.testCorpId,prodCorpId:z.prodCorpId});return}if($==="mark"||$==="mark-test"||$==="mark-prod"){let z=q??E(Y.options.corp);if(!z)throw i4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let U=w1(z),I=$==="mark-test"?"test":$==="mark-prod"?"production":E(Y.options.env)??E(Y.options.environment);if(I!=="production"&&I!=="test")throw i4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(W0(Y.options.confirm)===!0||W0(Y.options.yes)===!0))throw Q9(`Refusing to change environment tag of enterprise '${U.name}' (${U.id}) to '${I}' without --confirm. Marking alters synchronization safety guards.`,`seal-use corps mark ${U.id} --env ${I} --confirm`);let Q=a7(U.id,{environment:I});j0({id:Q.id,name:Q.name,environment:Q.environment,testCorpId:Q.testCorpId,prodCorpId:Q.prodCorpId});return}if($==="bind-test"){let z,U;if(q&&Y.command[3])z=q,U=Y.command[3];else if(q){let Z=E(Y.options.corp),V=E(Y.options["test-corp"])??E(Y.options.testCorp);if(Z)z=Z,U=q;else if(V)z=q,U=V}if(!z||!U)throw i4(`Usage: seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let I=w1(z),J=w1(U);if(I.id===J.id)throw i4(`Cannot bind enterprise '${I.id}' to itself.`);if(I.prodCorpId&&I.prodCorpId!==J.id)throw i4(`Cannot use '${I.id}' as a production enterprise because it is already registered as a test enterprise for '${I.prodCorpId}'. Multi-tier chaining is not permitted.`);if(J.testCorpId&&J.testCorpId!==I.id)throw i4(`Cannot bind '${J.id}' as a test enterprise because it already has a bound test enterprise '${J.testCorpId}'. Multi-tier chaining is not permitted.`);let Q=W0(Y.options.force)===!0;if(I.testCorpId&&I.testCorpId!==J.id||J.prodCorpId&&J.prodCorpId!==I.id){if(!Q)throw Q9(`Enterprise binding conflict: production enterprise '${I.id}' is bound to '${I.testCorpId??"none"}', and test enterprise '${J.id}' is bound to '${J.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,`seal-use corps bind-test ${I.id} ${J.id} --confirm --force`)}if(!(W0(Y.options.confirm)===!0||W0(Y.options.yes)===!0)){let Z=Q?" --force":"";throw Q9(`Refusing to bind test enterprise '${J.name}' (${J.id}) to production enterprise '${I.name}' (${I.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${J.id}' as a test environment.`,`seal-use corps bind-test ${I.id} ${J.id} --confirm${Z}`)}if(I.testCorpId&&I.testCorpId!==J.id)try{a7(I.testCorpId,{prodCorpId:void 0})}catch{}if(J.prodCorpId&&J.prodCorpId!==I.id)try{a7(J.prodCorpId,{testCorpId:void 0})}catch{}let H=a7(I.id,{environment:"production",testCorpId:J.id}),G=a7(J.id,{environment:"test",prodCorpId:I.id});j0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:G.id,name:G.name,environment:G.environment,prodCorpId:G.prodCorpId}});return}if($==="unbind-test"){let z=q??E(Y.options.corp),U=w1(z);if(!U.testCorpId&&!U.prodCorpId){j0({unbound:!1,message:`Enterprise '${U.name}' (${U.id}) does not have an active test enterprise binding.`});return}let I=U.testCorpId?U.id:U.prodCorpId,J=U.testCorpId?U.testCorpId:U.id;if(!(W0(Y.options.confirm)===!0||W0(Y.options.yes)===!0))throw Q9(`Refusing to unbind production enterprise '${I}' and test enterprise '${J}' without --confirm.`,`seal-use corps unbind-test ${U.id} --confirm`);a7(I,{testCorpId:void 0});try{a7(J,{prodCorpId:void 0})}catch{}j0({success:!0,unboundProduction:I,unboundTest:J});return}if($==="sync-test"){let z=q??E(Y.options.corp),U=w1(z);if(!U.testCorpId)throw i4(`Production enterprise '${U.name}' (${U.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${U.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let I=w1(U.testCorpId);if(I.environment!=="test")throw Error(`Target enterprise '${I.name}' (${I.id}) is marked as '${I.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let J=await Z1(U),Q=await Z1(I),[K,H,G,Z,V,X,w,L]=await Promise.all([x1(J,U.seal.endpoints.approvalStylePreferences).catch(()=>({})),x1(Q,I.seal.endpoints.approvalStylePreferences).catch(()=>({})),b6(J),b6(Q),B$(J).catch(()=>[]),B$(Q).catch(()=>[]),d3(J,{limit:100}).catch(()=>({articles:[]})),d3(Q,{limit:100}).catch(()=>({articles:[]}))]),F=(w.articles||[]).filter((Q0)=>!Q0.isDeleted),O=(L.articles||[]).filter((Q0)=>!Q0.isDeleted),A=new Map(O.map((Q0)=>[Q0.title.trim(),Q0])),B=[],P=[],T=new Set(F.map((Q0)=>Q0.title.trim()));for(let Q0 of F){let v0=Q0.title.trim(),f0=A.get(v0);if(!f0)B.push(Q0);else{let c0=f0.content!==Q0.content,R1=(f0.purpose??"")!==(Q0.purpose??""),a0=f0.enabled!==Q0.enabled,r1=f0.contentType!==Q0.contentType,F1=(f0.status??"")!==(Q0.status??""),b1=JSON.stringify([...f0.scenarios??[]].sort())!==JSON.stringify([...Q0.scenarios??[]].sort()),$1=JSON.stringify([...f0.tags??[]].sort())!==JSON.stringify([...Q0.tags??[]].sort());if(c0||R1||a0||r1||F1||b1||$1)P.push({testId:f0.id,prodDoc:Q0,reasons:[...c0?["content"]:[],...R1?["purpose"]:[],...a0?["enabled"]:[],...r1?["contentType"]:[],...F1?["status"]:[],...b1?["scenarios"]:[],...$1?["tags"]:[]]})}}let y=O.filter((Q0)=>!T.has(Q0.title.trim())),k=[...V].sort((Q0,v0)=>v0.versionNumber-Q0.versionNumber)[0],R=k?.versionNumber,n=([...X].sort((Q0,v0)=>v0.versionNumber-Q0.versionNumber)[0]?.versionNumber??0)+1,g=ch0(U.name,R,X),i=E(Y.options["version-name"])??E(Y.options.versionName)??ph0(U.name,R,g,n),$0={...H,tone:K.tone,language:K.language,detailLevel:K.detailLevel,outputFormat:K.outputFormat,examples:K.examples??[],prohibitedPhrases:K.prohibitedPhrases??[],customInstructions:K.customInstructions,decisionPreferences:K.decisionPreferences,thinkingDepthPreference:K.thinkingDepthPreference};if(W0(Y.options["dry-run"])===!0||W0(Y.options.dryRun)===!0){j0({dryRun:!0,source:{id:U.id,name:U.name,environment:U.environment,latestPublishedVersion:k?{versionNumber:k.versionNumber,versionName:k.versionName}:null,documentsCount:F.length},target:{id:I.id,name:I.name,environment:I.environment},versionMappingPlan:{sourceProdVersionNumber:R??null,sourceProdVersionName:k?.versionName??null,targetTestExpectedVersionNumber:n,targetTestPublishVersionName:i,iteration:g},preferencesDiff:{decisionPreferences:{before:H.decisionPreferences,after:K.decisionPreferences},thinkingDepthPreference:{before:H.thinkingDepthPreference,after:K.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:G.rules.length,targetExistingDraftRuleCount:Z.rules.length,toDeleteCount:Z.rules.length,toCreateCount:G.rules.length,rulesToSync:G.rules.map((Q0,v0)=>({index:v0+1,sourceRuleId:Q0.id,sourceRuleCode:Q0.code??v0+1,expectedTargetCode:`rule-${v0+1}`,description:Q0.description,scope:Q0.scope,strictness:Q0.strictness}))},documentsPlan:{sourceDocumentCount:F.length,targetExistingDocumentCount:O.length,toCreateCount:B.length,toCreate:B.map((Q0)=>({title:Q0.title,purpose:Q0.purpose,contentType:Q0.contentType,scenarios:Q0.scenarios})),toUpdateCount:P.length,toUpdate:P.map((Q0)=>({targetDocumentId:Q0.testId,title:Q0.prodDoc.title,reasons:Q0.reasons})),toDeleteCount:y.length,toDelete:y.map((Q0)=>({targetDocumentId:Q0.id,title:Q0.title}))},publishingPlan:{targetCorpId:I.id,publishVersionName:i,publishTarget:"test"},hosecloudSyncPlan:(()=>{if(U.source.type!=="hose")return{sourceType:U.source.type,skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let Q0=(K.integrations??[]).filter((c0)=>c0.type==="hosecloud"),v0=new Set,f0=Q0.filter((c0)=>{let R1=c0.corporationId??U.id;if(v0.has(R1))return!1;return v0.add(R1),!0});return{sourceType:"hose",outboundName:sh0(U.name),targetMode:"assisted",integrationsCount:f0.length,integrations:f0.map((c0)=>({corporationId:c0.corporationId,apiOrigin:c0.apiOrigin,customApiUrl:c0.customApiUrl}))}})(),productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(W0(Y.options.yes)===!0||W0(Y.options.confirm)===!0))throw Q9(`Refusing to overwrite test enterprise '${I.name}' (${I.id}) with preferences, ${G.rules.length} draft rules, and ${F.length} knowledge documents from production enterprise '${U.name}' (${U.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,`seal-use corps sync-test ${U.id} --yes`);await h5(Q,$0,I.seal.endpoints.approvalStylePreferences);let p=[];for(let Q0 of y)await iw(Q,Q0.id),p.push({id:Q0.id,title:Q0.title});let d=[];for(let Q0 of P)await bw(Q,Q0.testId,{title:Q0.prodDoc.title,purpose:Q0.prodDoc.purpose,content:Q0.prodDoc.content,contentType:Q0.prodDoc.contentType,status:Q0.prodDoc.status,enabled:Q0.prodDoc.ena Line truncated
Run 'seal-use corps bind-test ${U.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,
or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`);J=U}else if(J=w1(U.testCorpId),J.environment!=="test"&&!Y)throw Error(`Target enterprise '${J.name}' (${J.id}) is marked as '${J.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`);let Q=j(z.options.recordId)??j(z.options["record-id"])??j(z.options.id),K=j(z.options.recordIds)??j(z.options["record-ids"]),w=K?K.split(",").map((n)=>n.trim()).filter(Boolean):void 0,G=j(z.options.sn)??j(z.options.documentSn)??j(z.options["document-sn"]),H=j(z.options.sns)??j(z.options["document-sns"]),W=H?H.split(",").map((n)=>n.trim()).filter(Boolean):void 0,V=_0(z.options.limit)??(!Q&&!w&&!G&&!W?1:void 0),X=j(z.options.status),L=j(z.options.startDate)??j(z.options["start-date"]),D=j(z.options.endDate)??j(z.options["end-date"]),O=await J1(U),A=U.id===J.id?O:await J1(J),T=j(z.options.webhook)??j(z.options.selector),M=j(z.options.snSuffix)??j(z.options["sn-suffix"]),v=j(z.options.snPrefix)??j(z.options["sn-prefix"]),x=j(z.options.docIdSuffix)??j(z.options["doc-id-suffix"]),h=j(z.options.docIdPrefix)??j(z.options["doc-id-prefix"]),k=V0(z.options.dryRun)??V0(z.options["dry-run"]),E={recordId:Q,recordIds:w,sn:G,sns:W,limit:V,status:X,startDate:L,endDate:D};console.error(`[corps-replay-test] 正式企业「${U.name}」(${U.id}) -> 测试企业「${J.name}」(${J.id})`);let f=await tU({query:E,sourceClient:O,targetClient:A,sourceCorp:U,targetCorp:J,webhookSelector:T,snPrefix:v,snSuffix:M,docIdPrefix:h,docIdSuffix:x,dryRun:k});if(k){console.error(`[corps-replay-test] 预览模式:已成功从 ${U.name} 提取单据并转换为 Webhook Payload(未实际推送)。`),console.log(JSON.stringify(f,null,2));return}if(f.success)if(f.totalCount===1&&f.replayedDocument)console.error(`\uD83D\uDFE2 成功重放单据「${f.replayedDocument.documentSN}」至 ${J.name} (${f.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDFE2 成功重放 ${f.successCount} 条单据(来自「${U.name}」)至「${J.name}」(${f.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34 单据重放部分或全部失败(成功 ${f.successCount} 条,失败 ${f.failureCount} 条)至「${J.name}」`);if(console.error(`\uD83D\uDC49 Next action: seal-use approval-runs list --corp ${J.id} --limit ${f.totalCount}`),console.log(JSON.stringify(f,null,2)),!f.success)process.exitCode=1;return}if($==="switch"){let q=I;if(!q)throw Error("Usage: seal-use corps switch <corpId>");let U=K4();if(!U.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-use config mode stateful` first.");let Y=w1(q);yI({...U,stateful:!0,defaultCorpId:Y.id}),T0({current:!0,id:Y.id,name:Y.name});return}if($==="probe-hose"){await $X1(s6(z.json));return}if($==="hose-staffs"){await IX1(s6(z.json));return}if($==="add-hose"){await zX1(s6(z.json));return}if($==="add-seal"){await qX1(s6(z.json));return}if($==="add-link"){let q=I??j(z.options.link)??j(z.options.url);if(!q)throw Error("Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]");await UX1(q,j(z.options.name),V0(z.options.overwrite)===!0);return}throw Error(`Unknown corps command: ${$??""}. Run 'seal-use help' for available commands.`)}function LF0($){return[...$].slice(0,6).join("")+"(Seal测)"}async function eZ1($,I,z,q){if($.source.type!=="hose")return{skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let U=($.source.appKey??$.source.key)?.trim(),Y=($.source.appSecurity??$.source.password)?.trim();if(!U||!Y)return{skipped:!0,reason:"prod hose source missing appKey/appSecurity (or key/password)"};let[J,Q]=await Promise.all([E1(z,$.seal.endpoints.approvalStylePreferences).catch(()=>({})),E1(q,I.seal.endpoints.approvalStylePreferences).catch(()=>({}))]),K=(J.integrations??[]).filter((A)=>A.type==="hosecloud");if(K.length===0)return{skipped:!0,reason:"prod Seal enterprise has no hosecloud integrations configured"};let w=new Set,G=[];for(let A of K){let T=A.corporationId??$.id;if(!w.has(T))w.add(T),G.push(A)}let H=Q.integrations??[],W=new Map(H.filter((A)=>A.type==="hosecloud").map((A)=>[A.corporationId,A])),V=LF0($.name),X=[],L=G.map((A)=>{let T=W.get(A.corporationId),M=T?.signKey??tZ1(6).toString("hex");return X.push({signKey:M,outboundName:V,corporationId:A.corporationId,action:T?"updated":"created"}),{type:"hosecloud",signKey:M,outboundName:V,mode:"assisted",apiKey:U,apiSecret:Y,apiOrigin:A.apiOrigin,...A.customApiUrl?{customApiUrl:A.customApiUrl}:{},corporationId:A.corporationId}}),D=H.filter((A)=>A.type!=="hosecloud"),O={...Q,integrations:[...D,...L]};return await i8(q,O,I.seal.endpoints.approvalStylePreferences),{skipped:!1,synced:X}}async function $X1($){let I=L9($,"appKey"),z=L9($,"appSecurity"),q=b1($,"domain"),U=await tz(I,z,q),Y=await SW(U.domain,U.openapiToken).catch(()=>[]) Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${E.length} candidate administrators:
- ${f}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!L)if(!G&&Y)L=Y;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let D=b1($,"id")??W,O=V??W,A=b1($,"sealUrl")??`https://${W.toLowerCase()}.sealai.cc`,T={id:D,name:O,environment:"production",seal:{url:A,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:H,appKey:z,appSecurity:q,corpId:W,staffId:L},auth:{refreshTtl:300}};if(G)vW(D),await VY(T);let M=zx();WF0(M,{recursive:!0,mode:448});let v=ZF0(M,`${bO(D)}.json`);if(HF0(v)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${v}. Pass "overwrite": true to replace it.`);VF0(v,`${JSON.stringify(T,null,2)}
`,{mode:384}),T0({id:D,name:O,corpId:W,domain:H,staffId:L,verified:G,path:v})}async function qX1($){let I=L9($,"token"),z=(b1($,"sealUrl")??b1($,"url")??"").replace(/\/+$/,"");if(!z)throw Error("Missing required JSON field: sealUrl");let q=Bk($,"expiresIn")??2592000,U=$.force===!0||$.verify===!1?!1:!0,Y=DF0($),J=U?await YX1(z,I,p4(Y)):void 0;OF0($,{token:I,sealUrl:z,expiresIn:q,verify:U,remote:J,custom:Y})}function DF0($){return{headers:au.parse($.headers),cookies:su.parse($.cookies)}}async function UX1($,I,z){let q=await RW($),U=d6(q.sealUrl,q.token),Y=await v6(U),J={user:Y.user,tenant:Y.tenant};gW(q.corpId,J.tenant),OF0({id:q.corpId,corpId:q.corpId,name:I,provider:"hosecloud",overwrite:z},{token:q.token,sealUrl:q.sealUrl,expiresIn:q.expiresIn,verify:!0,remote:J})}function OF0($,I){let{token:z,sealUrl:q,expiresIn:U,verify:Y,remote:J}=I,Q=I.custom??DF0($),K=J?.user,w=J?.tenant,G=b1($,"tenantSlug")??t7(w?.tenantSlug),H=b1($,"tenantId")??t7(w?.id),W=b1($,"tenantName")??t7(w?.name),V=b1($,"id")??G??H;if(!V)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let X=b1($,"staffId")??t7(K?.providerUserId)??t7(K?.id)??"seal",L=b1($,"provider")??t7(K?.provider)??t7(w?.providerConfig?.provider),D=b1($,"corpId")??G??H??V,O={id:V,name:b1($,"name")??W??V,environment:"production",seal:{url:q,tenantSlug:G,headers:Q.headers,cookies:Q.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:z,sealUrl:q,expiresIn:U,staffId:X,corpId:D,tenantId:H,tenantSlug:G,tenantName:W,providerUserId:t7(K?.providerUserId),provider:L},auth:{refreshTtl:300}},A=zx();WF0(A,{recursive:!0,mode:448});let T=ZF0(A,`${bO(V)}.json`);if(HF0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);VF0(T,`${JSON.stringify(O,null,2)}
`,{mode:384}),T0({id:V,name:O.name,tenantId:H,tenantSlug:G,verified:Y,path:T})}async function YX1($,I,z={}){let q=d6($,I,z),U=await v6(q);return{user:U.user??{},tenant:U.tenant??{}}}function t7($){return typeof $==="string"&&$?$:void 0}F3();w$();c4();A4();G4();u1();async function FF0($,I){let z=await RW($),q=d6(z.sealUrl,z.token),U=await v6(q);gW(z.corpId,U.tenant);let Y=await ez(q,{note:I});T0({tenant:{id:U.tenant.id,name:U.tenant.name,tenantSlug:U.tenant.tenantSlug,corpId:z.corpId},user:{id:U.user.id,name:U.user.name,providerUserId:U.user.providerUserId,isAdmin:U.user.isAdmin},delegation:Y,expiresIn:z.expiresIn})}async function NF0($,I,z,q,U){if($==="list"){await N0("seal_delegation_list",z,q,{},Z0(U.options));return}if($==="create"){let Y=j(U.options.note)??(I?[I,...U.command.slice(2)].join(" "):void 0);await N0("seal_delegation_create",z,q,{note:Y},Z0(U.options));return}if($==="revoke"){let Y=I??j(U.options.tokenId);if(!Y)throw Error("Usage: seal-use delegation revoke <tokenId>");await N0("seal_delegation_revoke",z,q,{tokenId:Y},Z0(U.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}A4();G4();u1();c4();k$();import{readFileSync as JX1}from"node:fs";async function MF0($,I,z,q,U,Y){if(!$||$==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`);J=U}else if(J=w1(U.testCorpId),J.environment!=="test"&&!I)throw Error(`Target enterprise '${J.name}' (${J.id}) is marked as '${J.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`);let Q=E(Y.options.recordId)??E(Y.options["record-id"])??E(Y.options.id),K=E(Y.options.recordIds)??E(Y.options["record-ids"]),H=K?K.split(",").map((n)=>n.trim()).filter(Boolean):void 0,G=E(Y.options.sn)??E(Y.options.documentSn)??E(Y.options["document-sn"]),Z=E(Y.options.sns)??E(Y.options["document-sns"]),V=Z?Z.split(",").map((n)=>n.trim()).filter(Boolean):void 0,X=g0(Y.options.limit)??(!Q&&!H&&!G&&!V?1:void 0),w=E(Y.options.status),L=E(Y.options.startDate)??E(Y.options["start-date"]),F=E(Y.options.endDate)??E(Y.options["end-date"]),O=await Z1(U),A=U.id===J.id?O:await Z1(J),B=E(Y.options.webhook)??E(Y.options.selector),P=E(Y.options.snSuffix)??E(Y.options["sn-suffix"]),T=E(Y.options.snPrefix)??E(Y.options["sn-prefix"]),y=E(Y.options.docIdSuffix)??E(Y.options["doc-id-suffix"]),v=E(Y.options.docIdPrefix)??E(Y.options["doc-id-prefix"]),k=W0(Y.options.dryRun)??W0(Y.options["dry-run"]),R={recordId:Q,recordIds:H,sn:G,sns:V,limit:X,status:w,startDate:L,endDate:F};console.error(`[corps-replay-test] 正式企业「${U.name}」(${U.id}) -> 测试企业「${J.name}」(${J.id})`);let c=await nI({query:R,sourceClient:O,targetClient:A,sourceCorp:U,targetCorp:J,webhookSelector:B,snPrefix:T,snSuffix:P,docIdPrefix:v,docIdSuffix:y,dryRun:k});if(k){console.error(`[corps-replay-test] 预览模式:已成功从 ${U.name} 提取单据并转换为 Webhook Payload(未实际推送)。`),console.log(JSON.stringify(c,null,2));return}if(c.success)if(c.totalCount===1&&c.replayedDocument)console.error(`\uD83D\uDFE2 成功重放单据「${c.replayedDocument.documentSN}」至 ${J.name} (${c.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDFE2 成功重放 ${c.successCount} 条单据(来自「${U.name}」)至「${J.name}」(${c.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34 单据重放部分或全部失败(成功 ${c.successCount} 条,失败 ${c.failureCount} 条)至「${J.name}」`);if(console.error(`\uD83D\uDC49 Next action: seal-use approval-runs list --corp ${J.id} --limit ${c.totalCount}`),console.log(JSON.stringify(c,null,2)),!c.success)process.exitCode=1;return}if($==="switch"){let z=q;if(!z)throw Error("Usage: seal-use corps switch <corpId>");let U=B4();if(!U.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-use config mode stateful` first.");let I=w1(z);eq({...U,stateful:!0,defaultCorpId:I.id}),j0({current:!0,id:I.id,name:I.name});return}if($==="probe-hose"){await Fb1(R8(Y.json));return}if($==="hose-staffs"){await Ob1(R8(Y.json));return}if($==="add-hose"){await Mb1(R8(Y.json));return}if($==="add-seal"){await Nb1(R8(Y.json));return}if($==="add-link"){let z=q??E(Y.options.link)??E(Y.options.url);if(!z)throw Error("Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]");await Db1(z,E(Y.options.name),W0(Y.options.overwrite)===!0);return}throw Error(`Unknown corps command: ${$??""}. Run 'seal-use help' for available commands.`)}function sh0($){return[...$].slice(0,6).join("")+"(Seal测)"}async function Lb1($,q,Y,z){if($.source.type!=="hose")return{skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let U=($.source.appKey??$.source.key)?.trim(),I=($.source.appSecurity??$.source.password)?.trim();if(!U||!I)return{skipped:!0,reason:"prod hose source missing appKey/appSecurity (or key/password)"};let[J,Q]=await Promise.all([x1(Y,$.seal.endpoints.approvalStylePreferences).catch(()=>({})),x1(z,q.seal.endpoints.approvalStylePreferences).catch(()=>({}))]),K=(J.integrations??[]).filter((A)=>A.type==="hosecloud");if(K.length===0)return{skipped:!0,reason:"prod Seal enterprise has no hosecloud integrations configured"};let H=new Set,G=[];for(let A of K){let B=A.corporationId??$.id;if(!H.has(B))H.add(B),G.push(A)}let Z=Q.integrations??[],V=new Map(Z.filter((A)=>A.type==="hosecloud").map((A)=>[A.corporationId,A])),X=sh0($.name),w=[],L=G.map((A)=>{let B=V.get(A.corporationId),P=B?.signKey??Xb1(6).toString("hex");return w.push({signKey:P,outboundName:X,corporationId:A.corporationId,action:B?"updated":"created"}),{type:"hosecloud",signKey:P,outboundName:X,mode:"assisted",apiKey:U,apiSecret:I,apiOrigin:A.apiOrigin,...A.customApiUrl?{customApiUrl:A.customApiUrl}:{},corporationId:A.corporationId}}),F=Z.filter((A)=>A.type!=="hosecloud"),O={...Q,integrations:[...F,...L]};return await h5(z,O,q.seal.endpoints.approvalStylePreferences),{skipped:!1,synced:w}}async function Fb1($){let q=O3($,"appKey"),Y=O3($,"appSecurity"),z=q4($,"domain"),U=await Sz(q,Y,z),I=await _w(U.domain,U.openapiToken).catch(()=>[]) Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${R.length} candidate administrators:
- ${c}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!L)if(!G&&I)L=I;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let F=q4($,"id")??V,O=X??V,A=q4($,"sealUrl")??`https://${V.toLowerCase()}.sealai.cc`,B={id:F,name:O,environment:"production",seal:{url:A,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:Z,appKey:Y,appSecurity:z,corpId:V,staffId:L},auth:{refreshTtl:300}};if(G)Pw(F),await jJ(B);let P=xi();mh0(P,{recursive:!0,mode:448});let T=oh0(P,`${nA(F)}.json`);if(dh0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);lh0(T,`${JSON.stringify(B,null,2)}
`,{mode:384}),j0({id:F,name:O,corpId:V,domain:Z,staffId:L,verified:G,path:T})}async function Nb1($){let q=O3($,"token"),Y=(q4($,"sealUrl")??q4($,"url")??"").replace(/\/+$/,"");if(!Y)throw Error("Missing required JSON field: sealUrl");let z=Jd($,"expiresIn")??2592000,U=$.force===!0||$.verify===!1?!1:!0,I=th0($),J=U?await Ab1(Y,q,L6(I)):void 0;ah0($,{token:q,sealUrl:Y,expiresIn:z,verify:U,remote:J,custom:I})}function th0($){return{headers:vi.parse($.headers),cookies:hi.parse($.cookies)}}async function Db1($,q,Y){let z=await Bw($),U=N8(z.sealUrl,z.token),I=await z8(U),J={user:I.user,tenant:I.tenant};Tw(z.corpId,J.tenant),ah0({id:z.corpId,corpId:z.corpId,name:q,provider:"hosecloud",overwrite:Y},{token:z.token,sealUrl:z.sealUrl,expiresIn:z.expiresIn,verify:!0,remote:J})}function ah0($,q){let{token:Y,sealUrl:z,expiresIn:U,verify:I,remote:J}=q,Q=q.custom??th0($),K=J?.user,H=J?.tenant,G=q4($,"tenantSlug")??Z2(H?.tenantSlug),Z=q4($,"tenantId")??Z2(H?.id),V=q4($,"tenantName")??Z2(H?.name),X=q4($,"id")??G??Z;if(!X)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let w=q4($,"staffId")??Z2(K?.providerUserId)??Z2(K?.id)??"seal",L=q4($,"provider")??Z2(K?.provider)??Z2(H?.providerConfig?.provider),F=q4($,"corpId")??G??Z??X,O={id:X,name:q4($,"name")??V??X,environment:"production",seal:{url:z,tenantSlug:G,headers:Q.headers,cookies:Q.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:Y,sealUrl:z,expiresIn:U,staffId:w,corpId:F,tenantId:Z,tenantSlug:G,tenantName:V,providerUserId:Z2(K?.providerUserId),provider:L},auth:{refreshTtl:300}},A=xi();mh0(A,{recursive:!0,mode:448});let B=oh0(A,`${nA(X)}.json`);if(dh0(B)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${B}. Pass "overwrite": true to replace it.`);lh0(B,`${JSON.stringify(O,null,2)}
`,{mode:384}),j0({id:X,name:O.name,tenantId:Z,tenantSlug:G,verified:I,path:B})}async function Ab1($,q,Y={}){let z=N8($,q,Y),U=await z8(z);return{user:U.user??{},tenant:U.tenant??{}}}function Z2($){return typeof $==="string"&&$?$:void 0}E9();b8();J6();p4();_4();o1();async function eh0($,q){let Y=await Bw($),z=N8(Y.sealUrl,Y.token),U=await z8(z);Tw(Y.corpId,U.tenant);let I=await kz(z,{note:q});j0({tenant:{id:U.tenant.id,name:U.tenant.name,tenantSlug:U.tenant.tenantSlug,corpId:Y.corpId},user:{id:U.user.id,name:U.user.name,providerUserId:U.user.providerUserId,isAdmin:U.user.isAdmin},delegation:I,expiresIn:Y.expiresIn})}async function $g0($,q,Y,z,U){if($==="list"){await P0("seal_delegation_list",Y,z,{},F0(U.options));return}if($==="create"){let I=E(U.options.note)??(q?[q,...U.command.slice(2)].join(" "):void 0);await P0("seal_delegation_create",Y,z,{note:I},F0(U.options));return}if($==="revoke"){let I=q??E(U.options.tokenId);if(!I)throw Error("Usage: seal-use delegation revoke <tokenId>");await P0("seal_delegation_revoke",Y,z,{tokenId:I},F0(U.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}p4();_4();o1();J6();V$();import{readFileSync as Pb1}from"node:fs";async function qg0($,q,Y,z,U,I){if(!$||$==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
`+`支持的审批系统与发布目标:
`+` • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>
@@ -668,22 +926,22 @@ 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 J=$==="hosecloud",Q=$==="hosecloud"?I:$,K=$==="hosecloud"?z:I;if(!J)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(Q==="requirements"){await N0("seal_deploy_hosecloud_requirements",q,U,{},Z0(Y.options));return}if(Q==="list"){await N0("seal_deploy_hosecloud_list",q,U,{},Z0(Y.options));return}if(Q==="get"){let w=K??j(Y.options.signKey)??j(Y.options["sign-key"]);if(!w){let H=((await E1(q)).integrations??[]).filter((W)=>W.type==="hosecloud");if(H.length===0)throw Error(`当前企业 (${U.name}) 尚未添加合思发布配置。
`+" • 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 J=$==="hosecloud",Q=$==="hosecloud"?q:$,K=$==="hosecloud"?Y:q;if(!J)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(Q==="requirements"){await P0("seal_deploy_hosecloud_requirements",z,U,{},F0(I.options));return}if(Q==="list"){await P0("seal_deploy_hosecloud_list",z,U,{},F0(I.options));return}if(Q==="get"){let H=K??E(I.options.signKey)??E(I.options["sign-key"]);if(!H){let Z=((await x1(z)).integrations??[]).filter((V)=>V.type==="hosecloud");if(Z.length===0)throw Error(`当前企业 (${U.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${U.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${U.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let W of H){let V=W.outboundName??"SealAI 审批",X=W.signKey,L=W.apiOrigin??"production";console.error(` • "${V}" (signKey: ${X}, 环境: ${L})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${X} --corp ${U.id}
`)}throw new N4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,H.length===1?`seal-use deploy hosecloud get ${H[0].signKey} --corp ${U.id}`:void 0)}await N0("seal_deploy_hosecloud_get",q,U,{signKey:w},Z0(Y.options));return}if(Q==="status"){await N0("seal_deploy_hosecloud_status",q,U,{},Z0(Y.options));return}if(Q==="configure"){let w=j(Y.options.input),G=w?JSON.parse(JX1(w,"utf8")):s6(Y.json);if(!G||Object.keys(G).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await N0("seal_deploy_hosecloud_configure",q,U,{...G,dryRun:V0(Y.options.dryRun)??V0(Y.options["dry-run"])},Z0(Y.options));return}if(Q==="sync"){let w=K??j(Y.options.signKey)??j(Y.options["sign-key"]),G=V0(Y.options.auto)??V0(Y.options.yes);if(!w){let W=((await E1(q)).integrations??[]).filter((X)=>X.type==="hosecloud");if(W.length===0)throw Error(`当前企业 (${U.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${U.id}`);let V=W[0];if(V&&W.length===1&&G){let X=V.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${X})`),await N0("seal_deploy_hosecloud_sync",q,U,{signKey:X},Z0(Y.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${U.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of W){let L=X.outboundName??"SealAI 审批",D=X.signKey,O=X.apiOrigin??"production";console.error(` • "${L}" (signKey: ${D}, 环境: ${O})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${D} --corp ${U.id}
`)}if(W.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${U.id}
`);throw new N4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,W.length===1?`seal-use deploy hosecloud sync ${W[0].signKey} --corp ${U.id}`:void 0)}await N0("seal_deploy_hosecloud_sync",q,U,{signKey:w},Z0(Y.options));return}throw Error(`Unknown deploy hosecloud action: ${Q??""}. Available: requirements, list, get, status, configure, sync.`)}Wx();import{accessSync as MX1,constants as AX1,existsSync as x6,readdirSync as PX1}from"node:fs";import{homedir as TX1}from"node:os";import{join as O9}from"node:path";G9();import{existsSync as pk,mkdirSync as hF0,rmSync as OX1,writeFileSync as FX1}from"node:fs";import{homedir as SF0}from"node:os";import{dirname as NX1,join as ck}from"node:path";var AF0=`---
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let X=V.outboundName??"SealAI 审批",w=V.signKey,L=V.apiOrigin??"production";console.error(` • "${X}" (signKey: ${w}, 环境: ${L})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${w} --corp ${U.id}
`)}throw new b4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,Z.length===1?`seal-use deploy hosecloud get ${Z[0].signKey} --corp ${U.id}`:void 0)}await P0("seal_deploy_hosecloud_get",z,U,{signKey:H},F0(I.options));return}if(Q==="status"){await P0("seal_deploy_hosecloud_status",z,U,{},F0(I.options));return}if(Q==="configure"){let H=E(I.options.input),G=H?JSON.parse(Pb1(H,"utf8")):R8(I.json);if(!G||Object.keys(G).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await P0("seal_deploy_hosecloud_configure",z,U,{...G,dryRun:W0(I.options.dryRun)??W0(I.options["dry-run"])},F0(I.options));return}if(Q==="sync"){let H=K??E(I.options.signKey)??E(I.options["sign-key"]),G=W0(I.options.auto)??W0(I.options.yes);if(!H){let V=((await x1(z)).integrations??[]).filter((w)=>w.type==="hosecloud");if(V.length===0)throw Error(`当前企业 (${U.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${U.id}`);let X=V[0];if(X&&V.length===1&&G){let w=X.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${w})`),await P0("seal_deploy_hosecloud_sync",z,U,{signKey:w},F0(I.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${U.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let w of V){let L=w.outboundName??"SealAI 审批",F=w.signKey,O=w.apiOrigin??"production";console.error(` • "${L}" (signKey: ${F}, 环境: ${O})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${F} --corp ${U.id}
`)}if(V.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${U.id}
`);throw new b4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,V.length===1?`seal-use deploy hosecloud sync ${V[0].signKey} --corp ${U.id}`:void 0)}await P0("seal_deploy_hosecloud_sync",z,U,{signKey:H},F0(I.options));return}throw Error(`Unknown deploy hosecloud action: ${Q??""}. Available: requirements, list, get, status, configure, sync.`)}ti();import{accessSync as ub1,constants as fb1,existsSync as X8,readdirSync as bb1}from"node:fs";import{homedir as ib1}from"node:os";import{join as N3}from"node:path";Q3();import{existsSync as Pd,mkdirSync as Xg0,rmSync as yb1,writeFileSync as xb1}from"node:fs";import{homedir as Vg0}from"node:os";import{dirname as kb1,join as Bd}from"node:path";var Yg0=`---
name: seal-use
description: "v0.10.20: 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.23: 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.20
short-description: Seal tenant and Hose approval automation (v0.10.20)
version: 0.10.23
short-description: Seal tenant and Hose approval automation (v0.10.23)
---
# Seal Use (v0.10.20)
# Seal Use (v0.10.23)
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.
@@ -765,7 +1023,7 @@ seal-use corps list
- 规则本地工作流: \`seal-use rules pull\` 导出草稿规则,\`rules lint\` 做质量检查,\`rules push --dry-run\` 预览增量更新,确认后用 \`--yes\` 写入;\`rules map\` 查询 \`corps sync-test\` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 \`references/rule-lightweight.md\` 和 \`references/cli.md\`。
- 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|sourceDocumentId|id] --corp <corpId>\`, \`approval-runs count\`, \`analytics insight|risks|performance|analyze\`, 以及 \`approval-runs export\`(Excel 报表);需要追踪单据时再使用 \`url\` 或 \`bridge\`。
- 审核大盘统计与去重分析: \`seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp <corpId>\`, \`approval-runs count\`, \`analytics insight|risks|performance|analyze\`, 以及 \`approval-runs export\`(Excel 报表,文件名强制追加精确到分钟的 \`_YYYYMMDD_HHmm\` 时间戳后缀防止覆盖;支持 \`--sn <SN1,SN2>\` 定向筛选极速导出并跳过全量分页;追加 \`--with-flow\` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,200 条以上单据约增加 30 秒);需要追踪单据时再使用 \`url\` 或 \`bridge\`。
- User-facing 合思 authorization link (合思/易快报授权): \`seal-use auth hose-link --corp <corpId> --expire 7200\`; read \`references/hose-enterprise-auth.md\`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink.
- Delegation links management: \`seal-use delegation list --corp <corpId>\`, \`create [--note ...] --corp <corpId>\`, \`create --from-link <url> [--note ...]\`, \`revoke <tokenId> --corp <corpId>\`.
- User & Contacts Management (用户搜索、激活与一键代生成授权): \`seal-use users search [keyword] --corp <corpId>\`, \`users delegation <userIdOrPhone> --corp <corpId>\` (仅适用于 Seal 本地创建的账号 \`provider: local\`;对合思同步账号系统拒绝重置密码,需改用 \`auth hose-link\`), \`users activate <userId> --corp <corpId>\`, \`users create --name ... --phone ... --corp <corpId>\`, \`users reset-password <userId> --corp <corpId>\`, \`users get <userId> --corp <corpId>\`, \`users delete <userId> --corp <corpId>\`.
@@ -773,8 +1031,8 @@ 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 ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>\` 检查企业环境、租户连通性、已激活通道与材料包预检;\`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\` 的官方服务端导入流程相互独立。
- Webhook 准备看板与审批回调管理: \`seal-use webhook ready [<资源包.zip>] [--webhook <idOrName>] --corp <corpId>\` 检查企业环境、租户连通性、已激活通道与资源包预检;\`seal-use webhook <list|get|add|update|delete> --corp <corpId>\`.
- Webhook 资源包管理 (Webhook Resource Pack): \`seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>\` 从线上审核记录直接打包导出为标准 Webhook 资源包(包含根目录 \`信息表.xlsx\` 与下载好的单据附件),便于通过邮件/微信等第三方渠道离线分发;\`seal-use webhook resource-pack preview <资源包.zip> --corp <corpId>\` 本地预检单据与附件;\`seal-use webhook resource-pack push <资源包.zip> [--webhook <idOrName>] --corp <corpId>\` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 \`--webhook\`)。CLI 简写别名 \`pack\`,旧名 \`material-pack\` 完整向下兼容保留。每个 Webhook 可配置资源包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。资源包格式:ZIP 根目录名 = \`documentId\`(或 \`documentId@annotation\`),Excel 附件列以 \`[附件]\` 为前缀(如 \`[附件]合同协议\`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明附件的单据必须有对应根目录,ZIP 中的文件必须在某个 \`[附件]\` 列中声明)。详见 \`references/cli.md\` 中 "Webhook Resource Pack Workflow" 一节。它与 Seal 官方在模拟测试中使用的 \`simulation material_pack\` 流程相互独立,避免混淆。
- 审批记录转 Webhook 重放 (Universal Record Replay): \`seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]\` 以及生产测专用快捷命令 \`seal-use corps replay-test [<prodCorpId>] [--force]\`。通用支持从历史审批记录(Webhook 来源、Hose 来源等)汲取结构化表单与明细字段,自动清洗规范化字段类型,支持按状态/数量批量重放到目标企业 Webhook 触发审批。默认推荐并导向测试企业(测试企业无 Webhook 时自动开通辅助模式通道并锁定环境隔离);若用户未绑定测试企业或明确要求向生产企业重放,支持通过 \`--force\` 显式执行,方便环境回归验证与 Bad Case 靶向调试。
- HTTP REST API & Docs Server: \`seal-use http [--port 8787] [--host 127.0.0.1]\` (提供 \`/docs\` 交互文档、\`/openapi.json\`、\`POST /api/cli\` 与 \`/v1/*\` REST API)。
@@ -836,6 +1094,10 @@ seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use approval-runs export --corp <corpId> --downloads --completed-only
# Add --with-flow to also populate E人工行为 / E人工意见 columns (Hose Open API, adds ~30s):
seal-use approval-runs export --corp <corpId> --downloads --with-flow
# Target specific document SNs for instant export without full pagination:
seal-use approval-runs export --corp <corpId> --sn B26002307,B26002144 --with-flow --downloads
seal-use analytics insight --corp <corpId>
seal-use contacts departments --corp <corpId>
seal-use data invoices --corp <corpId> --limit 20
@@ -859,7 +1121,7 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
- \`references/enterprise-onboarding.md\`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- \`references/approval-run-lightweight.md\`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- \`references/rule-lightweight.md\`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- \`references/rule-lint.md\`: 规则质量检查器(Linter)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- \`references/rule-lint.md\`: 规则质量检查器(Linter,含 builtin / strict / hlab 官方规范)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- \`references/customer-feedback-rule-remediation.md\`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- \`references/hose-enterprise-auth.md\`: Hose 企业配置、认证诊断、授权链接。
- \`references/hose-enterprise-init.md\`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
@@ -871,11 +1133,11 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
## Safety
Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real \`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
`;var PF0=`interface:
`;var zg0=`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 TF0=`# Rule Lightweight Queries
`;var Ug0=`# 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.
@@ -986,7 +1248,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 EF0=`# Approval Bad Case Catalog
`;var Ig0=`# 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.
@@ -1036,7 +1298,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 BF0="# 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 the user-level `~/.config/seal-use/enterprises` directory is loaded. A configured\n `testEnterprisesDir` is loaded first for test-tenant workflows. The current working directory's\n `./enterprises` directory is not loaded implicitly.\n- Set `SEAL_USE_ENTERPRISES_DIR` to use one explicit directory instead. Legacy\n `~/.config/seal-home/enterprises` files are migrated to the primary directory when possible.\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 count [--corp <corpId>]\nseal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]\nseal-use rules clear [--corp <corpId>] [--dry-run|--yes]\nseal-use rules versions [--corp <corpId>]\nseal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]\nseal-use rules get --corp <corpId> --version <number|latest> --code '#0038'\nseal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205\nseal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]\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 linters [--corp <corpId>]\nseal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]\nseal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]\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 [--check] [--force] [--version <v>]\nseal-use update check\nseal-use update changelog [--limit <n>]\nseal-use changelog [--limit <n>]\nseal-use mcp\nseal-use mcp config\nseal-use mcp-config\nseal-use skill dump\nseal-use skill install [--dir <path>|--local]\nseal-use skill status\nseal-use doctor [--quiet]\nseal-use doctor tenant [--corp <corpId>] [--quiet]\nseal-use doctor guide\nseal-use doctor paths\nseal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\nseal-use probe [<corpId>]\nseal-use tools list\nseal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict] [--corp <corpId>]\nseal-use corps search <query> [--env <production|test>] [--strict]\nseal-use corps get <corpId>\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps mark <corpId> --env <production|test> [--confirm]\nseal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]\nseal-use corps unbind-test [<corpId>] [--confirm]\nseal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]\nseal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--force]\nseal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\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]Line truncated
`;var Jg0="# 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 the user-level `~/.config/seal-use/enterprises` directory is loaded. A configured\n `testEnterprisesDir` is loaded first for test-tenant workflows. The current working directory's\n `./enterprises` directory is not loaded implicitly.\n- Set `SEAL_USE_ENTERPRISES_DIR` to use one explicit directory instead. Legacy\n `~/.config/seal-home/enterprises` files are migrated to the primary directory when possible.\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 count [--corp <corpId>]\nseal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]\nseal-use rules clear [--corp <corpId>] [--dry-run|--yes]\nseal-use rules versions [--corp <corpId>]\nseal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]\nseal-use rules get --corp <corpId> --version <number|latest> --code '#0038'\nseal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205\nseal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]\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 linters [--corp <corpId>]\nseal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]\nseal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]\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 [--check] [--force] [--version <v>]\nseal-use update check\nseal-use update changelog [--limit <n>]\nseal-use changelog [--limit <n>]\nseal-use mcp\nseal-use mcp config\nseal-use mcp-config\nseal-use skill dump\nseal-use skill install [--dir <path>|--local]\nseal-use skill status\nseal-use doctor [--quiet]\nseal-use doctor tenant [--corp <corpId>] [--quiet]\nseal-use doctor guide\nseal-use doctor paths\nseal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\nseal-use probe [<corpId>]\nseal-use tools list\nseal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict] [--corp <corpId>]\nseal-use corps search <query> [--env <production|test>] [--strict]\nseal-use corps get <corpId>\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps mark <corpId> --env <production|test> [--confirm]\nseal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]\nseal-use corps unbind-test [<corpId>] [--confirm]\nseal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]\nseal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--force]\nseal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\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]Line 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.
@@ -1257,7 +1519,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 RF0=`# Customer Feedback Rule Remediation
`;var Hg0=`# 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.
@@ -1427,7 +1689,7 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var gF0=`# Enterprise Onboarding
`;var Gg0=`# Enterprise Onboarding
Read 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.
@@ -1561,7 +1823,7 @@ seal-use auth diagnose --corp <discovered-id> # Hose source
Report the human enterprise name, identity provider, credential method, and whether verification succeeded. Do not expose internal IDs unless they help with troubleshooting. Do not perform approval, rule, document, simulation, publishing, or other business mutations just because onboarding succeeded; continue only with the user's requested task and its normal confirmation rules.
If a temporary assistance-link or browser session expires, explain that it must be renewed or recaptured. Recommend standard Hose app credentials when the user needs durable unattended access.
`;var _F0=`# Hose Enterprise Auth
`;var Zg0=`# Hose Enterprise Auth
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -1626,7 +1888,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 CF0=`# Hose Enterprise Initialization & Automated Discovery
`;var Wg0=`# 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.
@@ -1732,7 +1994,7 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var yF0={"SKILL.md":AF0,"agents/openai.yaml":PF0,"references/rule-lightweight.md":TF0,"references/approval-bad-cases.md":EF0,"references/cli.md":BF0,"references/approval-run-lightweight.md":jF0,"references/approval-attachment-trace.md":vF0,"references/customer-feedback-rule-remediation.md":RF0,"references/enterprise-onboarding.md":gF0,"references/hose-enterprise-auth.md":_F0,"references/hose-enterprise-init.md":CF0};function uF0(){return yF0["SKILL.md"]||""}function pI(){return ck(SF0(),".agents","skills","seal-use")}function xF0(){return ck(SF0(),".agents","skills","seal-home")}function kF0(){let $=xF0();if(pk($))try{return OX1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function dk($=pI()){kF0(),hF0($,{recursive:!0});let I=[];for(let[z,q]of Object.entries(yF0)){let U=ck($,z);hF0(NX1(U),{recursive:!0}),FX1(U,q,"utf8"),I.push(z)}return{targetDir:$,files:I}}function mk(){let $=xF0(),I=pI(),z=pk($),q=pk(I);if(z||q)return kF0(),dk(I),{synced:!0,targetDir:I};return{synced:!1}}var lk=[{name:"配置与状态根目录",category:"config",standardPath:"~/.config/seal-use",purpose:"用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",accessMode:"read-write",retention:"persistent"},{name:"企业配置文件目录",category:"config",standardPath:"~/.config/seal-use/enterprises",purpose:"存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",accessMode:"read-write",retention:"persistent"},{name:"全局配置文件",category:"config",standardPath:"~/.config/seal-use/config.json",purpose:"维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",accessMode:"read-write",retention:"persistent"},{name:"会话凭据安全缓存",category:"config",standardPath:"~/.config/seal-use/seal_tokens.json",purpose:"缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",accessMode:"read-write",retention:"cache"},{name:"规则版本映射快照",category:"config",standardPath:"~/.config/seal-use/mappings",purpose:"存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",accessMode:"read-write",retention:"persistent"},{name:"后台守护服务日志",category:"config",standardPath:"~/.config/seal-use/service.log",purpose:"常驻后台 HTTP 服务守护进程运行输出日志。",accessMode:"read-write",retention:"persistent"},{name:"全局命令行程序",category:"binary",standardPath:"/opt/homebrew/bin/seal-use",purpose:"macOS / Linux 全局独立单文件二进制程序;附带软链接 seal-home -> seal-use 兼容旧指令。",accessMode:"executable",retention:"persistent"},{name:"AI Agent 技能主目录",category:"skill",standardPath:"~/.agents/skills/seal-use",purpose:"面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",accessMode:"read-write",retention:"persistent"},{name:"报表默认导出目录",category:"export",standardPath:"~/Downloads",purpose:"执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",accessMode:"read-write",retention:"persistent"},{name:"系统隔离临时目录",category:"temp",standardPath:"/tmp 或 /var/folders/.../T",purpose:"自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",accessMode:"transient",retention:"ephemeral"}],ok=[{topic:"敏感凭据脱敏保护",guarantee:"appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",enforcement:"CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"},{topic:"正式环境与测试环境严格隔离",guarantee:"正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",enforcement:"corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"},{topic:"跨环境规则同步安全基线",guarantee:"corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",enforcement:"规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"},{topic:"只读诊断无副作用原则",guarantee:"doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",enforcement:"核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"}],rk=[{domain:"corps (企业管理)",summary:"多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同 Line truncated
`;var wg0={"SKILL.md":Yg0,"agents/openai.yaml":zg0,"references/rule-lightweight.md":Ug0,"references/approval-bad-cases.md":Ig0,"references/cli.md":Jg0,"references/approval-run-lightweight.md":Qg0,"references/approval-attachment-trace.md":Kg0,"references/customer-feedback-rule-remediation.md":Hg0,"references/enterprise-onboarding.md":Gg0,"references/hose-enterprise-auth.md":Zg0,"references/hose-enterprise-init.md":Wg0};function Lg0(){return wg0["SKILL.md"]||""}function TY(){return Bd(Vg0(),".agents","skills","seal-use")}function Fg0(){return Bd(Vg0(),".agents","skills","seal-home")}function Og0(){let $=Fg0();if(Pd($))try{return yb1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Td($=TY()){Og0(),Xg0($,{recursive:!0});let q=[];for(let[Y,z]of Object.entries(wg0)){let U=Bd($,Y);Xg0(kb1(U),{recursive:!0}),xb1(U,z,"utf8"),q.push(Y)}return{targetDir:$,files:q}}function Ed(){let $=Fg0(),q=TY(),Y=Pd($),z=Pd(q);if(Y||z)return Og0(),Td(q),{synced:!0,targetDir:q};return{synced:!1}}var jd=[{name:"配置与状态根目录",category:"config",standardPath:"~/.config/seal-use",purpose:"用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",accessMode:"read-write",retention:"persistent"},{name:"企业配置文件目录",category:"config",standardPath:"~/.config/seal-use/enterprises",purpose:"存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",accessMode:"read-write",retention:"persistent"},{name:"全局配置文件",category:"config",standardPath:"~/.config/seal-use/config.json",purpose:"维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",accessMode:"read-write",retention:"persistent"},{name:"会话凭据安全缓存",category:"config",standardPath:"~/.config/seal-use/seal_tokens.json",purpose:"缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",accessMode:"read-write",retention:"cache"},{name:"规则版本映射快照",category:"config",standardPath:"~/.config/seal-use/mappings",purpose:"存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",accessMode:"read-write",retention:"persistent"},{name:"后台守护服务日志",category:"config",standardPath:"~/.config/seal-use/service.log",purpose:"常驻后台 HTTP 服务守护进程运行输出日志。",accessMode:"read-write",retention:"persistent"},{name:"全局命令行程序",category:"binary",standardPath:"/opt/homebrew/bin/seal-use",purpose:"macOS / Linux 全局独立单文件二进制程序;附带软链接 seal-home -> seal-use 兼容旧指令。",accessMode:"executable",retention:"persistent"},{name:"AI Agent 技能主目录",category:"skill",standardPath:"~/.agents/skills/seal-use",purpose:"面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",accessMode:"read-write",retention:"persistent"},{name:"报表默认导出目录",category:"export",standardPath:"~/Downloads",purpose:"执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",accessMode:"read-write",retention:"persistent"},{name:"系统隔离临时目录",category:"temp",standardPath:"/tmp 或 /var/folders/.../T",purpose:"自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",accessMode:"transient",retention:"ephemeral"}],_d=[{topic:"敏感凭据脱敏保护",guarantee:"appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",enforcement:"CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"},{topic:"正式环境与测试环境严格隔离",guarantee:"正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",enforcement:"corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"},{topic:"跨环境规则同步安全基线",guarantee:"corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",enforcement:"规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"},{topic:"只读诊断无副作用原则",guarantee:"doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",enforcement:"核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"}],Cd=[{domain:"corps (企业管理)",summary:"多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同 Line truncated
> 本文档由 \`seal-use\` 单文件二进制程序内嵌提供,纯内存只读,未向用户电脑写入任何临时文件。
@@ -1755,14 +2017,14 @@ seal-use corps hose-staffs --json '{
| 目录名称 | 类别 | 规范路径 | 作用与生命周期 |
| :--- | :--- | :--- | :--- |
${lk.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
${jd.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
`)}
---
## 3. 安全与数据隐私保证
${ok.map(($,I)=>`### 3.${I+1} ${$.topic}
${_d.map(($,q)=>`### 3.${q+1} ${$.topic}
- **安全承诺**:${$.guarantee}
- **实现约束**:${$.enforcement}
`).join(`
@@ -1772,9 +2034,9 @@ ${ok.map(($,I)=>`### 3.${I+1} ${$.topic}
## 4. 业务域能力图谱
${rk.map(($)=>`### \`seal-use ${$.domain}\`
${Cd.map(($)=>`### \`seal-use ${$.domain}\`
* **能力定位**:${$.summary}
* **核心命令**:${$.primaryCommands.map((I)=>`\`seal-use ${I}\``).join("、")}
* **核心命令**:${$.primaryCommands.map((q)=>`\`seal-use ${q}\``).join("、")}
`).join(`
`)}
@@ -1785,20 +2047,20 @@ ${rk.map(($)=>`### \`seal-use ${$.domain}\`
- **环境自检**:运行 \`seal-use doctor\`,一键检查当前运行时版本、本地目录健康度、企业资产接入数量以及守护服务状态。
- **查看企业配置源文件**:运行 \`seal-use corps get <corpId>\`,可直接查看指定企业的本地 JSON 存储绝对路径。
- **查阅完整操作手册**:运行 \`seal-use doctor guide\` 随时在离线状态下查看本文档。
`}function bF0($){if(!x6($))return 0;try{return PX1($).filter((I)=>I.endsWith(".json")).length}catch{return 0}}function sO($){try{return MX1($,AX1.W_OK),!0}catch{return!1}}function tk(){let $=TX1(),I=O9($,".config","seal-use"),z=O9(I,"enterprises"),q=O9(I,"config.json"),U=O9(I,"seal_tokens.json"),Y=O9(I,"mappings"),J=pI(),Q=O9($,"Downloads"),w=["/opt/homebrew/bin/seal-use","/usr/local/bin/seal-use",O9($,".local","bin","seal-use"),O9($,"bin","seal-use")].find((M)=>x6(M))??process.execPath,G={configDir:{name:"配置根目录",path:I,exists:x6(I),writable:x6(I)?sO(I):!1,description:"用户持久化配置与企业状态根目录"},enterprisesDir:{name:"企业配置目录",path:z,exists:x6(z),writable:x6(z)?sO(z):!1,fileCount:bF0(z),description:"企业连接配置(JSON)保存路径"},globalConfigFile:{name:"全局配置文件",path:q,exists:x6(q),description:"全局工作模式与默认企业配置"},tokenStore:{name:"凭据缓存",path:U,exists:x6(U),description:"会话凭据与令牌缓存"},mappingsDir:{name:"规则版本映射快照",path:Y,exists:x6(Y),fileCount:bF0(Y),description:"生产与测试规则版本映射对照表"},agentSkillDir:{name:"AI Agent 技能目录",path:J,exists:x6(O9(J,"SKILL.md")),description:"本地 Agent 技能主目录"},exportDefaultDir:{name:"报表默认导出目录",path:Q,exists:x6(Q),writable:x6(Q)?sO(Q):!1,description:"审核大盘报表默认写入目录"},lintersDir:{name:"规则校验器目录 (用户自定义)",path:Q8,exists:x6(Q8),writable:x6(Q8)?sO(Q8):!1,description:"用户私有规则校验脚本存放目录"},officialLintersDir:{name:"官方内置规则校验器目录",path:L5,exists:x6(L5),description:"官方标准与严格风控校验脚本目录 (系统自动保护与重写)"},globalBinary:{name:"全局命令行二进制",path:w,exists:x6(w),description:"系统全局命令执行入口"}},H=[];try{H=O$()}catch{H=[]}let V=K4().defaultCorpId??H[0]?.id,X=H.find((M)=>M.id===V),L=H.filter((M)=>(M.environment??"production").toLowerCase()==="test").length,D=H.length-L,O=[];if(O.push({id:"executable",title:"命令行二进制",status:"ok",message:`当前执行路径: ${process.execPath}`}),G.configDir?.exists&&G.configDir.writable)O.push({id:"config_dir",title:"配置目录访问",status:"ok",message:`${I} (正常读写)`});else if(G.configDir?.exists)O.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`${I} (存在但可能不可写)`});else O.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`未检测到配置目录 ${I},首次运行配置命令时将自动创建`});if(H.length>0)O.push({id:"enterprises",title:"企业接入状态",status:"ok",message:`已接入 ${H.length} 家企业 (正式: ${D}, 测试: ${L})`});else O.push({id:"enterprises",title:"企业接入状态",status:"warn",message:"当前未检测到企业配置,请使用 seal-use corps add-hose 或 add-seal 接入企业"});if(G.agentSkillDir?.exists)O.push({id:"agent_skill",title:"AI Agent 技能",status:"ok",message:`已就绪于 ${J}`});else O.push({id:"agent_skill",title:"AI Agent 技能",status:"warn",message:`未在 ${J} 检测到技能,可运行 'seal-use skill sync' 安装`});let A=O.some((M)=>M.status==="warn"||M.status==="error"),T=typeof globalThis.Bun<"u"?`Bun ${globalThis.Bun.version}`:`Node ${process.version}`;return{doctor:A?"warning":"ok",timestamp:new Date().toISOString(),runtime:{version:q1,executablePath:process.execPath,platform:`${process.platform} (${process.arch})`,engine:T},directories:G,enterprises:{total:H.length,productionCount:D,testCount:L,activeCorpId:X?.id,activeCorpName:X?.name},checks:O,knowledge:{summary:"内嵌系统架构与目录规范白皮书(纯内存只读,零写入依赖)",directorySpecsCount:lk.length,securityPoliciesCount:ok.length,domainCapabilitiesCount:rk.length,guideCommand:"seal-use doctor guide"}}}function nF0($){let I=[],z=$.doctor==="ok"?"✨":"⚠️";I.push(`\uD83E\uDE7A [Seal Use Doctor] 系统健康诊断看板 ${z}`),I.push("─────────────────────────────────────────────────────────────"),I.push("【运行环境】"),I.push(` 版本号: ${$.runtime.version}`),I.push(` 程序路径: ${$.runtime.executablePath}`),I.push(` 操作系统: ${$.runtime.platform}`),I.push(` 执行引擎: ${$.runtime.engine}`),I.push(""),I.push("【核心路径状态】");for(let[,q]of Object.entries($.directories)){let U=q.exists?"✓":"○",Y=q.exists?q.fileCount!==void 0?`(${q.fileCount} 个文件)`:q.writable?"(就绪/可写)":"(存在)":"(未创建)";I.push(` ${U} ${q.name.padEnd(16," ")}: ${q.path} ${Y}`)}if(I.push(""),I.push("【企业资产概览】"),I.push(` 接入企业总计: ${$.enterprises.total} 家 (生产: ${$.enterprises.productionCount}, 测试: ${$.enterprises.testCount})`),$.enterprises.activeCorpId)I.push(` 当前激活企业: ${$.enterprises.activeCLine truncated
`)}G4();u1();async function cF0($,I,z){let q=($??I??"").toLowerCase();if(q==="guide"||q==="doc"||q==="knowledge"||q==="book"){console.error(`\uD83D\uDCD6 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(fF0());return}if(q==="paths"||q==="dirs"||q==="directories"){let J=tk();T0(J.directories);return}if(q==="tenant"||q==="corp"||q==="enterprise"){let{selectCorp:J}=await Promise.resolve().then(() => (A4(),dD0)),{createSealClient:Q}=await Promise.resolve().then(() => (w$(),wr)),{stringOption:K}=await Promise.resolve().then(() => (G4(),xD0)),{diagnoseTenantContract:w,formatTenantDoctorDashboard:G}=await Promise.resolve().then(() => (pF0(),iF0)),H=K(z.options.corp)??(I&&I!==q?I:void 0)??(z.command[2]&&z.command[2]!==q?z.command[2]:void 0),W=J(H),V=await Q(W),X=await w(V,W);if(!(V0(z.options.quiet)||V0(z.options.silent)))console.error(G(X));T0(X);return}let U=tk();if(!(V0(z.options.quiet)||V0(z.options.silent)))console.error(nF0(U));T0(U)}G4();import{createServer as _X1}from"node:http";A4();import{URL as vX1}from"node:url";var dF0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.20",description:`Planned HTTP contract for the seal-use wrapped backend API.
`}function Ng0($){if(!X8($))return 0;try{return bb1($).filter((q)=>q.endsWith(".json")).length}catch{return 0}}function $P($){try{return ub1($,fb1.W_OK),!0}catch{return!1}}function Rd(){let $=ib1(),q=N3($,".config","seal-use"),Y=N3(q,"enterprises"),z=N3(q,"config.json"),U=N3(q,"seal_tokens.json"),I=N3(q,"mappings"),J=TY(),Q=N3($,"Downloads"),H=["/opt/homebrew/bin/seal-use","/usr/local/bin/seal-use",N3($,".local","bin","seal-use"),N3($,"bin","seal-use")].find((P)=>X8(P))??process.execPath,G={configDir:{name:"配置根目录",path:q,exists:X8(q),writable:X8(q)?$P(q):!1,description:"用户持久化配置与企业状态根目录"},enterprisesDir:{name:"企业配置目录",path:Y,exists:X8(Y),writable:X8(Y)?$P(Y):!1,fileCount:Ng0(Y),description:"企业连接配置(JSON)保存路径"},globalConfigFile:{name:"全局配置文件",path:z,exists:X8(z),description:"全局工作模式与默认企业配置"},tokenStore:{name:"凭据缓存",path:U,exists:X8(U),description:"会话凭据与令牌缓存"},mappingsDir:{name:"规则版本映射快照",path:I,exists:X8(I),fileCount:Ng0(I),description:"生产与测试规则版本映射对照表"},agentSkillDir:{name:"AI Agent 技能目录",path:J,exists:X8(N3(J,"SKILL.md")),description:"本地 Agent 技能主目录"},exportDefaultDir:{name:"报表默认导出目录",path:Q,exists:X8(Q),writable:X8(Q)?$P(Q):!1,description:"审核大盘报表默认写入目录"},lintersDir:{name:"规则校验器目录 (用户自定义)",path:b$,exists:X8(b$),writable:X8(b$)?$P(b$):!1,description:"用户私有规则校验脚本存放目录"},officialLintersDir:{name:"官方内置规则校验器目录",path:i$,exists:X8(i$),description:"官方标准与严格风控校验脚本目录 (系统自动保护与重写)"},globalBinary:{name:"全局命令行二进制",path:H,exists:X8(H),description:"系统全局命令执行入口"}},Z=[];try{Z=r8()}catch{Z=[]}let X=B4().defaultCorpId??Z[0]?.id,w=Z.find((P)=>P.id===X),L=Z.filter((P)=>(P.environment??"production").toLowerCase()==="test").length,F=Z.length-L,O=[];if(O.push({id:"executable",title:"命令行二进制",status:"ok",message:`当前执行路径: ${process.execPath}`}),G.configDir?.exists&&G.configDir.writable)O.push({id:"config_dir",title:"配置目录访问",status:"ok",message:`${q} (正常读写)`});else if(G.configDir?.exists)O.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`${q} (存在但可能不可写)`});else O.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`未检测到配置目录 ${q},首次运行配置命令时将自动创建`});if(Z.length>0)O.push({id:"enterprises",title:"企业接入状态",status:"ok",message:`已接入 ${Z.length} 家企业 (正式: ${F}, 测试: ${L})`});else O.push({id:"enterprises",title:"企业接入状态",status:"warn",message:"当前未检测到企业配置,请使用 seal-use corps add-hose 或 add-seal 接入企业"});if(G.agentSkillDir?.exists)O.push({id:"agent_skill",title:"AI Agent 技能",status:"ok",message:`已就绪于 ${J}`});else O.push({id:"agent_skill",title:"AI Agent 技能",status:"warn",message:`未在 ${J} 检测到技能,可运行 'seal-use skill sync' 安装`});let A=O.some((P)=>P.status==="warn"||P.status==="error"),B=typeof globalThis.Bun<"u"?`Bun ${globalThis.Bun.version}`:`Node ${process.version}`;return{doctor:A?"warning":"ok",timestamp:new Date().toISOString(),runtime:{version:Q1,executablePath:process.execPath,platform:`${process.platform} (${process.arch})`,engine:B},directories:G,enterprises:{total:Z.length,productionCount:F,testCount:L,activeCorpId:w?.id,activeCorpName:w?.name},checks:O,knowledge:{summary:"内嵌系统架构与目录规范白皮书(纯内存只读,零写入依赖)",directorySpecsCount:jd.length,securityPoliciesCount:_d.length,domainCapabilitiesCount:Cd.length,guideCommand:"seal-use doctor guide"}}}function Dg0($){let q=[],Y=$.doctor==="ok"?"✨":"⚠️";q.push(`\uD83E\uDE7A [Seal Use Doctor] 系统健康诊断看板 ${Y}`),q.push("─────────────────────────────────────────────────────────────"),q.push("【运行环境】"),q.push(` 版本号: ${$.runtime.version}`),q.push(` 程序路径: ${$.runtime.executablePath}`),q.push(` 操作系统: ${$.runtime.platform}`),q.push(` 执行引擎: ${$.runtime.engine}`),q.push(""),q.push("【核心路径状态】");for(let[,z]of Object.entries($.directories)){let U=z.exists?"✓":"○",I=z.exists?z.fileCount!==void 0?`(${z.fileCount} 个文件)`:z.writable?"(就绪/可写)":"(存在)":"(未创建)";q.push(` ${U} ${z.name.padEnd(16," ")}: ${z.path} ${I}`)}if(q.push(""),q.push("【企业资产概览】"),q.push(` 接入企业总计: ${$.enterprises.total} 家 (生产: ${$.enterprises.productionCount}, 测试: ${$.enterprises.testCount})`),$.enterprises.activeCorpId)q.push(` 当前激活企业: ${$.enterprises.activeCLine truncated
`)}_4();o1();async function Bg0($,q,Y){let z=($??q??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(Mg0());return}if(z==="paths"||z==="dirs"||z==="directories"){let J=Rd();j0(J.directories);return}if(z==="tenant"||z==="corp"||z==="enterprise"){let{selectCorp:J}=await Promise.resolve().then(() => (p4(),Tv0)),{createSealClient:Q}=await Promise.resolve().then(() => (b8(),b10)),{stringOption:K}=await Promise.resolve().then(() => (_4(),Fv0)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:G}=await Promise.resolve().then(() => (Pg0(),Ag0)),Z=K(Y.options.corp)??(q&&q!==z?q:void 0)??(Y.command[2]&&Y.command[2]!==z?Y.command[2]:void 0),V=J(Z),X=await Q(V),w=await H(X,V);if(!(W0(Y.options.quiet)||W0(Y.options.silent)))console.error(G(w));j0(w);return}let U=Rd();if(!(W0(Y.options.quiet)||W0(Y.options.silent)))console.error(Dg0(U));j0(U)}_4();import{createServer as ob1}from"node:http";p4();import{URL as db1}from"node:url";var Tg0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.23",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${q1})</title>
<title>Seal Home API Docs (v${Q1})</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 {
@@ -1817,24 +2079,24 @@ 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 t4($,I,z,q){let U=$.handler;return U(I,z,{corp:q})}async function lF0($,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 z=$.headers.host||"localhost",q=$.headers["x-forwarded-proto"]||"http",U=new vX1($.url||"/",`${q}://${z}`),Y=U.pathname.replace(/\/+$/,"")||"/",J=($.method||"GET").toUpperCase();try{if(J==="GET"&&Y==="/"){e1(I,200,{name:"seal-use",version:q1,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(J==="GET"&&Y==="/docs"){gX1(I,200,mF0());return}if(J==="GET"&&Y==="/openapi.json"){e1(I,200,eO());return}if(J==="GET"&&Y==="/health"){e1(I,200,{status:"ok",version:q1,name:"seal-use",timestamp:new Date().toISOString()});return}if(J==="POST"&&(Y==="/shutdown"||Y==="/api/shutdown")){e1(I,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(J==="POST"&&Y==="/api/cli"){let Q=await IF($),K=(typeof Q?.command==="string"?Q.command:"").trim();if(!K){$F(I,400,"Missing 'command' property in request body");return}let w=ak(K),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 Xw(G),W=void 0;try{if(H.stdout.trim().startsWith("{")||H.stdout.trim().startsWith("["))W=JSON.parse(H.stdout)}catch{}e1(I,H.isError?400:200,{success:!H.isError,stdout:H.stdout,stderr:H.stderr,exitCode:H.exitCode,data:W});return}if(J==="POST"&&Y.startsWith("/api/tool/")){let Q=Y.slice(10).trim(),K=n4(Q);if(!K){$F(I,404,`Tool not found: '${Q}'`);return}let w=await IF($)||{},G=e6($,U,w),H=w1(G),W=await J1(H),V={...w};delete V.corp;let X=await t4(K,W,V,H);e1(I,200,X);return}if(Y.startsWith("/v1/")){if(await RX1($,I,J,Y,U))return}$F(I,404,`Cannot ${J} ${Y}. Visit /docs for available endpoints.`)}catch(Q){let K=Q instanceof Error?Q.message:String(Q);$F(I,500,K)}}async function RX1($,I,z,q,U){let Y=Object.fromEntries(U.searchParams.entries());if(z==="GET"&&q==="/v1/corps"){let J=O$(),Q=K4();return e1(I,200,{count:J.length,mode:Q.stateful?"stateful":"stateless",defaultCorpId:Q.defaultCorpId,corps:J.map((K)=>({id:K.id,name:K.name,sourceType:K.source.type,sealUrl:K.seal?.url}))}),!0}if(z==="GET"&&q==="/v1/whoami"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_whoami"),G=await t4(w,K,{},Q);return e1(I,200,G),!0}if(z==="GET"&&q==="/v1/session"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_session_get"),G=await t4(w,K,{},Q);return e1(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/summary"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_approval_runs_summary"),G=await t4(w,K,Y,Q);return e1(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/stats"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_approval_runs_stats"),G=await t4(w,K,Y,Q);return e1(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/pick"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_approval_run_pick"),G=await t4(w,K,Y,Q);return e1(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/url"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_approval_run_url_get"),G=await t4(w,K,Y,Q);return e1(I,200,G),!0}if(q.startsWith("/v1/approval-runs/")){let J=q.slice(18).split("/"),Q=J[0],K=J[1];if(Q&&!["summary","pick","stats","url","bridge"].includes(Q)){let w=e6($,U,Y),G=w1(w),H=await J1(G);if(!K){let W=n4("seal_approval_run_get"),V=await t4(W,H,{recordId:Q,...Y},G);return e1(I,200,V),!0}if(K==="attachments"){let W=n4("seal_approval_run_attachments_get"),V=await t4(W,H,{recordId:Q,...Y},G);return e1(I,200,V),!0}if(K==="cited-rules"){let W=n4("seal_approval_run_cited_rules_get"),V=await t4(W,H,{recordId:Q,...Y},G);return e1(I,200,V),!0}if(K==="document-summary"){let W=n4("seal_approval_run_document_summary_get"),V=await t4(W,H,{recordId:Q,...Y},G);return e1(I,200,V),!0}if(K==="result"){let W=n4("seal_approval_run_result_get"),V=await t4(W,H,{recordId:Q,...Y},G);return e1(I,200,V),!0}}}if(z==="GET"&&q==="/v1/approval-runs"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_approval_runs_search"),G=await t4(w,K,{...Y,limit:Y.limit?Number(Y.limit):void 0,offset:Y.offset?Number(Y.offset):void 0,includeBridge:Y.includeBridge==="true"},Q);return e1(I,200,G),!0}if(z==="GET"&&q==="/v1/approval/rules"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_approval_rules_list"),G=await t4(w,K,Y,Q);return e1(I,200,G),!0}if(z==="GET"&&q==="/v1/simulation/batches"){let J=e6($,U,Y),Q=w1(J),K=await J1(Q),w=n4("seal_simulation_batches_list"),G=await t4(w,K,Y,Q);return e1(I,200,G),!0}if(z==="POST"&&q==="/v1/simulation/create-batch"){let J=await IF($)||{},Q=e6($,U,J),K=w1(Q),w=await J1Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${q1}) started`),console.error(` URL: http://${z}:${I}`),console.error(` Docs: http://${z}:${I}/docs`),console.error(` OpenAPI: http://${z}:${I}/openapi.json`),console.error(` CLI Exec: POST http://${z}:${I}/api/cli`),console.error(` REST API: http://${z}:${I}/v1/...
`);U(q)})})}async function oF0($){let I=_0($.options.port)??_0($.options.p),z=j($.options.host)??j($.options.h),q=await UF({port:I,host:z}),U=()=>{q.close(()=>{process.exit(0)})};process.on("SIGINT",U),process.on("SIGTERM",U),await new Promise(()=>{})}A4();u1();async function rF0($,I,z,q){if($==="config"||$==="get"){await N0("seal_llm_config_get",I,z,{},Z0(q.options));return}if($==="providers"||$==="list"){await N0("seal_llm_providers_list",I,z,{},Z0(q.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}u1();async function tF0($,I){if($==="config"||$==="json"){sk();return}await ek()}function sk(){T0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}u1();function aF0($){let I=eO();T0(I,{...Z0($.options),allowFull:!0})}A4();u1();async function sF0($,I,z,q){if($==="available"){await N0("seal_permissions_available_list",I,z,{},Z0(q.options));return}if($==="configs"||$==="list"){await N0("seal_permissions_configs_list",I,z,{},Z0(q.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}A4();G4();u1();import{readFileSync as eF0}from"node:fs";async function $N0($,I,z,q,U,Y,J){if(!$||$==="get"){await N0("seal_preference_get",U,Y,{},Z0(J.options));return}if($==="decision"){if(I==="update"||!I){let Q=j(J.options.input),K=Q?JSON.parse(eF0(Q,"utf8")):s6(J.json);if(!K||Object.keys(K).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await N0("seal_preference_decision_update",U,Y,{...K,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},Z0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let Q=j(J.options.default)??j(J.options.level)??q;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await N0("seal_preference_thinking_depth_set",U,Y,{defaultLevel:Q,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},Z0(J.options));return}if(I==="policies"){if(z==="list"||!z){await N0("seal_preference_thinking_depth_policies_list",U,Y,{},Z0(J.options));return}if(z==="upsert"){let Q=j(J.options.input),K=Q?JSON.parse(eF0(Q,"utf8")):s6(J.json);if(!K||!K.id||!K.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await N0("seal_preference_thinking_depth_policies_upsert",U,Y,{...K,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},Z0(J.options));return}if(z==="remove"||z==="delete"){let Q=q??j(J.options.id)??j(J.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await N0("seal_preference_thinking_depth_policies_remove",U,Y,{policyId:Q,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},Z0(J.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}G9();w$();c4();async function IN0($={}){let I=O$(),z=K4(),q=d7(I,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$.corpId},w9());console.log(`[probe] corp=${q.id} source=${q.source.type}`);let U=await VY(q);console.log("[probe] seal enterprise"),console.log(JSON.stringify(U,null,2));let Y=await J1(q),J=await aW(Y,{documentLimit:20,stylePreferencesEndpoint:q.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error: ${J.stylePreferences.error}`},null,2))}G4();async function zN0($,I,z){let q=I??j(z.options.corp)??($&&$!=="--corp"?$:void 0);await IN0({corpId:q})}Zx();A4();k$();G4();u1();async function $f($,I,z,q,U){if($==="count"){await N0("seal_approval_rules_list",z,q,{countOnly:!0},Z0(U.options));return}if($==="list"){if(V0(U.options.count)){await N0("seal_approval_rules_list",z,q,{countOnly:!0},Z0(U.options));return}let Y=_0(U.options.limit),J=_0(U.options.offset);if(V0(U.options.summary)){await N0("seal_approval_rules_list",z,q,{fields:iD0,limit:Y,offset:J},Z0(U.options));return}let Q=await o7("seal_approval_rules_list",z,q,{limit:Y,offset:J});pD0(Q,V0(U.options.full)===!0),T0(Q);return}if($==="clear"){let Y=V0(U.options.yes)===!0,J=V0(U.options.dryRun)??V0(U.options["dry-run"])??!Y;if(!Y&&!J)throw X5("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${q.id} --dry-run`);let Q=await o7("seal_approval_rules_clear",z,q,{dryRun:J,recode:V0(U.options.recode)});if(!Y&&J&&Q&&typeof Q==="object"){T0({...Q,nextCommand:`seal-use rules clear --corp ${q.id} --yes`},Z0(U.options));return}T0(Q,Z0(U.options));return}if($==="versions"){await N0("seal_approval_rule_versions_list",z,q,{},Z0(U.options));return}if($==="version"){let Y=I??j(U.op Line truncated
`).filter(Boolean),Y=U.slice(-I);return{logFile:z,lines:Y,totalLines:U.length}}async function uX1($){let I=KF($),z=qf($),q=Lw($);JN0($.stateDir);let U=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):zF),Y=$.host??(process.env.HOST?process.env.HOST:qF);JF(I,`${process.pid}
`,{mode:384}),JF(z,JSON.stringify({pid:process.pid,port:U,host:Y,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),ZY(q,`service starting on http://${Y}:${U} pid=${process.pid}`);let J=null;try{J=await UF({port:U,host:Y,silent:!0}),ZY(q,`service listening pid=${process.pid}`)}catch(K){if(ZY(q,`service failed to bind port ${U}: ${K instanceof Error?K.message:String(K)}`),QF(I)===process.pid)N5(I,{force:!0}),N5(z,{force:!0});throw K}let Q=()=>{if(J)J.close(),J=null;if(QF(I)===process.pid)N5(I,{force:!0}),N5(z,{force:!0});ZY(q,`stopped pid=${process.pid}`)};await new Promise((K)=>{let w=!1,G=()=>{if(w)return;w=!0,Q(),process.off("SIGTERM",G),process.off("SIGINT",G),K()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function qN0($){JN0($.stateDir);let I=XY($);if(I.running)return I;let z=$.launcher??{command:process.execPath,args:[$.entryFile]},q=[...z.args??[],"service","run"];if($.port)q.push("--port",String($.port));if($.host)q.push("--host",String($.host));let U=CX1(z.command,q,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});U.unref();let Y=KF($);return JF(Y,`${U.pid}
`,{mode:384}),ZY(Lw($),`started pid=${U.pid}`),{started:!0,...XY($)}}function UN0($,I={}){let z=KF($),q=qf($),U=QF(z);if(!U||!YN0(U,$.appRoot))return N5(z,{force:!0}),N5(q,{force:!0}),I.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(U,"SIGTERM"),N5(z,{force:!0}),N5(q,{force:!0}),ZY(Lw($),`stop requested pid=${U}`),I.quiet?void 0:{stopped:!0,pid:U}}function YN0($,I){if(!xX1($))return!1;try{let z=hX1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(z.includes(I)||z.includes("seal-use")||z.includes("src/cli.ts"))&&z.includes("service")&&z.includes("run")}catch{return!1}}function xX1($){try{return process.kill($,0),!0}catch{return!1}}function KF($){return zf($.stateDir,"service.pid")}function qf($){return zf($.stateDir,"service.json")}function Lw($){return zf($.stateDir,"service.log")}function QF($){if(!YF($))return;let I=Number(If($,"utf8").trim());return Number.isInteger(I)&&I>0?I:void 0}function JN0($){SX1($,{recursive:!0,mode:448})}function ZY($,I){JF($,`${new Date().toISOString()} ${I}
`,{flag:"a",mode:384})}u1();G4();var Uf=fX1(kX1(),".config","seal-use");async function Yf($,I,z){let q=z?_0(z.options.port)??_0(z.options.p):void 0,U=z?j(z.options.host)??j(z.options.h):void 0,Y=z?_0(z.options.lines)??_0(z.options.n):void 0,J=await cI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:Uf,version:q1,launcher:I.launcher,port:q,host:U},{maxLines:Y});if(J!==void 0)T0(J)}A4();G4();u1();import{existsSync as bX1,readFileSync as QN0}from"node:fs";async function KN0($,I,z,q,U){if($==="batch-records"||$==="records"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation batch-records <batchId>");await N0("seal_simulation_batch_records_get",z,q,{batchId:Y,query:j(U.options.query)},Z0(U.options));return}if($==="create"||$==="run"){let Y=j(U.options.mode)??j(U.options.sourceSystem)??j(U.options["source-system"])??"hosecloud",J=Y==="material-pack"?"material_pack":Y,Q=j(U.options.schemaConfig)??j(U.options["schema-config"]),K=Q?JSON.parse(QN0(Q,"utf8")):void 0,w=j(U.options.input),G=w?JSON.parse(QN0(w,"utf8")):s6(U.json),H=j(U.options.packageId)??j(U.options["package-id"]),W=q6(U.options.packageIds)??q6(U.options["package-ids"])??(H?[H]:void 0),V=q6(U.options.flowIds)??q6(U.options["flow-ids"])??q6(U.options.documentSn)??q6(U.options["document-sn"]),X=j(U.options.signKey)??j(U.options["sign-key"])??j(U.options.integration),L=V0(U.options.noWait)??V0(U.options["no-wait"]);await N0("seal_simulation_batch_create",z,q,{mode:J,sourceSystem:J,flowIds:V,documentSn:V,rejectNodeName:j(U.options.rejectNode)??j(U.options["reject-node"])??null,thinkingDepthOverride:j(U.options.thinkingDepth)??j(U.options["thinking-depth"]),skipInvoiceGeneration:V0(U.options.skipInvoiceGeneration)??V0(U.options["skip-invoice-generation"]),skipExpenseExtraction:V0(U.options.skipExpenseExtraction)??V0(U.options["skip-expense-extraction"]),disableAttachmentCache:V0(U.options.disableAttachmentCache)??V0(U.options["disable-attachment-cache"]),signKey:X,packageIds:W,packageId:H,templateId:j(U.options.templateId)??j(U.options["template-id"]),schemaConfig:K,requestIds:q6(U.options.requestIds)??q6(U.options["request-ids"]),workflowTypeId:j(U.options.workflowTypeId)??j(U.options["workflow-type-id"]),flowStatusList:q6(U.options.flowStatusList)?.map(Number)??q6(U.options["flow-status-list"])?.map(Number),businessCodes:q6(U.options.businessCodes)??q6(U.options["business-codes"]),documentType:j(U.options.documentType)??j(U.options["document-type"]),startTime:_0(U.options.startTime)??_0(U.options["start-time"]),endTime:_0(U.options.endTime)??_0(U.options["end-time"]),status:q6(U.options.status),limit:_0(U.options.limit),noWait:L,rawParams:G},Z0(U.options));return}if($==="wait"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await N0("seal_simulation_batch_wait",z,q,{batchId:Y,timeout:j(U.options.timeout),pollInterval:j(U.options.pollInterval)??j(U.options["poll-interval"])},Z0(U.options));return}if($==="status"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation status <batchId>");await N0("seal_simulation_batch_status",z,q,{batchId:Y},Z0(U.options));return}if($==="clean"||$==="delete"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation clean <batchId>");await N0("seal_simulation_batch_clean",z,q,{batchId:Y},Z0(U.options));return}if($==="specifications"){let Y=I??j(U.options.integration)??j(U.options.signKey)??j(U.options["sign-key"]);await N0("seal_simulation_specifications_list",z,q,{signKey:Y},Z0(U.options));return}if($==="approval-definitions"||$==="definitions"){await N0("seal_simulation_feishu_approval_definitions_list",z,q,{},Z0(U.options));return}if($==="list"){await N0("seal_simulation_batches_list",z,q,{limit:_0(U.options.limit)},Z0(U.options));return}if($==="get"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation get <batchId>");await N0("seal_simulation_batch_get",z,q,{batchId:Y},Z0(U.options));return}if($==="templates"){await N0("seal_simulation_templates_get",z,q,{},Z0(U.options));return}if($==="integrations"){await N0("seal_simulation_integrations_get",z,q,{},Z0(U.options));return}if($==="package-upload"){let Y=I??j(U.options.file);if(!Y)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!bX1(Y))throw Error(`File not found: ${Y}`);await N0("seal_simulation_material_package_upload",z,q,{filePath:Y},Z0(U.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as wN0}from"node:fs";import{join as wF}from"node:path";G4();u1();function GN0($,I,z){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${uF0()}
`);return}if($==="install"||$==="init"||$==="sync"){let q=V0(z.options.local)||V0(z.options.workspace),U=j(z.options.dir)??j(z.options.target)??I,Y=U?U:q?wF(process.cwd(),".agents","skills","seal-use"):pI(),J=dk(Y);T0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files});return}if($==="status"||$==="get"||!$){let q=pI(),U=wF(process.cwd(),".agents","skills","seal-use");T0({global:{dir:q,installed:wN0(wF(q,"SKILL.md"))},local:{dir:U,installed:wN0(wF(U,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}u1();async function HN0($,I){if($==="config"){T0(await VY(I));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}k$();A4();G4();u1();w$();k$();c4();tK();function Jf($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let I=$.toUpperCase().trim();if(I==="APPROVE"||I==="PASS")return"APPROVE";if(I==="REJECT"||I==="DENIED")return"REJECT";if(I==="MANUAL"||I==="ASSISTED")return"MANUAL";if(I==="ERROR"||I==="FAILED")return"ERROR";return I}async function WN0($){let{sourceCorp:I,targetCorp:z,sourceClient:q,targetClient:U,samples:Y=10,dryRun:J=!1,pollIntervalMs:Q=2000,timeoutMs:K=45000,snPrefix:w="REG_",fetchFn:G=fetch}=$;if(z.environment!=="test")throw new N4(`重放目标企业「${z.name}」(${z.id}) 的环境为「${z.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${I.id} <testCorpId>`);let H=await N3(U),V=(Array.isArray(H.features)?H.features:[]).find((u)=>u?.code==="ai-approval"),X=typeof V?.balance==="number"?V.balance:0,L=typeof V?.deductionAmount==="number"&&V.deductionAmount>0?V.deductionAmount:120,D=Y*L;if(X<D)throw new N4(`测试企业「${z.name}」AI 审批额度不足:当前剩余 ${X} 点,本次回归抽样 ${Y} 笔需要约 ${D} 点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${z.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1,Math.floor(X/L))})`);let O=await s4(q,{limit:Y,status:"completed"}),A=Array.isArray(O.records)?O.records:[];if(A.length===0){let u=await s4(q,{limit:Y});A=Array.isArray(u.records)?u.records:[]}if(A.length===0)throw new N4(`在母企业「${I.name}」(${I.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(A=A.slice(0,Y),J){let u=A.map((c)=>{let m=c.sourceDocumentSN??c.id,e=c?.result?.decision??c.aiDecision??c?.decision,G0=Jf(e),M0=c?.result?.summary??c.aiSummary;return{sn:m,sourceRecordId:c.id,prodDecision:G0,prodSummary:M0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:I.id,name:I.name,environment:I.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:X,deductionAmount:L,estimatedRequired:D},metrics:{sampleCount:u.length,successCount:u.length,failureCount:0,matchCount:u.length,flipCount:0,concordanceRate:1},flips:[],records:u}}let T=await Jx(U,z),M=[];for(let u of A){let c=Date.now(),m=u.sourceDocumentSN??u.id,e=Jf(u?.result?.decision??u.aiDecision??u?.decision),G0=u?.result?.summary??u.aiSummary;try{let M0=await X4(q,u.id),g0=`${w}${m}`,G1=Ux(M0,{snPrefix:w,docIdPrefix:w});await Yx(T.incomingDocumentWebhook.url,T.secret,G1,G,p4(z.seal));let S0=null,$1=Date.now();while(Date.now()-$1<K){await new Promise((S4)=>setTimeout(S4,Q));let T4=await s4(U,{sourceDocumentSN:g0,limit:1});if(T4.records&&T4.records.length>0){let S4=T4.records[0];if(S4.status==="completed"||S4.status==="failed"){S0=S4;break}}}if(!S0){M.push({sn:m,sourceRecordId:u.id,prodDecision:e,prodSummary:G0,status:"FAILED",error:`测试租户单据审核超时 (${Math.round(K/1000)}s 未完成)`,durationMs:Date.now()-c});continue}let A0=Jf(S0?.result?.decision??S0.aiDecision??S0?.decision??(S0.status==="completed"?"APPROVE":"ERROR")),U0=S0?.result?.summary??S0.aiSummary,v0=e===A0,I1=v0?"MATCHED":"FLIPPED",W1={sn:m,sourceRecordId:u.id,prodDecision:e,prodSummary:G0,testRecordId:S0.id,testDecision:A0,testSummary:U0,status:I1,durationMs:Date.now()-c};if(!v0)W1.diff={from:e,to:A0,reasonDiff:U0&&G0&&U0!==G0?`生产: ${G0.slice(0,60)}... -> 测试: ${U0.slice(0,60)}...`:void 0};M.push(W1)}catch(M0){M.push({sn:m,sourceRecordId:u.id,prodDecision:e,prodSummary:G0,status:"FAILED",error:M0 instanceof Error?M0.message:String(M0),durationMs:Date.now()-c})}}let v=M.filter((u)=>u.status==="MATCHED"||u.status==="FLIPPED"),x=M.filter((u)=>u.status==="MATCHED"),h=M.filter((u)=>u.status==="FLIPPED"),k=M.filter((u)=>u.status==="FAILED").length,E=x.length,f=h.length,n=E+f,g=n>0?E/n:0,b=f>0,p=b?"REGRESSIONS_DETECTED":"CLEAN",q0=!b&&k===0,R;try{let u=await N3(U),m=(Array.isArray(u.features)?u.features:[]).find((e)=>e?.code==="ai-approval");if(typeof m?.balance==="number")R=m.balance}catch{}return{ok:!b&&k===0,verdict:p,safeToPublish:q0,timestamp:new Date().toISOString(),sourceCorp:{id:I.id,name:I.name,environment:I.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:X,deductionAmount:L,estimatedRequired:D,balanceAfter:R},metrics:{sampleCount:M.length,successCount:v.length,failureCount:k,matchCount:E,flipCount:f,concordanceRate:Number(g.toFixed(4))},flips:h,records:M}}function VN0($){let{sourceCorp:I,targetCorp:z,verdict:q,safeToPublish:U,metrics:Y,quota:J,flips:Q,records:K}=$,w=q==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":q==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",G=["",`\uD83E\uDDEA [Seal Use Test] 规则回归测试矩阵: 生产「${I.name}」-> 测试靶场「${z.name}」`,` 判定: ${w} · 准许发布: ${U?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),` 样本总数: ${Y.sampleCount} | 一致通过: ${Y.matchCount} | 决策翻转: ${Y.flipCount} | 异常失败: ${Y.failureCount}`,` 一致率: ${(Y.concordanceRate*100).toFixed(1)}% | 消耗预估: ${J.estimatedRequired} 点 (余量: ${J.balanceBefore}${J.balanceAfter!==void 0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(Q.length>0){G.push(` ⚠️ 决策翻转清单 (${Q.length} 笔单据在新规则下结果改变):`);for(let H of Q)if(G.push(` • 单据 [${H.sn}]: 原生产判定「${H.prodDecision}」 ➔ 测试新判定「${H.testDecision}」`),H.diff?.reasonDiff)G.push(` 理由差异: ${H.diff.reasonDiff}`);G.push(" "+"─".repeat(65)),G.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(q==="CLEAN")G.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% Line truncated
`)}async function Qf($,I,z){let q=($??I??"regression").toLowerCase();if(q==="regression"||q==="regress"||q==="matrix"){let U=j(z.options.corp)??(I&&I!==q?I:void 0),Y=w1(U),J=Y,Q=Y;if(Y.environment==="test"){Q=Y;let A=j(z.options["prod-corp"])??j(z.options.prod)??Y.prodCorpId;if(!A)throw new N4(`测试企业「${Y.name}」(${Y.id}) 未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-use corps bind-test <prodCorpId> ${Y.id}`);J=w1(A)}else{J=Y;let A=j(z.options["test-corp"])??j(z.options.test)??Y.testCorpId;if(!A)throw new N4(`生产企业「${Y.name}」(${Y.id}) 未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${Y.id} <testCorpId>`);Q=w1(A)}let K=await J1(J),w=await J1(Q),G=_0(z.options.samples)??_0(z.options.limit)??_0(z.options.n)??10,H=V0(z.options["dry-run"]),W=V0(z.options["fail-on-flips"]),V=_0(z.options["poll-interval"])??2000,X=_0(z.options.timeout)??45000,L=j(z.options["sn-prefix"])??"REG_",D=await WN0({sourceCorp:J,targetCorp:Q,sourceClient:K,targetClient:w,samples:G,dryRun:H,pollIntervalMs:V,timeoutMs:X,snPrefix:L,failOnFlips:W});if(!(V0(z.options.quiet)||V0(z.options.silent)))console.error(VN0(D));if(T0(D),W&&!D.ok)throw new N4(`回归测试发现 ${D.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,1);return}throw new N4(`未知的 test 子命令: "${q}"。
可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,2,"seal-use test regression --help")}A4();G4();u1();async function ZN0($,I,z,q){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await N0($,I,z,s6(q.json),Z0(q.options))}fO();u1();function XN0(){T0(Jw.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as nX1,mkdirSync as iX1,renameSync as Kf,rmSync as pX1,unlinkSync as NN0,writeFileSync as LN0}from"node:fs";import{dirname as cX1,join as DN0}from"node:path";import{spawnSync as dI}from"node:child_process";function GF($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let z=$.toLowerCase().replace(/\\/g,"/");return!z.endsWith("/bun")&&!z.endsWith("/bun.exe")&&!z.endsWith("/node")&&!z.endsWith("/node.exe")}u1();var MN0="yunyingk/seal-use",Ow="yunyingk/seal-home";var dX1="SEAL_USE_GITHUB_REPO",mX1="SEAL_HOME_GITHUB_REPO";async function AN0($,I={}){let z={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Uf,version:q1,launcher:$.launcher},q=I.repo||process.env[dX1]?.trim()||process.env[mX1]?.trim()||MN0,U=I.targetVersion?.trim(),Y=U&&U.toLowerCase()!=="latest"?U:void 0;if(Y){let M=Y.replace(/^v/,""),v=PN0(M,q1);if(v<0)if(!Dj&&I.force);else{T0({updated:!1,currentVersion:q1,targetVersion:M,mode:GF()?"binary":"source",message:!Dj?`Cannot downgrade seal-use from dev build v${q1} to release v${M}. Use --force to overwrite.`:`Cannot downgrade seal-use from v${q1} to older version v${M}. Updates must be forward-only.`});return}if(v===0&&!I.force){T0({updated:!1,currentVersion:q1,targetVersion:M,mode:GF()?"binary":"source",message:`seal-use is already at version v${q1}. Use --force to reinstall.`});return}}if(I.changelogOnly){let M=await wf(q,I.limit??10);T0({currentVersion:q1,totalQueried:M.length,releases:M.map((v)=>({version:v.version,tagName:v.tagName,publishedAt:v.publishedAt,author:v.author,releaseNotes:v.notes,releaseUrl:v.htmlUrl,isCurrent:v.version===q1,isNewer:Dw(v.version,q1)}))});return}if(!GF()){if(I.checkOnly){let v=await wf(q,30),x=v[0],h=x?.version??q1,k=v.find((n)=>n.version===q1),E=Dw(h,q1),f=v.filter((n)=>Dw(n.version,q1));T0({updated:!1,updateAvailable:E,currentVersion:q1,currentVersionPublishedAt:k?.publishedAt,latestVersion:h,latestVersionPublishedAt:x?.publishedAt,behindCount:f.length,pendingReleases:f.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.htmlUrl})),releaseNotes:x?.notes??"",releaseUrl:x?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let M=XY(z).running;if(M)await cI("stop",z);try{FN0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(v){console.error(`git pull skipped: ${v instanceof Error?v.message:String(v)}`)}if(FN0("bun",["install"],{cwd:$.appRoot}),M)await cI("start",z);T0({updated:!0,serviceRestarted:M,version:q1,mode:"source"});return}let J=lX1(),Q=oX1(),K=await wf(q,30),w=Y?K.find((M)=>M.version===Y||M.tagName===Y||M.tagName===`v${Y}`)??await ON0(q,Y):K[0]??await ON0(q);if(!w){T0({updated:!1,currentVersion:q1,mode:"binary",message:`Failed to query releases from repository '${q}'`});return}let G=w.version,H=K.find((M)=>M.version===q1),W=Dw(G,q1),V=W||Boolean(I.force),X=K.filter((M)=>Dw(M.version,q1));if(I.checkOnly){T0({updated:!1,updateAvailable:W,currentVersion:q1,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:w.publishedAt,behindCount:X.length,pendingReleases:X.map((M)=>({version:M.version,tagName:M.tagName,publishedAt:M.publishedAt,author:M.author,releaseNotes:M.notes,releaseUrl:M.htmlUrl})),releaseNotes:w.notes,releaseUrl:w.htmlUrl,mode:"binary"});return}if(!V){T0({updated:!1,currentVersion:q1,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:w.publishedAt,mode:"binary",message:`seal-use is already up to date (v${q1})`});return}let L=rX1(w.assets,J,Q);if(!L)throw Error(`No compatible binary found for ${J}-${Q} in release v${G}. Available assets: ${w.assets.map((M)=>M.name).join(", ")}`);let D=XY(z).running;if(D)await cI("stop",z);let O=process.execPath,A=cX1(O),T=DN0(A,`.tmp-update-${Date.now()}`);iX1(T,{recursive:!0});try{let M=DN0(T,L.name);await tX1(L.downloadUrl,M,w.tagName,L.name);let v=M;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))v=aX1(M,T,J);else if(L.name.endsWith(".zip"))v=sX1(M,T,J);if(nX1(v,493),process.platform==="darwin")try{dI("/usr/bin/codesign",["--remove-signature",v],{stdio:"ignore"}),dI("/usr/bin/codesign",["--force","--sign","-",v],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let h=`${O}.old.${Date.now()}`;try{Kf(O,h)}catch{}Kf(v,O)}else Kf(v,O);if(D)await cI("start",z);let x=mk();T0({updated:!0,fromVersion:q1,toVersion:G,serviceRestarted:D,skillSynced:x.synced?x.targetDir:!1,mode:"binary"})}finally{try{pX1(T,{recursive:!0,force:!0})}catch{}}}function lX1(){if(process.platform==="darwin")retur Line truncated
`)}catch{}}async function tX1($,I,z,q){let U=Gf(),Y=[],J=z?z.startsWith("v")?z:`v${z}`:void 0,Q=q||$.split("/").pop()||"";if(U!=="github"){if(J&&Q)Y.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${Q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${Q}`);if($.startsWith("https://git.ying-qing.cn"))Y.push($)}if(U!=="gitea")if(J&&Q){let L=`https://github.com/${MN0}/releases/download/${J}/${Q}`;if(!process.env.CI)Y.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);Y.push(L)}else if($.includes("github.com")){if(!process.env.CI)Y.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Y.push($)}else Y.push($);let K=Array.from(new Set(Y)),w,G=6000,H=6000,W=307200,V=1e4,X=180000;for(let L=0;L<K.length;L++){let D=K[L],O=new AbortController,A="",T=(h)=>{A=h;try{O.abort()}catch{}},M=setTimeout(()=>{T("Connection timed out (no response headers within 6s)")},G),v,x;try{HF(`==> [${L+1}/${K.length}] Downloading via: ${D}`);let h=await fetch(D,{signal:O.signal});if(M)clearTimeout(M),M=void 0;if(!h.ok)throw Error(`HTTP ${h.status} ${h.statusText}`);v=setTimeout(()=>{T("Overall download time exceeded 3 minutes")},X);let k=Number(h.headers.get("content-length"))||0,E=h.body?.getReader();if(!E){let p=Buffer.from(await h.arrayBuffer());if(p.length<1000)throw Error(`Downloaded content is suspiciously small (${p.length} bytes)`);LN0(I,p),HF(`✓ Download succeeded (${(p.length/1024/1024).toFixed(1)} MB)`);return}let f=[],n=0,g=0;x=setTimeout(()=>{if(n<W){let p=(n/1024).toFixed(1);T(`Initial transfer too slow (${p} KB < 300 KB in 6s), switching mirror...`)}},H);while(!0){let p=E.read(),q0,R=new Promise((e,G0)=>{q0=setTimeout(()=>{G0(Error("Data transfer stalled (no chunk received for 10s)"))},V)}),u;try{u=await Promise.race([p,R])}finally{if(q0)clearTimeout(q0)}let{done:c,value:m}=u;if(c)break;if(m){if(f.push(m),n+=m.length,x&&n>=W)clearTimeout(x),x=void 0;let e=Date.now();if(e-g>200){g=e;let G0=k?Math.round(n/k*100):0,M0=(n/1048576).toFixed(1),g0=k?(k/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${G0}% (${M0} / ${g0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let b=Buffer.concat(f);if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);LN0(I,b),HF(`✓ Download completed successfully (${(b.length/1024/1024).toFixed(1)} MB)`);return}catch(h){if(M)clearTimeout(M);if(x)clearTimeout(x);if(v)clearTimeout(v);let k=A||(h instanceof Error?h.message:String(h));w=Error(k),HF(`
↳ Mirror failed: ${w.message}`)}finally{if(M)clearTimeout(M);if(x)clearTimeout(x);if(v)clearTimeout(v)}}throw Error(`Failed to download asset from all mirrors: ${w?.message}`)}function aX1($,I,z){let q=dI("tar",["-xzf",$,"-C",I],{stdio:"pipe"});if(q.status!==0)throw Error(`Failed to extract tar archive: ${q.stderr.toString()}`);NN0($);let U=z==="windows"?"seal-use.exe":"seal-use",Y=dI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),J=Y.find((Q)=>Q.endsWith(`/${U}`)||Q.endsWith(U));if(J)return J;return Y[0]||$}function sX1($,I,z){let q=dI("unzip",["-q","-o",$,"-d",I],{stdio:"pipe"});if(q.status!==0)throw Error(`Failed to extract zip archive: ${q.stderr.toString()}`);NN0($);let U=z==="windows"?"seal-use.exe":"seal-use",Y=dI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),J=Y.find((Q)=>Q.endsWith(`/${U}`)||Q.endsWith(U));if(J)return J;return Y[0]||$}function PN0($,I){let z=$.replace(/^v/,"").split(".").map((U)=>Number.parseInt(U,10)||0),q=I.replace(/^v/,"").split(".").map((U)=>Number.parseInt(U,10)||0);for(let U=0;U<Math.max(z.length,q.length);U++){let Y=z[U]??0,J=q[U]??0;if(Y>J)return 1;if(Y<J)return-1}return 0}function Dw($,I){return PN0($,I)>0}function FN0($,I,z={}){let q=dI($,I,{cwd:z.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(q.stdout)console.error(q.stdout.trimEnd());if(q.stderr)console.error(q.stderr.trimEnd());if(q.status!==0)throw Error(`${$} ${I.join(" ")} failed with status ${q.status}`)}A4();G4();u1();async function TN0($,I,z,q,U){if($==="create"){let Y=j(U.options.name)??I,J=j(U.options.phone);if(!Y||!J)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let Q=j(U.options.dept)??j(U.options.departmentId);await N0("seal_user_create",z,q,{name:Y,phone:J,departmentIds:Q?[Q]:void 0},Z0(U.options));return}if($==="reset-password"){let Y=I??j(U.options.userId);if(!Y)throw Error("Usage: seal-use users reset-password <userId>");await N0("seal_user_reset_password",z,q,{userId:Y},Z0(U.options));return}if($==="search"||$==="list"){let Y=I??j(U.options.keyword)??j(U.options.query)??"";await N0("seal_user_search",z,q,{keyword:Y},Z0(U.options));return}if($==="get"){let Y=I??j(U.options.userId);if(!Y)throw Error("Usage: seal-use users get <userId>");await N0("seal_user_get",z,q,{userId:Y},Z0(U.options));return}if($==="delete"){let Y=I??j(U.options.userId);if(!Y)throw Error("Usage: seal-use users delete <userId>");await N0("seal_user_delete",z,q,{userId:Y},Z0(U.options));return}if($==="activate"){let Y=I??j(U.options.userId);if(!Y)throw Error("Usage: seal-use users activate <userId>");await N0("seal_user_activate",z,q,{userId:Y},Z0(U.options));return}if($==="delegation"||$==="impersonate"){let Y=I??j(U.options.userId)??j(U.options.phone);if(!Y)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let J=j(U.options.note);await N0("seal_user_delegation_create",z,q,{userIdOrPhone:Y,note:J},Z0(U.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}k$();A4();G4();_k();u1();var EN0=Hf(Hf(Hf($L1(import.meta.url)))),IL1=new Set(["config","service","stop","http","serve","update","tools","corps","corp","tool","source","auth","delegation","users","contacts","data","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","analytics","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","doctor","changelog","test"]),zL1=new Set(["http","server","web","mcp"]);function qL1($){if(!$.length)return!1;let I=$[0]?.toLowerCase(),z=$[1]?.toLowerCase();if(I&&zL1.has(I))return!0;if((I==="service"||I==="daemon")&&z==="run")return!0;return!1}var BN0=Promise.resolve();function Xw($,I={}){if(qL1($))return jN0($,I);let z=BN0.then(()=>jN0($,I));return BN0=z.then(()=>{return},()=>{return}),z}async function jN0($,I){let z=[],q=[],U=console.log,Y=console.error,J={appRoot:I.appRoot??EN0,entryFile:I.entryFile??eX1(I.appRoot??EN0,"src","cli.ts"),launcher:I.launcher};console.log=(...Q)=>{z.push(Ck(Q))},console.error=(...Q)=>{q.push(Ck(Q))};try{return await UL1($,J),{stdout:Kw(z),stderr:Kw(q),isError:!1,exitCode:0}}catch(Q){let K=ww(Q instanceof Error?Q.message:String(Q)),w=UO(Q);if(q.push(K),w.nextAction&&!K.includes("Next action:"))q.push(`\uD83D\uDC49 Next action: ${w.nextAction}`);return{stdout:Kw(z),stderr:Kw(q),isError:!0,exitCode:w.exitCode}}finally{console.log=U,console.error=Y}}async function UL1($,I){let z=Ek($),[q,U,Y]=z.command;if(q==="version"||q==="v"||Boolean(z.options.version)||Boolean(z.options.v)||Boolean(z.options.V)){T0(UQ);return}let J=bD0(z);if(J.isHelp){cD0(J.target);return}if(!q||!IL1.has(q))throw Error(`Unknown command: ${z.command.join(" ")}. Run 'seal-use help' for available commands.`);if(q==="webhook"&&U==="material-pack"&&Y==="preview"){let w=z.command[3]??j(z.options.file)??j(z.options.input);if(!w)throw Error("Usage: seal-use webhook material-pack preview <材料包.zip>");await lD0(w,GY(z.options));return}if(q==="openapi"){aF0(z);return}if(q==="mcp-config"){sk();return}if(q==="skill"){GN0(U,Y,z);return}if(q==="mcp"||q==="server"){await tF0(U,z);return}if(q==="probe"){await zN0(U,Y,z);return}if(q==="doctor"){await cF0(U,Y,z);return}if(q==="test"){await Qf(U,Y,z);return}if(q==="config"){$O0(U,Y,z);return}if(q==="service"){await Yf(U,I,z);return}if(q==="stop"){await Yf("stop",I,z);return}if(q==="http"||q==="serve"){await oF0(z);return}if(q==="update"||q==="changelog"){let w=q==="changelog"||U==="changelog"||U==="log"||U==="history"||V0(z.options.changelog)===!0,G=U==="check"||V0(z.options.check)===!0||V0(z.options["check-only"])===!0,H=j(z.options.version)??j(z.options.tag)??(!w&&!G&&U&&!U.startsWith("-")?U:void 0);await AN0(I,{checkOnly:G,changelogOnly:w,lim Line truncated
</html>`}async function B6($,q,Y,z){let U=$.handler;return U(q,Y,{corp:z})}async function jg0($,q){if(q.setHeader("Access-Control-Allow-Origin","*"),q.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),q.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),$.method==="OPTIONS"){q.writeHead(204),q.end();return}let Y=$.headers.host||"localhost",z=$.headers["x-forwarded-proto"]||"http",U=new db1($.url||"/",`${z}://${Y}`),I=U.pathname.replace(/\/+$/,"")||"/",J=($.method||"GET").toUpperCase();try{if(J==="GET"&&I==="/"){V4(q,200,{name:"seal-use",version:Q1,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(J==="GET"&&I==="/docs"){lb1(q,200,Eg0());return}if(J==="GET"&&I==="/openapi.json"){V4(q,200,qP());return}if(J==="GET"&&I==="/health"){V4(q,200,{status:"ok",version:Q1,name:"seal-use",timestamp:new Date().toISOString()});return}if(J==="POST"&&(I==="/shutdown"||I==="/api/shutdown")){V4(q,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(J==="POST"&&I==="/api/cli"){let Q=await zP($),K=(typeof Q?.command==="string"?Q.command:"").trim();if(!K){YP(q,400,"Missing 'command' property in request body");return}let H=vd(K),G=H[0]==="seal-use"||H[0]==="seal-home"||H[0]?.endsWith("/seal-use")||H[0]?.endsWith("/seal-home")?H.slice(1):H,Z=await ZW(G),V=void 0;try{if(Z.stdout.trim().startsWith("{")||Z.stdout.trim().startsWith("["))V=JSON.parse(Z.stdout)}catch{}V4(q,Z.isError?400:200,{success:!Z.isError,stdout:Z.stdout,stderr:Z.stderr,exitCode:Z.exitCode,data:V});return}if(J==="POST"&&I.startsWith("/api/tool/")){let Q=I.slice(10).trim(),K=X6(Q);if(!K){YP(q,404,`Tool not found: '${Q}'`);return}let H=await zP($)||{},G=v8($,U,H),Z=w1(G),V=await Z1(Z),X={...H};delete X.corp;let w=await B6(K,V,X,Z);V4(q,200,w);return}if(I.startsWith("/v1/")){if(await mb1($,q,J,I,U))return}YP(q,404,`Cannot ${J} ${I}. Visit /docs for available endpoints.`)}catch(Q){let K=Q instanceof Error?Q.message:String(Q);YP(q,500,K)}}async function mb1($,q,Y,z,U){let I=Object.fromEntries(U.searchParams.entries());if(Y==="GET"&&z==="/v1/corps"){let J=r8(),Q=B4();return V4(q,200,{count:J.length,mode:Q.stateful?"stateful":"stateless",defaultCorpId:Q.defaultCorpId,corps:J.map((K)=>({id:K.id,name:K.name,sourceType:K.source.type,sealUrl:K.seal?.url}))}),!0}if(Y==="GET"&&z==="/v1/whoami"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_whoami"),G=await B6(H,K,{},Q);return V4(q,200,G),!0}if(Y==="GET"&&z==="/v1/session"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_session_get"),G=await B6(H,K,{},Q);return V4(q,200,G),!0}if(Y==="GET"&&z==="/v1/approval-runs/summary"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_approval_runs_summary"),G=await B6(H,K,I,Q);return V4(q,200,G),!0}if(Y==="GET"&&z==="/v1/approval-runs/stats"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_approval_runs_stats"),G=await B6(H,K,I,Q);return V4(q,200,G),!0}if(Y==="GET"&&z==="/v1/approval-runs/pick"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_approval_run_pick"),G=await B6(H,K,I,Q);return V4(q,200,G),!0}if(Y==="GET"&&z==="/v1/approval-runs/url"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_approval_run_url_get"),G=await B6(H,K,I,Q);return V4(q,200,G),!0}if(z.startsWith("/v1/approval-runs/")){let J=z.slice(18).split("/"),Q=J[0],K=J[1];if(Q&&!["summary","pick","stats","url","bridge"].includes(Q)){let H=v8($,U,I),G=w1(H),Z=await Z1(G);if(!K){let V=X6("seal_approval_run_get"),X=await B6(V,Z,{recordId:Q,...I},G);return V4(q,200,X),!0}if(K==="attachments"){let V=X6("seal_approval_run_attachments_get"),X=await B6(V,Z,{recordId:Q,...I},G);return V4(q,200,X),!0}if(K==="cited-rules"){let V=X6("seal_approval_run_cited_rules_get"),X=await B6(V,Z,{recordId:Q,...I},G);return V4(q,200,X),!0}if(K==="document-summary"){let V=X6("seal_approval_run_document_summary_get"),X=await B6(V,Z,{recordId:Q,...I},G);return V4(q,200,X),!0}if(K==="result"){let V=X6("seal_approval_run_result_get"),X=await B6(V,Z,{recordId:Q,...I},G);return V4(q,200,X),!0}}}if(Y==="GET"&&z==="/v1/approval-runs"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_approval_runs_search"),G=await B6(H,K,{...I,limit:I.limit?Number(I.limit):void 0,offset:I.offset?Number(I.offset):void 0,includeBridge:I.includeBridge==="true"},Q);return V4(q,200,G),!0}if(Y==="GET"&&z==="/v1/approval/rules"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_approval_rules_list"),G=await B6(H,K,I,Q);return V4(q,200,G),!0}if(Y==="GET"&&z==="/v1/simulation/batches"){let J=v8($,U,I),Q=w1(J),K=await Z1(Q),H=X6("seal_simulation_batches_list"),G=await B6(H,K,I,Q);return V4(q,200,G),!0}if(Y==="POST"&&z==="/v1/simulation/create-batch"){let J=await zP($)||{},Q=v8($,U,J),K=w1(Q),H=await Z1Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${Q1}) started`),console.error(` URL: http://${Y}:${q}`),console.error(` Docs: http://${Y}:${q}/docs`),console.error(` OpenAPI: http://${Y}:${q}/openapi.json`),console.error(` CLI Exec: POST http://${Y}:${q}/api/cli`),console.error(` REST API: http://${Y}:${q}/v1/...
`);U(z)})})}async function _g0($){let q=g0($.options.port)??g0($.options.p),Y=E($.options.host)??E($.options.h),z=await JP({port:q,host:Y}),U=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",U),process.on("SIGTERM",U),await new Promise(()=>{})}p4();o1();async function Cg0($,q,Y,z){if($==="config"||$==="get"){await P0("seal_llm_config_get",q,Y,{},F0(z.options));return}if($==="providers"||$==="list"){await P0("seal_llm_providers_list",q,Y,{},F0(z.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}o1();async function Rg0($,q){if($==="config"||$==="json"){hd();return}await gd()}function hd(){j0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}o1();function vg0($){let q=qP();j0(q,{...F0($.options),allowFull:!0})}p4();o1();async function hg0($,q,Y,z){if($==="available"){await P0("seal_permissions_available_list",q,Y,{},F0(z.options));return}if($==="configs"||$==="list"){await P0("seal_permissions_configs_list",q,Y,{},F0(z.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}p4();_4();o1();import{readFileSync as gg0}from"node:fs";async function Sg0($,q,Y,z,U,I,J){if(!$||$==="get"){await P0("seal_preference_get",U,I,{},F0(J.options));return}if($==="decision"){if(q==="update"||!q){let Q=E(J.options.input),K=Q?JSON.parse(gg0(Q,"utf8")):R8(J.json);if(!K||Object.keys(K).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await P0("seal_preference_decision_update",U,I,{...K,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(q==="set"){let Q=E(J.options.default)??E(J.options.level)??z;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await P0("seal_preference_thinking_depth_set",U,I,{defaultLevel:Q,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}if(q==="policies"){if(Y==="list"||!Y){await P0("seal_preference_thinking_depth_policies_list",U,I,{},F0(J.options));return}if(Y==="upsert"){let Q=E(J.options.input),K=Q?JSON.parse(gg0(Q,"utf8")):R8(J.json);if(!K||!K.id||!K.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await P0("seal_preference_thinking_depth_policies_upsert",U,I,{...K,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}if(Y==="remove"||Y==="delete"){let Q=z??E(J.options.id)??E(J.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await P0("seal_preference_thinking_depth_policies_remove",U,I,{policyId:Q,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}Q3();b8();J6();async function yg0($={}){let q=r8(),Y=B4(),z=e7(q,{stateful:Y.stateful,defaultCorpId:Y.defaultCorpId,corpId:$.corpId},J3());console.log(`[probe] corp=${z.id} source=${z.source.type}`);let U=await jJ(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(U,null,2));let I=await Z1(z),J=await dw(I,{documentLimit:20,stylePreferencesEndpoint:z.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error: ${J.stylePreferences.error}`},null,2))}_4();async function xg0($,q,Y){let z=q??E(Y.options.corp)??($&&$!=="--corp"?$:void 0);await yg0({corpId:z})}ei();p4();V$();_4();o1();async function Sd($,q,Y,z,U){if($==="count"){await P0("seal_approval_rules_list",Y,z,{countOnly:!0},F0(U.options));return}if($==="list"){if(W0(U.options.count)){await P0("seal_approval_rules_list",Y,z,{countOnly:!0},F0(U.options));return}let I=g0(U.options.limit),J=g0(U.options.offset);if(W0(U.options.summary)){await P0("seal_approval_rules_list",Y,z,{fields:Av0,limit:I,offset:J},F0(U.options));return}let Q=await H2("seal_approval_rules_list",Y,z,{limit:I,offset:J});Pv0(Q,W0(U.options.full)===!0),j0(Q);return}if($==="clear"){let I=W0(U.options.yes)===!0,J=W0(U.options.dryRun)??W0(U.options["dry-run"])??!I;if(!I&&!J)throw Q9("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${z.id} --dry-run`);let Q=await H2("seal_approval_rules_clear",Y,z,{dryRun:J,recode:W0(U.options.recode)});if(!I&&J&&Q&&typeof Q==="object"){j0({...Q,nextCommand:`seal-use rules clear --corp ${z.id} --yes`},F0(U.options));return}j0(Q,F0(U.options));return}if($==="versions"){await P0("seal_approval_rule_versions_list",Y,z,{},F0(U.options));return}if($==="version"){let I=q??E(U.op Line truncated
`).filter(Boolean),I=U.slice(-q);return{logFile:Y,lines:I,totalLines:U.length}}async function eb1($){let q=GP($),Y=kd($),z=WW($);bg0($.stateDir);let U=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):UP),I=$.host??(process.env.HOST?process.env.HOST:IP);KP(q,`${process.pid}
`,{mode:384}),KP(Y,JSON.stringify({pid:process.pid,port:U,host:I,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),_J(z,`service starting on http://${I}:${U} pid=${process.pid}`);let J=null;try{J=await JP({port:U,host:I,silent:!0}),_J(z,`service listening pid=${process.pid}`)}catch(K){if(_J(z,`service failed to bind port ${U}: ${K instanceof Error?K.message:String(K)}`),HP(q)===process.pid)L9(q,{force:!0}),L9(Y,{force:!0});throw K}let Q=()=>{if(J)J.close(),J=null;if(HP(q)===process.pid)L9(q,{force:!0}),L9(Y,{force:!0});_J(z,`stopped pid=${process.pid}`)};await new Promise((K)=>{let H=!1,G=()=>{if(H)return;H=!0,Q(),process.off("SIGTERM",G),process.off("SIGINT",G),K()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function kg0($){bg0($.stateDir);let q=CJ($);if(q.running)return q;let Y=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...Y.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let U=rb1(Y.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});U.unref();let I=GP($);return KP(I,`${U.pid}
`,{mode:384}),_J(WW($),`started pid=${U.pid}`),{started:!0,...CJ($)}}function ug0($,q={}){let Y=GP($),z=kd($),U=HP(Y);if(!U||!fg0(U,$.appRoot))return L9(Y,{force:!0}),L9(z,{force:!0}),q.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(U,"SIGTERM"),L9(Y,{force:!0}),L9(z,{force:!0}),_J(WW($),`stop requested pid=${U}`),q.quiet?void 0:{stopped:!0,pid:U}}function fg0($,q){if(!$i1($))return!1;try{let Y=sb1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(Y.includes(q)||Y.includes("seal-use")||Y.includes("src/cli.ts"))&&Y.includes("service")&&Y.includes("run")}catch{return!1}}function $i1($){try{return process.kill($,0),!0}catch{return!1}}function GP($){return xd($.stateDir,"service.pid")}function kd($){return xd($.stateDir,"service.json")}function WW($){return xd($.stateDir,"service.log")}function HP($){if(!QP($))return;let q=Number(yd($,"utf8").trim());return Number.isInteger(q)&&q>0?q:void 0}function bg0($){tb1($,{recursive:!0,mode:448})}function _J($,q){KP($,`${new Date().toISOString()} ${q}
`,{flag:"a",mode:384})}o1();_4();var ud=Yi1(qi1(),".config","seal-use");async function fd($,q,Y){let z=Y?g0(Y.options.port)??g0(Y.options.p):void 0,U=Y?E(Y.options.host)??E(Y.options.h):void 0,I=Y?g0(Y.options.lines)??g0(Y.options.n):void 0,J=await EY($,{appRoot:q.appRoot,entryFile:q.entryFile,stateDir:ud,version:Q1,launcher:q.launcher,port:z,host:U},{maxLines:I});if(J!==void 0)j0(J)}p4();_4();o1();import{existsSync as zi1,readFileSync as ig0}from"node:fs";async function ng0($,q,Y,z,U){if($==="batch-records"||$==="records"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation batch-records <batchId>");await P0("seal_simulation_batch_records_get",Y,z,{batchId:I,query:E(U.options.query)},F0(U.options));return}if($==="create"||$==="run"){let I=E(U.options.mode)??E(U.options.sourceSystem)??E(U.options["source-system"])??"hosecloud",J=I==="material-pack"?"material_pack":I,Q=E(U.options.schemaConfig)??E(U.options["schema-config"]),K=Q?JSON.parse(ig0(Q,"utf8")):void 0,H=E(U.options.input),G=H?JSON.parse(ig0(H,"utf8")):R8(U.json),Z=E(U.options.packageId)??E(U.options["package-id"]),V=v6(U.options.packageIds)??v6(U.options["package-ids"])??(Z?[Z]:void 0),X=v6(U.options.flowIds)??v6(U.options["flow-ids"])??v6(U.options.documentSn)??v6(U.options["document-sn"]),w=E(U.options.signKey)??E(U.options["sign-key"])??E(U.options.integration),L=W0(U.options.noWait)??W0(U.options["no-wait"]);await P0("seal_simulation_batch_create",Y,z,{mode:J,sourceSystem:J,flowIds:X,documentSn:X,rejectNodeName:E(U.options.rejectNode)??E(U.options["reject-node"])??null,thinkingDepthOverride:E(U.options.thinkingDepth)??E(U.options["thinking-depth"]),skipInvoiceGeneration:W0(U.options.skipInvoiceGeneration)??W0(U.options["skip-invoice-generation"]),skipExpenseExtraction:W0(U.options.skipExpenseExtraction)??W0(U.options["skip-expense-extraction"]),disableAttachmentCache:W0(U.options.disableAttachmentCache)??W0(U.options["disable-attachment-cache"]),signKey:w,packageIds:V,packageId:Z,templateId:E(U.options.templateId)??E(U.options["template-id"]),schemaConfig:K,requestIds:v6(U.options.requestIds)??v6(U.options["request-ids"]),workflowTypeId:E(U.options.workflowTypeId)??E(U.options["workflow-type-id"]),flowStatusList:v6(U.options.flowStatusList)?.map(Number)??v6(U.options["flow-status-list"])?.map(Number),businessCodes:v6(U.options.businessCodes)??v6(U.options["business-codes"]),documentType:E(U.options.documentType)??E(U.options["document-type"]),startTime:g0(U.options.startTime)??g0(U.options["start-time"]),endTime:g0(U.options.endTime)??g0(U.options["end-time"]),status:v6(U.options.status),limit:g0(U.options.limit),noWait:L,rawParams:G},F0(U.options));return}if($==="wait"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await P0("seal_simulation_batch_wait",Y,z,{batchId:I,timeout:E(U.options.timeout),pollInterval:E(U.options.pollInterval)??E(U.options["poll-interval"])},F0(U.options));return}if($==="status"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation status <batchId>");await P0("seal_simulation_batch_status",Y,z,{batchId:I},F0(U.options));return}if($==="clean"||$==="delete"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation clean <batchId>");await P0("seal_simulation_batch_clean",Y,z,{batchId:I},F0(U.options));return}if($==="specifications"){let I=q??E(U.options.integration)??E(U.options.signKey)??E(U.options["sign-key"]);await P0("seal_simulation_specifications_list",Y,z,{signKey:I},F0(U.options));return}if($==="approval-definitions"||$==="definitions"){await P0("seal_simulation_feishu_approval_definitions_list",Y,z,{},F0(U.options));return}if($==="list"){await P0("seal_simulation_batches_list",Y,z,{limit:g0(U.options.limit)},F0(U.options));return}if($==="get"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation get <batchId>");await P0("seal_simulation_batch_get",Y,z,{batchId:I},F0(U.options));return}if($==="templates"){await P0("seal_simulation_templates_get",Y,z,{},F0(U.options));return}if($==="integrations"){await P0("seal_simulation_integrations_get",Y,z,{},F0(U.options));return}if($==="package-upload"){let I=q??E(U.options.file);if(!I)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!zi1(I))throw Error(`File not found: ${I}`);await P0("seal_simulation_material_package_upload",Y,z,{filePath:I},F0(U.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as cg0}from"node:fs";import{join as ZP}from"node:path";_4();o1();function pg0($,q,Y){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${Lg0()}
`);return}if($==="install"||$==="init"||$==="sync"){let z=W0(Y.options.local)||W0(Y.options.workspace),U=E(Y.options.dir)??E(Y.options.target)??q,I=U?U:z?ZP(process.cwd(),".agents","skills","seal-use"):TY(),J=Td(I);j0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files});return}if($==="status"||$==="get"||!$){let z=TY(),U=ZP(process.cwd(),".agents","skills","seal-use");j0({global:{dir:z,installed:cg0(ZP(z,"SKILL.md"))},local:{dir:U,installed:cg0(ZP(U,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}o1();async function dg0($,q){if($==="config"){j0(await jJ(q));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}V$();p4();_4();o1();b8();V$();J6();DZ();function bd($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let q=$.toUpperCase().trim();if(q==="APPROVE"||q==="PASS")return"APPROVE";if(q==="REJECT"||q==="DENIED")return"REJECT";if(q==="MANUAL"||q==="ASSISTED")return"MANUAL";if(q==="ERROR"||q==="FAILED")return"ERROR";return q}async function mg0($){let{sourceCorp:q,targetCorp:Y,sourceClient:z,targetClient:U,samples:I=10,dryRun:J=!1,pollIntervalMs:Q=2000,timeoutMs:K=45000,snPrefix:H="REG_",fetchFn:G=fetch}=$;if(Y.environment!=="test")throw new b4(`重放目标企业「${Y.name}」(${Y.id}) 的环境为「${Y.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${q.id} <testCorpId>`);let Z=await g2(U),X=(Array.isArray(Z.features)?Z.features:[]).find((u)=>u?.code==="ai-approval"),w=typeof X?.balance==="number"?X.balance:0,L=typeof X?.deductionAmount==="number"&&X.deductionAmount>0?X.deductionAmount:120,F=I*L;if(w<F)throw new b4(`测试企业「${Y.name}」AI 审批额度不足:当前剩余 ${w} 点,本次回归抽样 ${I} 笔需要约 ${F} 点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${Y.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1,Math.floor(w/L))})`);let O=await y4(z,{limit:I,status:"completed"}),A=Array.isArray(O.records)?O.records:[];if(A.length===0){let u=await y4(z,{limit:I});A=Array.isArray(u.records)?u.records:[]}if(A.length===0)throw new b4(`在母企业「${q.name}」(${q.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(A=A.slice(0,I),J){let u=A.map((p)=>{let d=p.sourceDocumentSN??p.id,Y0=p?.result?.decision??p.aiDecision??p?.decision,t=bd(Y0),H0=p?.result?.summary??p.aiSummary;return{sn:d,sourceRecordId:p.id,prodDecision:t,prodSummary:H0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:q.id,name:q.name,environment:q.environment??"production"},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:F},metrics:{sampleCount:u.length,successCount:u.length,failureCount:0,matchCount:u.length,flipCount:0,concordanceRate:1},flips:[],records:u}}let B=await pi(U,Y),P=[];for(let u of A){let p=Date.now(),d=u.sourceDocumentSN??u.id,Y0=bd(u?.result?.decision??u.aiDecision??u?.decision),t=u?.result?.summary??u.aiSummary;try{let H0=await e1(z,u.id),w0=`${H}${d}`,T0=ni(H0,{snPrefix:H,docIdPrefix:H});await ci(B.incomingDocumentWebhook.url,B.secret,T0,G,L6(Y.seal));let R0=null,E0=Date.now();while(Date.now()-E0<K){await new Promise((a0)=>setTimeout(a0,Q));let R1=await y4(U,{sourceDocumentSN:w0,limit:1});if(R1.records&&R1.records.length>0){let a0=R1.records[0];if(a0.status==="completed"||a0.status==="failed"){R0=a0;break}}}if(!R0){P.push({sn:d,sourceRecordId:u.id,prodDecision:Y0,prodSummary:t,status:"FAILED",error:`测试租户单据审核超时 (${Math.round(K/1000)}s 未完成)`,durationMs:Date.now()-p});continue}let i0=bd(R0?.result?.decision??R0.aiDecision??R0?.decision??(R0.status==="completed"?"APPROVE":"ERROR")),Q0=R0?.result?.summary??R0.aiSummary,v0=Y0===i0,f0=v0?"MATCHED":"FLIPPED",c0={sn:d,sourceRecordId:u.id,prodDecision:Y0,prodSummary:t,testRecordId:R0.id,testDecision:i0,testSummary:Q0,status:f0,durationMs:Date.now()-p};if(!v0)c0.diff={from:Y0,to:i0,reasonDiff:Q0&&t&&Q0!==t?`生产: ${t.slice(0,60)}... -> 测试: ${Q0.slice(0,60)}...`:void 0};P.push(c0)}catch(H0){P.push({sn:d,sourceRecordId:u.id,prodDecision:Y0,prodSummary:t,status:"FAILED",error:H0 instanceof Error?H0.message:String(H0),durationMs:Date.now()-p})}}let T=P.filter((u)=>u.status==="MATCHED"||u.status==="FLIPPED"),y=P.filter((u)=>u.status==="MATCHED"),v=P.filter((u)=>u.status==="FLIPPED"),k=P.filter((u)=>u.status==="FAILED").length,R=y.length,c=v.length,n=R+c,g=n>0?R/n:0,b=c>0,i=b?"REGRESSIONS_DETECTED":"CLEAN",$0=!b&&k===0,j;try{let u=await g2(U),d=(Array.isArray(u.features)?u.features:[]).find((Y0)=>Y0?.code==="ai-approval");if(typeof d?.balance==="number")j=d.balance}catch{}return{ok:!b&&k===0,verdict:i,safeToPublish:$0,timestamp:new Date().toISOString(),sourceCorp:{id:q.id,name:q.name,environment:q.environment??"production"},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:F,balanceAfter:j},metrics:{sampleCount:P.length,successCount:T.length,failureCount:k,matchCount:R,flipCount:c,concordanceRate:Number(g.toFixed(4))},flips:v,records:P}}function lg0($){let{sourceCorp:q,targetCorp:Y,verdict:z,safeToPublish:U,metrics:I,quota:J,flips:Q,records:K}=$,H=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",G=["",`\uD83E\uDDEA [Seal Use Test] 规则回归测试矩阵: 生产「${q.name}」-> 测试靶场「${Y.name}」`,` 判定: ${H} · 准许发布: ${U?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),` 样本总数: ${I.sampleCount} | 一致通过: ${I.matchCount} | 决策翻转: ${I.flipCount} | 异常失败: ${I.failureCount}`,` 一致率: ${(I.concordanceRate*100).toFixed(1)}% | 消耗预估: ${J.estimatedRequired} 点 (余量: ${J.balanceBefore}${J.balanceAfter!==void 0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(Q.length>0){G.push(` ⚠️ 决策翻转清单 (${Q.length} 笔单据在新规则下结果改变):`);for(let Z of Q)if(G.push(` • 单据 [${Z.sn}]: 原生产判定「${Z.prodDecision}」 ➔ 测试新判定「${Z.testDecision}」`),Z.diff?.reasonDiff)G.push(` 理由差异: ${Z.diff.reasonDiff}`);G.push(" "+"─".repeat(65)),G.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")G.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% Line truncated
`)}async function id($,q,Y){let z=($??q??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let U=E(Y.options.corp)??(q&&q!==z?q:void 0),I=w1(U),J=I,Q=I;if(I.environment==="test"){Q=I;let A=E(Y.options["prod-corp"])??E(Y.options.prod)??I.prodCorpId;if(!A)throw new b4(`测试企业「${I.name}」(${I.id}) 未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-use corps bind-test <prodCorpId> ${I.id}`);J=w1(A)}else{J=I;let A=E(Y.options["test-corp"])??E(Y.options.test)??I.testCorpId;if(!A)throw new b4(`生产企业「${I.name}」(${I.id}) 未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${I.id} <testCorpId>`);Q=w1(A)}let K=await Z1(J),H=await Z1(Q),G=g0(Y.options.samples)??g0(Y.options.limit)??g0(Y.options.n)??10,Z=W0(Y.options["dry-run"]),V=W0(Y.options["fail-on-flips"]),X=g0(Y.options["poll-interval"])??2000,w=g0(Y.options.timeout)??45000,L=E(Y.options["sn-prefix"])??"REG_",F=await mg0({sourceCorp:J,targetCorp:Q,sourceClient:K,targetClient:H,samples:G,dryRun:Z,pollIntervalMs:X,timeoutMs:w,snPrefix:L,failOnFlips:V});if(!(W0(Y.options.quiet)||W0(Y.options.silent)))console.error(lg0(F));if(j0(F),V&&!F.ok)throw new b4(`回归测试发现 ${F.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,1);return}throw new b4(`未知的 test 子命令: "${z}"。
可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,2,"seal-use test regression --help")}p4();_4();o1();async function og0($,q,Y,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await P0($,q,Y,R8(z.json),F0(z.options))}iA();o1();function rg0(){j0(YW.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as Ui1,mkdirSync as Ii1,renameSync as nd,rmSync as Ji1,unlinkSync as $S0,writeFileSync as sg0}from"node:fs";import{dirname as Qi1,join as tg0}from"node:path";import{spawnSync as jY}from"node:child_process";function WP($=process.execPath,q=import.meta.url){if(q.includes("/$bunfs/")||q.includes("\\$bunfs\\"))return!0;let Y=$.toLowerCase().replace(/\\/g,"/");return!Y.endsWith("/bun")&&!Y.endsWith("/bun.exe")&&!Y.endsWith("/node")&&!Y.endsWith("/node.exe")}o1();var qS0="yunyingk/seal-use",VW="yunyingk/seal-home";var Ki1="SEAL_USE_GITHUB_REPO",Hi1="SEAL_HOME_GITHUB_REPO";async function YS0($,q={}){let Y={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:ud,version:Q1,launcher:$.launcher},z=q.repo||process.env[Ki1]?.trim()||process.env[Hi1]?.trim()||qS0,U=q.targetVersion?.trim(),I=U&&U.toLowerCase()!=="latest"?U:void 0;if(I){let P=I.replace(/^v/,""),T=zS0(P,Q1);if(T<0)if(!Nv&&q.force);else{j0({updated:!1,currentVersion:Q1,targetVersion:P,mode:WP()?"binary":"source",message:!Nv?`Cannot downgrade seal-use from dev build v${Q1} to release v${P}. Use --force to overwrite.`:`Cannot downgrade seal-use from v${Q1} to older version v${P}. Updates must be forward-only.`});return}if(T===0&&!q.force){j0({updated:!1,currentVersion:Q1,targetVersion:P,mode:WP()?"binary":"source",message:`seal-use is already at version v${Q1}. Use --force to reinstall.`});return}}if(q.changelogOnly){let P=await cd(z,q.limit??10);j0({currentVersion:Q1,totalQueried:P.length,releases:P.map((T)=>({version:T.version,tagName:T.tagName,publishedAt:T.publishedAt,author:T.author,releaseNotes:T.notes,releaseUrl:T.htmlUrl,isCurrent:T.version===Q1,isNewer:XW(T.version,Q1)}))});return}if(!WP()){if(q.checkOnly){let T=await cd(z,30),y=T[0],v=y?.version??Q1,k=T.find((n)=>n.version===Q1),R=XW(v,Q1),c=T.filter((n)=>XW(n.version,Q1));j0({updated:!1,updateAvailable:R,currentVersion:Q1,currentVersionPublishedAt:k?.publishedAt,latestVersion:v,latestVersionPublishedAt:y?.publishedAt,behindCount:c.length,pendingReleases:c.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.htmlUrl})),releaseNotes:y?.notes??"",releaseUrl:y?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let P=CJ(Y).running;if(P)await EY("stop",Y);try{eg0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(T){console.error(`git pull skipped: ${T instanceof Error?T.message:String(T)}`)}if(eg0("bun",["install"],{cwd:$.appRoot}),P)await EY("start",Y);j0({updated:!0,serviceRestarted:P,version:Q1,mode:"source"});return}let J=Gi1(),Q=Zi1(),K=await cd(z,30),H=I?K.find((P)=>P.version===I||P.tagName===I||P.tagName===`v${I}`)??await ag0(z,I):K[0]??await ag0(z);if(!H){j0({updated:!1,currentVersion:Q1,mode:"binary",message:`Failed to query releases from repository '${z}'`});return}let G=H.version,Z=K.find((P)=>P.version===Q1),V=XW(G,Q1),X=V||Boolean(q.force),w=K.filter((P)=>XW(P.version,Q1));if(q.checkOnly){j0({updated:!1,updateAvailable:V,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,behindCount:w.length,pendingReleases:w.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl})),releaseNotes:H.notes,releaseUrl:H.htmlUrl,mode:"binary"});return}if(!X){j0({updated:!1,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,mode:"binary",message:`seal-use is already up to date (v${Q1})`});return}let L=Wi1(H.assets,J,Q);if(!L)throw Error(`No compatible binary found for ${J}-${Q} in release v${G}. Available assets: ${H.assets.map((P)=>P.name).join(", ")}`);let F=CJ(Y).running;if(F)await EY("stop",Y);let O=process.execPath,A=Qi1(O),B=tg0(A,`.tmp-update-${Date.now()}`);Ii1(B,{recursive:!0});try{let P=tg0(B,L.name);await Xi1(L.downloadUrl,P,H.tagName,L.name);let T=P;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))T=Vi1(P,B,J);else if(L.name.endsWith(".zip"))T=wi1(P,B,J);if(Ui1(T,493),process.platform==="darwin")try{jY("/usr/bin/codesign",["--remove-signature",T],{stdio:"ignore"}),jY("/usr/bin/codesign",["--force","--sign","-",T],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let v=`${O}.old.${Date.now()}`;try{nd(O,v)}catch{}nd(T,O)}else nd(T,O);if(F)await EY("start",Y);let y=Ed();j0({updated:!0,fromVersion:Q1,toVersion:G,serviceRestarted:F,skillSynced:y.synced?y.targetDir:!1,mode:"binary"})}finally{try{Ji1(B,{recursive:!0,force:!0})}catch{}}}function Gi1(){if(process.platform==="darwin")retur Line truncated
`)}catch{}}async function Xi1($,q,Y,z){let U=pd(),I=[],J=Y?Y.startsWith("v")?Y:`v${Y}`:void 0,Q=z||$.split("/").pop()||"";if(U!=="github"){if(J&&Q)I.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${Q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${Q}`);if($.startsWith("https://git.ying-qing.cn"))I.push($)}if(U!=="gitea")if(J&&Q){let L=`https://github.com/${qS0}/releases/download/${J}/${Q}`;if(!process.env.CI)I.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);I.push(L)}else if($.includes("github.com")){if(!process.env.CI)I.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);I.push($)}else I.push($);let K=Array.from(new Set(I)),H,G=6000,Z=6000,V=307200,X=1e4,w=180000;for(let L=0;L<K.length;L++){let F=K[L],O=new AbortController,A="",B=(v)=>{A=v;try{O.abort()}catch{}},P=setTimeout(()=>{B("Connection timed out (no response headers within 6s)")},G),T,y;try{XP(`==> [${L+1}/${K.length}] Downloading via: ${F}`);let v=await fetch(F,{signal:O.signal});if(P)clearTimeout(P),P=void 0;if(!v.ok)throw Error(`HTTP ${v.status} ${v.statusText}`);T=setTimeout(()=>{B("Overall download time exceeded 3 minutes")},w);let k=Number(v.headers.get("content-length"))||0,R=v.body?.getReader();if(!R){let i=Buffer.from(await v.arrayBuffer());if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);sg0(q,i),XP(`✓ Download succeeded (${(i.length/1024/1024).toFixed(1)} MB)`);return}let c=[],n=0,g=0;y=setTimeout(()=>{if(n<V){let i=(n/1024).toFixed(1);B(`Initial transfer too slow (${i} KB < 300 KB in 6s), switching mirror...`)}},Z);while(!0){let i=R.read(),$0,j=new Promise((Y0,t)=>{$0=setTimeout(()=>{t(Error("Data transfer stalled (no chunk received for 10s)"))},X)}),u;try{u=await Promise.race([i,j])}finally{if($0)clearTimeout($0)}let{done:p,value:d}=u;if(p)break;if(d){if(c.push(d),n+=d.length,y&&n>=V)clearTimeout(y),y=void 0;let Y0=Date.now();if(Y0-g>200){g=Y0;let t=k?Math.round(n/k*100):0,H0=(n/1048576).toFixed(1),w0=k?(k/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${t}% (${H0} / ${w0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let b=Buffer.concat(c);if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);sg0(q,b),XP(`✓ Download completed successfully (${(b.length/1024/1024).toFixed(1)} MB)`);return}catch(v){if(P)clearTimeout(P);if(y)clearTimeout(y);if(T)clearTimeout(T);let k=A||(v instanceof Error?v.message:String(v));H=Error(k),XP(`
↳ Mirror failed: ${H.message}`)}finally{if(P)clearTimeout(P);if(y)clearTimeout(y);if(T)clearTimeout(T)}}throw Error(`Failed to download asset from all mirrors: ${H?.message}`)}function Vi1($,q,Y){let z=jY("tar",["-xzf",$,"-C",q],{stdio:"pipe"});if(z.status!==0)throw Error(`Failed to extract tar archive: ${z.stderr.toString()}`);$S0($);let U=Y==="windows"?"seal-use.exe":"seal-use",I=jY("find",[q,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),J=I.find((Q)=>Q.endsWith(`/${U}`)||Q.endsWith(U));if(J)return J;return I[0]||$}function wi1($,q,Y){let z=jY("unzip",["-q","-o",$,"-d",q],{stdio:"pipe"});if(z.status!==0)throw Error(`Failed to extract zip archive: ${z.stderr.toString()}`);$S0($);let U=Y==="windows"?"seal-use.exe":"seal-use",I=jY("find",[q,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),J=I.find((Q)=>Q.endsWith(`/${U}`)||Q.endsWith(U));if(J)return J;return I[0]||$}function zS0($,q){let Y=$.replace(/^v/,"").split(".").map((U)=>Number.parseInt(U,10)||0),z=q.replace(/^v/,"").split(".").map((U)=>Number.parseInt(U,10)||0);for(let U=0;U<Math.max(Y.length,z.length);U++){let I=Y[U]??0,J=z[U]??0;if(I>J)return 1;if(I<J)return-1}return 0}function XW($,q){return zS0($,q)>0}function eg0($,q,Y={}){let z=jY($,q,{cwd:Y.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(z.stdout)console.error(z.stdout.trimEnd());if(z.stderr)console.error(z.stderr.trimEnd());if(z.status!==0)throw Error(`${$} ${q.join(" ")} failed with status ${z.status}`)}p4();_4();o1();async function US0($,q,Y,z,U){if($==="create"){let I=E(U.options.name)??q,J=E(U.options.phone);if(!I||!J)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let Q=E(U.options.dept)??E(U.options.departmentId);await P0("seal_user_create",Y,z,{name:I,phone:J,departmentIds:Q?[Q]:void 0},F0(U.options));return}if($==="reset-password"){let I=q??E(U.options.userId);if(!I)throw Error("Usage: seal-use users reset-password <userId>");await P0("seal_user_reset_password",Y,z,{userId:I},F0(U.options));return}if($==="search"||$==="list"){let I=q??E(U.options.keyword)??E(U.options.query)??"";await P0("seal_user_search",Y,z,{keyword:I},F0(U.options));return}if($==="get"){let I=q??E(U.options.userId);if(!I)throw Error("Usage: seal-use users get <userId>");await P0("seal_user_get",Y,z,{userId:I},F0(U.options));return}if($==="delete"){let I=q??E(U.options.userId);if(!I)throw Error("Usage: seal-use users delete <userId>");await P0("seal_user_delete",Y,z,{userId:I},F0(U.options));return}if($==="activate"){let I=q??E(U.options.userId);if(!I)throw Error("Usage: seal-use users activate <userId>");await P0("seal_user_activate",Y,z,{userId:I},F0(U.options));return}if($==="delegation"||$==="impersonate"){let I=q??E(U.options.userId)??E(U.options.phone);if(!I)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let J=E(U.options.note);await P0("seal_user_delegation_create",Y,z,{userIdOrPhone:I,note:J},F0(U.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}V$();p4();_4();Zd();o1();var IS0=dd(dd(dd(Fi1(import.meta.url)))),Oi1=new Set(["config","service","stop","http","serve","update","tools","corps","corp","tool","source","auth","delegation","users","contacts","data","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","analytics","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","doctor","changelog","test"]),Mi1=new Set(["http","server","web","mcp"]);function Ni1($){if(!$.length)return!1;let q=$[0]?.toLowerCase(),Y=$[1]?.toLowerCase();if(q&&Mi1.has(q))return!0;if((q==="service"||q==="daemon")&&Y==="run")return!0;return!1}var JS0=Promise.resolve();function ZW($,q={}){if(Ni1($))return QS0($,q);let Y=JS0.then(()=>QS0($,q));return JS0=Y.then(()=>{return},()=>{return}),Y}async function QS0($,q){let Y=[],z=[],U=console.log,I=console.error,J={appRoot:q.appRoot??IS0,entryFile:q.entryFile??Li1(q.appRoot??IS0,"src","cli.ts"),launcher:q.launcher};console.log=(...Q)=>{Y.push(Wd(Q))},console.error=(...Q)=>{z.push(Wd(Q))};try{return await Di1($,J),{stdout:UW(Y),stderr:UW(z),isError:!1,exitCode:0}}catch(Q){let K=IW(Q instanceof Error?Q.message:String(Q)),H=LD(Q);if(z.push(K),H.nextAction&&!K.includes("Next action:"))z.push(`\uD83D\uDC49 Next action: ${H.nextAction}`);return{stdout:UW(Y),stderr:UW(z),isError:!0,exitCode:H.exitCode}}finally{console.log=U,console.error=I}}async function Di1($,q){let Y=Id($),[z,U,I]=Y.command;if(z==="version"||z==="v"||Boolean(Y.options.version)||Boolean(Y.options.v)||Boolean(Y.options.V)){j0(FK);return}let J=Nv0(Y);if(J.isHelp){Bv0(J.target);return}if(!z||!Oi1.has(z))throw Error(`Unknown command: ${Y.command.join(" ")}. Run 'seal-use help' for available commands.`);if(z==="webhook"&&(U==="resource-pack"||U==="pack"||U==="material-pack")&&I==="preview"){let H=Y.command[3]??E(Y.options.file)??E(Y.options.input);if(!H)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await jv0(H,BJ(Y.options));return}if(z==="openapi"){vg0(Y);return}if(z==="mcp-config"){hd();return}if(z==="skill"){pg0(U,I,Y);return}if(z==="mcp"||z==="server"){await Rg0(U,Y);return}if(z==="probe"){await xg0(U,I,Y);return}if(z==="doctor"){await Bg0(U,I,Y);return}if(z==="test"){await id(U,I,Y);return}if(z==="config"){Sv0(U,I,Y);return}if(z==="service"){await fd(U,q,Y);return}if(z==="stop"){await fd("stop",q,Y);return}if(z==="http"||z==="serve"){await _g0(Y);return}if(z==="update"||z==="changelog"){let H=z==="changelog"||U==="changelog"||U==="log"||U==="history"||W0(Y.options.changelog)===!0,G=U==="check"||W0(Y.options.check)===!0||W0(Y.options["check-only"])===!0,Z=E(Y.options.version)??E(Y.options.tag)??(!H&&!G&&U&&!U.startsWith("-")?U:void 0);await YS0 Line truncated
`)?"":`
`}`);process.exitCode=$.exitCode}var VL1=Boolean(t.main==t.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&vN0(process.argv[1])===vN0(F9));if(VL1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await WL1();else ek().catch(($)=>{console.error($),process.exitCode=1});export{ak as tokenizeCommand,ek as startServer,wL1 as resolveMcpEnabled,GL1 as createServer,QL1 as SEAL_MCP_ENABLED_ENV,JL1 as SEAL_CLI_TOOL_NAME,KL1 as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=$.exitCode}var Ri1=Boolean(m.main==m.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&KS0(process.argv[1])===KS0(D3));if(Ri1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await Ci1();else gd().catch(($)=>{console.error($),process.exitCode=1});export{vd as tokenizeCommand,gd as startServer,Ei1 as resolveMcpEnabled,ji1 as createServer,Bi1 as SEAL_MCP_ENABLED_ENV,Pi1 as SEAL_CLI_TOOL_NAME,Ti1 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.20",
"version": "0.10.23",
"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.20
version: 0.10.23
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.20",
"version": "0.10.23",
"type": "module",
"module": "src/server.ts",
"bin": {
@@ -24,6 +24,7 @@
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"archiver": "^8.0.0",
"exceljs": "^4.4.0",
"iconv-lite": "^0.7.3",
"ky": "^2.0.2",
@@ -32,6 +33,7 @@
"zod": "^4.4.3"
},
"devDependencies": {
"@types/archiver": "^8.0.0",
"@types/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
"bun-types": "^1.3.14",
+12 -8
View File
@@ -1,12 +1,12 @@
---
name: seal-use
description: "v0.10.20: 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.23: 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.20
short-description: Seal tenant and Hose approval automation (v0.10.20)
version: 0.10.23
short-description: Seal tenant and Hose approval automation (v0.10.23)
---
# Seal Use (v0.10.20)
# Seal Use (v0.10.23)
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.
@@ -88,7 +88,7 @@ seal-use corps list
- 规则本地工作流: `seal-use rules pull` 导出草稿规则,`rules lint` 做质量检查,`rules push --dry-run` 预览增量更新,确认后用 `--yes` 写入;`rules map` 查询 `corps sync-test` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 `references/rule-lightweight.md` 和 `references/cli.md`。
- 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|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表);需要追踪单据时再使用 `url` 或 `bridge`。
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表,文件名强制追加精确到分钟的 `_YYYYMMDD_HHmm` 时间戳后缀防止覆盖;支持 `--sn <SN1,SN2>` 定向筛选极速导出并跳过全量分页;追加 `--with-flow` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,200 条以上单据约增加 30 秒);需要追踪单据时再使用 `url` 或 `bridge`。
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Delegation links management: `seal-use delegation list --corp <corpId>`, `create [--note ...] --corp <corpId>`, `create --from-link <url> [--note ...]`, `revoke <tokenId> --corp <corpId>`.
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-use users search [keyword] --corp <corpId>`, `users delegation <userIdOrPhone> --corp <corpId>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId> --corp <corpId>`, `users create --name ... --phone ... --corp <corpId>`, `users reset-password <userId> --corp <corpId>`, `users get <userId> --corp <corpId>`, `users delete <userId> --corp <corpId>`.
@@ -96,8 +96,8 @@ 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 ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>` 检查企业环境、租户连通性、已激活通道与材料包预检;`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` 的官方服务端导入流程相互独立。
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<资源包.zip>] [--webhook <idOrName>] --corp <corpId>` 检查企业环境、租户连通性、已激活通道与资源包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 资源包管理 (Webhook Resource Pack): `seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>` 从线上审核记录直接打包导出为标准 Webhook 资源包(包含根目录 `信息表.xlsx` 与下载好的单据附件),便于通过邮件/微信等第三方渠道离线分发;`seal-use webhook resource-pack preview <资源包.zip> --corp <corpId>` 本地预检单据与附件;`seal-use webhook resource-pack push <资源包.zip> [--webhook <idOrName>] --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。CLI 简写别名 `pack`,旧名 `material-pack` 完整向下兼容保留。每个 Webhook 可配置资源包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。资源包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明附件的单据必须有对应根目录,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Webhook Resource Pack Workflow" 一节。它与 Seal 官方在模拟测试中使用的 `simulation material_pack` 流程相互独立,避免混淆。
- 审批记录转 Webhook 重放 (Universal Record Replay): `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` 以及生产测专用快捷命令 `seal-use corps replay-test [<prodCorpId>] [--force]`。通用支持从历史审批记录(Webhook 来源、Hose 来源等)汲取结构化表单与明细字段,自动清洗规范化字段类型,支持按状态/数量批量重放到目标企业 Webhook 触发审批。默认推荐并导向测试企业(测试企业无 Webhook 时自动开通辅助模式通道并锁定环境隔离);若用户未绑定测试企业或明确要求向生产企业重放,支持通过 `--force` 显式执行,方便环境回归验证与 Bad Case 靶向调试。
- HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
@@ -159,6 +159,10 @@ seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use approval-runs export --corp <corpId> --downloads --completed-only
# Add --with-flow to also populate E人工行为 / E人工意见 columns (Hose Open API, adds ~30s):
seal-use approval-runs export --corp <corpId> --downloads --with-flow
# Target specific document SNs for instant export without full pagination:
seal-use approval-runs export --corp <corpId> --sn B26002307,B26002144 --with-flow --downloads
seal-use analytics insight --corp <corpId>
seal-use contacts departments --corp <corpId>
seal-use data invoices --corp <corpId> --limit 20
@@ -182,7 +186,7 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
- `references/enterprise-onboarding.md`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- `references/rule-lint.md`: 规则质量检查器(Linter)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- `references/rule-lint.md`: 规则质量检查器(Linter,含 builtin / strict / hlab 官方规范)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。
- `references/hose-enterprise-init.md`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
+33 -20
View File
@@ -114,14 +114,15 @@ seal-use permissions configs [--corp <corpId>]
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 ready [<资源包.zip>] [--webhook <idOrName>] [--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>] [--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>]
seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]
seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
@@ -144,9 +145,12 @@ seal-use analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO
seal-use analytics risks <tagId> --corp <corpId> [--start-date <ISO>] [--end-date <ISO>]
seal-use analytics performance --corp <corpId> [--start-date <ISO|ms>] [--end-date <ISO|ms>]
seal-use analytics analyze <recordId> --corp <corpId>
seal-use analytics export --corp <corpId> [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>]
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 analytics export --corp <corpId> [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force]
seal-use approval-runs count --corp <corpId> [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>]
seal-use approval-runs export --corp <corpId> [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--out <file>] [--with-flow]
# --sn / --sns: 定向筛选单据编号(支持逗号/分号/空格分隔,跳过全量分页,秒级定向导出特定单据)
# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,默认关闭以节省合思 API 调用)
# 导出文件名自动追加精确到分钟的 _YYYYMMDD_HHmm 时间戳后缀防止文件覆盖,格式:${企业名称}_审核记录_${时间区间}_${条数}_${导出时间戳}.xlsx
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>
@@ -286,14 +290,15 @@ Approval knowledge documents & style:
Webhook integrations:
- `seal-use webhook ready [<材料包.zip|信息表.xlsx>] [--webhook <idOrName>] [--corp <corpId>]`
- `seal-use webhook ready [<资源包.zip|信息表.xlsx>] [--webhook <idOrName>] [--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>] [--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>`
- `seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>` (将线上审核记录打包导出为标准 Webhook 资源包,支持按条数、状态或指定单据 ID 筛选)
- `seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
- `seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>` (别名 `pack`,旧名 `material-pack` 兼容支持)
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持)
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.
@@ -476,14 +481,16 @@ Update style preferences:
}
```
## Material Pack Workflow
## Webhook Resource Pack Workflow (Webhook 资源包)
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.
A **Webhook resource pack** (webhook 资源包 / 资源包, CLI: `resource-pack`, alias: `pack`, legacy alias: `material-pack`) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is designed for exporting online approval runs and transferring them offline across environments or teams to be replayed via inbound Webhooks.
> **Note**: This is distinct from Seal backend's native simulation "材料包" (`simulation material_pack` / `/api/v1/material-packages/upload`). Calling this standard "Webhook 资源包" avoids confusion.
### ZIP structure convention
```
材料包.zip
资源包.zip
├── 信息表.xlsx ← must exist at ZIP root
├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)
│ ├── 合同协议/
@@ -497,13 +504,14 @@ A **material pack** (材料包) is a ZIP file that bundles an Excel information
- 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.
- Documents without attachments do not require a directory entry in the ZIP.
### 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 |
| 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).
@@ -524,25 +532,30 @@ 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 次...`
4. **Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire resource 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」在信息表中找不到对应的会议编号`
6. **documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet that declares attachments must have a matching ZIP root dir (exact match or `documentId@annotation`), and every ZIP root dir must match a declared `documentId`. 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
# Export online approval records to a local Webhook resource pack ZIP
seal-use webhook resource-pack export --limit 10 --corp <sourceCorpId>
# Export specific records and save to Downloads
seal-use webhook resource-pack export <recordId> --to-downloads --corp <sourceCorpId>
# Check environment readiness and optionally pre-validate the resource 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>
seal-use webhook resource-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>
seal-use webhook resource-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>
seal-use webhook resource-pack push <pack.zip> [--webhook <nameOrId>] --corp <corpId>
# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)
```
+33 -1
View File
@@ -50,7 +50,26 @@ seal-use config lint enable --linter builtin --min-score 80
seal-use config lint disable
```
## Built-In Detection Rules
## Official Linters
| Linter Name | Scope & Purpose | Aliases |
| :--- | :--- | :--- |
| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |
| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |
| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |
```bash
# Inspect available linters
seal-use rules linters
# Lint rules using HLab SOP standard
seal-use rules lint --linter hlab --corp <corpId>
# Lint local rule workspace offline with HLab standard
seal-use rules lint --linter hlab --file ./rules.local.json
```
## Built-In Detection Rules (`builtin`)
| Code | Level | Description | Recommendation |
| :--- | :---: | :--- | :--- |
@@ -58,6 +77,19 @@ seal-use config lint disable
| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |
| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |
## HLab SOP Detection Rules (`hlab`)
| Code | Level | Description | Recommendation |
| :--- | :---: | :--- | :--- |
| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |
| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |
| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `- PASS:`, `- FAIL:`, `- 证据不足:`. |
| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |
| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |
| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |
| `RISK_SUPPRESSION` | `error` | Contains negative suppression directives (`忽略行程冲突`, `不识别为风险`, `无需提示`). | Avoid suppressing audit baselines; use closed `**例外**` clauses instead. |
| `HANGING_EXCEPTION` | `error` | Exception trigger found without verifiable evidence keyword. | Specify verifiable evidence document or attachment in `**例外**` block. |
## Custom TS Linters (Plugin-as-Code)
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts` or `./linters/<name>.ts`:
+1 -1
View File
@@ -140,7 +140,7 @@ describe("CLI version & help handling", () => {
expect(parsed.updated).toBe(true);
expect(parsed.mode).toBe("source");
expect(parsed.version).toBe(VERSION);
});
}, 20000);
test("mcp-config outputs valid mcp configuration json", () => {
const result = runCli(["mcp-config"]);
+2 -1
View File
@@ -84,7 +84,8 @@ export async function handleAnalyticsCommand(
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
limit: numberOption(args.options.limit),
outputFile: stringOption(args.options.out) ?? stringOption(args.options["output-file"]) ?? stringOption(args.options.outputFile),
toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options["to-downloads"])
toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options["to-downloads"]),
force: booleanOption(args.options.force)
});
printJson(result);
return;
+89 -7
View File
@@ -1,7 +1,7 @@
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 { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs-export.js";
import {
downloadApprovalRunAttachments,
extractApprovalRunAttachments
@@ -71,6 +71,14 @@ export async function handleApprovalRunsCommand(
}
if (action === "count") {
const rawStart =
stringOption(args.options.start) ??
stringOption(args.options.startDate) ??
stringOption(args.options.since);
const rawEnd =
stringOption(args.options.end) ??
stringOption(args.options.endDate);
await runTool(
"seal_approval_runs_count",
client,
@@ -79,7 +87,9 @@ export async function handleApprovalRunsCommand(
status: stringOption(args.options.status),
sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"]),
taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]),
search: stringOption(args.options.search) ?? stringOption(args.options.query)
search: stringOption(args.options.search) ?? stringOption(args.options.query),
startDate: rawStart ? normalizeTimestamp(rawStart, false) : undefined,
endDate: rawEnd ? normalizeTimestamp(rawEnd, true) : undefined
},
outputOptions(args.options)
);
@@ -94,8 +104,13 @@ export async function handleApprovalRunsCommand(
{
limit: numberOption(args.options.limit),
offset: numberOption(args.options.offset),
startDate: stringOption(args.options.startDate),
endDate: stringOption(args.options.endDate),
startDate:
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since),
endDate:
stringOption(args.options.endDate) ??
stringOption(args.options.end),
status: stringOption(args.options.status),
taskMode: stringOption(args.options.taskMode),
manualApprovalStatus: stringOption(args.options.manualApprovalStatus),
@@ -151,6 +166,16 @@ export async function handleApprovalRunsCommand(
if (action === "get") {
const recordId = args.command[2];
if (!recordId) throw new Error("Missing approval run recordId");
if (booleanOption(args.options.flow)) {
await runTool(
"seal_approval_run_flow_get",
client,
corp,
{ recordId },
outputOptions(args.options)
);
return;
}
await runTool(
"seal_approval_run_get",
client,
@@ -298,14 +323,52 @@ export async function handleApprovalRunsCommand(
return;
}
if (action === "flow") {
const target =
maybeName ??
args.command[2] ??
stringOption(args.options.sn) ??
stringOption(args.options.id) ??
stringOption(args.options.recordId);
if (!target) {
throw new Error("Usage: seal-use approval-runs flow <recordId|SN>");
}
await runTool(
"seal_approval_run_flow_get",
client,
corp,
{ target },
outputOptions(args.options)
);
return;
}
if (action === "export") {
const rawSn =
stringOption(args.options.sn) ??
stringOption(args.options.sns) ??
stringOption(args.options.sourceDocumentSN);
const snList = rawSn
? rawSn
.split(/[,;\s]+/)
.map((s) => s.trim())
.filter(Boolean)
: undefined;
const result = await exportApprovalRunsToExcel(client, corp, {
sns: snList,
limit: numberOption(args.options.limit),
startDate:
stringOption(args.options.start) ??
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since),
endDate: stringOption(args.options.end) ?? stringOption(args.options.endDate),
endDate:
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until),
status: stringOption(args.options.status),
manualApprovalStatus:
stringOption(args.options["manual-status"]) ??
@@ -317,8 +380,27 @@ export async function handleApprovalRunsCommand(
stringOption(args.options.out) ??
stringOption(args.options.output) ??
stringOption(args.options.file),
toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options.download)
toDownloads:
booleanOption(args.options["to-downloads"]) ??
booleanOption(args.options.downloads) ??
booleanOption(args.options.download),
force: booleanOption(args.options.force),
withFlow:
booleanOption(args.options["with-flow"]) ??
(booleanOption(args.options["no-flow"]) ? false : undefined),
flowConcurrency:
numberOption(args.options["flow-concurrency"]) ??
numberOption(args.options.concurrency),
excludeDeleted:
booleanOption(args.options["exclude-deleted"]) ??
(booleanOption(args.options["include-deleted"]) ? false : undefined),
taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]),
sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"])
});
console.error(`👉 查看导出文件: open "${result.filePath}"`);
if (!args.options["with-flow"] && corp.source.type === "hose") {
console.error(`👉 提示: 追加 --with-flow 可额外拉取合思原生审批流,输出 E人工行为 / E人工意见。`);
}
printJson(result, outputOptions(args.options));
return;
}
@@ -0,0 +1,238 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../runner.js";
import { exportApprovalRunsToResourcePack } from "../../domains/seal/material-pack/export.js";
import { previewResourcePack } from "../../domains/seal/material-pack/service.js";
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
config: process.env.SEAL_USE_CONFIG_FILE,
tokenStore: process.env.SEAL_USE_TOKEN_STORE
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
}
function setupMockEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-pack-cli-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
const fs = require("node:fs");
fs.mkdirSync(enterprises, { recursive: true });
const corpConfig = {
id: "test-corp-pack",
name: "测试资源包企业",
environment: "test",
source: {
type: "direct",
token: "mock-valid-token",
sealUrl: "https://test-pack.sealai.cc"
},
seal: {
baseUrl: "https://test-pack.sealai.cc",
token: "mock-valid-token",
endpoints: {
approvalStylePreferences: "api/v1/system/preferences/approval-style"
}
}
};
writeFileSync(join(enterprises, "test-corp-pack.json"), JSON.stringify(corpConfig, null, 2));
const tokens = {
"test-corp-pack": {
token: "mock-valid-token",
expiresAt: Date.now() + 3600_000
}
};
writeFileSync(join(root, "tokens.json"), JSON.stringify(tokens, null, 2));
return { root, enterprises };
}
describe("Webhook Resource Pack CLI Commands", () => {
test("preview works via resource-pack, pack, and material-pack aliases", async () => {
const { root } = setupMockEnv();
// Generate a valid pack first
const mockRuns = [
{
id: "run-p1",
corpId: "test-corp-pack",
status: "APPROVED",
sourceDocumentId: "DOC-CLI-01",
createdAt: "2026-09-12T10:00:00Z",
document: {
id: "DOC-CLI-01",
sn: "SN-CLI-01",
title: "战略合作交流会",
fields: [
{ key: "total_amount", label: "总金额", type: "AMOUNT", value: 5000 },
{ key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "年度战略会议" }
]
}
}
];
const mockClient = {
get: () => ({
json: async () => ({
code: 0,
data: mockRuns[0]
})
})
} as any;
const testZipPath = join(root, "test-resource-pack.zip");
await exportApprovalRunsToResourcePack(
mockClient,
{
id: "test-corp-pack",
name: "测试企业",
source: {
type: "direct",
token: "mock-valid-token",
sealUrl: "https://test-pack.sealai.cc",
expiresIn: 3600,
staffId: "direct"
},
seal: { url: "https://test-pack.sealai.cc", endpoints: { approvalStylePreferences: "" } }
} as any,
{
outputFile: testZipPath,
recordId: "run-p1"
}
);
expect(existsSync(testZipPath)).toBe(true);
// 1. Test seal-use webhook resource-pack preview
const cliRes1 = await runCli(["webhook", "resource-pack", "preview", testZipPath]);
if (cliRes1.isError) {
throw new Error(`CLI Error 1: ${cliRes1.stderr}`);
}
const res1 = JSON.parse(cliRes1.stdout);
expect(res1.documents).toHaveLength(1);
expect(res1.documents[0].documentId).toBe("DOC-CLI-01");
// 2. Test seal-use webhook pack preview (alias)
const cliRes2 = await runCli(["webhook", "pack", "preview", testZipPath]);
if (cliRes2.isError) {
throw new Error(`CLI Error 2: ${cliRes2.stderr}`);
}
const res2 = JSON.parse(cliRes2.stdout);
expect(res2.documents).toHaveLength(1);
expect(res2.documents[0].documentId).toBe("DOC-CLI-01");
// 3. Test legacy seal-use webhook material-pack preview (backward compatibility)
const cliRes3 = await runCli(["webhook", "material-pack", "preview", testZipPath]);
if (cliRes3.isError) {
throw new Error(`CLI Error 3: ${cliRes3.stderr}`);
}
const res3 = JSON.parse(cliRes3.stdout);
expect(res3.documents).toHaveLength(1);
expect(res3.documents[0].documentId).toBe("DOC-CLI-01");
});
test("export CLI command generates resource pack ZIP", async () => {
const { root } = setupMockEnv();
const mockRun = {
id: "run-exp-1",
corpId: "test-corp-pack",
status: "APPROVED",
sourceDocumentId: "DOC-EXP-01",
createdAt: "2026-09-12T10:00:00Z",
document: {
id: "DOC-EXP-01",
sn: "SN-EXP-01",
title: "新零售峰会支出",
fields: [
{ key: "total_amount", label: "总金额", type: "AMOUNT", value: 8800 },
{ key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "峰会场地租用" }
]
}
};
// Mock fetch for online calls
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : (input as any).url ? String((input as any).url) : String(input);
if (url.includes("auth/me") || url.includes("get-session")) {
return new Response(
JSON.stringify({
code: 0,
data: {
user: { id: "u-1", name: "Admin", isAdmin: true },
tenant: { id: "t-1", name: "测试租户", tenantSlug: "test-pack" }
}
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
if (url.includes("run-exp-1") || url.includes("approvals")) {
return new Response(JSON.stringify({ code: 0, data: mockRun }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
return new Response(JSON.stringify({ code: 0, data: {} }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}) as any;
const outZip = join(root, "exported-by-cli.zip");
const exportCliRes = await runCli([
"webhook",
"resource-pack",
"export",
"run-exp-1",
"-o",
outZip,
"--corp",
"test-corp-pack"
]);
if (exportCliRes.isError) {
throw new Error(`Export CLI Error: ${exportCliRes.stderr}`);
}
expect(existsSync(outZip)).toBe(true);
const parsedOut = JSON.parse(exportCliRes.stdout);
expect(parsedOut.recordCount).toBe(1);
expect(parsedOut.filePath).toBe(outZip);
expect(parsedOut.nextAction).toContain("seal-use webhook resource-pack push");
// Verify it with preview
const { readFileSync } = await import("node:fs");
const preview = await previewResourcePack(readFileSync(outZip), "exported-by-cli.zip");
expect(preview.documents).toHaveLength(1);
expect(preview.documents[0]?.documentId).toBe("DOC-EXP-01");
});
});
+73 -6
View File
@@ -14,6 +14,7 @@ import {
} from "../../domains/seal/webhook-replay.js";
import {
checkWebhookReadiness,
exportApprovalRunsToResourcePack,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
@@ -32,7 +33,7 @@ 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(
export async function handleWebhookResourcePackPreview(
filePath: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
@@ -41,6 +42,8 @@ export async function handleWebhookMaterialPackPreview(
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy), null, 2));
}
export const handleWebhookMaterialPackPreview = handleWebhookResourcePackPreview;
export async function handleWebhookCommand(
action: string | undefined,
maybeName: string | undefined,
@@ -201,19 +204,81 @@ export async function handleWebhookCommand(
return;
}
if (action === "material-pack" || action === "material-pack-push") {
const operation = action === "material-pack-push" ? "push" : maybeName;
const filePath = action === "material-pack-push"
if (
action === "resource-pack" ||
action === "pack" ||
action === "material-pack" ||
action === "material-pack-push" ||
action === "resource-pack-push"
) {
const operation = (action === "material-pack-push" || action === "resource-pack-push")
? "push"
: maybeName;
if (operation === "export" || operation === "pull") {
const recordId =
stringOption(args.options.recordId) ??
stringOption(args.options["record-id"]) ??
stringOption(args.options.id) ??
(args.command[3] && !args.command[3].endsWith(".zip") && !args.command[3].startsWith("-") ? args.command[3] : undefined);
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
const limit = numberOption(args.options.limit) ?? (recordId || recordIds ? undefined : 10);
const status = stringOption(args.options.status);
const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]);
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
const includeAttachments =
booleanOption(args.options["no-attachments"]) === true
? false
: booleanOption(args.options.attachments) !== false;
const outputFile =
stringOption(args.options.output) ??
stringOption(args.options.outputFile) ??
stringOption(args.options["output-file"]) ??
stringOption(args.options.o) ??
stringOption(args.options.file) ??
(args.command[3]?.endsWith(".zip") ? args.command[3] : undefined);
const toDownloads =
booleanOption(args.options.toDownloads) ?? booleanOption(args.options["to-downloads"]) ?? false;
const result = await exportApprovalRunsToResourcePack(client, corp, {
recordId,
recordIds,
limit,
status,
startDate,
endDate,
docIdPrefix,
docIdSuffix,
includeAttachments,
outputFile,
toDownloads
});
console.error(
`🟢 成功导出 Webhook 资源包: ${result.filePath} (共 ${result.recordCount} 条单据,${result.attachmentCount} 个附件,${(result.fileSizeBytes / 1024).toFixed(1)} KB)`
);
console.error(`👉 Next action: ${result.nextAction}`);
console.log(JSON.stringify(result, null, 2));
return;
}
const filePath = (action === "material-pack-push" || action === "resource-pack-push")
? stringOption(args.options.file) ?? stringOption(args.options.input)
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
if (operation === "preview") {
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
return;
}
if (operation !== "push") throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
if (operation !== "push") throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
let integration: WebhookIntegration;
@@ -238,6 +303,8 @@ export async function handleWebhookCommand(
materialPackFilePolicy: integration.materialPackFilePolicy,
customHeaders: resolveSealCustomHeaders(corp.seal)
});
console.error(`🟢 Webhook 资源包推送完成 (成功 ${result.results.length} 条单据)`);
console.error(`👉 Next action: seal-use approval-runs list --corp ${corp.id} --limit ${result.results.length}`);
console.log(JSON.stringify(result, null, 2));
return;
}
+16
View File
@@ -220,4 +220,20 @@ describe("CLI help execution for lifecycle commands", () => {
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use stop");
});
test("approval-runs --help prints updated count and export parameter usage", async () => {
const result = await runCli(["approval-runs", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>]");
expect(result.stdout).toContain("approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only]");
});
test("analytics export --help prints force parameter usage", async () => {
const result = await runCli(["analytics", "export", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("--force");
expect(result.stdout).toContain("Force export when time range exceeds 180 days");
});
});
+53 -11
View File
@@ -272,14 +272,37 @@ export const HELP_REGISTRY: AreaHelp[] = [
usage: ["seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]"]
},
{
name: "material-pack preview",
summary: "Inspect and validate a material pack ZIP or Excel sheet",
usage: ["seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]"]
name: "resource-pack export",
summary: "Export online approval records to a local Webhook resource pack ZIP (alias: pack export)",
usage: [
"seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]",
"seal-use webhook resource-pack export <recordId> [--output <file.zip>] [--corp <corpId>]",
"seal-use webhook resource-pack export --record-ids <id1,id2> [--corp <corpId>]"
],
options: [
{ flag: "<recordId>", description: "Single approval run record ID to export" },
{ flag: "--record-ids <ids>", description: "Comma-separated list of approval run record IDs" },
{ flag: "--limit <n>", description: "Limit number of records to export (default: 10)" },
{ flag: "--status <status>", description: "Filter records by status (e.g. completed, approved)" },
{ flag: "--start-date <YYYY-MM-DD>", description: "Filter records starting from date" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Filter records up to date" },
{ flag: "--doc-id-prefix <str>", description: "Optional prefix prepended to exported documentId/meetingId" },
{ flag: "--doc-id-suffix <str>", description: "Optional suffix appended to exported documentId/meetingId" },
{ flag: "--no-attachments", description: "Skip downloading and packaging attachments" },
{ flag: "-o, --output <file.zip>", description: "Target ZIP file path" },
{ flag: "--to-downloads", description: "Save directly to ~/Downloads" },
{ flag: "--corp <corpId>", description: "Source enterprise configuration ID" }
]
},
{
name: "material-pack push",
summary: "Upload and push a material pack to webhook endpoint",
usage: ["seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]"]
name: "resource-pack preview",
summary: "Inspect and validate a Webhook resource pack ZIP or Excel sheet (alias: pack preview)",
usage: ["seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]"]
},
{
name: "resource-pack push",
summary: "Upload attachments and push documents from a resource pack ZIP to Webhook (alias: pack push)",
usage: ["seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]"]
},
{
name: "replay",
@@ -322,13 +345,31 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "count",
summary: "Count approval runs filtered by status",
usage: ["seal-use approval-runs count [--status APPROVED] [--corp <corpId>]"]
summary: "Count approval runs filtered by status or time range",
usage: ["seal-use approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--corp <corpId>]"]
},
{
name: "export",
summary: "Export approval run audit records to Excel workbook",
usage: ["seal-use approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>] [--corp <corpId>]"]
summary: "Export approval run audit records to Excel workbook. Add --with-flow to include E人工行为 / E人工意见 columns (requires Hose Open API; adds ~30s for large batches).",
usage: ["seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]"],
options: [
{ flag: "--sn, --sns <SNs>", description: "Target specific document SNs (comma-separated, e.g. B26002307,B26002144); fast indexed search bypassing full pagination" },
{ flag: "--with-flow", description: "Enrich export with Hose human actions and opinions in E人工行为 / E人工意见 columns (rejection 2-B, mid-flow modifications, action emojis)" },
{ flag: "--start <date>", description: "Filter records by start date (YYYY-MM-DD or ms timestamp)" },
{ flag: "--end <date>", description: "Filter records by end date (YYYY-MM-DD or ms timestamp)" },
{ flag: "--force", description: "Force export when time range exceeds 180 days" },
{ flag: "--status <status>", description: "Filter by system status (e.g. completed, processing)" },
{ flag: "--manual-status <status>", description: "Filter by manual approval status (e.g. APPROVED, TERMINATED)" },
{ flag: "--completed-only", description: "Only export completed approval runs" },
{ flag: "--limit <n>", description: "Maximum number of records to export" },
{ flag: "--downloads, --to-downloads", description: "Save exported workbook directly to user's ~/Downloads directory" },
{ flag: "--out <file>", description: "Custom output file path" }
]
},
{
name: "flow",
summary: "Get Hose approval flow timeline, staff opinions, and align with AI runs",
usage: ["seal-use approval-runs flow <recordId|SN> [--corp <corpId>]"]
},
{
name: "list",
@@ -796,12 +837,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "export",
aliases: ["report", "download"],
summary: "Export smart insights risk report to high-fidelity Excel workbook",
usage: ["seal-use analytics export [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]"],
usage: ["seal-use analytics export [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force] [--limit <n>] [--corp <corpId>]"],
options: [
{ flag: "--downloads", description: "Save directly to the user's Downloads directory" },
{ flag: "--out <file>", description: "Custom destination file path" },
{ flag: "--start-date <ISO>", description: "Filter beginning time range" },
{ flag: "--end-date <ISO>", description: "Filter ending time range" },
{ flag: "--force", description: "Force export when time range exceeds 180 days" },
{ flag: "--limit <n>", description: "Maximum risk tags to drill down into" }
]
}
+12 -4
View File
@@ -34,7 +34,11 @@ import { handleToolCommand } from "./commands/tool.js";
import { handleToolsListCommand } from "./commands/tools.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleUsersCommand } from "./commands/users.js";
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
import {
handleWebhookCommand,
handleWebhookMaterialPackPreview,
handleWebhookResourcePackPreview
} from "./commands/webhook.js";
import { classifyCliError } from "./errors.js";
import { selectCorp } from "./helpers.js";
import {
@@ -193,10 +197,14 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
if (area === "webhook" && action === "material-pack" && maybeName === "preview") {
if (
area === "webhook" &&
(action === "resource-pack" || action === "pack" || 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, materialPackFilePolicyOptions(args.options));
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");
await handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
return;
}
+1 -1
View File
@@ -357,7 +357,7 @@ export async function fetchHoseCloseApiToken(
};
}
async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
+44
View File
@@ -0,0 +1,44 @@
// --- Hose OpenAPI (hose-open) ---
export {
fetchHoseOpenFlowDetails,
fetchHoseOpenAllLogs,
fetchHoseOpenVersioned,
fetchHoseOpenCompositeFlow,
type FetchHoseOpenVersionedOptions
} from "./open/api.js";
// --- Hose CloseAPI (hose-close) ---
export {
searchCloseBacklogs,
getCloseBacklogDetailById,
resolveCloseBacklogId,
fetchRawCloseHoseFlow,
HOSE_CLOSE_LOOKUP_SELECT,
HOSE_CLOSE_DETAIL_SELECT,
HOSE_CLOSE_JOINS,
type SearchCloseBacklogsOptions,
type CloseBacklogDetailOptions
} from "./close/api.js";
// Legacy aliases for backward compatibility
import {
searchCloseBacklogs,
getCloseBacklogDetailById,
resolveCloseBacklogId,
fetchRawCloseHoseFlow,
HOSE_CLOSE_LOOKUP_SELECT,
HOSE_CLOSE_DETAIL_SELECT,
HOSE_CLOSE_JOINS,
type SearchCloseBacklogsOptions,
type CloseBacklogDetailOptions
} from "./close/api.js";
export const HOSE_FLOW_LOOKUP_SELECT = HOSE_CLOSE_LOOKUP_SELECT;
export const HOSE_FLOW_DETAIL_SELECT = HOSE_CLOSE_DETAIL_SELECT;
export const HOSE_FLOW_JOINS = HOSE_CLOSE_JOINS;
export type SearchBacklogsOptions = SearchCloseBacklogsOptions;
export type BacklogDetailOptions = CloseBacklogDetailOptions;
export const searchBacklogs = searchCloseBacklogs;
export const getBacklogDetailById = getCloseBacklogDetailById;
export const resolveBacklogId = resolveCloseBacklogId;
export const fetchRawHoseFlow = fetchRawCloseHoseFlow;
+43
View File
@@ -0,0 +1,43 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import {
createHoseOpenClient,
createHoseOpenClientWithCredentials,
type HoseOpenClientCredentials
} from "./open/client.js";
import {
createHoseCloseClient,
createHoseCloseClientWithCredentials,
getHoseCloseHeaders,
type HoseCloseClientCredentials
} from "./close/client.js";
// Re-exports with explicit open vs close distinction
export {
createHoseOpenClient,
createHoseOpenClientWithCredentials,
type HoseOpenClientCredentials
} from "./open/client.js";
export {
createHoseCloseClient,
createHoseCloseClientWithCredentials,
getHoseCloseHeaders,
type HoseCloseClientCredentials
} from "./close/client.js";
// Legacy aliases for backward compatibility
export type HoseClientCredentials = HoseCloseClientCredentials;
export const getHoseHeaders = getHoseCloseHeaders;
export const createHoseClientWithCredentials = createHoseCloseClientWithCredentials;
/**
* Default Hose client creator: uses Hose OpenAPI (hose-open).
* Bypasses row-level permission fences and requires no proxy staff ID.
*/
export async function createHoseClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
): Promise<KyInstance> {
return createHoseOpenClient(corp, customHeaders);
}
+118
View File
@@ -0,0 +1,118 @@
import type { KyInstance } from "ky";
import {
RawHoseBacklogItemSchema,
type RawHoseBacklogDetailResponse,
type RawHoseBacklogItem,
type RawHoseBacklogSearchResponse
} from "./types.js";
export const HOSE_CLOSE_LOOKUP_SELECT = "flowId(form(code,title),`...`),`...`";
export const HOSE_CLOSE_DETAIL_SELECT =
"flowId(form(specificationId(id,name,code),`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
export const HOSE_CLOSE_JOINS = [
"flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments",
"flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code",
"flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments",
"flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code",
"flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code"
] as const;
export interface SearchCloseBacklogsOptions {
filterBy: string;
limit?: { start: number; count: number };
select?: string;
}
export interface CloseBacklogDetailOptions {
select?: string;
joins?: readonly string[] | string[];
}
export async function searchCloseBacklogs(
client: KyInstance,
corpId: string,
options: SearchCloseBacklogsOptions
): Promise<RawHoseBacklogItem[]> {
const response = await client.post("api/flow/v2/backlogs/search", {
searchParams: { corpId },
json: {
filterBy: options.filterBy,
limit: options.limit ?? { start: 0, count: 100 },
select: options.select ?? HOSE_CLOSE_LOOKUP_SELECT
}
});
const data = (await response.json()) as RawHoseBacklogSearchResponse;
return (data.items ?? []).map((item) => RawHoseBacklogItemSchema.parse(item));
}
export async function getCloseBacklogDetailById(
client: KyInstance,
corpId: string,
backlogId: string,
options?: CloseBacklogDetailOptions
): Promise<Record<string, unknown> | undefined> {
const params = new URLSearchParams({ corpId });
const joins = options?.joins ?? HOSE_CLOSE_JOINS;
for (const join of joins) {
params.append("join", join);
}
const response = await client.post("api/flow/v2/backlogs/id", {
searchParams: params,
json: {
filterBy: `(id==${JSON.stringify(backlogId)})`,
select: options?.select ?? HOSE_CLOSE_DETAIL_SELECT
}
});
const data = (await response.json()) as RawHoseBacklogDetailResponse;
return data.value ?? data.items?.[0];
}
export async function resolveCloseBacklogId(
client: KyInstance,
corpId: string,
target: string
): Promise<string> {
const cleanTarget = target.trim();
if (!cleanTarget) return target;
const filters = [
`(id==${JSON.stringify(cleanTarget)})||((flowId.id==${JSON.stringify(cleanTarget)})||(flowId.form.code==${JSON.stringify(cleanTarget)}))`,
`(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`
];
for (const filterBy of filters) {
try {
const items = await searchCloseBacklogs(client, corpId, {
filterBy,
limit: { start: 0, count: 100 },
select: HOSE_CLOSE_LOOKUP_SELECT
});
const match = items.find((item) => {
const flow = item.flowId && typeof item.flowId === "object" ? (item.flowId as Record<string, unknown>) : {};
const form = flow.form && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : {};
return item.id === cleanTarget || flow.id === cleanTarget || form.code === cleanTarget;
});
if (match && typeof match.id === "string") {
return match.id;
}
} catch {
// Fall through to next filter or return raw target
}
}
return cleanTarget;
}
export async function fetchRawCloseHoseFlow(
client: KyInstance,
corpId: string,
target: string
): Promise<Record<string, unknown> | undefined> {
const backlogId = await resolveCloseBacklogId(client, corpId, target);
return getCloseBacklogDetailById(client, corpId, backlogId);
}
+64
View File
@@ -0,0 +1,64 @@
import ky, { HTTPError, type KyInstance } from "ky";
import { ensureHoseCloseApiToken, normalizeBaseUrl } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
export interface HoseCloseClientCredentials {
domain: string;
corpId: string;
staffId: string;
accessToken: string;
}
export function getHoseCloseHeaders(credentials: HoseCloseClientCredentials): Record<string, string> {
return {
accesstoken: credentials.accessToken,
corpid: credentials.corpId,
staffid: credentials.staffId
};
}
export function createHoseCloseClientWithCredentials(
credentials: HoseCloseClientCredentials,
customHeaders?: Record<string, string>
): KyInstance {
return ky.create({
prefix: normalizeBaseUrl(credentials.domain),
timeout: 30000,
headers: {
...getHoseCloseHeaders(credentials),
...customHeaders
},
hooks: {
beforeError: [
async ({ error }) => {
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
}
});
}
export async function createHoseCloseClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
): Promise<KyInstance> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const tokenEntry = await ensureHoseCloseApiToken(corp);
return createHoseCloseClientWithCredentials(
{
domain: corp.source.domain,
corpId: corp.source.corpId,
staffId: corp.source.staffId,
accessToken: tokenEntry.token
},
customHeaders
);
}
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
+28
View File
@@ -0,0 +1,28 @@
import { z } from "zod";
export const RawHoseBacklogItemSchema = z
.object({
id: z.string(),
state: z.string().optional(),
nodeName: z.string().optional(),
flowId: z.record(z.string(), z.unknown()).optional(),
nodeState: z.record(z.string(), z.unknown()).optional()
})
.passthrough();
export type RawHoseBacklogItem = z.infer<typeof RawHoseBacklogItemSchema>;
export const RawHoseBacklogSearchResponseSchema = z
.object({
count: z.number().optional(),
items: z.array(z.record(z.string(), z.unknown())).default([])
})
.passthrough();
export type RawHoseBacklogSearchResponse = z.infer<typeof RawHoseBacklogSearchResponseSchema>;
export const RawHoseBacklogDetailResponseSchema = z
.object({
value: z.record(z.string(), z.unknown()).optional(),
items: z.array(z.record(z.string(), z.unknown())).optional()
})
.passthrough();
export type RawHoseBacklogDetailResponse = z.infer<typeof RawHoseBacklogDetailResponseSchema>;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
export * from "./flow.js";
export * as hoseOpen from "./open/index.js";
export * as hoseClose from "./close/index.js";
+179
View File
@@ -0,0 +1,179 @@
import type { KyInstance } from "ky";
import { HTTPError } from "ky";
import {
HoseOpenAllLogsResponseSchema,
HoseOpenFlowDetailsResponseSchema,
HoseOpenStaffResponseSchema,
HoseOpenVersionedResponseSchema,
type HoseOpenAllLogsItem,
type HoseOpenCompositeData,
type HoseOpenFlowDetailsValue,
type HoseOpenStaffItem,
type HoseOpenStaffQueryOptions,
type HoseOpenVersionedItem
} from "./types.js";
export async function fetchHoseOpenFlowDetails(
client: KyInstance,
flowId: string
): Promise<HoseOpenFlowDetailsValue | undefined> {
try {
const response = await client
.get("api/openapi/v1.1/flowDetails", {
searchParams: { flowId }
})
.json();
const parsed = HoseOpenFlowDetailsResponseSchema.parse(response);
return parsed.value;
} catch (error) {
if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) {
return undefined;
}
throw error;
}
}
export async function fetchHoseOpenAllLogs(
client: KyInstance,
flowId: string
): Promise<HoseOpenAllLogsItem[]> {
try {
const response = await client
.get("api/openapi/v1.1/flowDetails/allLogs", {
searchParams: { flowId }
})
.json();
const parsed = HoseOpenAllLogsResponseSchema.parse(response);
return parsed.items;
} catch (error) {
if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) {
return [];
}
throw error;
}
}
export interface FetchHoseOpenVersionedOptions {
pageNum?: number;
pageSize?: number;
convertFeeType?: boolean;
}
export async function fetchHoseOpenVersioned(
client: KyInstance,
flowId: string,
options?: FetchHoseOpenVersionedOptions
): Promise<HoseOpenVersionedItem[]> {
try {
const response = await client
.get("api/openapi/v1/flow/versioned", {
searchParams: {
flow_id: flowId,
pageNum: options?.pageNum ?? 1,
pageSize: options?.pageSize ?? 20,
convertFeeType: options?.convertFeeType ?? true
}
})
.json();
const parsed = HoseOpenVersionedResponseSchema.parse(response);
return parsed.items;
} catch (error) {
if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) {
return [];
}
throw error;
}
}
export async function fetchHoseOpenStaffs(
client: KyInstance,
options: HoseOpenStaffQueryOptions
): Promise<HoseOpenStaffItem[]> {
if (!options.conditionIds || options.conditionIds.length === 0) {
return [];
}
try {
const response = await client
.post("api/openapi/v1/staffs/getStaffIds", {
json: {
type: options.type,
conditionIds: options.conditionIds.slice(0, 100)
}
})
.json();
const parsed = HoseOpenStaffResponseSchema.parse(response);
return parsed.items;
} catch (error) {
if (options.conditionIds.length > 1) {
const items: HoseOpenStaffItem[] = [];
for (const id of options.conditionIds) {
try {
const res = await client
.post("api/openapi/v1/staffs/getStaffIds", {
json: { type: options.type, conditionIds: [id] }
})
.json();
const p = HoseOpenStaffResponseSchema.parse(res);
items.push(...p.items);
} catch {
// Gracefully continue on individual failure
}
}
return items;
}
return [];
}
}
export async function fetchHoseOpenCompositeFlow(
client: KyInstance,
flowId: string,
staffCache?: Map<string, HoseOpenStaffItem>
): Promise<HoseOpenCompositeData> {
const [flowDetails, allLogs, versions] = await Promise.all([
fetchHoseOpenFlowDetails(client, flowId),
fetchHoseOpenAllLogs(client, flowId).catch(() => []),
fetchHoseOpenVersioned(client, flowId).catch(() => [])
]);
const staffMap = staffCache ?? new Map<string, HoseOpenStaffItem>();
const missingStaffIds: string[] = [];
const addId = (id?: string | null) => {
if (id && typeof id === "string" && id !== "ebot" && !staffMap.has(id)) {
missingStaffIds.push(id);
}
};
for (const item of allLogs) {
addId(item.ownerId);
}
for (const log of flowDetails?.logs || []) {
addId(log.operatorId);
addId(log.nextOperatorId);
}
const uniqueIds = [...new Set(missingStaffIds)];
if (uniqueIds.length > 0) {
try {
const staffs = await fetchHoseOpenStaffs(client, {
type: "STAFFID",
conditionIds: uniqueIds
});
for (const s of staffs) {
if (s.id) staffMap.set(s.id, s);
if (s.cellphone) staffMap.set(s.cellphone, s);
}
} catch {
// Gracefully continue if staff lookup fails
}
}
return {
flowDetails,
allLogs,
versions,
staffMap
};
}
+55
View File
@@ -0,0 +1,55 @@
import ky, { HTTPError, type KyInstance } from "ky";
import { ensureHoseOpenapiToken, normalizeBaseUrl } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
export interface HoseOpenClientCredentials {
domain?: string;
accessToken: string;
}
export function createHoseOpenClientWithCredentials(
credentials: HoseOpenClientCredentials,
customHeaders?: Record<string, string>
): KyInstance {
const baseUrl = normalizeBaseUrl(credentials.domain || "https://app.ekuaibao.com");
return ky.create({
prefix: baseUrl,
timeout: 30000,
searchParams: {
accessToken: credentials.accessToken
},
headers: {
...customHeaders
},
hooks: {
beforeError: [
async ({ error }) => {
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
}
});
}
export async function createHoseOpenClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
): Promise<KyInstance> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const token = await ensureHoseOpenapiToken(corp);
return createHoseOpenClientWithCredentials(
{
domain: corp.source.domain,
accessToken: token
},
customHeaders
);
}
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
+173
View File
@@ -0,0 +1,173 @@
import { z } from "zod";
const nullableString = z.preprocess((v) => (v === null ? undefined : v), z.string().optional());
const nullableBoolean = z.preprocess((v) => (v === null ? undefined : v), z.boolean().optional());
const nullableNumber = z.preprocess((v) => (v === null ? undefined : v), z.number().optional());
// --- Hose OpenAPI: flowDetails ---
export const HoseOpenFlowLogAttributeSchema = z
.object({
nodeId: nullableString,
nodeName: nullableString,
nextId: nullableString,
nextName: nullableString,
comment: nullableString,
isUrgent: nullableBoolean,
isEbotNode: nullableBoolean,
isAuto: nullableBoolean,
isSkip: nullableBoolean,
skipped: nullableBoolean,
counterSign: nullableBoolean,
nextCounterSign: nullableBoolean,
complete: nullableBoolean
})
.passthrough();
export type HoseOpenFlowLogAttribute = z.infer<typeof HoseOpenFlowLogAttributeSchema>;
export const HoseOpenFlowLogSchema = z
.object({
id: nullableString,
action: nullableString,
state: nullableString,
operatorId: nullableString,
nextOperatorId: nullableString,
nextOperatorIds: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(z.string())).default([]),
time: nullableNumber,
attributes: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFlowLogAttributeSchema.optional())
})
.passthrough();
export type HoseOpenFlowLog = z.infer<typeof HoseOpenFlowLogSchema>;
export const HoseOpenFormDetailSchema = z
.object({
code: nullableString,
title: nullableString,
submitterId: nullableString,
submitDate: nullableNumber,
expenseDate: nullableNumber,
rejectionNum: z.preprocess((v) => (v === null ? undefined : v), z.union([z.number(), z.string()]).optional()),
reviewStatus: nullableString,
specificationId: nullableString,
payMoney: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.unknown()).optional()),
expenseMoney: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.unknown()).optional()),
details: z.preprocess((v) => (v === null ? undefined : v), z.array(z.record(z.string(), z.unknown())).optional())
})
.passthrough();
export type HoseOpenFormDetail = z.infer<typeof HoseOpenFormDetailSchema>;
export const HoseOpenFlowDetailsValueSchema = z
.object({
id: z.string(),
version: nullableNumber,
state: nullableString,
flowType: nullableString,
formType: nullableString,
ownerId: nullableString,
createTime: nullableNumber,
updateTime: nullableNumber,
form: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFormDetailSchema.optional()),
logs: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenFlowLogSchema)).default([]),
actions: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.array(z.string())).optional())
})
.passthrough();
export type HoseOpenFlowDetailsValue = z.infer<typeof HoseOpenFlowDetailsValueSchema>;
export const HoseOpenFlowDetailsResponseSchema = z
.object({
value: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFlowDetailsValueSchema.optional())
})
.passthrough();
export type HoseOpenFlowDetailsResponse = z.infer<typeof HoseOpenFlowDetailsResponseSchema>;
// --- Hose OpenAPI: flowDetails/allLogs ---
export const HoseOpenAllLogsItemSchema = z
.object({
id: z.string(),
flowId: nullableString,
nodeId: nullableString,
nodeName: nullableString,
ownerId: nullableString,
state: nullableString,
logId: nullableNumber,
action: nullableString,
createTime: nullableNumber,
updateTime: nullableNumber,
isUrgent: nullableBoolean
})
.passthrough();
export type HoseOpenAllLogsItem = z.infer<typeof HoseOpenAllLogsItemSchema>;
export const HoseOpenAllLogsResponseSchema = z
.object({
count: z.preprocess((v) => (typeof v === "number" ? v : 0), z.number()).default(0),
items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenAllLogsItemSchema)).default([])
})
.passthrough();
export type HoseOpenAllLogsResponse = z.infer<typeof HoseOpenAllLogsResponseSchema>;
// --- Hose OpenAPI: flow/versioned ---
export const HoseOpenVersionedItemSchema = z
.object({
id: nullableString,
flowId: nullableString,
version: nullableNumber,
state: nullableString,
createTime: nullableNumber,
updateTime: nullableNumber,
form: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFormDetailSchema.optional()),
logs: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenFlowLogSchema)).default([]),
modifyFlowLog: z.preprocess((v) => (Array.isArray(v) ? v : undefined), z.array(z.record(z.string(), z.unknown())).optional())
})
.passthrough();
export type HoseOpenVersionedItem = z.infer<typeof HoseOpenVersionedItemSchema>;
export const HoseOpenVersionedResponseSchema = z
.object({
count: z.preprocess((v) => (typeof v === "number" ? v : 0), z.number()).default(0),
items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenVersionedItemSchema)).default([])
})
.passthrough();
export type HoseOpenVersionedResponse = z.infer<typeof HoseOpenVersionedResponseSchema>;
// --- Hose OpenAPI Composite Result ---
export interface HoseOpenCompositeData {
flowDetails?: HoseOpenFlowDetailsValue;
allLogs: HoseOpenAllLogsItem[];
versions: HoseOpenVersionedItem[];
staffMap?: Map<string, HoseOpenStaffItem>;
}
// --- Hose OpenAPI: staffs/getStaffIds ---
export const HoseOpenStaffItemSchema = z
.object({
id: z.string(),
name: nullableString,
enName: nullableString,
nickName: nullableString,
code: nullableString,
cellphone: nullableString,
email: nullableString,
active: nullableBoolean,
userId: nullableString,
defaultDepartment: nullableString
})
.passthrough();
export type HoseOpenStaffItem = z.infer<typeof HoseOpenStaffItemSchema>;
export const HoseOpenStaffResponseSchema = z
.object({
items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenStaffItemSchema)).default([])
})
.passthrough();
export type HoseOpenStaffResponse = z.infer<typeof HoseOpenStaffResponseSchema>;
export interface HoseOpenStaffQueryOptions {
type: "STAFFID" | "CODE" | "CELLPHONE" | "MAIL" | "USERID";
conditionIds: string[];
}
+173
View File
@@ -0,0 +1,173 @@
import { z } from "zod";
export const HOSE_FLOW_ACTION_LABELS: Record<string, string> = {
"freeflow.submit": "提交送审",
"freeflow.agree": "审批同意",
"freeflow.autoAgree": "自动同意",
"freeflow.reject": "审批驳回",
"freeflow.back": "审批退回",
"freeflow.print": "打印单据",
"freeflow.retract": "单据撤回",
"freeflow.addnode": "加签/转交",
"freeflow.comment": "发表评论",
"freeflow.pay": "支付成功",
"freeflow.paying": "发起支付",
"freeflow.carbonCopy": "抄送单据",
"freeflow.cc": "抄送单据"
};
export const HOSE_FLOW_STATE_LABELS: Record<string, string> = {
APPROVING: "审批中",
APPROVED: "审批通过",
REJECTED: "审批驳回",
REVOKED: "已撤回",
CANCELED: "已取消",
CANCELLED: "已取消",
SKIPPED: "已跳过",
SUBMITTED: "已提交",
PENDING: "待审批",
WAITING: "待处理",
COMPLETED: "已完成",
DRAFT: "草稿",
PAID: "已支付",
PAYING: "支付中"
};
export const FlowPersonSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
code: z.string().optional()
});
export type FlowPerson = z.infer<typeof FlowPersonSchema>;
export const HoseFlowTimelineEntrySchema = z.object({
id: z.string().optional(),
nodeId: z.string().optional(),
time: z.number().optional(),
durationMs: z.number().optional(),
state: z.string().optional(),
rawState: z.string().optional(),
action: z.string().optional(),
rawAction: z.string().optional(),
nodeName: z.string().optional(),
comment: z.string().optional(),
rawComment: z.string().optional(),
automatic: z.boolean().default(false),
isEbot: z.boolean().default(false),
skipped: z.boolean().default(false),
operator: FlowPersonSchema.optional(),
nextOperators: z.array(FlowPersonSchema).default([]),
rejectTargetNodeName: z.string().optional(),
rejectTargetOperator: FlowPersonSchema.optional(),
resubmitRuleText: z.string().optional(),
isModification: z.boolean().default(false)
});
export type HoseFlowTimelineEntry = z.infer<typeof HoseFlowTimelineEntrySchema>;
export const HoseFlowPendingNodeSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
type: z.string().optional(),
state: z.enum(["当前", "后续", "已完成"]).default("后续"),
isCurrent: z.boolean().default(false),
approver: FlowPersonSchema.optional(),
approvers: z.array(FlowPersonSchema).default([])
});
export type HoseFlowPendingNode = z.infer<typeof HoseFlowPendingNodeSchema>;
export const HoseFlowMetricsSchema = z.object({
rejectionNum: z.number().int().nonnegative().default(0),
submitCount: z.number().int().positive().default(1),
sourceFlowVersion: z.union([z.string(), z.number()]).optional(),
isModifiedAfterReject: z.boolean().default(false),
retractCount: z.number().int().nonnegative().default(0),
isResubmittedAfterRetract: z.boolean().default(false)
});
export type HoseFlowMetrics = z.infer<typeof HoseFlowMetricsSchema>;
export const HoseStaffOpinionSchema = z.object({
nodeName: z.string().optional(),
operator: FlowPersonSchema.optional(),
action: z.string().optional(),
rawAction: z.string().optional(),
time: z.number().optional(),
comment: z.string(),
isEbot: z.boolean().default(false)
});
export type HoseStaffOpinion = z.infer<typeof HoseStaffOpinionSchema>;
export const HoseRejectionDetailSchema = z.object({
time: z.number().optional(),
nodeName: z.string().optional(),
operator: FlowPersonSchema.optional(),
isEbot: z.boolean().default(false),
reason: z.string(),
rawComment: z.string().optional(),
fromNodeName: z.string().optional(),
targetNodeName: z.string().optional(),
targetOperator: FlowPersonSchema.optional(),
resubmitRuleText: z.string().optional()
});
export type HoseRejectionDetail = z.infer<typeof HoseRejectionDetailSchema>;
export const HoseFlowDetailSchema = z.object({
backlogId: z.string(),
flowId: z.string().optional(),
billCode: z.string().optional(),
title: z.string().optional(),
state: z.string().optional(),
rawState: z.string().optional(),
currentNode: z.string().optional(),
specification: z.object({
id: z.string().optional(),
name: z.string().optional(),
code: z.string().optional()
}).optional(),
submitter: FlowPersonSchema.optional(),
owner: FlowPersonSchema.optional(),
submitDate: z.number().optional(),
updateTime: z.number().optional(),
history: z.array(HoseFlowTimelineEntrySchema),
pending: z.array(HoseFlowPendingNodeSchema),
metrics: HoseFlowMetricsSchema,
staffOpinions: z.array(HoseStaffOpinionSchema),
rejections: z.array(HoseRejectionDetailSchema),
raw: z.record(z.string(), z.unknown()).optional()
});
export type HoseFlowDetail = z.infer<typeof HoseFlowDetailSchema>;
export const RawHoseBacklogItemSchema = z.object({
id: z.string(),
state: z.string().optional(),
nodeName: z.string().optional(),
flowId: z.record(z.string(), z.unknown()).optional(),
nodeState: z.record(z.string(), z.unknown()).optional()
}).passthrough();
export type RawHoseBacklogItem = z.infer<typeof RawHoseBacklogItemSchema>;
export const RawHoseBacklogSearchResponseSchema = z.object({
count: z.number().optional(),
items: z.array(z.record(z.string(), z.unknown())).default([])
}).passthrough();
export type RawHoseBacklogSearchResponse = z.infer<typeof RawHoseBacklogSearchResponseSchema>;
export const RawHoseBacklogDetailResponseSchema = z.object({
value: z.record(z.string(), z.unknown()).optional(),
items: z.array(z.record(z.string(), z.unknown())).optional()
}).passthrough();
export type RawHoseBacklogDetailResponse = z.infer<typeof RawHoseBacklogDetailResponseSchema>;
export const HoseRunAlignmentSchema = z.object({
recordId: z.string(),
sourceDocumentSN: z.string().optional(),
taskMode: z.string().optional(),
aiDecision: z.string().optional(),
aiAction: z.string().optional(),
eHumanAction: z.string(),
eHumanComment: z.string(),
auditDrift: z.boolean().default(false),
auditDriftReason: z.string().optional(),
operator: FlowPersonSchema.optional()
});
export type HoseRunAlignment = z.infer<typeof HoseRunAlignmentSchema>;
+266 -4
View File
@@ -4,9 +4,15 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import ExcelJS from "exceljs";
import {
formatDate,
formatExportDateTag,
formatExportMinuteTag,
getBeijingDate,
getBeijingDateFrom,
getRuleBriefTitle,
normalizeManualApprovalStatus,
normalizeTimestamp,
resolveExportDateRange,
resolveOutputFilePath,
exportApprovalRunsToExcel
} from "./approval-runs-export.js";
@@ -59,13 +65,111 @@ describe("approval-runs-export helpers", () => {
});
expect(custom).toBe("/tmp/custom-export.xlsx");
const fixedTime = new Date("2026-09-15T10:26:00+08:00");
const dl = resolveOutputFilePath({
toDownloads: true,
corpName: "大黄蜂",
dateTag: "2026-08-07至今",
recordCount: 50
dateTag: "2026-08-07至2026-09-14",
recordCount: 50,
exportTime: fixedTime
});
expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至今_50条.xlsx");
expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至2026-09-14_50条_20260915_1026.xlsx");
const rangeDl = resolveOutputFilePath({
toDownloads: true,
corpName: "华铁大黄蜂",
dateTag: "2026-08-07至2026-09-13",
recordCount: 9780,
exportTime: fixedTime
});
expect(rangeDl).toContain("Downloads/华铁大黄蜂_审核记录_2026-08-07至2026-09-13_9780条_20260915_1026.xlsx");
});
test("formatExportMinuteTag formats in Asia/Shanghai correctly", () => {
const fixedTime = new Date("2026-09-15T10:26:00+08:00");
expect(formatExportMinuteTag(fixedTime)).toBe("20260915_1026");
});
test("formatDate formats dates, epoch timestamps, and strings cleanly in Asia/Shanghai", () => {
expect(formatDate("2026-08-07")).toBe("2026-08-07");
expect(formatDate("2026-08-07T12:00:00Z")).toBe("2026-08-07");
expect(formatDate("1786032000000")).toBe("2026-08-07");
expect(formatDate("1786032000")).toBe("2026-08-07");
expect(formatDate(1786032000000)).toBe("2026-08-07");
expect(formatDate(new Date("2026-08-07T00:00:00+08:00"))).toBe("2026-08-07");
expect(formatDate(undefined)).toBeUndefined();
expect(formatDate("")).toBeUndefined();
});
test("resolveExportDateRange standardizes date intervals without 至今 or 截至", () => {
const today = getBeijingDate(0);
const yesterday = getBeijingDate(-1);
// 1. Both start and end provided
const both = resolveExportDateRange({ startDate: "2026-08-07", endDate: "2026-09-13" });
expect(both.startDateStr).toBe("2026-08-07");
expect(both.endDateStr).toBe("2026-09-13");
expect(both.dateTag).toBe("2026-08-07至2026-09-13");
expect(both.spanDays).toBe(37);
// 2. Only start provided -> defaults end to today
const startOnly = resolveExportDateRange({ startDate: "2026-08-07" });
expect(startOnly.startDateStr).toBe("2026-08-07");
expect(startOnly.endDateStr).toBe(today);
expect(startOnly.dateTag).toBe(`2026-08-07至${today}`);
expect(startOnly.dateTag).not.toContain("至今");
// 3. Only end provided -> defaults start to 30 days before end
const endOnly = resolveExportDateRange({ endDate: "2026-09-13" });
expect(endOnly.endDateStr).toBe("2026-09-13");
expect(endOnly.startDateStr).toBe("2026-08-14");
expect(endOnly.dateTag).toBe("2026-08-14至2026-09-13");
expect(endOnly.dateTag).not.toContain("截至");
expect(endOnly.spanDays).toBe(30);
// 4. Neither provided -> defaults yesterday to today
const neither = resolveExportDateRange({});
expect(neither.startDateStr).toBe(yesterday);
expect(neither.endDateStr).toBe(today);
expect(neither.dateTag).toBe(`${yesterday}至${today}`);
expect(neither.dateTag).not.toContain("至今");
expect(neither.dateTag).not.toContain("截至");
expect(neither.spanDays).toBe(1);
// formatExportDateTag wrapper behaves identically
expect(formatExportDateTag("2026-08-07", "2026-09-13")).toBe("2026-08-07至2026-09-13");
expect(formatExportDateTag("2026-08-07", undefined)).toBe(`2026-08-07至${today}`);
expect(formatExportDateTag(undefined, "2026-09-13")).toBe("2026-08-14至2026-09-13");
expect(formatExportDateTag(undefined, undefined)).toBe(`${yesterday}至${today}`);
});
test("resolveExportDateRange intercepts invalid inputs and enforces 180-day span rule", () => {
// Start > End error
expect(() =>
resolveExportDateRange({ startDate: "2026-09-15", endDate: "2026-09-13" })
).toThrow("起始时间 (2026-09-15) 不能晚于结束时间 (2026-09-13)");
// Invalid format error
expect(() => resolveExportDateRange({ startDate: "invalid-date" })).toThrow(
"无效的起始时间参数"
);
expect(() => resolveExportDateRange({ endDate: "invalid-date" })).toThrow(
"无效的结束时间参数"
);
// Span > 180 days without force
expect(() =>
resolveExportDateRange({ startDate: "2026-01-01", endDate: "2026-09-13" })
).toThrow("时间跨度超过 180 天");
// Span > 180 days with force succeeds
const forced = resolveExportDateRange({
startDate: "2026-01-01",
endDate: "2026-09-13",
force: true
});
expect(forced.spanDays).toBeGreaterThan(180);
expect(forced.dateTag).toBe("2026-01-01至2026-09-13");
});
});
@@ -172,14 +276,21 @@ describe("exportApprovalRunsToExcel integration", () => {
expect(result.rejectReasonCount).toBe(1);
expect(existsSync(tmpOut)).toBe(true);
// Verify Excel contents with ExcelJS
// Verify Excel contents with ExcelJS: default export does NOT include E columns (Hose resource optimization)
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(1).getCell(9).value).toBe("人工审核");
expect(ws.getRow(1).getCell(10).value).toBe("人工驳回原因");
expect(ws.getRow(1).getCell(11).value).toBe("创建时间");
expect(ws.getRow(1).getCell(12).value).toBe("任务耗时");
expect(ws.getRow(2).getCell(1).value).toBe("B26001");
expect(ws.getRow(2).getCell(9).value).toBe("已支付/审批完成");
expect(ws.getRow(2).getCell(10).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("请上传正确的行程单凭据");
@@ -189,4 +300,155 @@ describe("exportApprovalRunsToExcel integration", () => {
}
}
});
test("generates excel workbook with E columns when withFlow is true for hose corp", async () => {
const hoseCorp: CorpConfig = {
...testCorp,
source: { type: "hose", corpId: "corp-hose-1" } as any
};
const mockClient = {
get: (url: string) => {
if (url.includes("api/v1/rules")) {
return {
json: async () => ({
rules: [{ id: "r1", code: 0, description: "发票真实性核验", scope: "全局", strictness: "SHOULD_FOLLOW" }]
})
};
}
if (url.includes("api/v1/approvals")) {
return {
json: async () => ({
total: 1,
records: [
{
id: "run-h1",
sourceDocumentSN: "B26001",
status: "completed",
taskMode: "assisted",
sourceSystem: "hosecloud",
document: { fields: [] },
result: { decision: "APPROVE", rulesResult: [] },
manualApprovalRecord: {
status: { label: "已通过", type: "APPROVED" }
},
createdAt: 1788760000000,
updatedAt: 1788760030000
}
]
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const tmpOut = join(tmpdir(), `test-export-flow-${Date.now()}.xlsx`);
try {
const result = await exportApprovalRunsToExcel(mockClient, hoseCorp, {
outputFile: tmpOut,
limit: 10,
pageDelayMs: 0,
withFlow: true
});
expect(result.recordCount).toBe(1);
const wb = new ExcelJS.Workbook();
await wb.xlsx.readFile(tmpOut);
const ws = wb.worksheets[0]!;
expect(ws.getRow(1).getCell(1).value).toBe("单据编号");
expect(ws.getRow(1).getCell(9).value).toBe("人工审核");
expect(ws.getRow(1).getCell(10).value).toBe("人工驳回原因");
expect(ws.getRow(1).getCell(11).value).toBe("E人工行为");
expect(ws.getRow(1).getCell(12).value).toBe("E人工意见");
expect(ws.getRow(1).getCell(13).value).toBe("创建时间");
} finally {
if (existsSync(tmpOut)) {
rmSync(tmpOut, { force: true });
}
}
});
test("rejects export without force when time range exceeds 180 days", async () => {
const mockClient = {} as any;
await expect(
exportApprovalRunsToExcel(mockClient, testCorp, {
startDate: "2026-01-01",
endDate: "2026-09-13"
})
).rejects.toThrow("时间跨度超过 180 天");
});
test("rejects export when startDate is after endDate", async () => {
const mockClient = {} as any;
await expect(
exportApprovalRunsToExcel(mockClient, testCorp, {
startDate: "2026-09-15",
endDate: "2026-09-13"
})
).rejects.toThrow("起始时间 (2026-09-15) 不能晚于结束时间 (2026-09-13)");
});
test("automatically excludes simulation tasks and records excludedSimulationCount", async () => {
const mockClient = {
get: (url: string) => {
if (url.includes("api/v1/rules")) {
return { json: async () => ({ rules: [] }) };
}
if (url.includes("api/v1/approvals")) {
return {
json: async () => ({
total: 3,
records: [
{
id: "run-sim-1",
sourceDocumentSN: "SIM001",
status: "completed",
taskMode: "simulation",
createdAt: 1788760000000
},
{
id: "run-real-1",
sourceDocumentSN: "REAL001",
status: "completed",
taskMode: "assisted",
createdAt: 1788760010000
},
{
id: "run-sim-2",
sourceDocumentSN: "SIM002",
status: "completed",
taskMode: "simulation",
createdAt: 1788760020000
}
]
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const tmpOut = join(tmpdir(), `test-export-sim-${Date.now()}.xlsx`);
try {
const result = await exportApprovalRunsToExcel(mockClient, testCorp, {
outputFile: tmpOut,
pageDelayMs: 0
});
expect(result.recordCount).toBe(1);
expect(result.excludedSimulationCount).toBe(2);
const wb = new ExcelJS.Workbook();
await wb.xlsx.readFile(tmpOut);
const ws = wb.worksheets[0]!;
expect(ws.rowCount).toBe(2); // 1 header + 1 real row
expect(ws.getRow(2).getCell(1).value).toBe("REAL001");
} finally {
if (existsSync(tmpOut)) {
rmSync(tmpOut, { force: true });
}
}
});
});
+592 -73
View File
@@ -5,6 +5,13 @@ import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow,
type HoseOpenStaffItem,
type HoseRunAlignment
} from "../hose/index.js";
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
export interface ApprovalRunsExportOptions {
@@ -18,6 +25,15 @@ export interface ApprovalRunsExportOptions {
toDownloads?: boolean;
pageSize?: number;
pageDelayMs?: number;
force?: boolean;
withFlow?: boolean;
flowConcurrency?: number;
flowBatchDelayMs?: number;
excludeDeleted?: boolean;
taskMode?: string;
sourceSystem?: string;
sns?: string[];
exportTime?: Date;
}
export interface ApprovalRunsExportResult {
@@ -30,6 +46,9 @@ export interface ApprovalRunsExportResult {
rejectReasonCount: number;
fileSizeBytes: number;
exportedAt: string;
driftCount?: number;
excludedDeletedCount?: number;
excludedSimulationCount?: number;
}
export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined {
@@ -50,6 +69,176 @@ export function normalizeTimestamp(val?: string | number, endOfDay = false): str
return str;
}
export function formatDate(val?: string | number | Date): string | undefined {
if (val === undefined || val === null || val === "") return undefined;
if (val instanceof Date) {
return Number.isNaN(val.getTime())
? undefined
: val.toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
}
const raw = String(val).trim();
if (!raw) return undefined;
if (/^\d{4}-\d{2}-\d{2}/.test(raw)) {
return raw.slice(0, 10);
}
if (/^\d{10}$/.test(raw)) {
const d = new Date(Number(raw) * 1000);
return Number.isNaN(d.getTime())
? undefined
: d.toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
}
if (/^\d{13}$/.test(raw) || /^\d+$/.test(raw)) {
const d = new Date(Number(raw));
return Number.isNaN(d.getTime())
? undefined
: d.toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
}
const d = new Date(raw);
return Number.isNaN(d.getTime())
? undefined
: d.toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
}
export function getBeijingDate(offsetDays = 0, baseDate = new Date()): string {
const d = new Date(baseDate.getTime() + offsetDays * 86400000);
return d.toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
}
export function getBeijingDateFrom(dateStr: string, offsetDays = 0): string {
const d = new Date(`${dateStr}T00:00:00+08:00`);
d.setDate(d.getDate() + offsetDays);
return d.toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
}
export interface ResolveExportDateRangeOptions {
startDate?: string | number | Date;
endDate?: string | number | Date;
force?: boolean;
maxSpanDays?: number;
silent?: boolean;
}
export interface ResolvedExportDateRange {
startDateStr: string;
endDateStr: string;
startDateTs: string;
endDateTs: string;
dateTag: string;
spanDays: number;
}
export function resolveExportDateRange(
options: ResolveExportDateRangeOptions = {}
): ResolvedExportDateRange {
const maxSpanDays = options.maxSpanDays ?? 180;
const hasStart =
options.startDate !== undefined &&
options.startDate !== null &&
String(options.startDate).trim() !== "";
const hasEnd =
options.endDate !== undefined &&
options.endDate !== null &&
String(options.endDate).trim() !== "";
let startDateStr = "";
let endDateStr = "";
if (hasStart) {
const formatted = formatDate(options.startDate);
if (!formatted) {
throw new Error(
`无效的起始时间参数: "${String(options.startDate)}"。请使用 YYYY-MM-DD 或有效时间戳。`
);
}
startDateStr = formatted;
}
if (hasEnd) {
const formatted = formatDate(options.endDate);
if (!formatted) {
throw new Error(
`无效的结束时间参数: "${String(options.endDate)}"。请使用 YYYY-MM-DD 或有效时间戳。`
);
}
endDateStr = formatted;
}
if (!hasStart && !hasEnd) {
// 默认昨天到今天
startDateStr = getBeijingDate(-1);
endDateStr = getBeijingDate(0);
if (!options.silent) {
console.error(
`ℹ️ 未指定导出起止时间,已自动采用默认区间: ${startDateStr}至${endDateStr}(昨天至今天)。`
);
}
} else if (hasStart && !hasEnd) {
// 默认到今天
endDateStr = getBeijingDate(0);
if (!options.silent) {
console.error(
`ℹ️ 未指定导出结束时间,已自动补齐截至今天: ${startDateStr}至${endDateStr}。`
);
}
} else if (!hasStart && hasEnd) {
// 默认从结束日期往前推 30 天
startDateStr = getBeijingDateFrom(endDateStr!, -30);
if (!options.silent) {
console.error(
`ℹ️ 未指定导出起始时间,已自动向前回溯 30 天: ${startDateStr}至${endDateStr}。`
);
}
} else {
// hasStart && hasEnd: 均已设置
}
// 校验前后顺序
const startTs = normalizeTimestamp(startDateStr, false)!;
const endTs = normalizeTimestamp(endDateStr, true)!;
if (Number(startTs) > Number(endTs)) {
throw new Error(`起始时间 (${startDateStr}) 不能晚于结束时间 (${endDateStr})。`);
}
// 计算天数跨度
const startDayMs = new Date(`${startDateStr}T00:00:00+08:00`).getTime();
const endDayMs = new Date(`${endDateStr}T00:00:00+08:00`).getTime();
const spanDays = Math.round((endDayMs - startDayMs) / 86400000);
if (spanDays > maxSpanDays) {
if (!options.force) {
throw new Error(
`时间跨度超过 ${maxSpanDays} 天(当前为 ${spanDays} 天),大范围导出耗时较长且占用系统资源。如确认需要导出,请添加 --force 参数强制执行。`
);
}
if (!options.silent) {
console.error(
`⚠️ 时间跨度超过 ${maxSpanDays} 天(当前为 ${spanDays} 天),已按 --force 强制执行大范围导出。`
);
}
}
const dateTag = `${startDateStr}至${endDateStr}`;
return {
startDateStr,
endDateStr,
startDateTs: startTs,
endDateTs: endTs,
dateTag,
spanDays
};
}
export function formatExportDateTag(
startDate?: string | number | Date,
endDate?: string | number | Date,
force = true,
silent = true
): string {
return resolveExportDateRange({ startDate, endDate, force, silent }).dateTag;
}
export function normalizeManualApprovalStatus(status?: string | string[]): string[] | undefined {
if (!status) return undefined;
const rawList = Array.isArray(status) ? status : [status];
@@ -78,12 +267,32 @@ export function getRuleBriefTitle(ruleId: string, desc?: string, scope?: string)
return clean.slice(0, 22);
}
export function formatExportMinuteTag(date: Date = new Date()): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Shanghai",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false
}).formatToParts(date);
const find = (type: string) => parts.find((p) => p.type === type)?.value || "";
const year = find("year");
const month = find("month");
const day = find("day");
const hour = find("hour");
const minute = find("minute");
return `${year}${month}${day}_${hour}${minute}`;
}
export function resolveOutputFilePath(options: {
outputFile?: string;
toDownloads?: boolean;
corpName: string;
dateTag?: string;
recordCount: number;
exportTime?: Date;
}): string {
if (options.outputFile) {
const p = resolve(options.outputFile);
@@ -97,7 +306,8 @@ export function resolveOutputFilePath(options: {
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`;
const timeTag = formatExportMinuteTag(options.exportTime || new Date());
const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}_${timeTag}.xlsx`;
let targetDir: string;
if (options.toDownloads) {
@@ -123,8 +333,21 @@ export async function exportApprovalRunsToExcel(
const pageDelayMs = options.pageDelayMs ?? 250;
const limit = options.limit ?? 100000;
const startDateTs = normalizeTimestamp(options.startDate, false);
const endDateTs = normalizeTimestamp(options.endDate, true);
const hasExplicitDate = Boolean(options.startDate || options.endDate);
const targetSns = Array.isArray(options.sns)
? options.sns.map((s) => s.trim()).filter(Boolean)
: [];
const hasTargetSns = targetSns.length > 0;
const targetSnsSet = new Set(targetSns);
const dateRange = resolveExportDateRange({
startDate: options.startDate,
endDate: options.endDate,
force: options.force,
silent: !hasExplicitDate && hasTargetSns
});
const { startDateTs, endDateTs } = dateRange;
let dateTag = dateRange.dateTag;
const manualStatusFilter = normalizeManualApprovalStatus(options.manualApprovalStatus);
// 1. 动态加载企业规则集,生成列定义
@@ -155,71 +378,197 @@ export async function exportApprovalRunsToExcel(
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) {
// 1.5 如果是合思企业且显式启用 withFlow,先探测单据规模并做耗时与频控提示
if (options.withFlow === true && corp.source.type === "hose") {
if (hasTargetSns) {
console.error(
`🎯 [单据筛选] 已指定定向筛选单号: [${targetSns.join(", ")}] (共 ${targetSns.length} 个)。`
);
} else {
try {
batch = await api.listApprovalRuns(client, {
limit: pageSize,
offset,
const probeData = await api.listApprovalRuns(client, {
limit: 1,
startDate: startDateTs,
endDate: endDateTs,
status: options.status,
sourceSystem: options.sourceSystem,
taskMode: options.taskMode,
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));
const probeTotal = probeData.total ?? probeData.records?.length ?? 0;
const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5));
const estSeconds = Math.max(1, Math.ceil((probeTotal / concurrency) * 0.4));
if (probeTotal > 50) {
console.error(
`⚠️ [审批流对齐提示] 目标区间内单据规模约为 ${probeTotal} 笔。系统已启用合思 Open API 保护限流(并发 ${concurrency}),预计审批流拉取耗时约 ${estSeconds} 秒。`
);
}
} catch {
// ignore probe error
}
}
}
if (!batch || !batch.records || batch.records.length === 0) break;
totalAvailable = batch.total ?? totalAvailable;
// 2. 温和分页拉取单据记录
const fetchedRecords: ApprovalRun[] = [];
let excludedSimulationCount = 0;
let excludedOtherSourceCount = 0;
for (const r of batch.records) {
if (options.includeCompletedOnly && r.status !== "completed") {
continue;
}
if (hasTargetSns && targetSns.length <= 50) {
console.error(`正在定向检索 ${targetSns.length} 个指定单号...`);
for (const sn of targetSns) {
try {
const batch = await api.listApprovalRuns(client, {
search: sn,
limit: 50,
startDate: hasExplicitDate ? startDateTs : undefined,
endDate: hasExplicitDate ? endDateTs : undefined,
status: options.status,
sourceSystem: options.sourceSystem,
taskMode: options.taskMode,
manualApprovalStatus: manualStatusFilter
});
const matched = (batch.records || []).filter((r) => r.sourceDocumentSN === sn);
for (const r of matched) {
if (r.taskMode === "simulation") {
excludedSimulationCount++;
continue;
}
if (options.taskMode && r.taskMode !== options.taskMode) continue;
if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) {
excludedOtherSourceCount++;
continue;
}
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);
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;
}
} else {
fetchedRecords.push(r);
} catch (e: any) {
console.error(`⚠️ 定向检索单号 [${sn}] 失败: ${e.message}`);
}
if (fetchedRecords.length >= limit) break;
}
console.error(`定向检索完成,成功匹配 ${fetchedRecords.length} 条记录。`);
} else {
let offset = 0;
let totalAvailable = 0;
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} 条`
);
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,
sourceSystem: options.sourceSystem,
taskMode: options.taskMode,
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 (hasTargetSns && (!r.sourceDocumentSN || !targetSnsSet.has(r.sourceDocumentSN))) {
continue;
}
// 过滤测试任务(仅保留真实审批任务)
if (r.taskMode === "simulation") {
excludedSimulationCount++;
continue;
}
if (options.taskMode && r.taskMode !== options.taskMode) {
continue;
}
// 如果企业是合思来源,仅拉取合思来源单据
if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) {
excludedOtherSourceCount++;
continue;
}
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));
}
}
}
if (batch.records.length < pageSize || offset >= totalAvailable) {
break;
}
if (excludedSimulationCount > 0) {
console.error(
`ℹ️ 已自动排除 ${excludedSimulationCount} 条模拟测试任务 (taskMode="simulation"),仅保留真实审批任务。`
);
}
if (excludedOtherSourceCount > 0) {
console.error(
`ℹ️ 已自动排除 ${excludedOtherSourceCount} 条非合思来源单据,仅保留合思业务单据。`
);
}
if (pageDelayMs > 0) {
await new Promise((r) => setTimeout(r, pageDelayMs));
if (!hasExplicitDate && hasTargetSns && fetchedRecords.length > 0) {
const dates = fetchedRecords
.map((r) => formatDate(r.createdAt || r.updatedAt))
.filter(Boolean) as string[];
if (dates.length > 0) {
dates.sort();
const minDate = dates[0]!;
const maxDate = dates[dates.length - 1]!;
dateTag = minDate === maxDate ? minDate : `${minDate}至${maxDate}`;
}
}
@@ -234,6 +583,8 @@ export async function exportApprovalRunsToExcel(
views: [{ state: "frozen", ySplit: 1, xSplit: 2 }]
});
const withFlow = options.withFlow === true && corp.source.type === "hose";
const baseColumns: Array<{ header: string; key: string; width: number }> = [
{ header: "单据编号", key: "sn", width: 16 },
{ header: "单据模板名称", key: "templateName", width: 26 },
@@ -245,6 +596,12 @@ export async function exportApprovalRunsToExcel(
{ header: "思考深度", key: "thinkingDepth", width: 12 },
{ header: "人工审核", key: "manualStatus", width: 16 },
{ header: "人工驳回原因", key: "humanRejectReason", width: 36 },
...(withFlow
? [
{ header: "E人工行为", key: "eHumanAction", width: 18 },
{ header: "E人工意见", key: "eHumanComment", width: 36 }
]
: []),
{ header: "创建时间", key: "createdAt", width: 20 },
{ header: "任务耗时", key: "duration", width: 12 },
{ header: "关联规则数", key: "hitRuleCount", width: 12 },
@@ -288,9 +645,104 @@ export async function exportApprovalRunsToExcel(
const statusCounts: Record<string, number> = {};
let rejectReasonCount = 0;
let driftCount = 0;
// 3.5 如果是合思租户且显式启用 withFlow(--with-flow),获取原生审批流并对齐 E人工行为 / E人工意见
const alignmentsByRecordId = new Map<string, HoseRunAlignment>();
const deletedSNs = new Set<string>();
const excludeDeleted = options.excludeDeleted ?? true;
if (options.withFlow === true && corp.source.type === "hose") {
try {
const runsByDocKey = new Map<string, ApprovalRun[]>();
for (const record of fetchedRecords) {
const docKey = record.sourceDocumentId || record.sourceDocumentSN;
if (docKey) {
const list = runsByDocKey.get(docKey) || [];
list.push(record);
runsByDocKey.set(docKey, list);
}
}
const uniqueDocKeys = Array.from(runsByDocKey.keys());
if (uniqueDocKeys.length > 0) {
const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5));
const batchDelayMs = options.flowBatchDelayMs ?? 150;
const estSeconds = Math.max(1, Math.ceil((uniqueDocKeys.length / concurrency) * (0.25 + batchDelayMs / 1000)));
console.error(
`正在拉取合思原生审批流以对齐人工行为与意见 (共 ${uniqueDocKeys.length} 个单据,并发限制: ${concurrency},批次间隔: ${batchDelayMs}ms,预计耗时约 ${estSeconds}s)...`
);
const openClient = await createHoseOpenClient(corp);
const staffCache = new Map<string, HoseOpenStaffItem>();
for (let i = 0; i < uniqueDocKeys.length; i += concurrency) {
const batchKeys = uniqueDocKeys.slice(i, i + concurrency);
await Promise.all(
batchKeys.map(async (docKey) => {
const runsForDoc = runsByDocKey.get(docKey)!;
const displaySN = runsForDoc[0]?.sourceDocumentSN || docKey;
try {
const flow = await getHoseOpenFlow(openClient, docKey, staffCache);
if (!flow) {
deletedSNs.add(displaySN);
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined);
for (const [recordId, align] of aligned.entries()) {
align.eHumanAction = "单据已删除";
align.eHumanComment = "合思系统中未找到该单据流转记录(可能已在合思端删除或作废)";
alignmentsByRecordId.set(recordId, align);
}
return;
}
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, flow);
for (const [recordId, align] of aligned.entries()) {
alignmentsByRecordId.set(recordId, align);
if (align.auditDrift) driftCount++;
}
} catch (err: any) {
console.error(`⚠️ 拉取单据 ${displaySN} 审批流失败: ${err.message},使用降级对齐。`);
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined);
for (const [recordId, align] of aligned.entries()) {
alignmentsByRecordId.set(recordId, align);
}
}
})
);
if (batchDelayMs > 0 && i + concurrency < uniqueDocKeys.length) {
await new Promise((r) => setTimeout(r, batchDelayMs));
}
if ((i + concurrency) % 20 < concurrency || i + concurrency >= uniqueDocKeys.length) {
const completed = Math.min(i + batchKeys.length, uniqueDocKeys.length);
const pct = Math.round((completed / uniqueDocKeys.length) * 100);
console.error(`[审批流进度] 已对齐: ${completed}/${uniqueDocKeys.length} (${pct}%)...`);
}
}
}
} catch (err: any) {
console.error(`⚠️ 对齐合思审批流失败: ${err.message},E人工行为与意见将使用默认值。`);
}
if (deletedSNs.size > 0) {
console.error(
`ℹ️ 检测到 ${deletedSNs.size} 个单据在合思端已删除或不存在(如: ${Array.from(deletedSNs).slice(0, 3).join(", ")}...)${
excludeDeleted ? ",已按要求自动排除。" : ",已在报表中标记为「单据已删除」。"
}`
);
}
}
let exportedRecordCount = 0;
let excludedDeletedCount = 0;
// 填充数据行
for (const record of fetchedRecords) {
const sn = record.sourceDocumentSN || record.sourceDocumentId;
if (excludeDeleted && sn && deletedSNs.has(sn)) {
excludedDeletedCount++;
continue;
}
exportedRecordCount++;
const res = (record.result as any) || {};
const doc = (record.document as any) || {};
@@ -325,17 +777,24 @@ export async function exportApprovalRunsToExcel(
// 4. AI 决策与行为
const aiDecision = res.decision || (record as any).aiDecision || "-";
let aiDecisionDesc = aiDecision;
const normAiDec = String(aiDecision).toUpperCase();
let aiDecisionDesc = String(aiDecision);
let aiAction = "-";
if (aiDecision === "APPROVE") {
if (normAiDec === "APPROVE" || normAiDec === "通过") {
aiDecisionDesc = "通过";
aiAction = "添加评论";
} else if (aiDecision === "REVIEW") {
} else if (normAiDec === "EXEMPT_APPROVE" || normAiDec === "免审通过" || normAiDec === "备注通过") {
aiDecisionDesc = "备注通过";
aiAction = "添加评论";
} else if (normAiDec === "REVIEW" || normAiDec === "转交复核") {
aiDecisionDesc = "转交复核";
aiAction = "转交复核";
} else if (aiDecision === "REJECT") {
} else if (normAiDec === "REJECT" || normAiDec === "驳回") {
aiDecisionDesc = "驳回";
aiAction = "驳回";
} else if (normAiDec === "ERROR" || normAiDec === "错误") {
aiDecisionDesc = "错误";
aiAction = "-";
}
// 5. 耗时计算
@@ -351,6 +810,7 @@ export async function exportApprovalRunsToExcel(
// 6. 人工审核状态与驳回原因
const mar = (record as any).manualApprovalRecord || {};
const marSourceStatus = String(mar.status?.sourceStatus || "");
let manualStatus = "-";
if (mar.status?.label) {
manualStatus = String(mar.status.label);
@@ -399,6 +859,10 @@ export async function exportApprovalRunsToExcel(
createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
}
const align = alignmentsByRecordId.get(record.id);
const eHumanAction = align ? align.eHumanAction : "-";
const eHumanComment = align ? align.eHumanComment : "-";
const rowData: Record<string, any> = {
sn: record.sourceDocumentSN || record.sourceDocumentId || "-",
templateName,
@@ -410,6 +874,12 @@ export async function exportApprovalRunsToExcel(
thinkingDepth: "标准",
manualStatus,
humanRejectReason,
...(withFlow
? {
eHumanAction,
eHumanComment
}
: {}),
createdAt: createdAtStr,
duration: durationStr,
hitRuleCount: hitRuleIds.length,
@@ -443,21 +913,41 @@ export async function exportApprovalRunsToExcel(
};
if (colNumber <= baseColumns.length) {
const colDef = baseColumns[colNumber - 1];
const colKey = colDef?.key || "";
const isLeftAligned = [
"sn",
"templateName",
"humanRejectReason",
"eHumanComment",
"hitRulesSummary",
"aiSummary"
].includes(colKey);
const isWrapText = [
"humanRejectReason",
"eHumanComment",
"hitRulesSummary",
"aiSummary"
].includes(colKey);
cell.alignment = {
vertical: "middle",
horizontal: [1, 2, 10, 14, 15].includes(colNumber) ? "left" : "center",
wrapText: [10, 14, 15].includes(colNumber)
horizontal: isLeftAligned ? "left" : "center",
wrapText: isWrapText
};
// AI 决策颜色区分
if (colNumber === 7) {
if (val === "通过") cell.font = { color: { argb: "FF16A34A" }, bold: true };
if (colKey === "aiDecision") {
if (val === "通过" || 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 };
else if (val === "错误" || val === "ERROR") cell.font = { color: { argb: "FFDC2626" }, bold: true };
}
// 人工审核高亮
if (colNumber === 9) {
if (colKey === "manualStatus") {
if (val.includes("驳回")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
@@ -467,13 +957,49 @@ export async function exportApprovalRunsToExcel(
} 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" } };
} else if (val.includes("取消") || val.includes("撤回")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF64748B" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF1F5F9" } };
}
}
// 人工驳回原因字体
if (colNumber === 10 && val !== "-") {
if (colKey === "humanRejectReason" && val !== "-") {
cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF991B1B" } };
}
// E人工行为高亮
if (colKey === "eHumanAction") {
if (val.includes("⚠️") || val.includes("修改")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFD97706" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
} else if (val.includes("驳回") || 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("处理中") ||
val.includes("审核中") ||
val.includes("审批中") ||
val.includes("支付中")
) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } };
} else if (val.includes("撤回") || val.includes("取消")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF64748B" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF1F5F9" } };
} else if (val === "无操作") {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF94A3B8" } };
}
}
// E人工意见字体
if (colKey === "eHumanComment" && val !== "-") {
cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF334155" } };
}
} else {
cell.alignment = { vertical: "middle", horizontal: "center" };
if (val.includes("不通过")) {
@@ -493,23 +1019,13 @@ export async function exportApprovalRunsToExcel(
}
// 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
recordCount: exportedRecordCount,
exportTime: options.exportTime
});
await workbook.xlsx.writeFile(targetPath);
@@ -521,11 +1037,14 @@ export async function exportApprovalRunsToExcel(
filePath: targetPath,
corpId: corp.id,
corpName,
recordCount: fetchedRecords.length,
recordCount: exportedRecordCount,
ruleColumnCount: sortedRuleKeys.length,
statusCounts,
rejectReasonCount,
fileSizeBytes: stat.size,
exportedAt: new Date().toISOString()
exportedAt: new Date().toISOString(),
driftCount,
excludedDeletedCount,
excludedSimulationCount
};
}
+58
View File
@@ -157,4 +157,62 @@ describe("insight-export domain", () => {
}
}
});
test("exportInsightReportToExcel rejects when time range exceeds 180 days without force", async () => {
const mockClient = {} as any;
const testCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "direct",
token: "mock-token",
sealUrl: "https://mock.sealai.cc",
expiresIn: 3600,
staffId: "direct"
},
auth: { refreshTtl: 300 }
};
await expect(
exportInsightReportToExcel(mockClient, testCorp, {
startDate: "2026-01-01",
endDate: "2026-09-13"
})
).rejects.toThrow("时间跨度超过 180 天");
});
test("exportInsightReportToExcel rejects when startDate is after endDate", async () => {
const mockClient = {} as any;
const testCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "direct",
token: "mock-token",
sealUrl: "https://mock.sealai.cc",
expiresIn: 3600,
staffId: "direct"
},
auth: { refreshTtl: 300 }
};
await expect(
exportInsightReportToExcel(mockClient, testCorp, {
startDate: "2026-09-15",
endDate: "2026-09-13"
})
).rejects.toThrow("起始时间 (2026-09-15) 不能晚于结束时间 (2026-09-13)");
});
});
+13 -16
View File
@@ -5,6 +5,7 @@ import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import { formatExportDateTag, resolveExportDateRange } from "./approval-runs-export.js";
import type { InsightPerformance } from "./types.js";
export interface InsightExportOptions {
@@ -13,6 +14,7 @@ export interface InsightExportOptions {
limit?: number;
outputFile?: string;
toDownloads?: boolean;
force?: boolean;
}
export interface InsightExportResult {
@@ -67,24 +69,23 @@ export async function exportInsightReportToExcel(
options: InsightExportOptions = {}
): Promise<InsightExportResult> {
const corpName = corp.name || corp.id;
const targetFilePath = resolveInsightOutputFilePath({
outputFile: options.outputFile,
toDownloads: options.toDownloads,
corpName,
corpId: corp.id
const dateRange = resolveExportDateRange({
startDate: options.startDate,
endDate: options.endDate,
force: options.force
});
const exportedAt = new Date().toISOString();
// 1. 并发拉取基础统计与性能指标
const [stats, perf] = await Promise.all([
api.getInsightStats(client, {
startDate: options.startDate ? String(options.startDate) : undefined,
endDate: options.endDate ? String(options.endDate) : undefined,
startDate: dateRange.startDateStr,
endDate: dateRange.endDateStr,
limit: options.limit ?? 100
}),
api.getInsightPerformance(client, {
startDate: options.startDate,
endDate: options.endDate
startDate: dateRange.startDateStr,
endDate: dateRange.endDateStr
}).catch((): InsightPerformance => ({
metrics: {},
sankeyData: { nodes: [], links: [] }
@@ -113,8 +114,8 @@ export async function exportInsightReportToExcel(
try {
const risksResult = await api.getInsightRisksByTag(client, {
tagId: tag.tagId,
startDate: options.startDate ? String(options.startDate) : undefined,
endDate: options.endDate ? String(options.endDate) : undefined
startDate: dateRange.startDateStr,
endDate: dateRange.endDateStr
});
for (const r of risksResult.risks || []) {
riskDetailRows.push({
@@ -355,11 +356,7 @@ export async function exportInsightReportToExcel(
}
// 4. 写入本地文件
let dateTag: string | undefined;
if (options.startDate) {
const raw = String(options.startDate).slice(0, 10).replace(/[-:]/g, "");
dateTag = `${raw}至今`;
}
const dateTag = dateRange.dateTag;
const targetPath = resolveInsightOutputFilePath({
outputFile: options.outputFile,
+217
View File
@@ -0,0 +1,217 @@
import type { RuleLintIssue, RuleLintResult, RuleLintTarget } from "./types.js";
export const HLAB_DISPOSAL_WORDS = [
"驳回单据",
"直接驳回",
"整单退回",
"退回单据",
"退单处理",
"进行提醒",
"请进行提醒",
"予以驳回",
"直接退回",
"无需人工关注",
"无需展示在最后的审核结论中"
];
export const HLAB_SCOPE_SKIP_WORDS = [
"若上传了",
"如上传了",
"若提供了",
"如提供了",
"附件需上传",
"上传了发票",
"提供了支付截图",
"提供了行程单",
"上传了行程单"
];
export const HLAB_RISK_SUPPRESSION_WORDS = [
"忽略行程冲突",
"忽略重复报销",
"忽略跨城一致性",
"不识别为风险",
"不作为风险事项",
"无需作为风险"
];
export const HLAB_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const HLAB_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票",
"流程"
];
/**
* 合思实验室 (HLab) 结构化审批规则校验器。
* 遵循 HLab 规则工业化编写规范 (Rule-as-SOP):
* 1. 结构完备性:必须包含【检查方法】与【判定标准】结构块
* 2. 三元闭环判定:必须具备 PASS、FAIL 与 证据不足 三个分支,且证据不足须明确转人工复核
* 3. 处置话术解耦:严禁在规则正文写整单处置动作(如驳回单据、直接驳回、进行提醒)
* 4. 适用场景防漏判:拦截在适用场景中设置材料存在前置条件,避免缺失材料时被静默跳过 (False SKIP)
* 5. 消极风险压制拦截:严禁在规则中配置忽略行程冲突或不识别风险等反模式
* 6. 例外条款闭环:包含例外必须指定核验凭据
*/
export function hlabRuleLinter(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const scopeText = (rule.scope || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则长度检查
if (text.length < 10) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 10 个字),无法承载 HLab 结构化规范所要求的判定逻辑",
suggestion: "请按照 HLab 工业化规范补充【检查方法】与【判定标准】"
});
} else if (text.length < 30 && !text.includes("**") && !text.includes("检查方法")) {
issues.push({
level: "warning",
code: "SHORT_DESCRIPTION",
message: "规则正文偏短且缺少结构化要素,可能缺少执行细节或证据边界",
suggestion: "建议扩充核验场景、限制标准或异常处理方式"
});
}
// 2. 结构完备性检查
const hasMethod = /\*\*检查方法\*\*|检查方法[::]/.test(text);
if (!hasMethod) {
issues.push({
level: "error",
code: "MISSING_CHECK_METHOD",
message: "规则正文缺少【检查方法】结构块,大模型难以确定数据提取来源与对齐逻辑",
suggestion: "建议在正文前部增加 **检查方法**:明确 SealAI 应读取的凭证类型、字段名称、归一化方式或前置规则依赖"
});
}
const hasStandard = /\*\*判定标准\*\*|判定标准[::]/.test(text);
if (!hasStandard) {
issues.push({
level: "error",
code: "MISSING_EVAL_STANDARD",
message: "规则正文缺少【判定标准】结构块,缺乏标准化判定边界",
suggestion: "建议在正文后部增加 **判定标准**:包含清晰的 PASS、FAIL 以及证据不足分支"
});
}
// 3. 三元闭环判定检查
const hasPass = /[-*•]?\s*PASS[::]/i.test(text);
const hasFail = /[-*•]?\s*FAIL[::]/i.test(text);
const hasInsufficient = /[-*•]?\s*证据不足[::]/.test(text);
if (!hasPass || !hasFail || !hasInsufficient) {
const missing: string[] = [];
if (!hasPass) missing.push("PASS");
if (!hasFail) missing.push("FAIL");
if (!hasInsufficient) missing.push("证据不足");
issues.push({
level: "error",
code: "INCOMPLETE_TERNARY_BRANCH",
message: `判定标准未形成三元闭环,缺少分支:${missing.join("、")}`,
suggestion: "HLab 规范要求必须提供完整的三元分支:- PASS(充分合规条件)、- FAIL(明确违规条件)、- 证据不足(容错与复核条件)"
});
}
// 4. 证据不足分支人工复核兜底检查
if (hasInsufficient) {
const snippet = text.split("证据不足")?.[1]?.slice(0, 100) || "";
const hasManualReview = /人工复核|人工核对|人工审核|转人工/.test(snippet);
if (!hasManualReview) {
issues.push({
level: "warning",
code: "INSUFFICIENT_WITHOUT_MANUAL_REVIEW",
message: "【证据不足】分支未明确指定转【人工复核】兜底,大模型在材料模糊或冲突时可能失控",
suggestion: "建议在【证据不足】分支末尾补充标准处置话术:'转人工复核',确保容错降级路径统一"
});
}
}
// 5. 整单处置动作越界拦截
for (const word of HLAB_DISPOSAL_WORDS) {
if (text.includes(word)) {
issues.push({
level: "warning",
code: "DISPOSAL_ACTION_LEAK",
snippet: word,
message: `规则正文包含整单处置动作话术 "${word}",违反 HLab 规则事实判定与处置动作解耦规范`,
suggestion: `请移除正文中的 "${word}";单据处置动作(驳回/提醒)应交由平台严格程度(必须遵守/仅建议)或业务工作流定义`
});
break;
}
}
// 6. 适用场景防静默漏判检查
if (scopeText) {
for (const word of HLAB_SCOPE_SKIP_WORDS) {
if (scopeText.includes(word)) {
issues.push({
level: "warning",
code: "SCOPE_FALSE_SKIP_PRONE",
snippet: word,
message: `适用场景包含材料上传前置判断 "${word}",当材料未上传时可能导致该规则被静默跳过(SKIP)而非报违规(FAIL)`,
suggestion: `建议适用场景仅保留业务与单据触发条件(如单据模板、费用类型);材料缺失的检查应显式置于【判定标准】的 FAIL 分支中`
});
break;
}
}
}
// 7. 消极风险压制拦截
for (const word of HLAB_RISK_SUPPRESSION_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "RISK_SUPPRESSION",
snippet: word,
message: `规则正文包含消极风险压制话术 "${word}",可能破坏模型正常审计底线或压制有效违规`,
suggestion: "请移除该规则或改写为正向合规要求;若需豁免特定场景,请在 **例外** 结构块中封闭说明豁免条件与凭证依据"
});
break;
}
}
// 8. 悬空例外与凭据检查
const matchedTrigger = HLAB_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = HLAB_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "error",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: `包含例外条款 "${matchedTrigger}",但未指定 AI 从何处核验该例外成立的凭据来源`,
suggestion: `HLab 规范要求例外条款必须明确凭据载体(如:在【**例外**】块中注明需提供专项 OA 审批 PDF 附件或商家盖章证明)`
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 25 - warningCount * 10);
return {
score,
passed: errorCount === 0,
issues
};
}
export default hlabRuleLinter;
+1
View File
@@ -1,6 +1,7 @@
export * from "./types.js";
export * from "./builtin.js";
export * from "./strict.js";
export * from "./hlab.js";
export * from "./official-templates.js";
export * from "./loader.js";
export * from "./service.js";
+119 -3
View File
@@ -152,11 +152,12 @@ describe("Rule Linter", () => {
const testOfficialDir = join(tmpdir(), `seal-official-linter-test-${Date.now()}`);
try {
// 1. 首次同步:生成 builtin.ts 与 strict.ts 明文文件
// 1. 首次同步:生成 builtin.ts、strict.ts 与 hlab.ts 明文文件
const firstSync = syncOfficialLinters(testOfficialDir);
expect(firstSync.synced.sort()).toEqual(["builtin.ts", "strict.ts"]);
expect(firstSync.synced.sort()).toEqual(["builtin.ts", "hlab.ts", "strict.ts"]);
expect(existsSync(join(testOfficialDir, "builtin.ts"))).toBe(true);
expect(existsSync(join(testOfficialDir, "strict.ts"))).toBe(true);
expect(existsSync(join(testOfficialDir, "hlab.ts"))).toBe(true);
const builtinPlaintext = readFileSync(join(testOfficialDir, "builtin.ts"), "utf8");
expect(builtinPlaintext).toContain("Seal 官方标准规则校验器");
@@ -166,6 +167,10 @@ describe("Rule Linter", () => {
expect(strictPlaintext).toContain("Seal 官方严格风控规则校验器");
expect(strictPlaintext).toContain("STRICT_QUANTITATIVE_INDICATORS");
const hlabPlaintext = readFileSync(join(testOfficialDir, "hlab.ts"), "utf8");
expect(hlabPlaintext).toContain("合思实验室 (HLab) 结构化规则校验器");
expect(hlabPlaintext).toContain("HLAB_DISPOSAL_WORDS");
// 2. 模拟客户私自篡改 official/builtin.ts
writeFileSync(join(testOfficialDir, "builtin.ts"), "// HACKED CONTENT", "utf8");
expect(readFileSync(join(testOfficialDir, "builtin.ts"), "utf8")).toBe("// HACKED CONTENT");
@@ -177,7 +182,7 @@ describe("Rule Linter", () => {
// 4. 再次执行同步:篡改的内容必须被官方重写,多余文件和子目录必须全部被干掉
const secondSync = syncOfficialLinters(testOfficialDir);
expect(secondSync.synced.sort()).toEqual(["builtin.ts", "strict.ts"]);
expect(secondSync.synced.sort()).toEqual(["builtin.ts", "hlab.ts", "strict.ts"]);
expect(secondSync.pruned.sort()).toEqual(["extra-subfolder", "my-custom-rule.ts", "random.txt"]);
// 验证官方文件已恢复明文
@@ -204,5 +209,116 @@ describe("Rule Linter", () => {
expect(res.passed).toBe(false);
expect(res.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
});
test("hlabRuleLinter enforces HLab SOP structure, ternary closure, action decoupling, and false-skip prevention", async () => {
const { hlabRuleLinter } = await import("./hlab.js");
// 1. 标准 HLab 结构化规则:满分通过
const perfectRule = {
scope: "单据模板或费用类型为业务招待费。",
description: `**检查方法**:
读取菜单凭证中的用餐开始时间和结束时间;两项均可识别时,按完整时间计算两者间隔。
**判定标准**:
- PASS:开始时间和结束时间均可识别,且用餐时间间隔大于15分钟。
- FAIL:开始时间和结束时间均可识别,且用餐时间间隔小于或等于15分钟;15分钟作为边界值计入不符合范围。
- 证据不足:菜单只记录其中一个时间、任一时间不可读或结束时间早于开始时间时,转人工复核。`
};
const perfectRes = hlabRuleLinter(perfectRule);
expect(perfectRes.passed).toBe(true);
expect(perfectRes.score).toBe(100);
expect(perfectRes.issues.length).toBe(0);
// 2. 缺失【检查方法】与【判定标准】
const noStructureRes = hlabRuleLinter({
description: "报销金额不能超过实际支付金额,否则驳回单据。"
});
expect(noStructureRes.passed).toBe(false);
expect(noStructureRes.issues.some((i) => i.code === "MISSING_CHECK_METHOD")).toBe(true);
expect(noStructureRes.issues.some((i) => i.code === "MISSING_EVAL_STANDARD")).toBe(true);
expect(noStructureRes.issues.some((i) => i.code === "DISPOSAL_ACTION_LEAK")).toBe(true);
// 3. 判定标准缺少三元分支中的 FAIL 与 证据不足
const partialBranchRes = hlabRuleLinter({
description: `**检查方法**:
核对发票金额与报销金额。
**判定标准**:
- PASS:发票金额等于报销金额。`
});
expect(partialBranchRes.passed).toBe(false);
const branchIssue = partialBranchRes.issues.find((i) => i.code === "INCOMPLETE_TERNARY_BRANCH");
expect(branchIssue).toBeDefined();
expect(branchIssue?.message).toContain("FAIL");
expect(branchIssue?.message).toContain("证据不足");
// 4. 证据不足分支未指定转人工复核
const noManualReviewRes = hlabRuleLinter({
description: `**检查方法**:
核对发票金额。
**判定标准**:
- PASS:发票金额合规。
- FAIL:发票金额不合规。
- 证据不足:发票不可读时不处理。`
});
expect(noManualReviewRes.passed).toBe(true); // 只有 warning 不会使 passed 为 false
expect(noManualReviewRes.issues.some((i) => i.code === "INSUFFICIENT_WITHOUT_MANUAL_REVIEW")).toBe(true);
// 5. 适用场景包含上传材料前置条件(防 False SKIP)
const falseSkipRes = hlabRuleLinter({
scope: "若上传了发票,费用类型为餐饮费。",
description: `**检查方法**:
检查发票抬头。
**判定标准**:
- PASS:抬头一致。
- FAIL:抬头不一致。
- 证据不足:抬头模糊时转人工复核。`
});
expect(falseSkipRes.issues.some((i) => i.code === "SCOPE_FALSE_SKIP_PRONE")).toBe(true);
// 6. 消极风险压制拦截
const suppressionRes = hlabRuleLinter({
description: `**检查方法**:
忽略行程冲突,只检查金额。
**判定标准**:
- PASS:金额合规。
- FAIL:金额超标。
- 证据不足:模糊时转人工复核。`
});
expect(suppressionRes.passed).toBe(false);
expect(suppressionRes.issues.some((i) => i.code === "RISK_SUPPRESSION")).toBe(true);
// 7. 悬空例外拦截
const hangingExceptionRes = hlabRuleLinter({
description: `**检查方法**:
检查差旅住宿费。特殊情况除外。
**判定标准**:
- PASS:住宿费未超标。
- FAIL:住宿费超标。
- 证据不足:转人工复核。`
});
expect(hangingExceptionRes.passed).toBe(false);
expect(hangingExceptionRes.issues.some((i) => i.code === "HANGING_EXCEPTION")).toBe(true);
});
test("loadRuleLinter loads hlab linter and aliases correctly", async () => {
const loadedHlab = await loadRuleLinter("hlab");
expect(loadedHlab.name).toBe("hlab");
expect(loadedHlab.type).toBe("official");
const loadedAlias = await loadRuleLinter("hlab-sop");
expect(loadedAlias.name).toBe("hlab");
expect(loadedAlias.type).toBe("official");
const { listAvailableLinters } = await import("./loader.js");
const linters = listAvailableLinters({ syncOfficial: false });
const hlabItem = linters.find((l) => l.name === "hlab");
expect(hlabItem).toBeDefined();
expect(hlabItem?.description).toContain("合思实验室 (HLab)");
});
});
+31 -4
View File
@@ -3,6 +3,7 @@ import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { builtinRuleLinter } from "./builtin.js";
import { hlabRuleLinter } from "./hlab.js";
import { OFFICIAL_LINTER_TEMPLATES } from "./official-templates.js";
import { strictRuleLinter } from "./strict.js";
import type { RuleLintContext, RuleLintResult, RuleLintTarget, RuleLinterFn } from "./types.js";
@@ -109,6 +110,12 @@ export function listAvailableLinters(options: { syncOfficial?: boolean } = { syn
type: "official",
path: join(OFFICIAL_LINTERS_DIR, "strict.ts"),
description: "Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"
},
{
name: "hlab",
type: "official",
path: join(OFFICIAL_LINTERS_DIR, "hlab.ts"),
description: "合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"
}
];
@@ -148,7 +155,7 @@ export function listAvailableLinters(options: { syncOfficial?: boolean } = { syn
export function resolveLinterPath(nameOrPath: string): {
path?: string;
isOfficial?: boolean;
officialKind?: "builtin" | "strict";
officialKind?: "builtin" | "strict" | "hlab";
} {
const norm = (nameOrPath || "").trim();
if (!norm || norm === "builtin" || norm === "default" || norm === "official/builtin" || norm === "official/builtin.ts") {
@@ -167,6 +174,21 @@ export function resolveLinterPath(nameOrPath: string): {
};
}
if (
norm === "hlab" ||
norm === "hlab-sop" ||
norm === "hlab-rules" ||
norm === "hlab-standard" ||
norm === "official/hlab" ||
norm === "official/hlab.ts"
) {
return {
path: join(OFFICIAL_LINTERS_DIR, "hlab.ts"),
isOfficial: true,
officialKind: "hlab"
};
}
// 显式相对或绝对路径
if (isAbsolute(norm) || norm.startsWith("./") || norm.startsWith("../")) {
const absPath = resolve(norm);
@@ -199,10 +221,15 @@ export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter>
const resolution = resolveLinterPath(nameOrPath ?? "builtin");
// 1. 处理官方内置校验器 (builtin / strict)
// 1. 处理官方内置校验器 (builtin / strict / hlab)
if (resolution.isOfficial) {
const fallbackFn = resolution.officialKind === "strict" ? strictRuleLinter : builtinRuleLinter;
const kind = resolution.officialKind === "strict" ? "official" : "builtin";
const fallbackFn =
resolution.officialKind === "strict"
? strictRuleLinter
: resolution.officialKind === "hlab"
? hlabRuleLinter
: builtinRuleLinter;
const kind = resolution.officialKind === "builtin" ? "builtin" : "official";
const officialPath = resolution.path;
if (officialPath && existsSync(officialPath)) {
+244 -1
View File
@@ -331,7 +331,250 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
export default lintRule;
`;
export const OFFICIAL_HLAB_LINTER_SOURCE = `/**
* ==============================================================================
* 合思实验室 (HLab) 结构化规则校验器 (HLab Structured SOP Rule Linter)
* ==============================================================================
*
* 存放路径: ~/.config/seal-use/linters/official/hlab.ts
* 维护说明: 本文件由 seal-use 官方自动同步并保护。
* 每次运行时系统会自动重写本文件并清理 official/ 目录下的非官方文件。
* 若您需要编写企业私有规则校验器,请将自定义 .ts 文件放置在外层的用户目录:
* ~/.config/seal-use/linters/ 即可,系统将自动识别并加载。
*/
export interface RuleLintTarget {
id?: string;
code?: string;
name?: string;
description: string;
scope?: string;
strictness?: string;
}
export interface RuleLintIssue {
level: "error" | "warning";
code: string;
message: string;
snippet?: string;
suggestion?: string;
}
export interface RuleLintResult {
score: number;
passed: boolean;
issues: RuleLintIssue[];
}
export const HLAB_DISPOSAL_WORDS = [
"驳回单据",
"直接驳回",
"整单退回",
"退回单据",
"退单处理",
"进行提醒",
"请进行提醒",
"予以驳回",
"直接退回",
"无需人工关注",
"无需展示在最后的审核结论中"
];
export const HLAB_SCOPE_SKIP_WORDS = [
"若上传了",
"如上传了",
"若提供了",
"如提供了",
"附件需上传",
"上传了发票",
"提供了支付截图",
"提供了行程单",
"上传了行程单"
];
export const HLAB_RISK_SUPPRESSION_WORDS = [
"忽略行程冲突",
"忽略重复报销",
"忽略跨城一致性",
"不识别为风险",
"不作为风险事项",
"无需作为风险"
];
export const HLAB_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const HLAB_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票",
"流程"
];
export function lintRule(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const scopeText = (rule.scope || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则长度检查
if (text.length < 10) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 10 个字),无法承载 HLab 结构化规范所要求的判定逻辑",
suggestion: "请按照 HLab 工业化规范补充【检查方法】与【判定标准】"
});
} else if (text.length < 30 && !text.includes("**") && !text.includes("检查方法")) {
issues.push({
level: "warning",
code: "SHORT_DESCRIPTION",
message: "规则正文偏短且缺少结构化要素,可能缺少执行细节或证据边界",
suggestion: "建议扩充核验场景、限制标准或异常处理方式"
});
}
// 2. 结构完备性检查
const hasMethod = /\\*\\*检查方法\\*\\*|检查方法[::]/.test(text);
if (!hasMethod) {
issues.push({
level: "error",
code: "MISSING_CHECK_METHOD",
message: "规则正文缺少【检查方法】结构块,大模型难以确定数据提取来源与对齐逻辑",
suggestion: "建议在正文前部增加 **检查方法**:明确 SealAI 应读取的凭证类型、字段名称、归一化方式或前置规则依赖"
});
}
const hasStandard = /\\*\\*判定标准\\*\\*|判定标准[::]/.test(text);
if (!hasStandard) {
issues.push({
level: "error",
code: "MISSING_EVAL_STANDARD",
message: "规则正文缺少【判定标准】结构块,缺乏标准化判定边界",
suggestion: "建议在正文后部增加 **判定标准**:包含清晰的 PASS、FAIL 以及证据不足分支"
});
}
// 3. 三元闭环判定检查
const hasPass = /[-*•]?\\s*PASS[::]/i.test(text);
const hasFail = /[-*•]?\\s*FAIL[::]/i.test(text);
const hasInsufficient = /[-*•]?\\s*证据不足[::]/.test(text);
if (!hasPass || !hasFail || !hasInsufficient) {
const missing: string[] = [];
if (!hasPass) missing.push("PASS");
if (!hasFail) missing.push("FAIL");
if (!hasInsufficient) missing.push("证据不足");
issues.push({
level: "error",
code: "INCOMPLETE_TERNARY_BRANCH",
message: \`判定标准未形成三元闭环,缺少分支:\${missing.join("、")}\`,
suggestion: "HLab 规范要求必须提供完整的三元分支:- PASS(充分合规条件)、- FAIL(明确违规条件)、- 证据不足(容错与复核条件)"
});
}
// 4. 证据不足分支人工复核兜底检查
if (hasInsufficient) {
const snippet = text.split("证据不足")?.[1]?.slice(0, 100) || "";
const hasManualReview = /人工复核|人工核对|人工审核|转人工/.test(snippet);
if (!hasManualReview) {
issues.push({
level: "warning",
code: "INSUFFICIENT_WITHOUT_MANUAL_REVIEW",
message: "【证据不足】分支未明确指定转【人工复核】兜底,大模型在材料模糊或冲突时可能失控",
suggestion: "建议在【证据不足】分支末尾补充标准处置话术:'转人工复核',确保容错降级路径统一"
});
}
}
// 5. 整单处置动作越界拦截
for (const word of HLAB_DISPOSAL_WORDS) {
if (text.includes(word)) {
issues.push({
level: "warning",
code: "DISPOSAL_ACTION_LEAK",
snippet: word,
message: \`规则正文包含整单处置动作话术 "\${word}",违反 HLab 规则事实判定与处置动作解耦规范\`,
suggestion: \`请移除正文中的 "\${word}";单据处置动作(驳回/提醒)应交由平台严格程度(必须遵守/仅建议)或业务工作流定义\`
});
break;
}
}
// 6. 适用场景防静默漏判检查
if (scopeText) {
for (const word of HLAB_SCOPE_SKIP_WORDS) {
if (scopeText.includes(word)) {
issues.push({
level: "warning",
code: "SCOPE_FALSE_SKIP_PRONE",
snippet: word,
message: \`适用场景包含材料上传前置判断 "\${word}",当材料未上传时可能导致该规则被静默跳过(SKIP)而非报违规(FAIL)\`,
suggestion: "建议适用场景仅保留业务与单据触发条件(如单据模板、费用类型);材料缺失的检查应显式置于【判定标准】的 FAIL 分支中"
});
break;
}
}
}
// 7. 消极风险压制拦截
for (const word of HLAB_RISK_SUPPRESSION_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "RISK_SUPPRESSION",
snippet: word,
message: \`规则正文包含消极风险压制话术 "\${word}",可能破坏模型正常审计底线或压制有效违规\`,
suggestion: "请移除该规则或改写为正向合规要求;若需豁免特定场景,请在 **例外** 结构块中封闭说明豁免条件与凭证依据"
});
break;
}
}
// 8. 悬空例外与凭据检查
const matchedTrigger = HLAB_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = HLAB_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "error",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: \`包含例外条款 "\${matchedTrigger}",但未指定 AI 从何处核验该例外成立的凭据来源\`,
suggestion: "HLab 规范要求例外条款必须明确凭据载体(如:在【**例外**】块中注明需提供专项 OA 审批 PDF 附件或商家盖章证明)"
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 25 - warningCount * 10);
return {
score,
passed: errorCount === 0,
issues
};
}
export default lintRule;
`;
export const OFFICIAL_LINTER_TEMPLATES: Record<string, string> = {
"builtin.ts": OFFICIAL_BUILTIN_LINTER_SOURCE,
"strict.ts": OFFICIAL_STRICT_LINTER_SOURCE
"strict.ts": OFFICIAL_STRICT_LINTER_SOURCE,
"hlab.ts": OFFICIAL_HLAB_LINTER_SOURCE
};
+306
View File
@@ -0,0 +1,306 @@
import { createWriteStream, mkdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { ZipArchive } from "archiver";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import { extractApprovalRunAttachments, sanitizeFileName } from "../attachments.js";
import type { ApprovalRun } from "../types.js";
import type { ResourcePackExportOptions, ResourcePackExportResult } from "./types.js";
export function resolveResourcePackOutputPath(options: ResourcePackExportOptions, corp: CorpConfig): string {
if (options.outputFile) {
return resolve(options.outputFile);
}
const dateStr = new Date().toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
const fileName = `webhook-resource-pack-${corp.id}-${dateStr}.zip`;
if (options.toDownloads) {
return join(homedir(), "Downloads", fileName);
}
return resolve(fileName);
}
interface DownloadedAttachment {
fileName: string;
zipPath: string;
buffer: Buffer;
sourceField: string;
}
export async function exportApprovalRunsToResourcePack(
client: KyInstance,
corp: CorpConfig,
options: ResourcePackExportOptions = {}
): Promise<ResourcePackExportResult> {
let runs: ApprovalRun[] = [];
if (options.recordId) {
process.stderr.write(`🔍 查询单据记录: ${options.recordId}...\n`);
const record = await api.getApprovalRun(client, options.recordId);
runs = [record];
} else if (options.recordIds && options.recordIds.length > 0) {
process.stderr.write(`🔍 批量查询 ${options.recordIds.length} 条单据记录...\n`);
runs = await Promise.all(options.recordIds.map((id) => api.getApprovalRun(client, id)));
} else {
const limit = options.limit ?? 10;
process.stderr.write(`🔍 检索企业「${corp.name}」(${corp.id}) 的线上审核记录 (限制 ${limit} 条)...\n`);
const listRes = await api.listApprovalRuns(client, {
limit,
status: options.status,
startDate: options.startDate !== undefined ? String(options.startDate) : undefined,
endDate: options.endDate !== undefined ? String(options.endDate) : undefined
});
const summaryRecords = listRes.records ?? [];
if (summaryRecords.length === 0) {
throw new Error(`未检索到符合条件的线上审核记录,无法导出 webhook 资源包。`);
}
process.stderr.write(`📥 正在拉取 ${summaryRecords.length} 条审核记录完整详情...\n`);
runs = await Promise.all(summaryRecords.map((r) => api.getApprovalRun(client, r.id)));
}
// 1. 提取并下载附件
const docAttachmentsMap = new Map<string, DownloadedAttachment[]>();
let totalDownloadedCount = 0;
for (const run of runs) {
const rawDoc = run.document as Record<string, unknown> | undefined;
const originalDocId =
run.sourceDocumentId ??
(typeof rawDoc?.id === "string" ? rawDoc.id : undefined) ??
(typeof rawDoc?.sourceDocumentId === "string" ? rawDoc.sourceDocumentId : undefined) ??
run.documentId ??
run.id;
const docId = `${options.docIdPrefix ?? ""}${originalDocId}${options.docIdSuffix ?? ""}`;
const downloadedList: DownloadedAttachment[] = [];
if (options.includeAttachments !== false) {
const extraction = extractApprovalRunAttachments(run, { summary: false });
const attachments = extraction.attachments as Array<Record<string, unknown>>;
const usedFileNames = new Set<string>();
for (const att of attachments) {
const downloadUrl = (att.ossSignedUrl as string | undefined) ?? (att.url as string | undefined);
if (!downloadUrl) continue;
const rawName = (att.fileName as string | undefined) ?? (att.fileId as string | undefined) ?? "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 (usedFileNames.has(targetName.toLowerCase())) {
targetName = `${stem}_${counter}${ext}`;
counter++;
}
usedFileNames.add(targetName.toLowerCase());
try {
process.stderr.write(`⬇ 下载单据「${docId}」附件: ${rawName}...\n`);
const res = await fetch(downloadUrl);
if (res.ok) {
const arrBuf = await res.arrayBuffer();
const buf = Buffer.from(arrBuf);
downloadedList.push({
fileName: targetName,
zipPath: `${docId}/${targetName}`,
buffer: buf,
sourceField: (att.sourceField as string | undefined) ?? "附件"
});
totalDownloadedCount++;
}
} catch (err) {
process.stderr.write(`⚠️ [跳过附件] 下载失败 ${rawName}: ${err}\n`);
}
}
}
docAttachmentsMap.set(docId, downloadedList);
}
// 2. 构建符合 Webhook 资源包标准的「信息表.xlsx」
const workbook = new ExcelJS.Workbook();
workbook.creator = "seal-use";
workbook.created = new Date();
// 收集所有出现的附件类别列标签
const allAttachmentLabels = new Set<string>();
for (const attachments of docAttachmentsMap.values()) {
for (const att of attachments) {
allAttachmentLabels.add(att.sourceField);
}
}
if (allAttachmentLabels.size === 0) {
allAttachmentLabels.add("附件");
}
// 收集动态普通字段列
const dynamicFieldLabels = new Set<string>();
for (const run of runs) {
const rawDoc = run.document as Record<string, unknown> | undefined;
const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : [];
for (const f of rawFields) {
if (f && typeof f === "object") {
const item = f as Record<string, unknown>;
const label = typeof item.label === "string" ? item.label.trim() : typeof item.key === "string" ? item.key.trim() : "";
const type = typeof item.type === "string" ? item.type.toUpperCase() : "";
if (label && type !== "ATTACHMENT" && type !== "LIST") {
dynamicFieldLabels.add(label);
}
}
}
}
// 基础标准列
const baseHeaders = ["会议编号", "会议名称", "状态", "总金额", "报销事由", "申请日期"];
// 排除已在基础列的动态字段
const filteredDynamicHeaders = Array.from(dynamicFieldLabels).filter(
(h) => !baseHeaders.includes(h) && h !== "单据编号" && h !== "单号"
);
// 附件列,严格加上 [附件] 前缀
const attachmentHeaders = Array.from(allAttachmentLabels).map((label) => `[附件]${label}`);
const mainHeaders = [...baseHeaders, ...filteredDynamicHeaders, ...attachmentHeaders];
const mainSheet = workbook.addWorksheet("主表");
mainSheet.addRow(mainHeaders);
// 设置表头粗体
mainSheet.getRow(1).font = { bold: true };
for (const run of runs) {
const rawDoc = run.document as Record<string, unknown> | undefined;
const originalSN =
run.sourceDocumentSN ??
(typeof rawDoc?.sn === "string" ? rawDoc.sn : undefined) ??
(typeof rawDoc?.sourceDocumentSN === "string" ? rawDoc.sourceDocumentSN : undefined) ??
run.id;
const originalDocId =
run.sourceDocumentId ??
(typeof rawDoc?.id === "string" ? rawDoc.id : undefined) ??
(typeof rawDoc?.sourceDocumentId === "string" ? rawDoc.sourceDocumentId : undefined) ??
run.documentId ??
run.id;
const docId = `${options.docIdPrefix ?? ""}${originalDocId}${options.docIdSuffix ?? ""}`;
const sn = `${options.docIdPrefix ?? ""}${originalSN}${options.docIdSuffix ?? ""}`;
const title = (typeof rawDoc?.title === "string" ? rawDoc.title : undefined) ?? (typeof rawDoc?.name === "string" ? rawDoc.name : undefined) ?? sn;
// 申请日期
let applyDateStr = "";
if (typeof rawDoc?.sourceStartTime === "number") {
applyDateStr = new Date(rawDoc.sourceStartTime * 1000).toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
} else if (typeof run.createdAt === "number") {
applyDateStr = new Date(run.createdAt).toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" });
} else if (typeof run.createdAt === "string") {
applyDateStr = run.createdAt.slice(0, 10);
}
// 字段映射
const fieldMap = new Map<string, unknown>();
const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : [];
for (const f of rawFields) {
if (f && typeof f === "object") {
const item = f as Record<string, unknown>;
const label = typeof item.label === "string" ? item.label.trim() : typeof item.key === "string" ? item.key.trim() : "";
if (label) {
fieldMap.set(label, item.value);
}
}
}
// 提取金额
let totalAmount: number | undefined;
const amountVal = fieldMap.get("总金额") ?? fieldMap.get("报销金额") ?? fieldMap.get("total_amount");
if (typeof amountVal === "number") {
totalAmount = amountVal;
} else if (amountVal && typeof amountVal === "object" && "amount" in amountVal && typeof (amountVal as any).amount === "number") {
totalAmount = (amountVal as any).amount;
}
const rowValues: unknown[] = [];
rowValues.push(docId); // 会议编号
rowValues.push(title); // 会议名称
rowValues.push(run.status ?? "已审批"); // 状态
rowValues.push(totalAmount ?? ""); // 总金额
rowValues.push(fieldMap.get("报销事由") ?? fieldMap.get("事由") ?? title); // 报销事由
rowValues.push(applyDateStr); // 申请日期
// 动态字段
for (const header of filteredDynamicHeaders) {
const val = fieldMap.get(header);
if (val === undefined || val === null) {
rowValues.push("");
} else if (typeof val === "object") {
if ("amount" in (val as any)) {
rowValues.push((val as any).amount);
} else {
rowValues.push(JSON.stringify(val));
}
} else {
rowValues.push(val);
}
}
// 附件字段
const docAttachments = docAttachmentsMap.get(docId) ?? [];
for (const rawLabel of allAttachmentLabels) {
const matching = docAttachments.filter((a) => a.sourceField === rawLabel || (allAttachmentLabels.size === 1));
if (matching.length > 0) {
rowValues.push(matching.map((m) => m.zipPath).join("\n"));
} else {
rowValues.push("");
}
}
mainSheet.addRow(rowValues);
}
// 3. 打包生成 ZIP 资源包
const outputFilePath = resolveResourcePackOutputPath(options, corp);
mkdirSync(dirname(outputFilePath), { recursive: true });
const xlsxBuffer = await workbook.xlsx.writeBuffer();
process.stderr.write(`📦 正在压缩生成 Webhook 资源包: ${outputFilePath}...\n`);
await new Promise<void>((resolvePromise, rejectPromise) => {
const outputStream = createWriteStream(outputFilePath);
const archive = new ZipArchive({ zlib: { level: 9 } });
outputStream.on("close", () => resolvePromise());
archive.on("error", (err: unknown) => rejectPromise(err));
archive.pipe(outputStream);
// 根目录写入 信息表.xlsx
archive.append(Buffer.from(xlsxBuffer), { name: "信息表.xlsx" });
// 写入各单据目录及附件
for (const attachments of docAttachmentsMap.values()) {
for (const att of attachments) {
archive.append(att.buffer, { name: att.zipPath });
}
}
archive.finalize();
});
const stats = statSync(outputFilePath);
return {
filePath: outputFilePath,
corpId: corp.id,
corpName: corp.name,
recordCount: runs.length,
attachmentCount: totalDownloadedCount,
fileSizeBytes: stats.size,
exportedAt: new Date().toISOString(),
nextAction: `seal-use webhook resource-pack push ${outputFilePath} --corp <targetCorpId>`
};
}
+1
View File
@@ -6,3 +6,4 @@ export * from "./parse.js";
export * from "./attachments.js";
export * from "./service.js";
export * from "./ready.js";
export * from "./export.js";
@@ -329,7 +329,7 @@ describe("Webhook material pack", () => {
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.nextAction).toContain("seal-use webhook resource-pack push")
expect(res.statusMessage).toContain("已自动锁定唯一 Webhook 通道")
})
@@ -458,7 +458,8 @@ describe("Webhook material pack", () => {
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("材料包预检失败")
expect(notFoundRes.resourcePack?.valid).toBe(false)
expect(notFoundRes.statusMessage).toContain("资源包预检失败")
const tmpFile = `/tmp/test-material-${Date.now()}.xlsx`
const { writeFileSync, unlinkSync } = await import("node:fs")
@@ -467,7 +468,9 @@ describe("Webhook material pack", () => {
const validRes = await checkWebhookReadiness(client, mockCorp, { filePath: tmpFile })
expect(validRes.ready).toBe(true)
expect(validRes.materialPack?.valid).toBe(true)
expect(validRes.resourcePack?.valid).toBe(true)
expect(validRes.materialPack?.documentCount).toBe(1)
expect(validRes.resourcePack?.documentCount).toBe(1)
expect(validRes.nextAction).toContain(tmpFile)
} finally {
unlinkSync(tmpFile)
+19 -1
View File
@@ -111,11 +111,29 @@ function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialFi
["报销事由", "reimbursement_reason", "TEXT"], ["po码", "po_code", "TEXT"], ["快递单号", "tracking_number", "TEXT"],
["申请日期", "application_date", "DATE"], ["更新日期", "updated_date", "DATE"]
]
return specs.flatMap(([label, key, type]) => {
const handledLabels = new Set(specs.map(([label]) => label))
const fields = 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))]
})
// Dynamic non-attachment columns
for (const [colLabel, colIdx] of map.entries()) {
if (handledLabels.has(colLabel) || isAttachmentColumn(colLabel)) continue
const value = row.getCell(colIdx).value
if (value == null || value === "") continue
const key = colLabel.toLowerCase().replace(/\s+/g, "_")
if (typeof value === "number") {
fields.push(field(key, colLabel, "NUMBER", value))
} else if (value instanceof Date) {
fields.push(field(key, colLabel, "DATE", value.toISOString()))
} else {
fields.push(text(key, colLabel, String(value)))
}
}
return fields
}
function buildDetailFields(row: ExcelJS.Row, map: Map<string, number>, specs: Array<[string, string, string]>): MaterialField[] {
+5 -4
View File
@@ -123,16 +123,16 @@ export async function checkWebhookReadiness(
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}`;
statusMessage = `资源包预检失败: ${materialPack.errors?.join("; ")}`;
nextAction = `seal-use webhook resource-pack preview ${materialPack.filePath}${corpFlag}`;
} else {
statusMessage = isSingle
? "所有通道正常,已自动锁定唯一 Webhook 通道,等待载入"
: `所有通道正常,检测到 ${activeWebhooks.length} 个 Webhook 通道,等待载入`;
const targetFile = materialPack?.filePath ?? "<材料包.zip>";
const targetFile = materialPack?.filePath ?? "<资源包.zip>";
const webhookOption = isSingle ? "" : ` --webhook ${defaultWebhook ? defaultWebhook.id : "<webhookIdOrName>"}`;
nextAction = `seal-use webhook material-pack push ${targetFile}${webhookOption}${corpFlag}`;
nextAction = `seal-use webhook resource-pack push ${targetFile}${webhookOption}${corpFlag}`;
}
return {
@@ -149,6 +149,7 @@ export async function checkWebhookReadiness(
authError,
activeWebhooks,
defaultWebhook,
resourcePack: materialPack,
materialPack,
statusMessage,
nextAction
@@ -0,0 +1,201 @@
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
import { existsSync, unlinkSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import type { ApprovalRun } from "../types.js";
import {
exportApprovalRunsToResourcePack,
resolveResourcePackOutputPath
} from "./export.js";
import { previewResourcePack } from "./service.js";
const mockCorp: CorpConfig = {
id: "test-corp",
name: "测试研发企业",
environment: "test",
source: {
type: "direct",
token: "mock-token",
sealUrl: "https://seal.example.com",
expiresIn: 3600,
staffId: "direct"
},
auth: {
refreshTtl: 300
},
seal: {
url: "https://seal.example.com",
endpoints: {
approvalStylePreferences: "/api/v1/approval-preferences"
}
}
};
describe("Webhook Resource Pack Export", () => {
let originalFetch: typeof globalThis.fetch;
const tempFiles: string[] = [];
beforeEach(() => {
originalFetch = globalThis.fetch;
});
afterEach(() => {
globalThis.fetch = originalFetch;
for (const f of tempFiles) {
if (existsSync(f)) {
try {
unlinkSync(f);
} catch {}
}
}
tempFiles.length = 0;
});
test("resolveResourcePackOutputPath generates correct paths", () => {
const defaultPath = resolveResourcePackOutputPath({}, mockCorp);
expect(defaultPath).toContain("webhook-resource-pack-test-corp-");
expect(defaultPath.endsWith(".zip")).toBe(true);
const customPath = resolveResourcePackOutputPath({ outputFile: "/tmp/custom-pack.zip" }, mockCorp);
expect(customPath).toBe("/tmp/custom-pack.zip");
const dlPath = resolveResourcePackOutputPath({ toDownloads: true }, mockCorp);
expect(dlPath).toContain("Downloads");
expect(dlPath.endsWith(".zip")).toBe(true);
});
test("exports online approval runs to valid Webhook resource pack ZIP and passes preview validation", async () => {
const mockRuns: ApprovalRun[] = [
{
id: "run-001",
corpId: "test-corp",
status: "APPROVED",
sourceDocumentId: "DOC-2026-001",
sourceDocumentSN: "SN-2026-001",
createdAt: "2026-09-10T08:00:00.000Z",
document: {
id: "DOC-2026-001",
sn: "SN-2026-001",
title: "上海差旅会议报销",
fields: [
{ key: "total_amount", label: "总金额", type: "AMOUNT", value: { amount: 3500, currency: "CNY" } },
{ key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "参加行业研讨峰会" },
{
key: "attachments",
label: "发票",
type: "ATTACHMENT",
value: [
{
fileId: "att-101",
fileName: "hotel_invoice.pdf",
fileType: "application/pdf",
sourceField: "发票",
ossSignedUrl: "https://oss.example.com/hotel_invoice.pdf"
}
]
}
]
}
},
{
id: "run-002",
corpId: "test-corp",
status: "APPROVED",
sourceDocumentId: "DOC-2026-002",
sourceDocumentSN: "SN-2026-002",
createdAt: "2026-09-11T09:30:00.000Z",
document: {
id: "DOC-2026-002",
sn: "SN-2026-002",
title: "技术评审会议(无附件)",
fields: [
{ key: "total_amount", label: "总金额", type: "AMOUNT", value: 1200 },
{ key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "架构设计评审" }
]
}
}
];
// Mock fetch for downloading attachment (> 500 bytes to satisfy default attachment policy)
const dummyPdfContent = Buffer.concat([
Buffer.from("%PDF-1.4 Mock PDF content for test verification\n"),
Buffer.alloc(1000, "A")
]);
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = String(input);
if (url === "https://oss.example.com/hotel_invoice.pdf") {
return new Response(dummyPdfContent, {
status: 200,
headers: { "Content-Type": "application/pdf" }
});
}
return new Response("Not found", { status: 404 });
}) as any;
// Mock KyInstance
const mockClient = {
get: (url: string) => ({
json: async () => {
if (url.includes("run-001")) {
return { code: 0, data: mockRuns[0] };
}
if (url.includes("run-002")) {
return { code: 0, data: mockRuns[1] };
}
if (url.includes("approvals")) {
return {
code: 0,
data: {
total: 2,
records: [
{ id: "run-001", sourceDocumentId: "DOC-2026-001", status: "APPROVED" },
{ id: "run-002", sourceDocumentId: "DOC-2026-002", status: "APPROVED" }
]
}
};
}
throw new Error(`Unexpected GET: ${url}`);
}
})
} as unknown as KyInstance;
const tmpZipPath = join(tmpdir(), `test-pack-export-${Date.now()}.zip`);
tempFiles.push(tmpZipPath);
const exportResult = await exportApprovalRunsToResourcePack(mockClient, mockCorp, {
outputFile: tmpZipPath,
limit: 2
});
expect(exportResult.filePath).toBe(tmpZipPath);
expect(exportResult.recordCount).toBe(2);
expect(exportResult.attachmentCount).toBe(1);
expect(exportResult.fileSizeBytes).toBeGreaterThan(500);
expect(exportResult.nextAction).toContain("seal-use webhook resource-pack push");
expect(existsSync(tmpZipPath)).toBe(true);
// Verify the exported ZIP with previewResourcePack
const zipBuffer = readFileSync(tmpZipPath);
const preview = await previewResourcePack(zipBuffer, "test-pack.zip");
expect(preview.warnings).toEqual([]);
expect(preview.documents).toHaveLength(2);
const doc1 = preview.documents.find((d) => d.documentId === "DOC-2026-001");
expect(doc1).toBeDefined();
expect(doc1?.fields.some((f) => f.key === "meeting_name" && String(f.value).includes("上海差旅"))).toBe(true);
// Check attachment injection on doc1
const invoiceAttField = doc1?.fields.find((f) => f.label === "发票" && f.type === "ATTACHMENT");
expect(invoiceAttField).toBeDefined();
expect(invoiceAttField?.value).toEqual([
{ path: "DOC-2026-001/hotel_invoice.pdf", fileName: "hotel_invoice.pdf" }
]);
const doc2 = preview.documents.find((d) => d.documentId === "DOC-2026-002");
expect(doc2).toBeDefined();
expect(doc2?.fields.some((f) => f.key === "meeting_name" && String(f.value).includes("技术评审"))).toBe(true);
});
});
+24 -9
View File
@@ -1,9 +1,9 @@
import { readFileSync } from "node:fs"
import { webhookHeaders } from "./signature.js"
import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js"
import { parseMaterialWorkbook } from "./parse.js"
import { parseMaterialWorkbook, type Parsed } from "./parse.js"
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js"
import { MaterialPackValidationError, type MaterialPackPreview, type MaterialPackPushResult } from "./types.js"
import { MaterialPackValidationError, type MaterialPackPreview, type MaterialPackPushResult, type ResourcePackPreview, type ResourcePackPushResult } from "./types.js"
import type { MaterialPackFilePolicyPatch } from "./policy.js"
function webhookInfo(url: string): { baseUrl: string; webhookId: string } {
@@ -17,7 +17,7 @@ function isZip(buffer: Uint8Array, fileName: string): boolean {
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"))
}
function validateDocIdDirectories(entries: ZipEntry[], documentIds: string[]): void {
function validateDocIdDirectories(entries: ZipEntry[], parsed: Parsed[]): void {
if (!entries.length) return // xlsx-only mode, skip
// Extract documentId from dir name: strip @annotation suffix
@@ -33,17 +33,23 @@ function validateDocIdDirectories(entries: ZipEntry[], documentIds: string[]): v
const errors: string[] = []
// Every documentId must have a matching root directory (possibly with @annotation)
for (const id of documentIds) {
if (!zipDocIds.has(id)) {
// Documents with declared attachments must have a matching root directory (possibly with @annotation)
for (const item of parsed) {
const id = item.document.documentId
const hasAttachments =
item.documentAttachments.length > 0 ||
Object.values(item.expenseAttachments).some((arr) => arr.length > 0) ||
Object.values(item.personAttachments).some((arr) => arr.length > 0)
if (hasAttachments && !zipDocIds.has(id)) {
errors.push(
`Excel 会议编号「${id}」在 ZIP 中找不到对应的根目录「${id}/」或「${id}@.../」。`
`Excel 会议编号「${id}」声明了附件,但在 ZIP 中找不到对应的根目录「${id}/」或「${id}@.../」。`
)
}
}
// Every root directory must correspond to a known documentId
const docIdSet = new Set(documentIds)
const docIdSet = new Set(parsed.map((p) => p.document.documentId))
for (const zipDocId of zipDocIds) {
if (!docIdSet.has(zipDocId)) {
errors.push(
@@ -71,7 +77,7 @@ async function prepare(
}
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))
validateDocIdDirectories(entries, parsed)
const plans = buildAttachmentPlans(entries, parsed)
const documents = parsed.map((item) => item.document)
return { entries, parsed, plans, documents, fileBuffer }
@@ -168,3 +174,12 @@ export async function pushMaterialPack(
export function readMaterialPackFile(filePath: string): { fileBuffer: Buffer; fileName: string } {
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\\/]/).pop() ?? "material-pack.zip" }
}
export const previewResourcePack = previewMaterialPack
export const pushResourcePack = pushMaterialPack
export const readResourcePackFile = readMaterialPackFile
export {
exportApprovalRunsToResourcePack,
exportApprovalRunsToResourcePack as exportResourcePack
} from "./export.js"
+44 -3
View File
@@ -32,18 +32,51 @@ export type MaterialPackPreview = {
attachmentPlan: MaterialAttachmentPlan[];
};
export type ResourcePackPreview = MaterialPackPreview;
export type MaterialPackPushResult = {
warnings: string[];
results: Array<{ documentId: string; document: MaterialDocument; pushResult: unknown }>;
};
export class MaterialPackValidationError extends Error {
export type ResourcePackPushResult = MaterialPackPushResult;
export class ResourcePackValidationError extends Error {
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
super([`材料包校验失败:${errors.length} 个错误`, ...errors.map((error) => `- ${error}`)].join("\n"))
this.name = "MaterialPackValidationError"
super([`webhook 资源包校验失败:${errors.length} 个错误`, ...errors.map((error) => `- ${error}`)].join("\n"))
this.name = "ResourcePackValidationError"
}
}
export const MaterialPackValidationError = ResourcePackValidationError;
export type MaterialPackValidationError = ResourcePackValidationError;
export interface ResourcePackExportOptions {
recordId?: string;
recordIds?: string[];
limit?: number;
startDate?: string | number;
endDate?: string | number;
status?: string;
outputFile?: string;
toDownloads?: boolean;
includeAttachments?: boolean;
docIdPrefix?: string;
docIdSuffix?: string;
customHeaders?: Record<string, string>;
}
export interface ResourcePackExportResult {
filePath: string;
corpId: string;
corpName: string;
recordCount: number;
attachmentCount: number;
fileSizeBytes: number;
exportedAt: string;
nextAction: string;
}
export type WebhookReadyResult = {
ready: boolean;
corp: {
@@ -79,6 +112,14 @@ export type WebhookReadyResult = {
name: string;
mode: string;
} | null;
resourcePack?: {
valid: boolean;
filePath: string;
fileName: string;
documentCount: number;
errors?: string[];
warnings?: string[];
};
materialPack?: {
valid: boolean;
filePath: string;
+33
View File
@@ -847,6 +847,39 @@ describe("sealTools", () => {
outboundName: "DingTalk AI Audit"
});
});
test("seal_approval_runs_count supports startDate and endDate and normalizes them", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_runs_count");
expect(tool).toBeDefined();
const schema = z.toJSONSchema(tool!.parameters) as {
properties?: Record<string, unknown>;
};
expect(schema.properties).toHaveProperty("startDate");
expect(schema.properties).toHaveProperty("endDate");
expect(schema.properties).toHaveProperty("status");
const requests: string[] = [];
const client = fakeApprovalRunsClient(requests);
const handler = tool!.handler as ToolHandler;
const res = await handler(
client,
{
status: "APPROVED",
startDate: "2026-08-07",
endDate: "2026-09-13"
},
fakeContext()
);
expect(res).toEqual({ total: 3 });
expect(requests).toHaveLength(1);
expect(requests[0]).toContain("api/v1/approvals?");
expect(requests[0]).toContain("startDate=1786032000000");
expect(requests[0]).toContain("endDate=1789315199999");
expect(requests[0]).toContain("APPROVED");
});
});
function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
+174 -5
View File
@@ -28,7 +28,12 @@ import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from
import {
extractApprovalRunAttachments
} from "./attachments.js";
import { exportApprovalRunsToExcel } from "./approval-runs-export.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "./approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "./insight-export.js";
import {
ThinkingPolicySchema,
@@ -265,7 +270,8 @@ export const sealTools = [
endDate: z.string().optional().describe("统计结束时间(ISO 8601 或时间戳)"),
limit: z.number().int().positive().optional().describe("最多下钻分析的风险标签数量"),
outputFile: z.string().optional().describe("自定义 Excel 保存路径"),
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录")
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录"),
force: z.boolean().optional().describe("时间跨度超过 180 天时是否强制导出")
}),
handler: async (
client: KyInstance,
@@ -1520,6 +1526,155 @@ export const sealTools = [
return fields.length > 0 ? pickRunFields(full, fields) : full;
}
},
{
name: "seal_approval_run_flow_get",
description: "获取合思原生审批流流转时间线、待办节点、员工意见、驳回原因及版本变更指标,并对齐 AI 运行记录与人工行为",
parameters: z.object({
target: z.string().optional().describe("合思单号 (sourceDocumentSN) 或 Seal 运行记录 ID (recordId)"),
recordId: z.string().optional().describe("Seal 运行记录 ID"),
sourceDocumentSN: z.string().optional().describe("合思单号 (sourceDocumentSN)")
}),
handler: async (
client: KyInstance,
params: { target?: string; recordId?: string; sourceDocumentSN?: string },
context: ToolContext
) => {
const corp = context.corp;
if (corp.source.type !== "hose") {
throw new Error(
`企业「${corp.name || corp.id}」非合思(hose)租户(来源类型: ${corp.source.type}),暂不支持合思原生审批流分析。`
);
}
const input = (params.target || params.sourceDocumentSN || params.recordId)?.trim();
if (!input) {
throw new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。");
}
let sn = input;
let targetRecord: ApprovalRun | undefined;
try {
targetRecord = await api.getApprovalRun(client, input);
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
}
} catch {
// Continue as SN
}
let runs: ApprovalRun[] = [];
try {
const runsData = await api.listApprovalRuns(client, {
search: sn,
sourceDocumentSN: sn,
limit: 100
});
runs = (runsData.records || []).filter(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
);
} catch {
// ignore
}
if (runs.length === 0 && targetRecord) {
runs = [targetRecord];
}
const flowId = targetRecord?.sourceDocumentId || runs[0]?.sourceDocumentId || sn;
const hoseClient = await createHoseOpenClient(corp);
const flow = await getHoseOpenFlow(hoseClient, flowId);
if (!flow) {
console.error(`⚠️ 单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`);
const fallbackAlignments = alignApprovalRunsWithHoseFlow(runs, undefined);
const fallbackRuns = runs.map((run) => {
const align = fallbackAlignments.get(run.id);
return {
recordId: run.id,
createdAt: run.createdAt,
createdAtFormatted: run.createdAt
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
: undefined,
taskMode: run.taskMode,
status: run.status,
aiDecision: align?.aiDecision || "-",
aiAction: align?.aiAction || "-",
eHumanAction: "单据已删除",
eHumanComment: "合思系统中未找到该单据流转记录(已在合思端删除或作废)",
auditDrift: false,
auditDriftReason: undefined,
operator: undefined
};
});
return {
sourceDocumentSN: sn,
corpId: corp.id,
corpName: corp.name,
sourceSystem: corp.source.type,
found: false,
deleted: true,
message: `单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`,
flow: undefined,
runsCount: runs.length,
runs: fallbackRuns,
auditDrift: false
};
}
const alignments = alignApprovalRunsWithHoseFlow(runs, flow);
const alignedRuns = runs.map((run) => {
const align = alignments.get(run.id);
return {
recordId: run.id,
createdAt: run.createdAt,
createdAtFormatted: run.createdAt
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
: undefined,
taskMode: run.taskMode,
status: run.status,
aiDecision: align?.aiDecision || "-",
aiAction: align?.aiAction || "-",
eHumanAction: align?.eHumanAction || "-",
eHumanComment: align?.eHumanComment || "-",
auditDrift: align?.auditDrift ?? false,
auditDriftReason: align?.auditDriftReason,
operator: align?.operator
};
});
const hasAuditDrift = alignedRuns.some((r) => r.auditDrift);
return {
sourceDocumentSN: sn,
corpId: corp.id,
corpName: corp.name,
sourceSystem: corp.source.type,
flow: {
backlogId: flow.backlogId,
flowId: flow.flowId,
billCode: flow.billCode,
title: flow.title,
state: flow.state,
rawState: flow.rawState,
currentNode: flow.currentNode,
specification: flow.specification,
submitter: flow.submitter,
owner: flow.owner,
metrics: flow.metrics,
rejections: flow.rejections,
staffOpinions: flow.staffOpinions,
timelineCount: flow.history.length,
pendingCount: flow.pending.length,
timeline: flow.history,
pending: flow.pending
},
runsCount: runs.length,
runs: alignedRuns,
auditDrift: hasAuditDrift
};
}
},
{
name: "seal_approval_run_cited_rules_get",
description: "从审批运行结果中抽取 AI 引用或命中的规则及应用分析",
@@ -2496,15 +2651,29 @@ export const sealTools = [
status: z.string().optional(),
sourceSystem: z.string().optional(),
taskMode: z.string().optional(),
search: z.string().optional()
search: z.string().optional(),
startDate: z.string().optional().describe("起始时间戳(毫秒)或日期字符串"),
endDate: z.string().optional().describe("结束时间戳(毫秒)或日期字符串")
}),
handler: async (client: KyInstance, params: { status?: string; sourceSystem?: string; taskMode?: string; search?: string }) => {
handler: async (
client: KyInstance,
params: {
status?: string;
sourceSystem?: string;
taskMode?: string;
search?: string;
startDate?: string;
endDate?: string;
}
) => {
const runs = await api.listApprovalRuns(client, {
limit: 1,
status: params.status,
sourceSystem: params.sourceSystem,
taskMode: params.taskMode,
search: params.search
search: params.search,
startDate: normalizeTimestamp(params.startDate, false),
endDate: normalizeTimestamp(params.endDate, true)
});
return {
total: runs.total ?? runs.records.length