d384d3c595
* feat: foundations F1-F4 + simple bug fixes Foundations (no consumer adoption yet): - F1 spawnHidden wrapper at src/shared/spawn.ts - F2 paths namespace with 18 accessors + invariant test (tests/shared/paths.test.ts) - F3 getUptimeSeconds at src/shared/uptime.ts - F4 ClassifiedProviderError at src/services/worker/provider-errors.ts + 6 tests Issue fixes (file-isolated, parallel-safe): - #2231: SECURITY.md at repo root for GitHub Security tab - #2240: dedupe observationIds before Chroma sync (ResponseProcessor.ts) - #2247: add task_complete to Codex session-end events - #2243: rsync excludes scripts/package.json + scripts/node_modules Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: validate Claude executable with --version and detect desktop app Extract findClaudeExecutable() into shared utility used by both SDKAgent and KnowledgeAgent (deduplication). Every candidate is now validated with --version (3s timeout). Desktop app executables in AppData/Program Files get an actionable error message directing users to install the CLI via npm. Closes #2222 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: use Zod schemas in OpenCode plugin to fix _zod.def crash OpenCode 1.14.x walks arg._zod.def at plugin registration, which crashes on plain JSON Schema objects like {type: "string"}. Replace with z.string().describe() so the Zod internals are present. Closes #2226, #2225, #2154 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: neutralize chroma-mcp CPU storm at the root Two surgical fixes to the chroma backfill path that together cause the sustained 60–80% CPU + orphan accumulation pattern reported across 1. ChromaMcpManager.getSpawnEnv: cap embedding-thread fanout ONNX Runtime / OpenBLAS / MKL all default to cpu_count(), so a 12-core machine spins 12 threads burning embeddings concurrently. The user's getSpawnEnv only handled SSL certs — no thread limits at all. Inject OMP_NUM_THREADS / ONNX_NUM_THREADS / OPENBLAS_NUM_THREADS / MKL_NUM_THREADS defaults of 2 (only if user hasn't pinned them), and ANONYMIZED_TELEMETRY=false to stop background HTTP from the embedding subprocess. Closes the storm at the source. 2. ChromaSync.backfill{Observations,Summaries,Prompts}: per-batch watermark The bump was in a trailing finally block. SIGKILL / OOM / power loss mid-flight skips finally entirely, so the watermark stayed at 0 and the next worker boot re-embedded the entire history (16K obs in #2220's case), which then pegged CPU forever in combination with (1). Move the bump inside the loop so progress is durable per batch. Closes #2214. Verification: - 26/26 chroma tests pass (tests/services/sync, tests/integration/chroma-vector-sync) - Bundle confirms thread caps and per-batch bumps are present - Full suite: 1429 pass / 20 fail — pre-existing failures only, no regression vs v12.4.9 baseline (1429 pass / 27 fail) Closes #2214. Substantially de-amplifies #2220 (the structural Job-Object cleanup is still tracked separately at #2216). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: kill chroma-mcp process tree and limit backfill concurrency Three fixes for orphan chroma-mcp processes and resource exhaustion: 1. killProcessTree() in ChromaMcpManager.stop() tears down the full uvx->uv->python->chroma-mcp spawn chain (pkill -P on POSIX, taskkill /T on Windows) before MCP client.close(). 2. Register chroma process with pgid for supervisor shutdown cascade. 3. backfillAllProjects() now processes max 3 projects concurrently with a re-entrancy guard to prevent overlapping fire-and-forget runs. Closes #2216, advances #2220, #2213 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * build: regenerate plugin artifacts after cherry-picks Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: foundation consumers + Cursor/stdin/queue/docs fixes F1 spawnHidden adoption (#2236): - 8 spawn → spawnHidden conversions across worker-utils, ProcessManager, npx-cli (install/runtime), supervisor/process-registry F3 getUptimeSeconds adoption (#2250): - Server.ts:165 (THE BUG: returned ms) - Server.ts:270, SessionRoutes.ts:326 (4th ms-bug consumer found), DataRoutes.ts:225 (refactor for consistency) #2188 stdin '{}' fallback removal: - Diagnostic logging to <DATA_DIR>/logs/runner-errors.log + CAPTURE_BROKEN marker; exit 0 to preserve Windows Terminal exit-code strategy #2196 ANTHROPIC_BASE_URL docs: - New docs/public/configuration/custom-anthropic-backends.mdx - Note: issue may need separate auto-detect feature; docs document existing plumbing only #2242 check-pending-queue endpoints: - Point at /api/processing-status + /api/processing per DataRoutes.ts; honor CLAUDE_MEM_WORKER_PORT env #2248 Cursor sessions never summarized: - Pulled reporter wbingli's tested fix (commit 46eaba44) - Bug A: cursor adapter now derives transcriptPath from cwd+sessionId - Bug B: parser accepts both line.type and line.role - Bug C: walk backward, prefer non-empty text, fallback to empty - Tests: 10-case regression suite + tests/fixtures/cursor-session.jsonl Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: F2 paths namespace adoption (#2237 + #2238) Replaced 24 hardcoded homedir() + '.claude-mem' sites across 18 source files with paths.<accessor>() calls from src/shared/paths.ts. Accessors used: dataDir, workerPid, settings, database, chroma, combinedCerts, transcriptsConfig, transcriptsState, corpora, supervisorRegistry, envFile, logsDir. Sites converted (file:area): - src/cli/claude-md-commands.ts (database) - src/services/context/ContextConfigLoader.ts (settings) - src/services/infrastructure/ProcessManager.ts (workerPid) - src/services/infrastructure/WorktreeAdoption.ts (settings) - src/services/integrations/CodexCliInstaller.ts (settings) - src/services/sync/ChromaMcpManager.ts (chroma + combinedCerts) - src/services/transcripts/config.ts (transcriptsConfig + transcriptsState) - src/services/worker/ClaudeProvider.ts (envFile) - src/services/worker/GeminiProvider.ts (envFile + 2 more) - src/services/worker/http/routes/DataRoutes.ts (dataDir) - src/services/worker/http/routes/SettingsRoutes.ts (settings + envFile) - src/services/worker/knowledge/CorpusStore.ts (corpora) - src/shared/EnvManager.ts (envFile) - src/supervisor/index.ts (supervisorRegistry) - src/supervisor/process-registry.ts (supervisorRegistry) - src/supervisor/shutdown.ts (supervisorRegistry) - src/utils/claude-md-utils.ts (database) - src/utils/logger.ts (logsDir + settings, lazy to avoid cycle) CLAUDE_MEM_DATA_DIR override now flows through 100% of the worker runtime; no per-file env reads needed. Verification: - Grep guard: zero homedir+'.claude-mem' sites remain in src/ (excluding paths.ts itself and SettingsDefaultsManager.ts) - F2 invariant test: 3/3 pass (60 expects) - Foundation tests: 19/19 pass Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: F4 provider classification + parser fence + OAuth keychain F4 adoption (#2244 + #2254): - Per-provider classifiers: classifyClaudeError, classifyGeminiError, classifyOpenRouterError. Each lives in the provider file. - New retry helper at src/services/worker/retry.ts: withRetry() honors ClassifiedProviderError.kind; retriable=transient/rate_limit (with retryAfterMs); not retriable=unrecoverable/auth_invalid/quota_exhausted. maxRetries=2, perAttemptTimeout=30s, exponential backoff with jitter. - GeminiProvider + OpenRouterProvider fetch calls wrapped with retry. Best-effort request-id capture (x-goog-request-id, x-request-id, x-openrouter-request-id) for dedup logging. - Deleted unrecoverablePatterns allowlist at worker-service.ts:540 area; worker dispatches on err.kind instead. - 28 new classifier tests at tests/worker/provider-classifiers.test.ts: 429-no-Retry-After, 500-with-quota-exceeded, OverloadedError, per-provider auth_invalid signals. #2233 Part A — parser fence handling: - src/sdk/prompts.ts: removed 4 fence markers from XML example blocks. Model now sees plain XML, eliminating the failure-mode that drained quota via repeated retries. - src/sdk/parser.ts: stripCodeFences() at top, called before parseAgentXml. Fence-tolerant regardless of model behavior. - TODO comment references #2233 Part B (tool-use migration as separate scope). - 4 fence-tolerance tests added to tests/sdk/parser.test.ts. #2215 OAuth token keychain: - New src/shared/oauth-token.ts (~360 LOC): readClaudeOAuthToken() reads from platform-native credential stores at worker spawn-time. - macOS: security find-generic-password -s "Claude Code-credentials" - Windows: PowerShell wrapper around CredRead (Win32 Advapi32.dll) - Linux: secret-tool lookup - Fallback: env CLAUDE_CODE_OAUTH_TOKEN with JWT exp claim or sidecar expiresAt validation; refuses stale-token injection. - EnvManager.buildIsolatedEnvWithFreshOAuth() (async) replaces silent process.env copy. Empty injection on absent; marker write on expired. - <DATA_DIR>/oauth-stale.marker surfaces "re-login via Claude Desktop" via existing SessionStart additionalContext mechanism (context.ts). - ClaudeProvider.startSession + KnowledgeAgent.prime/executeQuery now await the async env builder. - 17 oauth-token tests covering decodeJwtExpMs, marker round-trip, env-fallback expiry detection. Verification: - npx tsc --noEmit: only pre-existing bun-types error - bun test (foundations + new): 70 pass, 0 new fails (8 fails are pre-existing parser.test.ts cases unrelated to fence work) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: #2234 quota-aware wall-clock guard New src/services/worker/RateLimitStore.ts (207 LOC) — vendor pattern from meridian/rateLimitStore.ts (MIT, copied not depended). API: - class RateLimitStore: set/get/getAll/getMostRecentByWindow/size/clear, in-memory last-write-wins keyed by rateLimitType. - globalRateLimitStore singleton. - shouldAbortForQuota(authMethod, store, now?) → {abort, reason?, window?} - isApiKeyAuth(authMethod): matches both verbose getAuthMethodDescription strings and concise "api_key". Thresholds (auth-type gated): - api_key: never aborts (user authorized per-call spend). - cli/oauth/subscription: - five_hour utilization >= 0.95 OR resetsAt within 15min (with 0.85 utilization floor to avoid false trip on freshly-reset windows) - seven_day_opus >= 0.93 - seven_day_sonnet >= 0.92 - seven_day >= 0.93 - overage >= 0.95 ClaudeProvider integration (line 198, for-await loop): - Detects message.type === 'system' && subtype === 'rate_limit' - Records rate_limit_info via globalRateLimitStore.set - Calls shouldAbortForQuota(authMethod, globalRateLimitStore) - On abort: session.abortReason = 'quota:<window>', abortController.abort, break out of loop. Worker continues other sessions. Health endpoint (Server.ts:174): - New rateLimits field on /api/health from getMostRecentByWindow(). - Field shape: {five_hour?, seven_day?, seven_day_opus?, seven_day_sonnet?, overage?} each carrying utilization, status, resetsAt, observedAt. Tests (tests/worker/rate-limit-store.test.ts): - 22 cases covering store CRUD, isApiKeyAuth, abort decision matrix. - api_key never aborts at any utilization. - cli aborts at threshold breaches per window. - Reset-grace buffer with utilization floor. Verification: - npx tsc --noEmit: only pre-existing bun error - bun test tests/worker/rate-limit-store.test.ts: 22/22 pass - bun test tests/claude-provider-resume.test.ts: 9/9 pass - bun test tests/server/: 44/44 pass Plugin artifacts regenerated. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * build: regenerate worker-service.cjs after final build-and-sync Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: align test assertions with F4 classification + timeout Two test fixes for branch-introduced regressions vs main: 1. tests/gemini_provider.test.ts "should throw on other errors": F4's classifyGeminiError replaced upstream Error message with ClassifiedProviderError. Test was pinned to pre-F4 string. Updated assertion to match new "Gemini bad request (status 400)". 2. tests/infrastructure/graceful-shutdown.test.ts: Test pokes real ~/.claude-mem/supervisor.json registry which on a developer machine contains live worker + chroma-mcp PIDs. SIGTERM → wait → SIGKILL cascade takes ~6s end-to-end. Bumped per-test timeout to 15000ms. Underlying shutdown code unchanged. Future cleanup should mock getSupervisor() here. Result: branch failure count == main (77 pre-existing failures). No new regressions from this branch's work. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: address 4 Greptile P1/P2 findings on PR #2282 P1 (real bug): clearStaleMarker silently broken in ESM - src/shared/oauth-token.ts:14: add unlinkSync to top-level fs import - src/shared/oauth-token.ts:342: drop inline require('fs'), call unlinkSync directly. ESM has no require, so the previous code threw ReferenceError swallowed by try/catch — making clearStaleMarker a permanent no-op. Stale oauth marker would persist indefinitely after Claude Desktop refreshed the token. P2 (security): execSync shell-string interpolation - src/shared/find-claude-executable.ts:39: execSync(`"${candidate}" --version`) → execFileSync(candidate, ['--version']). Path containing ", ;, & — reachable on Windows via crafted CLAUDE_CODE_PATH in settings.json — would otherwise produce a malformed/exploitable command. P2 (security): PowerShell username injection - src/shared/oauth-token.ts:119: userInfo().username escaped with PS single-quote convention (' → '') before interpolation into `'Claude Code-credentials:${user}'`. Defensive against future Windows versions or domain-joined machines that may permit ' in usernames. P2 (style): Unreachable throw lastError post-loop - src/services/worker/retry.ts:109: explained as the safety net for opts.maxRetries < 0 (pathological input where the loop never executes and lastError is undefined). Annotated with comment + descriptive fallback Error so the dead-looking code is now self-documenting. Verification: - npx tsc --noEmit: clean (only pre-existing bun-types error) - bun test tests/shared/oauth-token.test.ts tests/worker/provider-classifiers.test.ts tests/worker/provider-errors.test.ts: 50 pass / 0 fail Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: tighten SECURITY.md data-flow and audit dates Fixes CodeRabbit comments #3178957249 (Data Storage section overstated "no external transmission" — softened to call out Claude Agent SDK, alternate provider, Chroma MCP, OAuth keychain, and registry fetches) and #3178957250 (Next Scheduled Audit was earlier than Last Updated; bumped Last Updated to 2026-05-03 and audit to 2026-09-16) on PR #2282. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: drop inline require('fs') in paths.ts Fixes CodeRabbit outside-diff comment on src/shared/paths.ts:25-29 from PR #2282 review. resolveDataDir() ran require('fs') inside an ESM module (this file uses import.meta.url and .js imports), which can break in strict ESM environments. readFileSync now imports at the top alongside existsSync/mkdirSync. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: block CLAUDE_CODE_OAUTH_TOKEN from parent env (issue #2215) Fixes CodeRabbit outside-diff comment on src/shared/EnvManager.ts:14-17 from PR #2282 review. The OAuth-token leak fix was bypassed because buildIsolatedEnv() copied every parent env var that wasn't in BLOCKED_ENV_VARS, but CLAUDE_CODE_OAUTH_TOKEN was not blocked. A stale parent token therefore still reached isolatedEnv even when the fresh keychain read returned expired/absent — defeating the fix documented inline at lines 178-183. Adds CLAUDE_CODE_OAUTH_TOKEN to BLOCKED_ENV_VARS and defensively deletes it again at the top of buildIsolatedEnvWithFreshOAuth() so the fresh-spawn-time read is the only path that can populate it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: validate cursor sessionId against path traversal Fixes CodeRabbit comment #3178957252 on PR #2282. The Cursor adapter took sessionId straight from stdin and concatenated it into a join(homedir(), '.cursor', 'projects', ..., sessionId, ...) path. A crafted value containing path separators or '..' segments could escape ~/.cursor/projects, and the later transcript read would then probe arbitrary local files. deriveCursorTranscriptPath() now rejects any sessionId that doesn't match /^[A-Za-z0-9_-]+$/ — Cursor's real session ids are UUID-style identifiers, so the safe whitelist is non-disruptive. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: scope stripCodeFences() to full-wrapper payloads only Fixes CodeRabbit comment #3178957253 on PR #2282. The previous regex greedily removed the first opening and last closing triple-backticks anywhere in the input, which could mangle valid content with internal fenced examples or surrounding prose — and ran before XML parsing so it created false negatives. stripCodeFences() now only strips when the entire payload is a single fenced block (start-to-end, with optional language tag and surrounding whitespace), capturing the inner content. Adds a regression test that feeds prose with internal triple-backtick markers around a real <observation> block and asserts the inner ``` are preserved. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: honor abortSignal during retry backoff sleep Fixes CodeRabbit comment #3178957263 on PR #2282. The retry helper used an unconditional `setTimeout` Promise for backoff between attempts, so an external abort that fired during the wait was delayed until the timer completed. The backoff now races setTimeout against opts.abortSignal: if the signal flips, the timer is cleared and the Promise rejects with 'Aborted' immediately. The abort listener is registered with { once: true } and removed when the timer fires to avoid leaks. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: abort immediately on provider-side rejected status Fixes CodeRabbit comment #3178957261 on PR #2282. shouldAbortForQuota() only checked utilization thresholds and reset-grace heuristics; a snapshot with status='rejected' (or overageStatus='rejected' on the overage window) but no utilization number could still return { abort: false }, letting the worker keep consuming after the provider had already declared the bucket exhausted. Provider-side rejection is now checked before utilization. When either rejection signal is present the guard returns abort=true with reason "quota:<window> rejected by provider". Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: only bump Chroma watermark on confirmed batch writes Fixes CodeRabbit comments #3178957259 (watermark advances on swallowed batch failures) and #3178957260 (backfillInProgress can stick true if init throws) on PR #2282. addDocuments() previously logged and swallowed per-batch failures with a void return type, so all three backfill loops (observations, summaries, prompts) bumped the watermark unconditionally after the call — turning a transient Chroma failure into permanently-skipped records. addDocuments() now returns the count of documents that actually landed (including delete+add reconcile retries), and each loop only advances the watermark when the batch wrote successfully. Failed batches log a debug message and continue so the loop still gets through the rest. backfillAllProjects() now constructs SessionStore and ChromaSync inside a try block so a constructor throw can't leave the static backfillInProgress guard stuck true and silently skip every later backfill. The finally always clears the guard and best-effort closes each resource. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: fall back to pid kill when process group is gone Fixes CodeRabbit outside-diff comment on src/supervisor/shutdown.ts:118-134 from PR #2282 review. signalProcess() returned silently when a pgid was present and process.kill(-pgid, signal) threw ESRCH, never attempting the per-pid signal. With the new chroma registration path that records a pgid alongside the pid, an already-collapsed group could turn shutdown into a no-op even though the root pid was still alive. The POSIX branch now tries -pgid first when present, and on ESRCH falls through to process.kill(pid, signal). Non-ESRCH errors still propagate. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: settings path, uptime clamp, fetch timeouts Fixes three smaller CodeRabbit issues on PR #2282: - SettingsRoutes (outside-diff #2282 review on lines 65-79): the parse-error response told users to delete ~/.claude-mem/settings.json even when paths.settings() resolved elsewhere. Now uses the resolved settingsPath variable in the message. - uptime.ts (#3178957264 / lines 2-3): getUptimeSeconds() could return a negative value if startedAtMs was in the future or the system clock moved backward. Clamps with Math.max(0, ...) so health endpoints never see negative seconds. - check-pending-queue.ts (#3178957248 / lines 27-45): checkWorkerHealth, getProcessingStatus and triggerProcessing all called fetch with no timeout, so the script could block forever if the worker accepted the TCP connection but never responded. Wraps each fetch with an AbortController + 10s timeout that throws a clear timeout message. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: walk descendants recursively when killing chroma-mcp tree Fixes CodeRabbit comment #3178957258 on PR #2282. The POSIX teardown in ChromaMcpManager.killProcessTree() relied on `pkill -P <pid>`, which only signals direct children. Under uv, chroma-mcp spawns python as a grandchild — when uv exits and python re-parents to init, pkill -P never reaches it and the descendant survives the "tree kill". killProcessTree() now collects the full descendant set via a recursive `pgrep -P` walk before each signal phase. The walk returns leaves first so signals propagate bottom-up (SIGTERM children before their parents, then again for SIGKILL after the 500ms grace window so any layer that re-parented during teardown still gets cleaned up). pgrep failures (no children, missing binary) return [] so this stays best-effort and falls back to the existing per-pid signal. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: tolerate malformed JSONL lines in transcript-parser Fixes Greptile P1 comment 3178964456 on PR #2282. extractLastMessageFromJsonl previously called JSON.parse(rawLine) with no guard. A truncated/malformed JSONL line — common when a transcript was crashed mid-write or partially flushed — would throw SyntaxError, crash the summarization pipeline for that session, and silently lose all prior valid messages. Fix: wrap JSON.parse in try/catch and skip bad lines. The empty-line guard only catches truly empty strings, not malformed fragments. Regression tests added for two cases: - Mixed valid + truncated lines: returns last valid match. - All lines malformed: returns empty string (no throw). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: classify FK constraint failures BEFORE provider classifier Fixes Greptile P1 comment 3178979583 on PR #2282. The F4 #2244 work introduced a regression: reclassifyAtDispatch always returns a non-null ClassifiedProviderError for known agent types (Claude/Gemini/OpenRouter), so the isFkConstraintFailure branch was dead code. Per-provider classifiers don't recognize "FOREIGN KEY constraint failed", so SQLite FK failures fell through to the default 'transient' kind and would retry indefinitely — restart loop on corrupted session DB state. Old unrecoverablePatterns explicitly listed FK constraint as unrecoverable; restoring that semantic by checking FK FIRST and only deferring to the classifier when not an FK error. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: validate CLAUDE_MEM_WORKER_PORT in check-pending-queue Parse the env var, range-check (1-65535), and fall back to 37777 with a console.warn on invalid input instead of letting a malformed value flow into the URL builder unchecked (CodeRabbit Minor on PR #2282). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: SIGKILL union of pre-TERM and post-wait descendant sets When the chroma-mcp root exits during the SIGTERM grace window, its descendants get re-parented to init and drop out of the post-wait pgrep -P scan. Without including the pre-TERM snapshot, those re-parented PIDs would never receive SIGKILL even though they were definitely children before SIGTERM and may still be alive (CodeRabbit Major on PR #2282). Compute Array.from(new Set([...descendantsBeforeTerm, ...descendantsBeforeKill])) and SIGKILL the union. The two sets typically overlap, so dedupe is required. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: enforce addDocuments return-count in direct sync paths syncObservation/syncSummary/syncUserPrompt now capture the written count from addDocuments() and only bump the watermark when every requested document landed in Chroma. addDocuments() tolerates per-batch failures (returns the actual written count), so the previous unconditional bump was silently marking unsynced rows as synced on transient errors — preventing the next backfill from retrying them (CodeRabbit Major on PR #2282). A partial write now logs a warn with the (requested, written) pair and preserves retryability on the next pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: guard backfill watermark against non-contiguous failures The backfill watermark is a single monotonic id, so it cannot represent sparse success: "synced through 200, gap at 201–250, then 251 onward" would, on restart, skip 201–250 forever because the watermark sat at either 200 or 251 — both lose data (CodeRabbit Major on PR #2282). Add a per-loop hadGap flag to backfillObservations / backfillSummaries / backfillPrompts. Once any batch under-writes, every subsequent batch must also skip the bump, regardless of whether it itself succeeded. Also tighten the failure check from `writtenInBatch <= 0` to `writtenInBatch < batch.length` so partial-batch writes are caught. The watermark stays at the last contiguously-synced position; the next backfill pass retries from there, eventually closing the gap. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: clear oauth-stale marker when token is absent When an OAuth token disappears entirely (user logs out, keychain cleared), buildIsolatedEnvWithFreshOAuth's absent branch was leaving any prior stale-marker file in place. The session-start hook would then keep surfacing an "expired token, re-login" warning even though the token is no longer expired — it's gone, and re-login was already done elsewhere or not applicable (CodeRabbit Minor on PR #2282). Call clearStaleMarker() in the absent branch the same way the present branch already does. Add a regression test exercising the full buildIsolatedEnvWithFreshOAuth path: pre-write a marker, force absent via spoofed unsupported platform, assert the marker is gone after. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: skip unknown message.content shapes instead of throwing extractLastMessageFromJsonl already tolerates malformed JSONL lines (JSON.parse failure -> continue), but a valid JSON line whose message.content is an unexpected type (null, number, plain object) was still throwing — contradicting the new tolerance and crashing the entire summary pipeline on a single weird line (CodeRabbit Major + Greptile P1 on PR #2282). Replace the `throw new Error(...)` with `continue` so a single bad content shape skips that line instead of failing the whole transcript read. Forward compat: future content schemas land harmlessly. Add regression tests covering null, number, and plain-object content; each must not throw and must fall back to the most recent valid line. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * review: guard null/primitive entries in message.content array Fixes CodeRabbit comment 3179004190 on PR #2282. The Array.isArray branch previously did `c.type === 'text'` directly, which throws if `c` is null or a primitive — possible in malformed logs. Tightened the filter with a type guard: requires c to be a non-null object with type === 'text' and a string text field. Same defensive class as the malformed-line and unknown-content-shape tolerances. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
177 lines
229 KiB
JavaScript
Executable File
177 lines
229 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
"use strict";var sd=Object.create;var Gi=Object.defineProperty;var od=Object.getOwnPropertyDescriptor;var id=Object.getOwnPropertyNames;var ad=Object.getPrototypeOf,cd=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ld=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of id(e))!cd.call(t,s)&&s!==r&&Gi(t,s,{get:()=>e[s],enumerable:!(n=od(e,s))||n.enumerable});return t};var pe=(t,e,r)=>(r=t!=null?sd(ad(t)):{},ld(e||!t||!t.__esModule?Gi(r,"default",{value:t,enumerable:!0}):r,t));var or=b(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.regexpCode=D.getEsmExportName=D.getProperty=D.safeStringify=D.stringify=D.strConcat=D.addCodeArg=D.str=D._=D.nil=D._Code=D.Name=D.IDENTIFIER=D._CodeOrName=void 0;var nr=class{};D._CodeOrName=nr;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ot=class extends nr{constructor(e){if(super(),!D.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};D.Name=ot;var ye=class extends nr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof ot&&(r[n.str]=(r[n.str]||0)+1),r),{})}};D._Code=ye;D.nil=new ye("");function ga(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Os(r,e[n]),r.push(t[++n]);return new ye(r)}D._=ga;var As=new ye("+");function ya(t,...e){let r=[sr(t[0])],n=0;for(;n<e.length;)r.push(As),Os(r,e[n]),r.push(As,sr(t[++n]));return up(r),new ye(r)}D.str=ya;function Os(t,e){e instanceof ye?t.push(...e._items):e instanceof ot?t.push(e):t.push(pp(e))}D.addCodeArg=Os;function up(t){let e=1;for(;e<t.length-1;){if(t[e]===As){let r=dp(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function dp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ot||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof ot))return`"${t}${e.slice(1)}`}function fp(t,e){return e.emptyStr()?t:t.emptyStr()?e:ya`${t}${e}`}D.strConcat=fp;function pp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:sr(Array.isArray(t)?t.join(","):t)}function mp(t){return new ye(sr(t))}D.stringify=mp;function sr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=sr;function hp(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new ye(`.${t}`):ga`[${t}]`}D.getProperty=hp;function gp(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new ye(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=gp;function yp(t){return new ye(t.toString())}D.regexpCode=yp});var xs=b(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.ValueScope=oe.ValueScopeName=oe.Scope=oe.varKinds=oe.UsedValueState=void 0;var se=or(),Cs=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},an;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(an||(oe.UsedValueState=an={}));oe.varKinds={const:new se.Name("const"),let:new se.Name("let"),var:new se.Name("var")};var cn=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof se.Name?e:this.name(e)}name(e){return new se.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};oe.Scope=cn;var ln=class extends se.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,se._)`.${new se.Name(r)}[${n}]`}};oe.ValueScopeName=ln;var _p=(0,se._)`\n`,Is=class extends cn{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?_p:se.nil}}get(){return this._scope}name(e){return new ln(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[o];if(c){let d=c.get(i);if(d)return d}else c=this._values[o]=new Map;c.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),u=l.length;return l[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,se._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=se.nil;for(let i in e){let c=e[i];if(!c)continue;let l=n[i]=n[i]||new Map;c.forEach(u=>{if(l.has(u))return;l.set(u,an.Started);let d=r(u);if(d){let f=this.opts.es5?oe.varKinds.var:oe.varKinds.const;o=(0,se._)`${o}${f} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,se._)`${o}${d}${this.opts._n}`;else throw new Cs(u);l.set(u,an.Completed)})}return o}};oe.ValueScope=Is});var R=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.or=M.and=M.not=M.CodeGen=M.operators=M.varKinds=M.ValueScopeName=M.ValueScope=M.Scope=M.Name=M.regexpCode=M.stringify=M.getProperty=M.nil=M.strConcat=M.str=M._=void 0;var I=or(),ve=xs(),Je=or();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return Je._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return Je.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return Je.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return Je.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return Je.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return Je.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return Je.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return Je.Name}});var pn=xs();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return pn.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return pn.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return pn.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return pn.varKinds}});M.operators={GT:new I._Code(">"),GTE:new I._Code(">="),LT:new I._Code("<"),LTE:new I._Code("<="),EQ:new I._Code("==="),NEQ:new I._Code("!=="),NOT:new I._Code("!"),OR:new I._Code("||"),AND:new I._Code("&&"),ADD:new I._Code("+")};var Ue=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ds=class extends Ue{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ve.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=vt(this.rhs,e,r)),this}get names(){return this.rhs instanceof I._CodeOrName?this.rhs.names:{}}},un=class extends Ue{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof I.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=vt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof I.Name?{}:{...this.lhs.names};return fn(e,this.rhs)}},Ns=class extends un{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},zs=class extends Ue{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ls=class extends Ue{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},js=class extends Ue{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},qs=class extends Ue{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=vt(this.code,e,r),this}get names(){return this.code instanceof I._CodeOrName?this.code.names:{}}},ir=class extends Ue{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(Sp(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>ct(e,r.names),{})}},Fe=class extends ir{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Us=class extends ir{},bt=class extends Fe{};bt.kind="else";var it=class t extends Fe{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new bt(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(_a(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=vt(this.condition,e,r),this}get names(){let e=super.names;return fn(e,this.condition),this.else&&ct(e,this.else.names),e}};it.kind="if";var at=class extends Fe{};at.kind="for";var Fs=class extends at{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=vt(this.iteration,e,r),this}get names(){return ct(super.names,this.iteration.names)}},Hs=class extends at{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ve.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=fn(super.names,this.from);return fn(e,this.to)}},dn=class extends at{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=vt(this.iterable,e,r),this}get names(){return ct(super.names,this.iterable.names)}},ar=class extends Fe{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ar.kind="func";var cr=class extends ir{render(e){return"return "+super.render(e)}};cr.kind="return";var Ws=class extends Fe{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&ct(e,this.catch.names),this.finally&&ct(e,this.finally.names),e}},lr=class extends Fe{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};lr.kind="catch";var ur=class extends Fe{render(e){return"finally"+super.render(e)}};ur.kind="finally";var Vs=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
`:""},this._extScope=e,this._scope=new ve.Scope({parent:e}),this._nodes=[new Us]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Ds(e,o,n)),o}const(e,r,n){return this._def(ve.varKinds.const,e,r,n)}let(e,r,n){return this._def(ve.varKinds.let,e,r,n)}var(e,r,n){return this._def(ve.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new un(e,r,n))}add(e,r){return this._leafNode(new Ns(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==I.nil&&this._leafNode(new qs(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,I.addCodeArg)(r,s));return r.push("}"),new I._Code(r)}if(e,r,n){if(this._blockNode(new it(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new it(e))}else(){return this._elseNode(new bt)}endIf(){return this._endBlockNode(it,bt)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Fs(e),r)}forRange(e,r,n,s,o=this.opts.es5?ve.varKinds.var:ve.varKinds.let){let i=this._scope.toName(e);return this._for(new Hs(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ve.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof I.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,I._)`${i}.length`,c=>{this.var(o,(0,I._)`${i}[${c}]`),n(o)})}return this._for(new dn("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ve.varKinds.var:ve.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,I._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new dn("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(at)}label(e){return this._leafNode(new zs(e))}break(e){return this._leafNode(new Ls(e))}return(e){let r=new cr;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(cr)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ws;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new lr(o),r(o)}return n&&(this._currNode=s.finally=new ur,this.code(n)),this._endBlockNode(lr,ur)}throw(e){return this._leafNode(new js(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=I.nil,n,s){return this._blockNode(new ar(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(ar)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof it))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};M.CodeGen=Vs;function ct(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function fn(t,e){return e instanceof I._CodeOrName?ct(t,e.names):t}function vt(t,e,r){if(t instanceof I.Name)return n(t);if(!s(t))return t;return new I._Code(t._items.reduce((o,i)=>(i instanceof I.Name&&(i=n(i)),i instanceof I._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof I._Code&&o._items.some(i=>i instanceof I.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Sp(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function _a(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,I._)`!${Gs(t)}`}M.not=_a;var Ep=Sa(M.operators.AND);function wp(...t){return t.reduce(Ep)}M.and=wp;var bp=Sa(M.operators.OR);function vp(...t){return t.reduce(bp)}M.or=vp;function Sa(t){return(e,r)=>e===I.nil?r:r===I.nil?e:(0,I._)`${Gs(e)} ${t} ${Gs(r)}`}function Gs(t){return t instanceof I.Name?t:(0,I._)`(${t})`}});var N=b(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.checkStrictMode=O.getErrorPath=O.Type=O.useFunc=O.setEvaluated=O.evaluatedPropsToName=O.mergeEvaluated=O.eachItem=O.unescapeJsonPointer=O.escapeJsonPointer=O.escapeFragment=O.unescapeFragment=O.schemaRefOrVal=O.schemaHasRulesButRef=O.schemaHasRules=O.checkUnknownRules=O.alwaysValidSchema=O.toHash=void 0;var j=R(),kp=or();function Pp(t){let e={};for(let r of t)e[r]=!0;return e}O.toHash=Pp;function Tp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ba(t,e),!va(e,t.self.RULES.all))}O.alwaysValidSchema=Tp;function ba(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||Ta(t,`unknown keyword: "${o}"`)}O.checkUnknownRules=ba;function va(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}O.schemaHasRules=va;function $p(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}O.schemaHasRulesButRef=$p;function Rp({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,j._)`${r}`}return(0,j._)`${t}${e}${(0,j.getProperty)(n)}`}O.schemaRefOrVal=Rp;function Mp(t){return ka(decodeURIComponent(t))}O.unescapeFragment=Mp;function Ap(t){return encodeURIComponent(Ys(t))}O.escapeFragment=Ap;function Ys(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}O.escapeJsonPointer=Ys;function ka(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}O.unescapeJsonPointer=ka;function Op(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}O.eachItem=Op;function Ea({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,c)=>{let l=i===void 0?o:i instanceof j.Name?(o instanceof j.Name?t(s,o,i):e(s,o,i),i):o instanceof j.Name?(e(s,i,o),o):r(o,i);return c===j.Name&&!(l instanceof j.Name)?n(s,l):l}}O.mergeEvaluated={props:Ea({mergeNames:(t,e,r)=>t.if((0,j._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,j._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,j._)`${r} || {}`).code((0,j._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,j._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,j._)`${r} || {}`),Bs(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pa}),items:Ea({mergeNames:(t,e,r)=>t.if((0,j._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,j._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,j._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,j._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Pa(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,j._)`{}`);return e!==void 0&&Bs(t,r,e),r}O.evaluatedPropsToName=Pa;function Bs(t,e,r){Object.keys(r).forEach(n=>t.assign((0,j._)`${e}${(0,j.getProperty)(n)}`,!0))}O.setEvaluated=Bs;var wa={};function Cp(t,e){return t.scopeValue("func",{ref:e,code:wa[e.code]||(wa[e.code]=new kp._Code(e.code))})}O.useFunc=Cp;var Ks;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ks||(O.Type=Ks={}));function Ip(t,e,r){if(t instanceof j.Name){let n=e===Ks.Num;return r?n?(0,j._)`"[" + ${t} + "]"`:(0,j._)`"['" + ${t} + "']"`:n?(0,j._)`"/" + ${t}`:(0,j._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,j.getProperty)(t).toString():"/"+Ys(t)}O.getErrorPath=Ip;function Ta(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}O.checkStrictMode=Ta});var He=b(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var X=R(),xp={data:new X.Name("data"),valCxt:new X.Name("valCxt"),instancePath:new X.Name("instancePath"),parentData:new X.Name("parentData"),parentDataProperty:new X.Name("parentDataProperty"),rootData:new X.Name("rootData"),dynamicAnchors:new X.Name("dynamicAnchors"),vErrors:new X.Name("vErrors"),errors:new X.Name("errors"),this:new X.Name("this"),self:new X.Name("self"),scope:new X.Name("scope"),json:new X.Name("json"),jsonPos:new X.Name("jsonPos"),jsonLen:new X.Name("jsonLen"),jsonPart:new X.Name("jsonPart")};Js.default=xp});var dr=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.extendErrors=Q.resetErrorsCount=Q.reportExtraError=Q.reportError=Q.keyword$DataError=Q.keywordError=void 0;var x=R(),mn=N(),re=He();Q.keywordError={message:({keyword:t})=>(0,x.str)`must pass "${t}" keyword validation`};Q.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,x.str)`"${t}" keyword must be ${e} ($data)`:(0,x.str)`"${t}" keyword is invalid ($data)`};function Dp(t,e=Q.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:c}=s,l=Ma(t,e,r);n??(i||c)?$a(o,l):Ra(s,(0,x._)`[${l}]`)}Q.reportError=Dp;function Np(t,e=Q.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,c=Ma(t,e,r);$a(s,c),o||i||Ra(n,re.default.vErrors)}Q.reportExtraError=Np;function zp(t,e){t.assign(re.default.errors,e),t.if((0,x._)`${re.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,x._)`${re.default.vErrors}.length`,e),()=>t.assign(re.default.vErrors,null)))}Q.resetErrorsCount=zp;function Lp({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,re.default.errors,c=>{t.const(i,(0,x._)`${re.default.vErrors}[${c}]`),t.if((0,x._)`${i}.instancePath === undefined`,()=>t.assign((0,x._)`${i}.instancePath`,(0,x.strConcat)(re.default.instancePath,o.errorPath))),t.assign((0,x._)`${i}.schemaPath`,(0,x.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,x._)`${i}.schema`,r),t.assign((0,x._)`${i}.data`,n))})}Q.extendErrors=Lp;function $a(t,e){let r=t.const("err",e);t.if((0,x._)`${re.default.vErrors} === null`,()=>t.assign(re.default.vErrors,(0,x._)`[${r}]`),(0,x._)`${re.default.vErrors}.push(${r})`),t.code((0,x._)`${re.default.errors}++`)}function Ra(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,x._)`new ${t.ValidationError}(${e})`):(r.assign((0,x._)`${n}.errors`,e),r.return(!1))}var lt={keyword:new x.Name("keyword"),schemaPath:new x.Name("schemaPath"),params:new x.Name("params"),propertyName:new x.Name("propertyName"),message:new x.Name("message"),schema:new x.Name("schema"),parentSchema:new x.Name("parentSchema")};function Ma(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,x._)`{}`:jp(t,e,r)}function jp(t,e,r={}){let{gen:n,it:s}=t,o=[qp(s,r),Up(t,r)];return Fp(t,e,o),n.object(...o)}function qp({errorPath:t},{instancePath:e}){let r=e?(0,x.str)`${t}${(0,mn.getErrorPath)(e,mn.Type.Str)}`:t;return[re.default.instancePath,(0,x.strConcat)(re.default.instancePath,r)]}function Up({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,x.str)`${e}/${t}`;return r&&(s=(0,x.str)`${s}${(0,mn.getErrorPath)(r,mn.Type.Str)}`),[lt.schemaPath,s]}function Fp(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:c}=t,{opts:l,propertyName:u,topSchemaRef:d,schemaPath:f}=c;n.push([lt.keyword,s],[lt.params,typeof e=="function"?e(t):e||(0,x._)`{}`]),l.messages&&n.push([lt.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([lt.schema,i],[lt.parentSchema,(0,x._)`${d}${f}`],[re.default.data,o]),u&&n.push([lt.propertyName,u])}});var Oa=b(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.boolOrEmptySchema=kt.topBoolOrEmptySchema=void 0;var Hp=dr(),Wp=R(),Vp=He(),Gp={message:"boolean schema is false"};function Kp(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Aa(t,!1):typeof r=="object"&&r.$async===!0?e.return(Vp.default.data):(e.assign((0,Wp._)`${n}.errors`,null),e.return(!0))}kt.topBoolOrEmptySchema=Kp;function Yp(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Aa(t)):r.var(e,!0)}kt.boolOrEmptySchema=Yp;function Aa(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Hp.reportError)(s,Gp,void 0,e)}});var Zs=b(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getRules=Pt.isJSONType=void 0;var Bp=["string","number","integer","boolean","null","object","array"],Jp=new Set(Bp);function Zp(t){return typeof t=="string"&&Jp.has(t)}Pt.isJSONType=Zp;function Xp(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Pt.getRules=Xp});var Xs=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.shouldUseRule=Ze.shouldUseGroup=Ze.schemaHasRulesForType=void 0;function Qp({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ca(t,n)}Ze.schemaHasRulesForType=Qp;function Ca(t,e){return e.rules.some(r=>Ia(t,r))}Ze.shouldUseGroup=Ca;function Ia(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Ze.shouldUseRule=Ia});var fr=b(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.reportTypeError=ee.checkDataTypes=ee.checkDataType=ee.coerceAndCheckDataType=ee.getJSONTypes=ee.getSchemaTypes=ee.DataType=void 0;var em=Zs(),tm=Xs(),rm=dr(),T=R(),xa=N(),Tt;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Tt||(ee.DataType=Tt={}));function nm(t){let e=Da(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ee.getSchemaTypes=nm;function Da(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(em.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ee.getJSONTypes=Da;function sm(t,e){let{gen:r,data:n,opts:s}=t,o=om(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,tm.schemaHasRulesForType)(t,e[0]));if(i){let c=eo(e,n,s.strictNumbers,Tt.Wrong);r.if(c,()=>{o.length?im(t,e,o):to(t)})}return i}ee.coerceAndCheckDataType=sm;var Na=new Set(["string","number","integer","boolean","null"]);function om(t,e){return e?t.filter(r=>Na.has(r)||e==="array"&&r==="array"):[]}function im(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,T._)`typeof ${s}`),c=n.let("coerced",(0,T._)`undefined`);o.coerceTypes==="array"&&n.if((0,T._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,T._)`${s}[0]`).assign(i,(0,T._)`typeof ${s}`).if(eo(e,s,o.strictNumbers),()=>n.assign(c,s))),n.if((0,T._)`${c} !== undefined`);for(let u of r)(Na.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);n.else(),to(t),n.endIf(),n.if((0,T._)`${c} !== undefined`,()=>{n.assign(s,c),am(t,c)});function l(u){switch(u){case"string":n.elseIf((0,T._)`${i} == "number" || ${i} == "boolean"`).assign(c,(0,T._)`"" + ${s}`).elseIf((0,T._)`${s} === null`).assign(c,(0,T._)`""`);return;case"number":n.elseIf((0,T._)`${i} == "boolean" || ${s} === null
|
|
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(c,(0,T._)`+${s}`);return;case"integer":n.elseIf((0,T._)`${i} === "boolean" || ${s} === null
|
|
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(c,(0,T._)`+${s}`);return;case"boolean":n.elseIf((0,T._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(c,!1).elseIf((0,T._)`${s} === "true" || ${s} === 1`).assign(c,!0);return;case"null":n.elseIf((0,T._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(c,null);return;case"array":n.elseIf((0,T._)`${i} === "string" || ${i} === "number"
|
|
|| ${i} === "boolean" || ${s} === null`).assign(c,(0,T._)`[${s}]`)}}}function am({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,T._)`${e} !== undefined`,()=>t.assign((0,T._)`${e}[${r}]`,n))}function Qs(t,e,r,n=Tt.Correct){let s=n===Tt.Correct?T.operators.EQ:T.operators.NEQ,o;switch(t){case"null":return(0,T._)`${e} ${s} null`;case"array":o=(0,T._)`Array.isArray(${e})`;break;case"object":o=(0,T._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,T._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,T._)`typeof ${e} ${s} ${t}`}return n===Tt.Correct?o:(0,T.not)(o);function i(c=T.nil){return(0,T.and)((0,T._)`typeof ${e} == "number"`,c,r?(0,T._)`isFinite(${e})`:T.nil)}}ee.checkDataType=Qs;function eo(t,e,r,n){if(t.length===1)return Qs(t[0],e,r,n);let s,o=(0,xa.toHash)(t);if(o.array&&o.object){let i=(0,T._)`typeof ${e} != "object"`;s=o.null?i:(0,T._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=T.nil;o.number&&delete o.integer;for(let i in o)s=(0,T.and)(s,Qs(i,e,r,n));return s}ee.checkDataTypes=eo;var cm={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,T._)`{type: ${t}}`:(0,T._)`{type: ${e}}`};function to(t){let e=lm(t);(0,rm.reportError)(e,cm)}ee.reportTypeError=to;function lm(t){let{gen:e,data:r,schema:n}=t,s=(0,xa.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var La=b(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.assignDefaults=void 0;var $t=R(),um=N();function dm(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)za(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>za(t,o,s.default))}hn.assignDefaults=dm;function za(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let c=(0,$t._)`${o}${(0,$t.getProperty)(e)}`;if(s){(0,um.checkStrictMode)(t,`default is ignored for: ${c}`);return}let l=(0,$t._)`${c} === undefined`;i.useDefaults==="empty"&&(l=(0,$t._)`${l} || ${c} === null || ${c} === ""`),n.if(l,(0,$t._)`${c} = ${(0,$t.stringify)(r)}`)}});var _e=b(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.validateUnion=L.validateArray=L.usePattern=L.callValidateCode=L.schemaProperties=L.allSchemaProperties=L.noPropertyInData=L.propertyInData=L.isOwnProperty=L.hasPropFunc=L.reportMissingProp=L.checkMissingProp=L.checkReportMissingProp=void 0;var q=R(),ro=N(),Xe=He(),fm=N();function pm(t,e){let{gen:r,data:n,it:s}=t;r.if(so(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,q._)`${e}`},!0),t.error()})}L.checkReportMissingProp=pm;function mm({gen:t,data:e,it:{opts:r}},n,s){return(0,q.or)(...n.map(o=>(0,q.and)(so(t,e,o,r.ownProperties),(0,q._)`${s} = ${o}`)))}L.checkMissingProp=mm;function hm(t,e){t.setParams({missingProperty:e},!0),t.error()}L.reportMissingProp=hm;function ja(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,q._)`Object.prototype.hasOwnProperty`})}L.hasPropFunc=ja;function no(t,e,r){return(0,q._)`${ja(t)}.call(${e}, ${r})`}L.isOwnProperty=no;function gm(t,e,r,n){let s=(0,q._)`${e}${(0,q.getProperty)(r)} !== undefined`;return n?(0,q._)`${s} && ${no(t,e,r)}`:s}L.propertyInData=gm;function so(t,e,r,n){let s=(0,q._)`${e}${(0,q.getProperty)(r)} === undefined`;return n?(0,q.or)(s,(0,q.not)(no(t,e,r))):s}L.noPropertyInData=so;function qa(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}L.allSchemaProperties=qa;function ym(t,e){return qa(e).filter(r=>!(0,ro.alwaysValidSchema)(t,e[r]))}L.schemaProperties=ym;function _m({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},c,l,u){let d=u?(0,q._)`${t}, ${e}, ${n}${s}`:e,f=[[Xe.default.instancePath,(0,q.strConcat)(Xe.default.instancePath,o)],[Xe.default.parentData,i.parentData],[Xe.default.parentDataProperty,i.parentDataProperty],[Xe.default.rootData,Xe.default.rootData]];i.opts.dynamicRef&&f.push([Xe.default.dynamicAnchors,Xe.default.dynamicAnchors]);let p=(0,q._)`${d}, ${r.object(...f)}`;return l!==q.nil?(0,q._)`${c}.call(${l}, ${p})`:(0,q._)`${c}(${p})`}L.callValidateCode=_m;var Sm=(0,q._)`new RegExp`;function Em({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,q._)`${s.code==="new RegExp"?Sm:(0,fm.useFunc)(t,s)}(${r}, ${n})`})}L.usePattern=Em;function wm(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let c=e.let("valid",!0);return i(()=>e.assign(c,!1)),c}return e.var(o,!0),i(()=>e.break()),o;function i(c){let l=e.const("len",(0,q._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ro.Type.Num},o),e.if((0,q.not)(o),c)})}}L.validateArray=wm;function bm(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,ro.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),c=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},c);e.assign(i,(0,q._)`${i} || ${c}`),t.mergeValidEvaluated(d,c)||e.if((0,q.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}L.validateUnion=bm});var Ha=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.validateKeywordUsage=Me.validSchemaType=Me.funcKeywordCode=Me.macroKeywordCode=void 0;var ne=R(),ut=He(),vm=_e(),km=dr();function Pm(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,c=e.macro.call(i.self,s,o,i),l=Fa(r,n,c);i.opts.validateSchema!==!1&&i.self.validateSchema(c,!0);let u=r.name("valid");t.subschema({schema:c,schemaPath:ne.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Me.macroKeywordCode=Pm;function Tm(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:c,it:l}=t;Rm(l,e);let u=!c&&e.compile?e.compile.call(l.self,o,i,l):e.validate,d=Fa(n,s,u),f=n.let("valid");t.block$data(f,p),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function p(){if(e.errors===!1)g(),e.modifying&&Ua(t),_(()=>t.error());else{let E=e.async?m():h();e.modifying&&Ua(t),_(()=>$m(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>g((0,ne._)`await `),S=>n.assign(f,!1).if((0,ne._)`${S} instanceof ${l.ValidationError}`,()=>n.assign(E,(0,ne._)`${S}.errors`),()=>n.throw(S))),E}function h(){let E=(0,ne._)`${d}.errors`;return n.assign(E,null),g(ne.nil),E}function g(E=e.async?(0,ne._)`await `:ne.nil){let S=l.opts.passContext?ut.default.this:ut.default.self,w=!("compile"in e&&!c||e.schema===!1);n.assign(f,(0,ne._)`${E}${(0,vm.callValidateCode)(t,d,S,w)}`,e.modifying)}function _(E){var S;n.if((0,ne.not)((S=e.valid)!==null&&S!==void 0?S:f),E)}}Me.funcKeywordCode=Tm;function Ua(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ne._)`${n.parentData}[${n.parentDataProperty}]`))}function $m(t,e){let{gen:r}=t;r.if((0,ne._)`Array.isArray(${e})`,()=>{r.assign(ut.default.vErrors,(0,ne._)`${ut.default.vErrors} === null ? ${e} : ${ut.default.vErrors}.concat(${e})`).assign(ut.default.errors,(0,ne._)`${ut.default.vErrors}.length`),(0,km.extendErrors)(t)},()=>t.error())}function Rm({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Fa(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ne.stringify)(r)})}function Mm(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Me.validSchemaType=Mm;function Am({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(c=>!Object.prototype.hasOwnProperty.call(t,c)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Me.validateKeywordUsage=Am});var Va=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.extendSubschemaMode=Qe.extendSubschemaData=Qe.getSubschema=void 0;var Ae=R(),Wa=N();function Om(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let c=t.schema[e];return r===void 0?{schema:c,schemaPath:(0,Ae._)`${t.schemaPath}${(0,Ae.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:c[r],schemaPath:(0,Ae._)`${t.schemaPath}${(0,Ae.getProperty)(e)}${(0,Ae.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Wa.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Qe.getSubschema=Om;function Cm(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:f}=e,p=c.let("data",(0,Ae._)`${e.data}${(0,Ae.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Ae.str)`${u}${(0,Wa.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Ae._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Ae.Name?s:c.let("data",s,!0);l(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Qe.extendSubschemaData=Cm;function Im(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Qe.extendSubschemaMode=Im});var oo=b((gv,Ga)=>{"use strict";Ga.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Ya=b((yv,Ka)=>{"use strict";var et=Ka.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};gn(e,n,s,t,"",t)};et.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};et.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};et.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};et.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function gn(t,e,r,n,s,o,i,c,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,c,l,u);for(var d in n){var f=n[d];if(Array.isArray(f)){if(d in et.arrayKeywords)for(var p=0;p<f.length;p++)gn(t,e,r,f[p],s+"/"+d+"/"+p,o,s,d,n,p)}else if(d in et.propsKeywords){if(f&&typeof f=="object")for(var m in f)gn(t,e,r,f[m],s+"/"+d+"/"+xm(m),o,s,d,n,m)}else(d in et.keywords||t.allKeys&&!(d in et.skipKeywords))&&gn(t,e,r,f,s+"/"+d,o,s,d,n)}r(n,s,o,i,c,l,u)}}function xm(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var pr=b(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.getSchemaRefs=ie.resolveUrl=ie.normalizeId=ie._getFullPath=ie.getFullPath=ie.inlineRef=void 0;var Dm=N(),Nm=oo(),zm=Ya(),Lm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function jm(t,e=!0){return typeof t=="boolean"?!0:e===!0?!io(t):e?Ba(t)<=e:!1}ie.inlineRef=jm;var qm=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function io(t){for(let e in t){if(qm.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(io)||typeof r=="object"&&io(r))return!0}return!1}function Ba(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Lm.has(r)&&(typeof t[r]=="object"&&(0,Dm.eachItem)(t[r],n=>e+=Ba(n)),e===1/0))return 1/0}return e}function Ja(t,e="",r){r!==!1&&(e=Rt(e));let n=t.parse(e);return Za(t,n)}ie.getFullPath=Ja;function Za(t,e){return t.serialize(e).split("#")[0]+"#"}ie._getFullPath=Za;var Um=/#\/?$/;function Rt(t){return t?t.replace(Um,""):""}ie.normalizeId=Rt;function Fm(t,e,r){return r=Rt(r),t.resolve(e,r)}ie.resolveUrl=Fm;var Hm=/^[a-z_][-a-z0-9._]*$/i;function Wm(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Rt(t[r]||e),o={"":s},i=Ja(n,s,!1),c={},l=new Set;return zm(t,{allKeys:!0},(f,p,m,h)=>{if(h===void 0)return;let g=i+p,_=o[h];typeof f[r]=="string"&&(_=E.call(this,f[r])),S.call(this,f.$anchor),S.call(this,f.$dynamicAnchor),o[p]=_;function E(w){let A=this.opts.uriResolver.resolve;if(w=Rt(_?A(_,w):w),l.has(w))throw d(w);l.add(w);let k=this.refs[w];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(f,k.schema,w):w!==Rt(g)&&(w[0]==="#"?(u(f,c[w],w),c[w]=f):this.refs[w]=g),w}function S(w){if(typeof w=="string"){if(!Hm.test(w))throw new Error(`invalid anchor "${w}"`);E.call(this,`#${w}`)}}}),c;function u(f,p,m){if(p!==void 0&&!Nm(f,p))throw d(m)}function d(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ie.getSchemaRefs=Wm});var gr=b(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.getData=tt.KeywordCxt=tt.validateFunctionCode=void 0;var rc=Oa(),Xa=fr(),co=Xs(),yn=fr(),Vm=La(),hr=Ha(),ao=Va(),v=R(),P=He(),Gm=pr(),We=N(),mr=dr();function Km(t){if(oc(t)&&(ic(t),sc(t))){Jm(t);return}nc(t,()=>(0,rc.topBoolOrEmptySchema)(t))}tt.validateFunctionCode=Km;function nc({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,v._)`${P.default.data}, ${P.default.valCxt}`,n.$async,()=>{t.code((0,v._)`"use strict"; ${Qa(r,s)}`),Bm(t,s),t.code(o)}):t.func(e,(0,v._)`${P.default.data}, ${Ym(s)}`,n.$async,()=>t.code(Qa(r,s)).code(o))}function Ym(t){return(0,v._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,v._)`, ${P.default.dynamicAnchors}={}`:v.nil}}={}`}function Bm(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,v._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,v._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,v._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,v._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,v._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,v._)`""`),t.var(P.default.parentData,(0,v._)`undefined`),t.var(P.default.parentDataProperty,(0,v._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,v._)`{}`)})}function Jm(t){let{schema:e,opts:r,gen:n}=t;nc(t,()=>{r.$comment&&e.$comment&&cc(t),th(t),n.let(P.default.vErrors,null),n.let(P.default.errors,0),r.unevaluated&&Zm(t),ac(t),sh(t)})}function Zm(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,v._)`${r}.evaluated`),e.if((0,v._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,v._)`${t.evaluated}.props`,(0,v._)`undefined`)),e.if((0,v._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,v._)`${t.evaluated}.items`,(0,v._)`undefined`))}function Qa(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,v._)`/*# sourceURL=${r} */`:v.nil}function Xm(t,e){if(oc(t)&&(ic(t),sc(t))){Qm(t,e);return}(0,rc.boolOrEmptySchema)(t,e)}function sc({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function oc(t){return typeof t.schema!="boolean"}function Qm(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&cc(t),rh(t),nh(t);let o=n.const("_errs",P.default.errors);ac(t,o),n.var(e,(0,v._)`${o} === ${P.default.errors}`)}function ic(t){(0,We.checkUnknownRules)(t),eh(t)}function ac(t,e){if(t.opts.jtd)return ec(t,[],!1,e);let r=(0,Xa.getSchemaTypes)(t.schema),n=(0,Xa.coerceAndCheckDataType)(t,r);ec(t,r,!n,e)}function eh(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,We.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function th(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,We.checkStrictMode)(t,"default is ignored in the schema root")}function rh(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Gm.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function nh(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function cc({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,v._)`${P.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,v.str)`${n}/$comment`,c=t.scopeValue("root",{ref:e.root});t.code((0,v._)`${P.default.self}.opts.$comment(${o}, ${i}, ${c}.schema)`)}}function sh(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,v._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,v._)`new ${s}(${P.default.vErrors})`)):(e.assign((0,v._)`${n}.errors`,P.default.vErrors),o.unevaluated&&oh(t),e.return((0,v._)`${P.default.errors} === 0`))}function oh({gen:t,evaluated:e,props:r,items:n}){r instanceof v.Name&&t.assign((0,v._)`${e}.props`,r),n instanceof v.Name&&t.assign((0,v._)`${e}.items`,n)}function ec(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:c,opts:l,self:u}=t,{RULES:d}=u;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,We.schemaHasRulesButRef)(o,d))){s.block(()=>uc(t,"$ref",d.all.$ref.definition));return}l.jtd||ih(t,e),s.block(()=>{for(let p of d.rules)f(p);f(d.post)});function f(p){(0,co.shouldUseGroup)(o,p)&&(p.type?(s.if((0,yn.checkDataType)(p.type,i,l.strictNumbers)),tc(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,yn.reportTypeError)(t)),s.endIf()):tc(t,p),c||s.if((0,v._)`${P.default.errors} === ${n||0}`))}}function tc(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,Vm.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,co.shouldUseRule)(n,o)&&uc(t,o.keyword,o.definition,e.type)})}function ih(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(ah(t,e),t.opts.allowUnionTypes||ch(t,e),lh(t,t.dataTypes))}function ah(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{lc(t.dataTypes,r)||lo(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),dh(t,e)}}function ch(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&lo(t,"use allowUnionTypes to allow union type keyword")}function lh(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,co.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>uh(e,i))&&lo(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function uh(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function lc(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function dh(t,e){let r=[];for(let n of t.dataTypes)lc(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function lo(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,We.checkStrictMode)(t,e,t.opts.strictTypes)}var _n=class{constructor(e,r,n){if((0,hr.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,We.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",dc(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,hr.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,r,n){this.failResult((0,v.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,v.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,v._)`${r} !== undefined && (${(0,v.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?mr.reportExtraError:mr.reportError)(this,this.def.error,r)}$dataError(){(0,mr.reportError)(this,this.def.$dataError||mr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,mr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=v.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=v.nil,r=v.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,v.or)((0,v._)`${s} === undefined`,r)),e!==v.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==v.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,v.or)(i(),c());function i(){if(n.length){if(!(r instanceof v.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,v._)`${(0,yn.checkDataTypes)(l,r,o.opts.strictNumbers,yn.DataType.Wrong)}`}return v.nil}function c(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,v._)`!${l}(${r})`}return v.nil}}subschema(e,r){let n=(0,ao.getSubschema)(this.it,e);(0,ao.extendSubschemaData)(n,this.it,e),(0,ao.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return Xm(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=We.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=We.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,v.Name)),!0}};tt.KeywordCxt=_n;function uc(t,e,r,n){let s=new _n(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,hr.funcKeywordCode)(s,r):"macro"in r?(0,hr.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,hr.funcKeywordCode)(s,r)}var fh=/^\/(?:[^~]|~0|~1)*$/,ph=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dc(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!fh.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=P.default.rootData}else{let u=ph.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(l("property/index",d));return n[e-d]}if(d>e)throw new Error(l("data",d));if(o=r[e-d],!s)return o}let i=o,c=s.split("/");for(let u of c)u&&(o=(0,v._)`${o}${(0,v.getProperty)((0,We.unescapeJsonPointer)(u))}`,i=(0,v._)`${i} && ${o}`);return i;function l(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}tt.getData=dc});var Sn=b(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});var uo=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};fo.default=uo});var yr=b(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});var po=pr(),mo=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,po.resolveUrl)(e,r,n),this.missingSchema=(0,po.normalizeId)((0,po.getFullPath)(e,this.missingRef))}};ho.default=mo});var wn=b(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.resolveSchema=Se.getCompilingSchema=Se.resolveRef=Se.compileSchema=Se.SchemaEnv=void 0;var ke=R(),mh=Sn(),dt=He(),Pe=pr(),fc=N(),hh=gr(),Mt=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Pe.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Se.SchemaEnv=Mt;function yo(t){let e=pc.call(this,t);if(e)return e;let r=(0,Pe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ke.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),c;t.$async&&(c=i.scopeValue("Error",{ref:mh.default,code:(0,ke._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:dt.default.data,parentData:dt.default.parentData,parentDataProperty:dt.default.parentDataProperty,dataNames:[dt.default.data],dataPathArr:[ke.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ke.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:c,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ke.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ke._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,hh.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();d=`${i.scopeRefs(dt.default.scope)}return ${f}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let m=new Function(`${dt.default.self}`,`${dt.default.scope}`,d)(this,this.scope.get());if(this.scope.value(l,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;m.evaluated={props:h instanceof ke.Name?void 0:h,items:g instanceof ke.Name?void 0:g,dynamicProps:h instanceof ke.Name,dynamicItems:g instanceof ke.Name},m.source&&(m.source.evaluated=(0,ke.stringify)(m.evaluated))}return t.validate=m,t}catch(f){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),f}finally{this._compilations.delete(t)}}Se.compileSchema=yo;function gh(t,e,r){var n;r=(0,Pe.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=Sh.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;i&&(o=new Mt({schema:i,schemaId:c,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=yh.call(this,o)}Se.resolveRef=gh;function yh(t){return(0,Pe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:yo.call(this,t)}function pc(t){for(let e of this._compilations)if(_h(e,t))return e}Se.getCompilingSchema=pc;function _h(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Sh(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||En.call(this,t,e)}function En(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pe._getFullPath)(this.opts.uriResolver,r),s=(0,Pe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return go.call(this,r,t);let o=(0,Pe.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let c=En.call(this,t,i);return typeof c?.schema!="object"?void 0:go.call(this,r,c)}if(typeof i?.schema=="object"){if(i.validate||yo.call(this,i),o===(0,Pe.normalizeId)(e)){let{schema:c}=i,{schemaId:l}=this.opts,u=c[l];return u&&(s=(0,Pe.resolveUrl)(this.opts.uriResolver,s,u)),new Mt({schema:c,schemaId:l,root:t,baseId:s})}return go.call(this,r,i)}}Se.resolveSchema=En;var Eh=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function go(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let c of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,fc.unescapeFragment)(c)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!Eh.has(c)&&u&&(e=(0,Pe.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,fc.schemaHasRulesButRef)(r,this.RULES)){let c=(0,Pe.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=En.call(this,n,c)}let{schemaId:i}=this.opts;if(o=o||new Mt({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var mc=b((vv,wh)=>{wh.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var So=b((kv,_c)=>{"use strict";var bh=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),gc=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function _o(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var vh=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function hc(t){return t.length=0,!0}function kh(t,e,r){if(t.length){let n=_o(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Ph(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,c=kh;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!c(s,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!c(s,n,r))break;c=hc}else{s.push(u);continue}}return s.length&&(c===hc?r.zone=s.join(""):i?n.push(s.join("")):n.push(_o(s))),r.address=n.join(""),r}function yc(t){if(Th(t,":")<2)return{host:t,isIPV6:!1};let e=Ph(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Th(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function $h(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function Rh(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function Mh(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!gc(r)){let n=yc(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}_c.exports={nonSimpleDomain:vh,recomposeAuthority:Mh,normalizeComponentEncoding:Rh,removeDotSegments:$h,isIPv4:gc,isUUID:bh,normalizeIPv6:yc,stringArrayToHexStripped:_o}});var vc=b((Pv,bc)=>{"use strict";var{isUUID:Ah}=So(),Oh=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Ch=["http","https","ws","wss","urn","urn:uuid"];function Ih(t){return Ch.indexOf(t)!==-1}function Eo(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Sc(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Ec(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function xh(t){return t.secure=Eo(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Dh(t){if((t.port===(Eo(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Nh(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Oh);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=wo(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function zh(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=wo(s);o&&(t=o.serialize(t,e));let i=t,c=t.nss;return i.path=`${n||e.nid}:${c}`,e.skipEscape=!0,i}function Lh(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Ah(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function jh(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var wc={scheme:"http",domainHost:!0,parse:Sc,serialize:Ec},qh={scheme:"https",domainHost:wc.domainHost,parse:Sc,serialize:Ec},bn={scheme:"ws",domainHost:!0,parse:xh,serialize:Dh},Uh={scheme:"wss",domainHost:bn.domainHost,parse:bn.parse,serialize:bn.serialize},Fh={scheme:"urn",parse:Nh,serialize:zh,skipNormalize:!0},Hh={scheme:"urn:uuid",parse:Lh,serialize:jh,skipNormalize:!0},vn={http:wc,https:qh,ws:bn,wss:Uh,urn:Fh,"urn:uuid":Hh};Object.setPrototypeOf(vn,null);function wo(t){return t&&(vn[t]||vn[t.toLowerCase()])||void 0}bc.exports={wsIsSecure:Eo,SCHEMES:vn,isValidSchemeName:Ih,getSchemeHandler:wo}});var Tc=b((Tv,Pn)=>{"use strict";var{normalizeIPv6:Wh,removeDotSegments:_r,recomposeAuthority:Vh,normalizeComponentEncoding:kn,isIPv4:Gh,nonSimpleDomain:Kh}=So(),{SCHEMES:Yh,getSchemeHandler:kc}=vc();function Bh(t,e){return typeof t=="string"?t=Oe(Ve(t,e),e):typeof t=="object"&&(t=Ve(Oe(t,e),e)),t}function Jh(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Pc(Ve(t,n),Ve(e,n),n,!0);return n.skipEscape=!0,Oe(s,n)}function Pc(t,e,r,n){let s={};return n||(t=Ve(Oe(t,r),r),e=Ve(Oe(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=_r(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=_r(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=_r(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=_r(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function Zh(t,e,r){return typeof t=="string"?(t=unescape(t),t=Oe(kn(Ve(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Oe(kn(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Oe(kn(Ve(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Oe(kn(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Oe(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],o=kc(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=Vh(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(c=_r(c)),i===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),s.push(c)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var Xh=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ve(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(Xh);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(Gh(n.host)===!1){let l=Wh(n.host);n.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=kc(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&Kh(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(c){n.error=n.error||"Host's domain name can not be converted to ASCII: "+c}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var bo={SCHEMES:Yh,normalize:Bh,resolve:Jh,resolveComponent:Pc,equal:Zh,serialize:Oe,parse:Ve};Pn.exports=bo;Pn.exports.default=bo;Pn.exports.fastUri=bo});var Rc=b(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});var $c=Tc();$c.code='require("ajv/dist/runtime/uri").default';vo.default=$c});var Nc=b(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.CodeGen=B.Name=B.nil=B.stringify=B.str=B._=B.KeywordCxt=void 0;var Qh=gr();Object.defineProperty(B,"KeywordCxt",{enumerable:!0,get:function(){return Qh.KeywordCxt}});var At=R();Object.defineProperty(B,"_",{enumerable:!0,get:function(){return At._}});Object.defineProperty(B,"str",{enumerable:!0,get:function(){return At.str}});Object.defineProperty(B,"stringify",{enumerable:!0,get:function(){return At.stringify}});Object.defineProperty(B,"nil",{enumerable:!0,get:function(){return At.nil}});Object.defineProperty(B,"Name",{enumerable:!0,get:function(){return At.Name}});Object.defineProperty(B,"CodeGen",{enumerable:!0,get:function(){return At.CodeGen}});var eg=Sn(),Ic=yr(),tg=Zs(),Sr=wn(),rg=R(),Er=pr(),Tn=fr(),Po=N(),Mc=mc(),ng=Rc(),xc=(t,e)=>new RegExp(t,e);xc.code="new RegExp";var sg=["removeAdditional","useDefaults","coerceTypes"],og=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),ig={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},ag={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ac=200;function cg(t){var e,r,n,s,o,i,c,l,u,d,f,p,m,h,g,_,E,S,w,A,k,le,fe,Wt,yt;let W=t.strict,Ge=(e=t.code)===null||e===void 0?void 0:e.optimize,be=Ge===!0||Ge===void 0?1:Ge||0,Vt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:xc,nd=(s=t.uriResolver)!==null&&s!==void 0?s:ng.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:W)!==null&&i!==void 0?i:!0,strictNumbers:(l=(c=t.strictNumbers)!==null&&c!==void 0?c:W)!==null&&l!==void 0?l:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:W)!==null&&d!==void 0?d:"log",strictTuples:(p=(f=t.strictTuples)!==null&&f!==void 0?f:W)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:W)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:be,regExp:Vt}:{optimize:be,regExp:Vt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Ac,loopEnum:(_=t.loopEnum)!==null&&_!==void 0?_:Ac,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(A=t.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(le=t.validateSchema)!==null&&le!==void 0?le:!0,validateFormats:(fe=t.validateFormats)!==null&&fe!==void 0?fe:!0,unicodeRegExp:(Wt=t.unicodeRegExp)!==null&&Wt!==void 0?Wt:!0,int32range:(yt=t.int32range)!==null&&yt!==void 0?yt:!0,uriResolver:nd}}var wr=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...cg(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new rg.ValueScope({scope:{},prefixes:og,es5:r,lines:n}),this.logger=mg(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,tg.getRules)(),Oc.call(this,ig,e,"NOT SUPPORTED"),Oc.call(this,ag,e,"DEPRECATED","warn"),this._metaOpts=fg.call(this),e.formats&&ug.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&dg.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),lg.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Mc;n==="id"&&(s={...Mc},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,f){await o.call(this,d.$schema);let p=this._addSchema(d,f);return p.validate||i.call(this,p)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(f){if(!(f instanceof Ic.default))throw f;return c.call(this,f),await l.call(this,f.missingSchema),i.call(this,d)}}function c({missingSchema:d,missingRef:f}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${f} cannot be resolved`)}async function l(d){let f=await u.call(this,d);this.refs[d]||await o.call(this,f.$schema),this.refs[d]||this.addSchema(f,d,r)}async function u(d){let f=this._loading[d];if(f)return f;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Er.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=Cc.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Sr.SchemaEnv({schema:{},schemaId:n});if(r=Sr.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Cc.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Er.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(gg.call(this,n,r),!r)return(0,Po.eachItem)(n,o=>ko.call(this,o)),this;_g.call(this,r);let s={...r,type:(0,Tn.getJSONTypes)(r.type),schemaType:(0,Tn.getJSONTypes)(r.schemaType)};return(0,Po.eachItem)(n,s.type.length===0?o=>ko.call(this,o,s):o=>s.type.forEach(i=>ko.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let c of o)i=i[c];for(let c in n){let l=n[c];if(typeof l!="object")continue;let{$data:u}=l.definition,d=i[c];u&&d&&(i[c]=Dc(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:c}=this.opts;if(typeof e=="object")i=e[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,Er.normalizeId)(i||n);let u=Er.getSchemaRefs.call(this,e,n);return l=new Sr.SchemaEnv({schema:e,schemaId:c,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),s&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Sr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Sr.compileSchema.call(this,e)}finally{this.opts=r}}};wr.ValidationError=eg.default;wr.MissingRefError=Ic.default;B.default=wr;function Oc(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function Cc(t){return t=(0,Er.normalizeId)(t),this.schemas[t]||this.refs[t]}function lg(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function ug(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function dg(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function fg(){let t={...this.opts};for(let e of sg)delete t[e];return t}var pg={log(){},warn(){},error(){}};function mg(t){if(t===!1)return pg;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var hg=/^[a-z_$][a-z0-9_$:-]*$/i;function gg(t,e){let{RULES:r}=this;if((0,Po.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!hg.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function ko(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let c={keyword:t,definition:{...e,type:(0,Tn.getJSONTypes)(e.type),schemaType:(0,Tn.getJSONTypes)(e.schemaType)}};e.before?yg.call(this,i,c,e.before):i.rules.push(c),o.all[t]=c,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function yg(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function _g(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Dc(e)),t.validateSchema=this.compile(e,!0))}var Sg={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Dc(t){return{anyOf:[t,Sg]}}});var zc=b(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var Eg={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};To.default=Eg});var Uc=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.callRef=ft.getValidate=void 0;var wg=yr(),Lc=_e(),ae=R(),Ot=He(),jc=wn(),$n=N(),bg={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:c,self:l}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return f();let d=jc.resolveRef.call(l,u,s,r);if(d===void 0)throw new wg.default(n.opts.uriResolver,s,r);if(d instanceof jc.SchemaEnv)return p(d);return m(d);function f(){if(o===u)return Rn(t,i,o,o.$async);let h=e.scopeValue("root",{ref:u});return Rn(t,(0,ae._)`${h}.validate`,u,u.$async)}function p(h){let g=qc(t,h);Rn(t,g,h,h.$async)}function m(h){let g=e.scopeValue("schema",c.code.source===!0?{ref:h,code:(0,ae.stringify)(h)}:{ref:h}),_=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:ae.nil,topSchemaRef:g,errSchemaPath:r},_);t.mergeEvaluated(E),t.ok(_)}}};function qc(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ae._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ft.getValidate=qc;function Rn(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:c,opts:l}=o,u=l.passContext?Ot.default.this:ae.nil;n?d():f();function d(){if(!c.$async)throw new Error("async schema referenced by sync schema");let h=s.let("valid");s.try(()=>{s.code((0,ae._)`await ${(0,Lc.callValidateCode)(t,e,u)}`),m(e),i||s.assign(h,!0)},g=>{s.if((0,ae._)`!(${g} instanceof ${o.ValidationError})`,()=>s.throw(g)),p(g),i||s.assign(h,!1)}),t.ok(h)}function f(){t.result((0,Lc.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(h){let g=(0,ae._)`${h}.errors`;s.assign(Ot.default.vErrors,(0,ae._)`${Ot.default.vErrors} === null ? ${g} : ${Ot.default.vErrors}.concat(${g})`),s.assign(Ot.default.errors,(0,ae._)`${Ot.default.vErrors}.length`)}function m(h){var g;if(!o.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(o.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(o.props=$n.mergeEvaluated.props(s,_.props,o.props));else{let E=s.var("props",(0,ae._)`${h}.evaluated.props`);o.props=$n.mergeEvaluated.props(s,E,o.props,ae.Name)}if(o.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(o.items=$n.mergeEvaluated.items(s,_.items,o.items));else{let E=s.var("items",(0,ae._)`${h}.evaluated.items`);o.items=$n.mergeEvaluated.items(s,E,o.items,ae.Name)}}}ft.callRef=Rn;ft.default=bg});var Fc=b($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var vg=zc(),kg=Uc(),Pg=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",vg.default,kg.default];$o.default=Pg});var Hc=b(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});var Mn=R(),rt=Mn.operators,An={maximum:{okStr:"<=",ok:rt.LTE,fail:rt.GT},minimum:{okStr:">=",ok:rt.GTE,fail:rt.LT},exclusiveMaximum:{okStr:"<",ok:rt.LT,fail:rt.GTE},exclusiveMinimum:{okStr:">",ok:rt.GT,fail:rt.LTE}},Tg={message:({keyword:t,schemaCode:e})=>(0,Mn.str)`must be ${An[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Mn._)`{comparison: ${An[t].okStr}, limit: ${e}}`},$g={keyword:Object.keys(An),type:"number",schemaType:"number",$data:!0,error:Tg,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Mn._)`${r} ${An[e].fail} ${n} || isNaN(${r})`)}};Ro.default=$g});var Wc=b(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var br=R(),Rg={message:({schemaCode:t})=>(0,br.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,br._)`{multipleOf: ${t}}`},Mg={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Rg,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),c=o?(0,br._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,br._)`${i} !== parseInt(${i})`;t.fail$data((0,br._)`(${n} === 0 || (${i} = ${r}/${n}, ${c}))`)}};Mo.default=Mg});var Gc=b(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});function Vc(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}Ao.default=Vc;Vc.code='require("ajv/dist/runtime/ucs2length").default'});var Kc=b(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var pt=R(),Ag=N(),Og=Gc(),Cg={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,pt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,pt._)`{limit: ${t}}`},Ig={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Cg,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?pt.operators.GT:pt.operators.LT,i=s.opts.unicode===!1?(0,pt._)`${r}.length`:(0,pt._)`${(0,Ag.useFunc)(t.gen,Og.default)}(${r})`;t.fail$data((0,pt._)`${i} ${o} ${n}`)}};Oo.default=Ig});var Yc=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var xg=_e(),On=R(),Dg={message:({schemaCode:t})=>(0,On.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,On._)`{pattern: ${t}}`},Ng={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Dg,code(t){let{data:e,$data:r,schema:n,schemaCode:s,it:o}=t,i=o.opts.unicodeRegExp?"u":"",c=r?(0,On._)`(new RegExp(${s}, ${i}))`:(0,xg.usePattern)(t,n);t.fail$data((0,On._)`!${c}.test(${e})`)}};Co.default=Ng});var Bc=b(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var vr=R(),zg={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,vr.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,vr._)`{limit: ${t}}`},Lg={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:zg,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?vr.operators.GT:vr.operators.LT;t.fail$data((0,vr._)`Object.keys(${r}).length ${s} ${n}`)}};Io.default=Lg});var Jc=b(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var kr=_e(),Pr=R(),jg=N(),qg={message:({params:{missingProperty:t}})=>(0,Pr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Pr._)`{missingProperty: ${t}}`},Ug={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qg,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:c}=i;if(!o&&r.length===0)return;let l=r.length>=c.loopRequired;if(i.allErrors?u():d(),c.strictRequired){let m=t.parentSchema.properties,{definedProperties:h}=t.it;for(let g of r)if(m?.[g]===void 0&&!h.has(g)){let _=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,jg.checkStrictMode)(i,E,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(Pr.nil,f);else for(let m of r)(0,kr.checkReportMissingProp)(t,m)}function d(){let m=e.let("missing");if(l||o){let h=e.let("valid",!0);t.block$data(h,()=>p(m,h)),t.ok(h)}else e.if((0,kr.checkMissingProp)(t,r,m)),(0,kr.reportMissingProp)(t,m),e.else()}function f(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,kr.noPropertyInData)(e,s,m,c.ownProperties),()=>t.error())})}function p(m,h){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(h,(0,kr.propertyInData)(e,s,m,c.ownProperties)),e.if((0,Pr.not)(h),()=>{t.error(),e.break()})},Pr.nil)}}};xo.default=Ug});var Zc=b(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});var Tr=R(),Fg={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Tr.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Tr._)`{limit: ${t}}`},Hg={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Fg,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Tr.operators.GT:Tr.operators.LT;t.fail$data((0,Tr._)`${r}.length ${s} ${n}`)}};Do.default=Hg});var Cn=b(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});var Xc=oo();Xc.code='require("ajv/dist/runtime/equal").default';No.default=Xc});var Qc=b(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});var zo=fr(),J=R(),Wg=N(),Vg=Cn(),Gg={message:({params:{i:t,j:e}})=>(0,J.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,J._)`{i: ${t}, j: ${e}}`},Kg={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Gg,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:c}=t;if(!n&&!s)return;let l=e.let("valid"),u=o.items?(0,zo.getSchemaTypes)(o.items):[];t.block$data(l,d,(0,J._)`${i} === false`),t.ok(l);function d(){let h=e.let("i",(0,J._)`${r}.length`),g=e.let("j");t.setParams({i:h,j:g}),e.assign(l,!0),e.if((0,J._)`${h} > 1`,()=>(f()?p:m)(h,g))}function f(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let _=e.name("item"),E=(0,zo.checkDataTypes)(u,_,c.opts.strictNumbers,zo.DataType.Wrong),S=e.const("indices",(0,J._)`{}`);e.for((0,J._)`;${h}--;`,()=>{e.let(_,(0,J._)`${r}[${h}]`),e.if(E,(0,J._)`continue`),u.length>1&&e.if((0,J._)`typeof ${_} == "string"`,(0,J._)`${_} += "_"`),e.if((0,J._)`typeof ${S}[${_}] == "number"`,()=>{e.assign(g,(0,J._)`${S}[${_}]`),t.error(),e.assign(l,!1).break()}).code((0,J._)`${S}[${_}] = ${h}`)})}function m(h,g){let _=(0,Wg.useFunc)(e,Vg.default),E=e.name("outer");e.label(E).for((0,J._)`;${h}--;`,()=>e.for((0,J._)`${g} = ${h}; ${g}--;`,()=>e.if((0,J._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{t.error(),e.assign(l,!1).break(E)})))}}};Lo.default=Kg});var el=b(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});var jo=R(),Yg=N(),Bg=Cn(),Jg={message:"must be equal to constant",params:({schemaCode:t})=>(0,jo._)`{allowedValue: ${t}}`},Zg={keyword:"const",$data:!0,error:Jg,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,jo._)`!${(0,Yg.useFunc)(e,Bg.default)}(${r}, ${s})`):t.fail((0,jo._)`${o} !== ${r}`)}};qo.default=Zg});var tl=b(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});var $r=R(),Xg=N(),Qg=Cn(),ey={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,$r._)`{allowedValues: ${t}}`},ty={keyword:"enum",schemaType:"array",$data:!0,error:ey,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let c=s.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,Xg.useFunc)(e,Qg.default)),d;if(c||n)d=e.let("valid"),t.block$data(d,f);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let m=e.const("vSchema",o);d=(0,$r.or)(...s.map((h,g)=>p(m,g)))}t.pass(d);function f(){e.assign(d,!1),e.forOf("v",o,m=>e.if((0,$r._)`${u()}(${r}, ${m})`,()=>e.assign(d,!0).break()))}function p(m,h){let g=s[h];return typeof g=="object"&&g!==null?(0,$r._)`${u()}(${r}, ${m}[${h}])`:(0,$r._)`${r} === ${g}`}}};Uo.default=ty});var rl=b(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});var ry=Hc(),ny=Wc(),sy=Kc(),oy=Yc(),iy=Bc(),ay=Jc(),cy=Zc(),ly=Qc(),uy=el(),dy=tl(),fy=[ry.default,ny.default,sy.default,oy.default,iy.default,ay.default,cy.default,ly.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uy.default,dy.default];Fo.default=fy});var Wo=b(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.validateAdditionalItems=void 0;var mt=R(),Ho=N(),py={message:({params:{len:t}})=>(0,mt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,mt._)`{limit: ${t}}`},my={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:py,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ho.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}nl(t,n)}};function nl(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let c=r.const("len",(0,mt._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,mt._)`${c} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ho.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,mt._)`${c} <= ${e.length}`);r.if((0,mt.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,c,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:Ho.Type.Num},u),i.allErrors||r.if((0,mt.not)(u),()=>r.break())})}}Rr.validateAdditionalItems=nl;Rr.default=my});var Vo=b(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.validateTuple=void 0;var sl=R(),In=N(),hy=_e(),gy={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ol(t,"additionalItems",e);r.items=!0,!(0,In.alwaysValidSchema)(r,e)&&t.ok((0,hy.validateArray)(t))}};function ol(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:c}=t;d(s),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=In.mergeEvaluated.items(n,r.length,c.items));let l=n.name("valid"),u=n.const("len",(0,sl._)`${o}.length`);r.forEach((f,p)=>{(0,In.alwaysValidSchema)(c,f)||(n.if((0,sl._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},l)),t.ok(l))});function d(f){let{opts:p,errSchemaPath:m}=c,h=r.length,g=h===f.minItems&&(h===f.maxItems||f[e]===!1);if(p.strictTuples&&!g){let _=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,In.checkStrictMode)(c,_,p.strictTuples)}}}Mr.validateTuple=ol;Mr.default=gy});var il=b(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});var yy=Vo(),_y={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,yy.validateTuple)(t,"items")};Go.default=_y});var cl=b(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});var al=R(),Sy=N(),Ey=_e(),wy=Wo(),by={message:({params:{len:t}})=>(0,al.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,al._)`{limit: ${t}}`},vy={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:by,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Sy.alwaysValidSchema)(n,e)&&(s?(0,wy.validateAdditionalItems)(t,s):t.ok((0,Ey.validateArray)(t)))}};Ko.default=vy});var ll=b(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var Ee=R(),xn=N(),ky={message:({params:{min:t,max:e}})=>e===void 0?(0,Ee.str)`must contain at least ${t} valid item(s)`:(0,Ee.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ee._)`{minContains: ${t}}`:(0,Ee._)`{minContains: ${t}, maxContains: ${e}}`},Py={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ky,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,c,{minContains:l,maxContains:u}=n;o.opts.next?(i=l===void 0?1:l,c=u):i=1;let d=e.const("len",(0,Ee._)`${s}.length`);if(t.setParams({min:i,max:c}),c===void 0&&i===0){(0,xn.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&i>c){(0,xn.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xn.alwaysValidSchema)(o,r)){let g=(0,Ee._)`${d} >= ${i}`;c!==void 0&&(g=(0,Ee._)`${g} && ${d} <= ${c}`),t.pass(g);return}o.items=!0;let f=e.name("valid");c===void 0&&i===1?m(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),c!==void 0&&e.if((0,Ee._)`${s}.length > 0`,p)):(e.let(f,!1),p()),t.result(f,()=>t.reset());function p(){let g=e.name("_valid"),_=e.let("count",0);m(g,()=>e.if(g,()=>h(_)))}function m(g,_){e.forRange("i",0,d,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:xn.Type.Num,compositeRule:!0},g),_()})}function h(g){e.code((0,Ee._)`${g}++`),c===void 0?e.if((0,Ee._)`${g} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,Ee._)`${g} > ${c}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,Ee._)`${g} >= ${i}`,()=>e.assign(f,!0)))}}};Yo.default=Py});var fl=b(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.validateSchemaDeps=Ce.validatePropertyDeps=Ce.error=void 0;var Bo=R(),Ty=N(),Ar=_e();Ce.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Bo.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Bo._)`{property: ${t},
|
|
missingProperty: ${n},
|
|
depsCount: ${e},
|
|
deps: ${r}}`};var $y={keyword:"dependencies",type:"object",schemaType:"object",error:Ce.error,code(t){let[e,r]=Ry(t);ul(t,e),dl(t,r)}};function Ry({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function ul(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let c=e[i];if(c.length===0)continue;let l=(0,Ar.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:c.length,deps:c.join(", ")}),s.allErrors?r.if(l,()=>{for(let u of c)(0,Ar.checkReportMissingProp)(t,u)}):(r.if((0,Bo._)`${l} && (${(0,Ar.checkMissingProp)(t,c,o)})`),(0,Ar.reportMissingProp)(t,o),r.else())}}Ce.validatePropertyDeps=ul;function dl(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let c in e)(0,Ty.alwaysValidSchema)(o,e[c])||(r.if((0,Ar.propertyInData)(r,n,c,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:c},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}Ce.validateSchemaDeps=dl;Ce.default=$y});var ml=b(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});var pl=R(),My=N(),Ay={message:"property name must be valid",params:({params:t})=>(0,pl._)`{propertyName: ${t.propertyName}}`},Oy={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Ay,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,My.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,pl.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Jo.default=Oy});var Xo=b(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});var Dn=_e(),Te=R(),Cy=He(),Nn=N(),Iy={message:"must NOT have additional properties",params:({params:t})=>(0,Te._)`{additionalProperty: ${t.additionalProperty}}`},xy={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Iy,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:c,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Nn.alwaysValidSchema)(i,r))return;let u=(0,Dn.allSchemaProperties)(n.properties),d=(0,Dn.allSchemaProperties)(n.patternProperties);f(),t.ok((0,Te._)`${o} === ${Cy.default.errors}`);function f(){e.forIn("key",s,_=>{!u.length&&!d.length?h(_):e.if(p(_),()=>h(_))})}function p(_){let E;if(u.length>8){let S=(0,Nn.schemaRefOrVal)(i,n.properties,"properties");E=(0,Dn.isOwnProperty)(e,S,_)}else u.length?E=(0,Te.or)(...u.map(S=>(0,Te._)`${_} === ${S}`)):E=Te.nil;return d.length&&(E=(0,Te.or)(E,...d.map(S=>(0,Te._)`${(0,Dn.usePattern)(t,S)}.test(${_})`))),(0,Te.not)(E)}function m(_){e.code((0,Te._)`delete ${s}[${_}]`)}function h(_){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){m(_);return}if(r===!1){t.setParams({additionalProperty:_}),t.error(),c||e.break();return}if(typeof r=="object"&&!(0,Nn.alwaysValidSchema)(i,r)){let E=e.name("valid");l.removeAdditional==="failing"?(g(_,E,!1),e.if((0,Te.not)(E),()=>{t.reset(),m(_)})):(g(_,E),c||e.if((0,Te.not)(E),()=>e.break()))}}function g(_,E,S){let w={keyword:"additionalProperties",dataProp:_,dataPropType:Nn.Type.Str};S===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,E)}}};Zo.default=xy});var yl=b(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var Dy=gr(),hl=_e(),Qo=N(),gl=Xo(),Ny={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&gl.default.code(new Dy.KeywordCxt(o,gl.default,"additionalProperties"));let i=(0,hl.allSchemaProperties)(r);for(let f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Qo.mergeEvaluated.props(e,(0,Qo.toHash)(i),o.props));let c=i.filter(f=>!(0,Qo.alwaysValidSchema)(o,r[f]));if(c.length===0)return;let l=e.name("valid");for(let f of c)u(f)?d(f):(e.if((0,hl.propertyInData)(e,s,f,o.opts.ownProperties)),d(f),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function u(f){return o.opts.useDefaults&&!o.compositeRule&&r[f].default!==void 0}function d(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};ei.default=Ny});var wl=b(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var _l=_e(),zn=R(),Sl=N(),El=N(),zy={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,c=(0,_l.allSchemaProperties)(r),l=c.filter(g=>(0,Sl.alwaysValidSchema)(o,r[g]));if(c.length===0||l.length===c.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof zn.Name)&&(o.props=(0,El.evaluatedPropsToName)(e,o.props));let{props:f}=o;p();function p(){for(let g of c)u&&m(g),o.allErrors?h(g):(e.var(d,!0),h(g),e.if(d))}function m(g){for(let _ in u)new RegExp(g).test(_)&&(0,Sl.checkStrictMode)(o,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",n,_=>{e.if((0,zn._)`${(0,_l.usePattern)(t,g)}.test(${_})`,()=>{let E=l.includes(g);E||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:El.Type.Str},d),o.opts.unevaluated&&f!==!0?e.assign((0,zn._)`${f}[${_}]`,!0):!E&&!o.allErrors&&e.if((0,zn.not)(d),()=>e.break())})})}}};ti.default=zy});var bl=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var Ly=N(),jy={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Ly.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};ri.default=jy});var vl=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});var qy=_e(),Uy={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:qy.validateUnion,error:{message:"must match a schema in anyOf"}};ni.default=Uy});var kl=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});var Ln=R(),Fy=N(),Hy={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ln._)`{passingSchemas: ${t.passing}}`},Wy={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Hy,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),c=e.let("passing",null),l=e.name("_valid");t.setParams({passing:c}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((d,f)=>{let p;(0,Fy.alwaysValidSchema)(s,d)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,Ln._)`${l} && ${i}`).assign(i,!1).assign(c,(0,Ln._)`[${c}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(c,f),p&&t.mergeEvaluated(p,Ln.Name)})})}}};si.default=Wy});var Pl=b(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var Vy=N(),Gy={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,Vy.alwaysValidSchema)(n,o))return;let c=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(c)})}};oi.default=Gy});var Rl=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});var jn=R(),$l=N(),Ky={message:({params:t})=>(0,jn.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,jn._)`{failingKeyword: ${t.ifClause}}`},Yy={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ky,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,$l.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Tl(n,"then"),o=Tl(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),c=e.name("_valid");if(l(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(c,u("then",d),u("else",d))}else s?e.if(c,u("then")):e.if((0,jn.not)(c),u("else"));t.pass(i,()=>t.error(!0));function l(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);t.mergeEvaluated(d)}function u(d,f){return()=>{let p=t.subschema({keyword:d},c);e.assign(i,c),t.mergeValidEvaluated(p,i),f?e.assign(f,(0,jn._)`${d}`):t.setParams({ifClause:d})}}}};function Tl(t,e){let r=t.schema[e];return r!==void 0&&!(0,$l.alwaysValidSchema)(t,r)}ii.default=Yy});var Ml=b(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});var By=N(),Jy={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,By.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ai.default=Jy});var Al=b(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});var Zy=Wo(),Xy=il(),Qy=Vo(),e_=cl(),t_=ll(),r_=fl(),n_=ml(),s_=Xo(),o_=yl(),i_=wl(),a_=bl(),c_=vl(),l_=kl(),u_=Pl(),d_=Rl(),f_=Ml();function p_(t=!1){let e=[a_.default,c_.default,l_.default,u_.default,d_.default,f_.default,n_.default,s_.default,r_.default,o_.default,i_.default];return t?e.push(Xy.default,e_.default):e.push(Zy.default,Qy.default),e.push(t_.default),e}ci.default=p_});var Ol=b(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});var H=R(),m_={message:({schemaCode:t})=>(0,H.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,H._)`{format: ${t}}`},h_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:m_,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:c}=t,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;s?p():m();function p(){let h=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),g=r.const("fDef",(0,H._)`${h}[${i}]`),_=r.let("fType"),E=r.let("format");r.if((0,H._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,H._)`${g}.type || "string"`).assign(E,(0,H._)`${g}.validate`),()=>r.assign(_,(0,H._)`"string"`).assign(E,g)),t.fail$data((0,H.or)(S(),w()));function S(){return l.strictSchema===!1?H.nil:(0,H._)`${i} && !${E}`}function w(){let A=d.$async?(0,H._)`(${g}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,H._)`${E}(${n})`,k=(0,H._)`(typeof ${E} == "function" ? ${A} : ${E}.test(${n}))`;return(0,H._)`${E} && ${E} !== true && ${_} === ${e} && !${k}`}}function m(){let h=f.formats[o];if(!h){S();return}if(h===!0)return;let[g,_,E]=w(h);g===e&&t.pass(A());function S(){if(l.strictSchema===!1){f.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function w(k){let le=k instanceof RegExp?(0,H.regexpCode)(k):l.code.formats?(0,H._)`${l.code.formats}${(0,H.getProperty)(o)}`:void 0,fe=r.scopeValue("formats",{key:o,ref:k,code:le});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,H._)`${fe}.validate`]:["string",k,fe]}function A(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,H._)`await ${E}(${n})`}return typeof _=="function"?(0,H._)`${E}(${n})`:(0,H._)`${E}.test(${n})`}}}};li.default=h_});var Cl=b(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});var g_=Ol(),y_=[g_.default];ui.default=y_});var Il=b(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.contentVocabulary=Ct.metadataVocabulary=void 0;Ct.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ct.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Dl=b(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var __=Fc(),S_=rl(),E_=Al(),w_=Cl(),xl=Il(),b_=[__.default,S_.default,(0,E_.default)(),w_.default,xl.metadataVocabulary,xl.contentVocabulary];di.default=b_});var zl=b(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.DiscrError=void 0;var Nl;(function(t){t.Tag="tag",t.Mapping="mapping"})(Nl||(qn.DiscrError=Nl={}))});var jl=b(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});var It=R(),fi=zl(),Ll=wn(),v_=yr(),k_=N(),P_={message:({params:{discrError:t,tagName:e}})=>t===fi.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,It._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},T_={keyword:"discriminator",type:"object",schemaType:"object",error:P_,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),u=e.const("tag",(0,It._)`${r}${(0,It.getProperty)(c)}`);e.if((0,It._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:fi.DiscrError.Tag,tag:u,tagName:c})),t.ok(l);function d(){let m=p();e.if(!1);for(let h in m)e.elseIf((0,It._)`${u} === ${h}`),e.assign(l,f(m[h]));e.else(),t.error(!1,{discrError:fi.DiscrError.Mapping,tag:u,tagName:c}),e.endIf()}function f(m){let h=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:m},h);return t.mergeEvaluated(g,It.Name),h}function p(){var m;let h={},g=E(s),_=!0;for(let A=0;A<i.length;A++){let k=i[A];if(k?.$ref&&!(0,k_.schemaHasRulesButRef)(k,o.self.RULES)){let fe=k.$ref;if(k=Ll.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,fe),k instanceof Ll.SchemaEnv&&(k=k.schema),k===void 0)throw new v_.default(o.opts.uriResolver,o.baseId,fe)}let le=(m=k?.properties)===null||m===void 0?void 0:m[c];if(typeof le!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(g||E(k)),S(le,A)}if(!_)throw new Error(`discriminator: "${c}" must be required`);return h;function E({required:A}){return Array.isArray(A)&&A.includes(c)}function S(A,k){if(A.const)w(A.const,k);else if(A.enum)for(let le of A.enum)w(le,k);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function w(A,k){if(typeof A!="string"||A in h)throw new Error(`discriminator: "${c}" values must be unique strings`);h[A]=k}}}};pi.default=T_});var ql=b((mk,$_)=>{$_.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var hi=b((U,mi)=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.MissingRefError=U.ValidationError=U.CodeGen=U.Name=U.nil=U.stringify=U.str=U._=U.KeywordCxt=U.Ajv=void 0;var R_=Nc(),M_=Dl(),A_=jl(),Ul=ql(),O_=["/properties"],Un="http://json-schema.org/draft-07/schema",xt=class extends R_.default{_addVocabularies(){super._addVocabularies(),M_.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(A_.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ul,O_):Ul;this.addMetaSchema(e,Un,!1),this.refs["http://json-schema.org/schema"]=Un}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Un)?Un:void 0)}};U.Ajv=xt;mi.exports=U=xt;mi.exports.Ajv=xt;Object.defineProperty(U,"__esModule",{value:!0});U.default=xt;var C_=gr();Object.defineProperty(U,"KeywordCxt",{enumerable:!0,get:function(){return C_.KeywordCxt}});var Dt=R();Object.defineProperty(U,"_",{enumerable:!0,get:function(){return Dt._}});Object.defineProperty(U,"str",{enumerable:!0,get:function(){return Dt.str}});Object.defineProperty(U,"stringify",{enumerable:!0,get:function(){return Dt.stringify}});Object.defineProperty(U,"nil",{enumerable:!0,get:function(){return Dt.nil}});Object.defineProperty(U,"Name",{enumerable:!0,get:function(){return Dt.Name}});Object.defineProperty(U,"CodeGen",{enumerable:!0,get:function(){return Dt.CodeGen}});var I_=Sn();Object.defineProperty(U,"ValidationError",{enumerable:!0,get:function(){return I_.default}});var x_=yr();Object.defineProperty(U,"MissingRefError",{enumerable:!0,get:function(){return x_.default}})});var Bl=b(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.formatNames=xe.fastFormats=xe.fullFormats=void 0;function Ie(t,e){return{validate:t,compare:e}}xe.fullFormats={date:Ie(Vl,Si),time:Ie(yi(!0),Ei),"date-time":Ie(Fl(!0),Kl),"iso-time":Ie(yi(),Gl),"iso-date-time":Ie(Fl(),Yl),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:q_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:K_,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:U_,int32:{type:"number",validate:W_},int64:{type:"number",validate:V_},float:{type:"number",validate:Wl},double:{type:"number",validate:Wl},password:!0,binary:!0};xe.fastFormats={...xe.fullFormats,date:Ie(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Si),time:Ie(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ei),"date-time":Ie(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Kl),"iso-time":Ie(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Gl),"iso-date-time":Ie(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Yl),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};xe.formatNames=Object.keys(xe.fullFormats);function D_(t){return t%4===0&&(t%100!==0||t%400===0)}var N_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,z_=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Vl(t){let e=N_.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&D_(r)?29:z_[n])}function Si(t,e){if(t&&e)return t>e?1:t<e?-1:0}var gi=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function yi(t){return function(r){let n=gi.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],c=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!c)return!1;if(s<=23&&o<=59&&i<60)return!0;let f=o-d*l,p=s-u*l-(f<0?1:0);return(p===23||p===-1)&&(f===59||f===-1)&&i<61}}function Ei(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Gl(t,e){if(!(t&&e))return;let r=gi.exec(t),n=gi.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var _i=/t|\s/i;function Fl(t){let e=yi(t);return function(n){let s=n.split(_i);return s.length===2&&Vl(s[0])&&e(s[1])}}function Kl(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Yl(t,e){if(!(t&&e))return;let[r,n]=t.split(_i),[s,o]=e.split(_i),i=Si(r,s);if(i!==void 0)return i||Ei(n,o)}var L_=/\/|:/,j_=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function q_(t){return L_.test(t)&&j_.test(t)}var Hl=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function U_(t){return Hl.lastIndex=0,Hl.test(t)}var F_=-(2**31),H_=2**31-1;function W_(t){return Number.isInteger(t)&&t<=H_&&t>=F_}function V_(t){return Number.isInteger(t)}function Wl(){return!0}var G_=/[^\\]\\Z/;function K_(t){if(G_.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Jl=b(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.formatLimitDefinition=void 0;var Y_=hi(),$e=R(),nt=$e.operators,Fn={formatMaximum:{okStr:"<=",ok:nt.LTE,fail:nt.GT},formatMinimum:{okStr:">=",ok:nt.GTE,fail:nt.LT},formatExclusiveMaximum:{okStr:"<",ok:nt.LT,fail:nt.GTE},formatExclusiveMinimum:{okStr:">",ok:nt.GT,fail:nt.LTE}},B_={message:({keyword:t,schemaCode:e})=>(0,$e.str)`should be ${Fn[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$e._)`{comparison: ${Fn[t].okStr}, limit: ${e}}`};Nt.formatLimitDefinition={keyword:Object.keys(Fn),type:"string",schemaType:"string",$data:!0,error:B_,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:c}=o;if(!i.validateFormats)return;let l=new Y_.KeywordCxt(o,c.RULES.all.format.definition,"format");l.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:c.formats,code:i.code.formats}),m=e.const("fmt",(0,$e._)`${p}[${l.schemaCode}]`);t.fail$data((0,$e.or)((0,$e._)`typeof ${m} != "object"`,(0,$e._)`${m} instanceof RegExp`,(0,$e._)`typeof ${m}.compare != "function"`,f(m)))}function d(){let p=l.schema,m=c.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${s}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,$e._)`${i.code.formats}${(0,$e.getProperty)(p)}`:void 0});t.fail$data(f(h))}function f(p){return(0,$e._)`${p}.compare(${r}, ${n}) ${Fn[s].fail} 0`}},dependencies:["format"]};var J_=t=>(t.addKeyword(Nt.formatLimitDefinition),t);Nt.default=J_});var eu=b((Or,Ql)=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});var zt=Bl(),Z_=Jl(),wi=R(),Zl=new wi.Name("fullFormats"),X_=new wi.Name("fastFormats"),bi=(t,e={keywords:!0})=>{if(Array.isArray(e))return Xl(t,e,zt.fullFormats,Zl),t;let[r,n]=e.mode==="fast"?[zt.fastFormats,X_]:[zt.fullFormats,Zl],s=e.formats||zt.formatNames;return Xl(t,s,r,n),e.keywords&&(0,Z_.default)(t),t};bi.get=(t,e="full")=>{let n=(e==="fast"?zt.fastFormats:zt.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Xl(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,wi._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Ql.exports=Or=bi;Object.defineProperty(Or,"__esModule",{value:!0});Or.default=bi});var je=require("fs"),Ji=require("path");var z=require("path"),os=require("os"),is=require("fs");var Ki=require("url");var Sd={};function ud(){return typeof __dirname<"u"?__dirname:(0,z.dirname)((0,Ki.fileURLToPath)(Sd.url))}var sE=ud();function dd(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,z.join)((0,os.homedir)(),".claude-mem"),e=(0,z.join)(t,"settings.json");try{if((0,is.existsSync)(e)){let{readFileSync:r}=require("fs"),n=JSON.parse(r(e,"utf-8")),s=n.env??n;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var F=dd(),Ur=process.env.CLAUDE_CONFIG_DIR||(0,z.join)((0,os.homedir)(),".claude"),Yi=(0,z.join)(Ur,"plugins","marketplaces","thedotmack"),fd=(0,z.join)(F,"archives"),pd=(0,z.join)(F,"logs"),md=(0,z.join)(F,"trash"),hd=(0,z.join)(F,"backups"),gd=(0,z.join)(F,"modes"),yd=(0,z.join)(F,"settings.json"),oE=(0,z.join)(F,"claude-mem.db"),_d=(0,z.join)(F,"vector-db"),Bi=(0,z.join)(F,"observer-sessions"),iE=(0,z.basename)(Bi),aE=(0,z.join)(Ur,"settings.json"),cE=(0,z.join)(Ur,"commands"),lE=(0,z.join)(Ur,"CLAUDE.md");var me={dataDir:()=>F,workerPid:()=>(0,z.join)(F,"worker.pid"),settings:()=>(0,z.join)(F,"settings.json"),database:()=>(0,z.join)(F,"claude-mem.db"),chroma:()=>(0,z.join)(F,"chroma"),combinedCerts:()=>(0,z.join)(F,"combined_certs.pem"),transcriptsConfig:()=>(0,z.join)(F,"transcript-watch.json"),transcriptsState:()=>(0,z.join)(F,"transcript-watch-state.json"),corpora:()=>(0,z.join)(F,"corpora"),supervisorRegistry:()=>(0,z.join)(F,"supervisor.json"),envFile:()=>(0,z.join)(F,".env"),logsDir:()=>pd,archives:()=>fd,trash:()=>md,backups:()=>hd,modes:()=>gd,vectorDb:()=>_d,observerSessions:()=>Bi};var as=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(as||{}),cs=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=me.logsDir();(0,je.existsSync)(e)||(0,je.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Ji.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=me.settings();if((0,je.existsSync)(e)){let r=(0,je.readFileSync)(e,"utf-8"),s=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=as[s]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${s} ${o}:${i}:${c}.${l}`}log(e,r,n,s,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),c=as[e].padEnd(5),l=r.padEnd(6),u="";s?.correlationId?u=`[${s.correlationId}] `:s?.sessionId&&(u=`[session-${s.sessionId}] `);let d="";if(o!=null)if(o instanceof Error)d=this.getLevel()===0?`
|
|
${o.message}
|
|
${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{d=`
|
|
`+JSON.stringify(o,null,2)}catch{d=" "+this.formatData(o)}else d=" "+this.formatData(o);let f="";if(s){let{sessionId:m,memorySessionId:h,correlationId:g,..._}=s;Object.keys(_).length>0&&(f=` {${Object.entries(_).map(([S,w])=>`${S}=${w}`).join(", ")}}`)}let p=`[${i}] [${c}] [${l}] ${u}${n}${f}${d}`;if(this.logFilePath)try{(0,je.appendFileSync)(this.logFilePath,p+`
|
|
`,"utf8")}catch(m){process.stderr.write(`[LOGGER] Failed to write to log file: ${m instanceof Error?m.message:String(m)}
|
|
`)}else process.stderr.write(p+`
|
|
`)}debug(e,r,n,s){this.log(0,e,r,n,s)}info(e,r,n,s){this.log(1,e,r,n,s)}warn(e,r,n,s){this.log(2,e,r,n,s)}error(e,r,n,s){this.log(3,e,r,n,s)}dataIn(e,r,n,s){this.info(e,`\u2192 ${r}`,n,s)}dataOut(e,r,n,s){this.info(e,`\u2190 ${r}`,n,s)}success(e,r,n,s){this.info(e,`\u2713 ${r}`,n,s)}failure(e,r,n,s){this.error(e,`\u2717 ${r}`,n,s)}timing(e,r,n,s){this.info(e,`\u23F1 ${r}`,s,{duration:`${n}ms`})}happyPathError(e,r,n,s,o=""){let u=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),d=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",f={...n,location:d};return this.warn(e,`[HAPPY-PATH] ${r}`,f,s),o}},y=new cs;var Ed=pe(require("zod/v3"),1),Fr=pe(require("zod/v4-mini"),1);function _t(t){return!!t._zod}function Ke(t,e){return _t(t)?Fr.safeParse(t,e):t.safeParse(e)}function Hr(t){if(!t)return;let e;if(_t(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Zi(t){if(_t(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var a=pe(require("zod/v4"),1),us="2025-11-25";var Xi=[us,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ye="io.modelcontextprotocol/related-task",Vr="2.0",V=a.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Qi=a.union([a.string(),a.number().int()]),ea=a.string(),mE=a.looseObject({ttl:a.union([a.number(),a.null()]).optional(),pollInterval:a.number().optional()}),wd=a.object({ttl:a.number().optional()}),bd=a.object({taskId:a.string()}),ds=a.looseObject({progressToken:Qi.optional(),[Ye]:bd.optional()}),ue=a.object({_meta:ds.optional()}),Gt=ue.extend({task:wd.optional()}),ta=t=>Gt.safeParse(t).success,G=a.object({method:a.string(),params:ue.loose().optional()}),he=a.object({_meta:ds.optional()}),ge=a.object({method:a.string(),params:he.loose().optional()}),K=a.looseObject({_meta:ds.optional()}),Gr=a.union([a.string(),a.number().int()]),ra=a.object({jsonrpc:a.literal(Vr),id:Gr,...G.shape}).strict(),fs=t=>ra.safeParse(t).success,na=a.object({jsonrpc:a.literal(Vr),...ge.shape}).strict(),sa=t=>na.safeParse(t).success,ps=a.object({jsonrpc:a.literal(Vr),id:Gr,result:K}).strict(),Kt=t=>ps.safeParse(t).success;var C;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(C||(C={}));var ms=a.object({jsonrpc:a.literal(Vr),id:Gr.optional(),error:a.object({code:a.number().int(),message:a.string(),data:a.unknown().optional()})}).strict();var oa=t=>ms.safeParse(t).success;var ia=a.union([ra,na,ps,ms]),hE=a.union([ps,ms]),Kr=K.strict(),vd=he.extend({requestId:Gr.optional(),reason:a.string().optional()}),Yr=ge.extend({method:a.literal("notifications/cancelled"),params:vd}),kd=a.object({src:a.string(),mimeType:a.string().optional(),sizes:a.array(a.string()).optional(),theme:a.enum(["light","dark"]).optional()}),Yt=a.object({icons:a.array(kd).optional()}),St=a.object({name:a.string(),title:a.string().optional()}),aa=St.extend({...St.shape,...Yt.shape,version:a.string(),websiteUrl:a.string().optional(),description:a.string().optional()}),Pd=a.intersection(a.object({applyDefaults:a.boolean().optional()}),a.record(a.string(),a.unknown())),Td=a.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,a.intersection(a.object({form:Pd.optional(),url:V.optional()}),a.record(a.string(),a.unknown()).optional())),$d=a.looseObject({list:V.optional(),cancel:V.optional(),requests:a.looseObject({sampling:a.looseObject({createMessage:V.optional()}).optional(),elicitation:a.looseObject({create:V.optional()}).optional()}).optional()}),Rd=a.looseObject({list:V.optional(),cancel:V.optional(),requests:a.looseObject({tools:a.looseObject({call:V.optional()}).optional()}).optional()}),Md=a.object({experimental:a.record(a.string(),V).optional(),sampling:a.object({context:V.optional(),tools:V.optional()}).optional(),elicitation:Td.optional(),roots:a.object({listChanged:a.boolean().optional()}).optional(),tasks:$d.optional()}),Ad=ue.extend({protocolVersion:a.string(),capabilities:Md,clientInfo:aa}),hs=G.extend({method:a.literal("initialize"),params:Ad});var Od=a.object({experimental:a.record(a.string(),V).optional(),logging:V.optional(),completions:V.optional(),prompts:a.object({listChanged:a.boolean().optional()}).optional(),resources:a.object({subscribe:a.boolean().optional(),listChanged:a.boolean().optional()}).optional(),tools:a.object({listChanged:a.boolean().optional()}).optional(),tasks:Rd.optional()}),Cd=K.extend({protocolVersion:a.string(),capabilities:Od,serverInfo:aa,instructions:a.string().optional()}),gs=ge.extend({method:a.literal("notifications/initialized"),params:he.optional()});var Br=G.extend({method:a.literal("ping"),params:ue.optional()}),Id=a.object({progress:a.number(),total:a.optional(a.number()),message:a.optional(a.string())}),xd=a.object({...he.shape,...Id.shape,progressToken:Qi}),Jr=ge.extend({method:a.literal("notifications/progress"),params:xd}),Dd=ue.extend({cursor:ea.optional()}),Bt=G.extend({params:Dd.optional()}),Jt=K.extend({nextCursor:ea.optional()}),Nd=a.enum(["working","input_required","completed","failed","cancelled"]),Zt=a.object({taskId:a.string(),status:Nd,ttl:a.union([a.number(),a.null()]),createdAt:a.string(),lastUpdatedAt:a.string(),pollInterval:a.optional(a.number()),statusMessage:a.optional(a.string())}),Et=K.extend({task:Zt}),zd=he.merge(Zt),Xt=ge.extend({method:a.literal("notifications/tasks/status"),params:zd}),Zr=G.extend({method:a.literal("tasks/get"),params:ue.extend({taskId:a.string()})}),Xr=K.merge(Zt),Qr=G.extend({method:a.literal("tasks/result"),params:ue.extend({taskId:a.string()})}),gE=K.loose(),en=Bt.extend({method:a.literal("tasks/list")}),tn=Jt.extend({tasks:a.array(Zt)}),rn=G.extend({method:a.literal("tasks/cancel"),params:ue.extend({taskId:a.string()})}),ca=K.merge(Zt),la=a.object({uri:a.string(),mimeType:a.optional(a.string()),_meta:a.record(a.string(),a.unknown()).optional()}),ua=la.extend({text:a.string()}),ys=a.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),da=la.extend({blob:ys}),Qt=a.enum(["user","assistant"]),wt=a.object({audience:a.array(Qt).optional(),priority:a.number().min(0).max(1).optional(),lastModified:a.iso.datetime({offset:!0}).optional()}),fa=a.object({...St.shape,...Yt.shape,uri:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:wt.optional(),_meta:a.optional(a.looseObject({}))}),Ld=a.object({...St.shape,...Yt.shape,uriTemplate:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:wt.optional(),_meta:a.optional(a.looseObject({}))}),jd=Bt.extend({method:a.literal("resources/list")}),qd=Jt.extend({resources:a.array(fa)}),Ud=Bt.extend({method:a.literal("resources/templates/list")}),Fd=Jt.extend({resourceTemplates:a.array(Ld)}),_s=ue.extend({uri:a.string()}),Hd=_s,Wd=G.extend({method:a.literal("resources/read"),params:Hd}),Vd=K.extend({contents:a.array(a.union([ua,da]))}),Gd=ge.extend({method:a.literal("notifications/resources/list_changed"),params:he.optional()}),Kd=_s,Yd=G.extend({method:a.literal("resources/subscribe"),params:Kd}),Bd=_s,Jd=G.extend({method:a.literal("resources/unsubscribe"),params:Bd}),Zd=he.extend({uri:a.string()}),Xd=ge.extend({method:a.literal("notifications/resources/updated"),params:Zd}),Qd=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}),ef=a.object({...St.shape,...Yt.shape,description:a.optional(a.string()),arguments:a.optional(a.array(Qd)),_meta:a.optional(a.looseObject({}))}),tf=Bt.extend({method:a.literal("prompts/list")}),rf=Jt.extend({prompts:a.array(ef)}),nf=ue.extend({name:a.string(),arguments:a.record(a.string(),a.string()).optional()}),sf=G.extend({method:a.literal("prompts/get"),params:nf}),Ss=a.object({type:a.literal("text"),text:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Es=a.object({type:a.literal("image"),data:ys,mimeType:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),ws=a.object({type:a.literal("audio"),data:ys,mimeType:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),of=a.object({type:a.literal("tool_use"),name:a.string(),id:a.string(),input:a.record(a.string(),a.unknown()),_meta:a.record(a.string(),a.unknown()).optional()}),af=a.object({type:a.literal("resource"),resource:a.union([ua,da]),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),cf=fa.extend({type:a.literal("resource_link")}),bs=a.union([Ss,Es,ws,cf,af]),lf=a.object({role:Qt,content:bs}),uf=K.extend({description:a.string().optional(),messages:a.array(lf)}),df=ge.extend({method:a.literal("notifications/prompts/list_changed"),params:he.optional()}),ff=a.object({title:a.string().optional(),readOnlyHint:a.boolean().optional(),destructiveHint:a.boolean().optional(),idempotentHint:a.boolean().optional(),openWorldHint:a.boolean().optional()}),pf=a.object({taskSupport:a.enum(["required","optional","forbidden"]).optional()}),pa=a.object({...St.shape,...Yt.shape,description:a.string().optional(),inputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),V).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()),outputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),V).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()).optional(),annotations:ff.optional(),execution:pf.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),vs=Bt.extend({method:a.literal("tools/list")}),mf=Jt.extend({tools:a.array(pa)}),nn=K.extend({content:a.array(bs).default([]),structuredContent:a.record(a.string(),a.unknown()).optional(),isError:a.boolean().optional()}),yE=nn.or(K.extend({toolResult:a.unknown()})),hf=Gt.extend({name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),er=G.extend({method:a.literal("tools/call"),params:hf}),gf=ge.extend({method:a.literal("notifications/tools/list_changed"),params:he.optional()}),_E=a.object({autoRefresh:a.boolean().default(!0),debounceMs:a.number().int().nonnegative().default(300)}),tr=a.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),yf=ue.extend({level:tr}),ks=G.extend({method:a.literal("logging/setLevel"),params:yf}),_f=he.extend({level:tr,logger:a.string().optional(),data:a.unknown()}),Sf=ge.extend({method:a.literal("notifications/message"),params:_f}),Ef=a.object({name:a.string().optional()}),wf=a.object({hints:a.array(Ef).optional(),costPriority:a.number().min(0).max(1).optional(),speedPriority:a.number().min(0).max(1).optional(),intelligencePriority:a.number().min(0).max(1).optional()}),bf=a.object({mode:a.enum(["auto","required","none"]).optional()}),vf=a.object({type:a.literal("tool_result"),toolUseId:a.string().describe("The unique identifier for the corresponding tool call."),content:a.array(bs).default([]),structuredContent:a.object({}).loose().optional(),isError:a.boolean().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),kf=a.discriminatedUnion("type",[Ss,Es,ws]),Wr=a.discriminatedUnion("type",[Ss,Es,ws,of,vf]),Pf=a.object({role:Qt,content:a.union([Wr,a.array(Wr)]),_meta:a.record(a.string(),a.unknown()).optional()}),Tf=Gt.extend({messages:a.array(Pf),modelPreferences:wf.optional(),systemPrompt:a.string().optional(),includeContext:a.enum(["none","thisServer","allServers"]).optional(),temperature:a.number().optional(),maxTokens:a.number().int(),stopSequences:a.array(a.string()).optional(),metadata:V.optional(),tools:a.array(pa).optional(),toolChoice:bf.optional()}),$f=G.extend({method:a.literal("sampling/createMessage"),params:Tf}),Ps=K.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens"]).or(a.string())),role:Qt,content:kf}),Ts=K.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(a.string())),role:Qt,content:a.union([Wr,a.array(Wr)])}),Rf=a.object({type:a.literal("boolean"),title:a.string().optional(),description:a.string().optional(),default:a.boolean().optional()}),Mf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),minLength:a.number().optional(),maxLength:a.number().optional(),format:a.enum(["email","uri","date","date-time"]).optional(),default:a.string().optional()}),Af=a.object({type:a.enum(["number","integer"]),title:a.string().optional(),description:a.string().optional(),minimum:a.number().optional(),maximum:a.number().optional(),default:a.number().optional()}),Of=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),default:a.string().optional()}),Cf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),oneOf:a.array(a.object({const:a.string(),title:a.string()})),default:a.string().optional()}),If=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),enumNames:a.array(a.string()).optional(),default:a.string().optional()}),xf=a.union([Of,Cf]),Df=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({type:a.literal("string"),enum:a.array(a.string())}),default:a.array(a.string()).optional()}),Nf=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({anyOf:a.array(a.object({const:a.string(),title:a.string()}))}),default:a.array(a.string()).optional()}),zf=a.union([Df,Nf]),Lf=a.union([If,xf,zf]),jf=a.union([Lf,Rf,Mf,Af]),qf=Gt.extend({mode:a.literal("form").optional(),message:a.string(),requestedSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),jf),required:a.array(a.string()).optional()})}),Uf=Gt.extend({mode:a.literal("url"),message:a.string(),elicitationId:a.string(),url:a.string().url()}),Ff=a.union([qf,Uf]),Hf=G.extend({method:a.literal("elicitation/create"),params:Ff}),Wf=he.extend({elicitationId:a.string()}),Vf=ge.extend({method:a.literal("notifications/elicitation/complete"),params:Wf}),sn=K.extend({action:a.enum(["accept","decline","cancel"]),content:a.preprocess(t=>t===null?void 0:t,a.record(a.string(),a.union([a.string(),a.number(),a.boolean(),a.array(a.string())])).optional())}),Gf=a.object({type:a.literal("ref/resource"),uri:a.string()});var Kf=a.object({type:a.literal("ref/prompt"),name:a.string()}),Yf=ue.extend({ref:a.union([Kf,Gf]),argument:a.object({name:a.string(),value:a.string()}),context:a.object({arguments:a.record(a.string(),a.string()).optional()}).optional()}),Bf=G.extend({method:a.literal("completion/complete"),params:Yf});var Jf=K.extend({completion:a.looseObject({values:a.array(a.string()).max(100),total:a.optional(a.number().int()),hasMore:a.optional(a.boolean())})}),Zf=a.object({uri:a.string().startsWith("file://"),name:a.string().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Xf=G.extend({method:a.literal("roots/list"),params:ue.optional()}),$s=K.extend({roots:a.array(Zf)}),Qf=ge.extend({method:a.literal("notifications/roots/list_changed"),params:he.optional()}),SE=a.union([Br,hs,Bf,ks,sf,tf,jd,Ud,Wd,Yd,Jd,er,vs,Zr,Qr,en,rn]),EE=a.union([Yr,Jr,gs,Qf,Xt]),wE=a.union([Kr,Ps,Ts,sn,$s,Xr,tn,Et]),bE=a.union([Br,$f,Hf,Xf,Zr,Qr,en,rn]),vE=a.union([Yr,Jr,Sf,Xd,Gd,gf,df,Xt,Vf]),kE=a.union([Kr,Cd,Jf,uf,rf,qd,Fd,Vd,nn,mf,Xr,tn,Et]),$=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===C.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new ls(s.elicitations,r)}return new t(e,r,n)}},ls=class extends ${constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(C.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Be(t){return t==="completed"||t==="failed"||t==="cancelled"}var cp=pe(require("zod/v4-mini"),1);var ip=require("zod/v3");var tp=require("zod/v3");var sp=require("zod/v3");var nw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Rs(t){let r=Hr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zi(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ms(t,e){let r=Ke(t,e);if(!r.success)throw r.error;return r.data}var lp=6e4,on=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Yr,r=>{this._oncancel(r)}),this.setNotificationHandler(Jr,r=>{this._onprogress(r)}),this.setRequestHandler(Br,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Zr,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new $(C.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Qr,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(c.type==="response"||c.type==="error"){let l=c.message,u=l.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),c.type==="response")d(l);else{let f=l,p=new $(f.error.code,f.error.message,f.error.data);d(p)}else{let f=c.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new $(C.InvalidParams,`Task not found: ${o}`);if(!Be(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Be(i.status)){let c=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[Ye]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(en,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new $(C.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(rn,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new $(C.InvalidParams,`Task not found: ${r.params.taskId}`);if(Be(s.status))throw new $(C.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(C.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof $?s:new $(C.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),$.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),Kt(o)||oa(o)?this._onresponse(o):fs(o)?this._onrequest(o,i):sa(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=$.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Ye]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:C.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):s?.send(d).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let c=ta(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{let f={relatedRequestId:e.id};o&&(f.relatedTask={taskId:o}),await this.notification(d,f)},sendRequest:async(d,f,p)=>{let m={...p,relatedRequestId:e.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});let h=m.relatedTask?.taskId??o;return h&&l&&await l.updateTaskStatus(h,"input_required"),await this.request(d,f,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let f={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},s?.sessionId):await s?.send(f)},async d=>{if(i.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:C.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},s?.sessionId):await s?.send(f)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),c=this._timeoutInfo.get(s);if(c&&i&&c.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Kt(e))n(e);else{let i=new $(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Kt(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let c=i.task;typeof c.taskId=="string"&&(o=!0,this._taskProgressTokens.set(c.taskId,r))}}if(o||this._progressHandlers.delete(r),Kt(e))s(e);else{let i=$.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof $?i:new $(C.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Et,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new $(C.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:c},Be(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:c.status==="failed"?yield{type:"error",error:new $(C.InternalError,`Task ${o} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new $(C.InternalError,`Task ${o} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof $?i:new $(C.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:c,relatedTask:l}=n??{};return new Promise((u,d)=>{let f=S=>{d(S)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),c&&this.assertTaskCapability(e.method)}catch(S){f(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),c&&(m.params={...m.params,task:c}),l&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Ye]:l}});let h=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`)));let w=S instanceof $?S:new $(C.RequestTimeout,String(S));d(w)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return d(S);try{let w=Ke(r,S.result);w.success?u(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??lp,_=()=>h($.fromError(C.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let E=l?.taskId;if(E){let S=w=>{let A=this._responseHandlers.get(p);A?A(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),d(w)})}else this._transport.send(m,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),d(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Xr,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},tn,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ca,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let c={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ye]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let c={...e,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[Ye]:r.relatedTask}}}),this._transport?.send(c,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ye]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Rs(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Ms(e,s);return Promise.resolve(r(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Rs(e);this._notificationHandlers.set(n,s=>{let o=Ms(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&fs(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new $(C.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new $(C.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new $(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new $(C.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let c=await n.getTask(s,r);if(c){let l=Xt.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Be(c.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let c=await n.getTask(s,r);if(!c)throw new $(C.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Be(c.status))throw new $(C.InvalidParams,`Cannot update task "${s}" from terminal status "${c.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let l=await n.getTask(s,r);if(l){let u=Xt.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Be(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function ma(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ha(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];ma(i)&&ma(o)?r[s]={...i,...o}:r[s]=o}return r}var tu=pe(hi(),1),ru=pe(eu(),1);function Q_(){let t=new tu.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ru.default)(t),t}var Hn=class{constructor(e){this._ajv=e??Q_()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Wn=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function nu(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function su(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Vn=class extends on{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(tr.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Hn,this.setRequestHandler(hs,n=>this._oninitialize(n)),this.setNotificationHandler(gs,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ks,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,c=tr.safeParse(i);return c.success&&this._loggingLevels.set(o,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Wn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ha(this._capabilities,e)}setRequestHandler(e,r){let s=Hr(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(_t(s)){let c=s;o=c._zod?.def?.value??c.value}else{let c=s;o=c._def?.value??c.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let c=async(l,u)=>{let d=Ke(er,l);if(!d.success){let h=d.error instanceof Error?d.error.message:String(d.error);throw new $(C.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:f}=d.data,p=await Promise.resolve(r(l,u));if(f.task){let h=Ke(Et,p);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new $(C.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let m=Ke(nn,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new $(C.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,c)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){su(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nu(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Xi.includes(r)?r:us,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Kr)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=i?Array.isArray(i.content)?i.content:[i.content]:[],l=c.some(u=>u.type==="tool_use");if(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ts,r):this.request({method:"sampling/createMessage",params:e},Ps,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},sn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},sn,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!c.valid)throw new $(C.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(i){throw i instanceof $?i:new $(C.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},$s,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var vi=pe(require("node:process"),1);var Gn=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),eS(r)}clear(){this._buffer=void 0}};function eS(t){return ia.parse(JSON.parse(t))}function ou(t){return JSON.stringify(t)+`
|
|
`}var Kn=class{constructor(e=vi.default.stdin,r=vi.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gn,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new 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(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){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(e){return new Promise(r=>{let n=ou(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Oi=pe(require("path"),1);var iu=require("node:child_process");function Yn(t,e,r){return(0,iu.spawn)(t,e??[],{windowsHide:!0,...r})}var ce={DEFAULT:3e5,HEALTH_CHECK:3e3,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function au(t){return process.platform==="win32"?Math.round(t*ce.WINDOWS_MULTIPLIER):t}var De=require("fs"),Cr=require("path"),ki=require("os"),Ne=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Cr.join)((0,ki.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Cr.join)((0,ki.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,De.existsSync)(e)){let i=this.getAllDefaults();try{let c=(0,Cr.dirname)(e);(0,De.existsSync)(c)||(0,De.mkdirSync)(c,{recursive:!0}),(0,De.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return this.applyEnvOverrides(i)}let r=(0,De.readFileSync)(e,"utf-8"),n=JSON.parse(r),s=n;if(n.env&&typeof n.env=="object"){s=n.env;try{(0,De.writeFileSync)(e,JSON.stringify(s,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))s[i]!==void 0&&(o[i]=s[i]);return this.applyEnvOverrides(o)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r instanceof Error?r.message:String(r)),this.applyEnvOverrides(this.getAllDefaults())}}};var ht=require("fs");var cu=require("child_process");var Le=require("fs"),$i=pe(require("path"),1);var tS=["CLAUDECODE_","CLAUDE_CODE_"],rS=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),nS=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),sS=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Pi(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(sS.has(r)){e[r]=n;continue}rS.has(r)||nS.has(r)||tS.some(s=>r.startsWith(s))||(e[r]=n)}return e}var oS=5e3,iS=1e3,aS=me.supervisorRegistry();function ze(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}function lu(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Le.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let s=e.slice(r+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return null;try{let e=(0,cu.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...process.env,LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Mi(t){if(!t||!ze(t.pid))return!1;if(!t.startToken)return!0;let e=lu(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var Ri=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=aS){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Le.mkdirSync)($i.default.dirname(this.registryPath),{recursive:!0}),!(0,Le.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Le.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,o]of Object.entries(n))this.entries.set(s,o)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize(),this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0;for(let[r,n]of this.entries)ze(n.pid)||(this.entries.delete(r),this.runtimeProcesses.delete(r),e+=1);return e>0&&this.persist(),e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;y.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(c=>c.pid)});let s=r.filter(c=>ze(c.pid));for(let c of s)try{typeof c.pgid=="number"&&process.platform!=="win32"?process.kill(-c.pgid,"SIGTERM"):process.kill(c.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},l):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(l)})}let o=Date.now()+oS;for(;Date.now()<o&&s.filter(l=>ze(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let i=s.filter(c=>ze(c.pid));for(let c of i){y.warn("SYSTEM",`Session process PID ${c.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:c.pid,pgid:c.pgid,sessionId:n});try{typeof c.pgid=="number"&&process.platform!=="win32"?process.kill(-c.pgid,"SIGKILL"):process.kill(c.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},l):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(l)})}}if(i.length>0){let c=Date.now()+iS;for(;Date.now()<c&&i.filter(u=>ze(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let c of r)this.entries.delete(c.id),this.runtimeProcesses.delete(c.id);return this.persist(),y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Le.mkdirSync)($i.default.dirname(this.registryPath),{recursive:!0}),(0,Le.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Ti=null;function Bn(){return Ti||(Ti=new Ri),Ti}var fu=require("child_process"),pu=require("fs"),mu=require("util");var cS=(0,mu.promisify)(fu.execFile),lS=me.workerPid();async function hu(t){let e=t.currentPid??process.pid,r=t.pidFilePath??lS,n=t.registry.getAll(),s=[...n].filter(i=>i.pid!==e).sort((i,c)=>Date.parse(c.startedAt)-Date.parse(i.startedAt));for(let i of s){if(!ze(i.pid)){t.registry.unregister(i.id);continue}try{await du(i,"SIGTERM")}catch(c){c instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},c):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(c)})}}await uu(s,5e3);let o=s.filter(i=>ze(i.pid));for(let i of o)try{await du(i,"SIGKILL")}catch(c){c instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},c):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(c)})}await uu(o,1e3);for(let i of s)t.registry.unregister(i.id);for(let i of n.filter(c=>c.pid===e))t.registry.unregister(i.id);try{(0,pu.rmSync)(r,{force:!0})}catch(i){i instanceof Error?y.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},i):y.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:r,error:String(i)})}t.registry.pruneDeadEntries()}async function uu(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.filter(s=>ze(s.pid)).length===0)return;await new Promise(s=>setTimeout(s,100))}}async function du(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){try{typeof n=="number"?process.kill(-n,e):process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let s=await uS();if(s){await new Promise((i,c)=>{s(r,e,l=>{if(!l){i();return}if(l.code==="ESRCH"){i();return}c(l)})});return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await cS("taskkill",o,{timeout:ce.POWERSHELL_COMMAND,windowsHide:!0})}async function uS(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return y.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var gu=3e4,Lt=null;function dS(){let e=Bn().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function yu(){Lt===null&&(Lt=setInterval(dS,gu),Lt.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:gu}))}function _u(){Lt!==null&&(clearInterval(Lt),Lt=null,y.debug("SYSTEM","Health checker stopped"))}var fS=me.workerPid(),Ai=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Jn({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,yu()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?y.error("SYSTEM","Error during shutdown",{},s):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(o){o instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}_u(),this.stopPromise=hu({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},pS=new Ai(Bn());function Su(){return pS}function Jn(t={}){let e=t.pidFilePath??fS;if(!(0,ht.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ht.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,ht.rmSync)(e,{force:!0}),"invalid"}return Mi(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ht.rmSync)(e,{force:!0}),"stale")}var mS=(()=>{let t=process.env.CLAUDE_MEM_HEALTH_TIMEOUT_MS;if(t){let e=parseInt(t,10);if(Number.isFinite(e)&&e>=500&&e<=3e5)return e;y.warn("SYSTEM","Invalid CLAUDE_MEM_HEALTH_TIMEOUT_MS, using default",{value:t,min:500,max:3e5})}return au(ce.HEALTH_CHECK)})();function hS(t,e={},r){return new Promise((n,s)=>{let o=setTimeout(()=>s(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(i=>{clearTimeout(o),n(i)},i=>{clearTimeout(o),s(i)})})}var Zn=null,Xn=null;function Ci(){if(Zn!==null)return Zn;let t=Oi.default.join(Ne.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=Ne.loadFromFile(t);return Zn=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Zn}function gS(){if(Xn!==null)return Xn;let t=Oi.default.join(Ne.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return Xn=Ne.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,Xn}function yS(t){return`http://${gS()}:${Ci()}${t}`}function Qn(t,e={}){let r=e.method??"GET",n=e.timeoutMs??mS,s=yS(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),n>0?hS(s,o,n):fetch(s,o)}var xi=pe(require("path"),1),we=require("fs");var gt=pe(require("path"),1),bu=require("os"),de=require("fs"),jt=require("child_process");var vu=require("util");var EP=(0,vu.promisify)(jt.exec),wP=me.dataDir(),Eu=me.workerPid();function wu(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function _S(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,jt.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},o):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(o))),null}return n.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}var Ii;function SS(t={}){let e=Object.keys(t).length===0;if(e&&Ii!==void 0)return Ii;let r=ES(t);return e&&r!==null&&(Ii=r),r}function ES(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(wu(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,bu.homedir)(),o=t.pathExists??de.existsSync,i=t.lookupInPath??_S,c=e==="win32"?[n.BUN,n.BUN_PATH,gt.default.join(s,".bun","bin","bun.exe"),gt.default.join(s,".bun","bin","bun"),n.USERPROFILE?gt.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?gt.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?gt.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,gt.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of c){let u=l?.trim();if(u&&(wu(u)&&o(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function st(t){return process.platform==="win32"?Math.round(t*2):t}function ku(t,e,r={}){Su().assertCanSpawn("worker daemon");let n=Pi({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=SS();if(!s){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let d=`Start-Process -FilePath '${s.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,f=Buffer.from(d,"utf16le").toString("base64");try{return(0,jt.execSync)(`powershell -NoProfile -EncodedCommand ${f}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:s},p instanceof Error?p:new Error(String(p)));return}}let o="/usr/bin/setsid",i=(0,de.existsSync)(o),u=Yn(i?o:s,i?[s,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function Pu(){try{if(!(0,de.existsSync)(Eu))return;let t=new Date;(0,de.utimesSync)(Eu,t,t)}catch{}}function Tu(){return Jn({logAlive:!1})}var $u=pe(require("net"),1);async function wS(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),s="";try{s=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:s}}async function Ru(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch(e){return e instanceof Error?y.debug("SYSTEM","Windows health check failed (port not in use)",{},e):y.debug("SYSTEM","Windows health check failed (port not in use)",{error:String(e)}),!1}return new Promise(e=>{let r=$u.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function Mu(t,e,r,n){let s=Date.now();for(;Date.now()-s<r;){try{if((await wS(t,e)).ok)return!0}catch(o){o instanceof Error?y.debug("SYSTEM",n,{},o):y.debug("SYSTEM",n,{error:String(o)})}await new Promise(o=>setTimeout(o,500))}return!1}function Ir(t,e=3e4){return Mu(t,"/api/health",e,"Service not ready yet, will retry")}function xr(t,e=3e4){return Mu(t,"/api/readiness",e,"Worker not ready yet, will retry")}var bS=120*1e3;function Di(){return xi.default.join(Ne.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function vS(){if(process.platform!=="win32")return!1;let t=Di();if(!(0,we.existsSync)(t))return!1;try{let e=(0,we.statSync)(t).mtimeMs;return Date.now()-e<bS}catch(e){return e instanceof Error?y.debug("SYSTEM","Could not stat worker spawn lock file",{},e):y.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function kS(){if(process.platform==="win32")try{let t=Di();(0,we.mkdirSync)(xi.default.dirname(t),{recursive:!0}),(0,we.writeFileSync)(t,"","utf-8")}catch{}}function es(){if(process.platform==="win32")try{let t=Di();(0,we.existsSync)(t)&&(0,we.unlinkSync)(t)}catch{}}async function Au(t,e){if(!e)return y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,we.existsSync)(e))return y.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),"dead";if(Tu()==="alive"){if(y.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Ir(t,st(ce.PORT_IN_USE_WAIT))){es();let l=await xr(t,st(ce.READINESS_WAIT));return y.info("SYSTEM","Worker became healthy while waiting on live PID"),l?"ready":"warming"}return y.warn("SYSTEM","Live PID detected but worker did not become healthy before timeout \u2014 likely still starting"),"warming"}if(await Ir(t,1e3)){es();let c=await xr(t,st(ce.READINESS_WAIT));return c||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),y.info("SYSTEM","Worker already running and healthy"),c?"ready":"warming"}if(await Ru(t)){if(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Ir(t,st(ce.PORT_IN_USE_WAIT))){es();let l=await xr(t,st(ce.READINESS_WAIT));return y.info("SYSTEM","Worker is now healthy"),l?"ready":"warming"}return y.error("SYSTEM","Port in use but worker not responding to health checks"),"dead"}if(vS())return y.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";if(y.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),kS(),ku(e,t)===void 0)return y.error("SYSTEM","Failed to spawn worker daemon"),"dead";if(!await Ir(t,st(ce.POST_SPAWN_WAIT)))return y.warn("SYSTEM","Worker spawned but health endpoint not responding within window \u2014 likely still starting in background"),"warming";let i=await xr(t,st(ce.READINESS_WAIT));return i||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),es(),Pu(),y.info("SYSTEM","Worker started successfully"),i?"ready":"warming"}var Ft=require("node:fs/promises"),Lr=require("node:path");var Iu=require("node:child_process"),te=require("node:fs"),Z=require("node:path"),Ui=require("node:os"),Li=require("node:module");var LS={},ji=typeof __filename<"u"?(0,Li.createRequire)(__filename):(0,Li.createRequire)(LS.url),qi={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"tsx",".ts":"typescript",".tsx":"tsx",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".php":"php",".ex":"elixir",".exs":"elixir",".lua":"lua",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".hs":"haskell",".zig":"zig",".css":"css",".scss":"scss",".toml":"toml",".yml":"yaml",".yaml":"yaml",".sql":"sql",".md":"markdown",".mdx":"markdown"};function xu(t,e){let r=t.slice(t.lastIndexOf("."));return qi[r]?qi[r]:e.extensionToLanguage[r]?e.extensionToLanguage[r]:"unknown"}function Du(t,e){return e.languageToQueryKey[t]?e.languageToQueryKey[t]:$S(t)}var Dr=new Map,qt={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};function zr(t){if(Dr.has(t))return Dr.get(t);let e=(0,Z.join)(t,".claude-mem.json"),r;try{let o=(0,te.readFileSync)(e,"utf-8");r=JSON.parse(o)}catch{return Dr.set(t,qt),qt}let n=r.grammars;if(!n||typeof n!="object"||Array.isArray(n))return Dr.set(t,qt),qt;let s={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};for(let[o,i]of Object.entries(n)){if(Nu[o]||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,l=c.package,u=c.extensions,d=c.query;if(!(typeof l!="string"||!Array.isArray(u))&&u.every(f=>typeof f=="string")){s.grammars[o]={package:l,extensions:u,query:typeof d=="string"?d:void 0};for(let f of u)qi[f]||(s.extensionToLanguage[f]=o);if(typeof d=="string"){let f=(0,Z.join)(t,d);try{let p=(0,te.readFileSync)(f,"utf-8"),m=`user_${o}`;Lu[m]=p,s.languageToQueryKey[o]=m}catch{console.error(`[smart-file-read] Custom query file not found: ${f}, falling back to generic`),s.languageToQueryKey[o]="generic"}}else s.languageToQueryKey[o]="generic"}}return Dr.set(t,s),s}var Nu={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",elixir:"tree-sitter-elixir",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},PS={markdown:"tree-sitter-markdown"};function TS(t){let e=Nu[t];if(!e)return null;let r=PS[t];if(r){try{let n=ji.resolve(e+"/package.json"),s=(0,Z.join)((0,Z.dirname)(n),r);if((0,te.existsSync)((0,Z.join)(s,"src")))return s}catch{}return null}try{let n=ji.resolve(e+"/package.json");return(0,Z.dirname)(n)}catch{return null}}function zu(t,e){let r=TS(t);if(r)return r;if(!e)return null;let s=zr(e).grammars[t];if(!s)return null;try{let o=(0,Z.join)(e,"node_modules",s.package,"package.json");if((0,te.existsSync)(o)){let i=(0,Z.dirname)(o);if((0,te.existsSync)((0,Z.join)(i,"src")))return i}}catch{}return console.error(`[smart-file-read] Grammar package not found for "${t}": ${s.package} (install it in your project's node_modules)`),null}var Lu={jsts:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(lexical_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)])) @const_func
|
|
(class_declaration name: (type_identifier) @name) @cls
|
|
(method_definition name: (property_identifier) @name) @method
|
|
(interface_declaration name: (type_identifier) @name) @iface
|
|
(type_alias_declaration name: (type_identifier) @name) @tdef
|
|
(enum_declaration name: (identifier) @name) @enm
|
|
(import_statement) @imp
|
|
(export_statement) @exp
|
|
`,python:`
|
|
(function_definition name: (identifier) @name) @func
|
|
(class_definition name: (identifier) @name) @cls
|
|
(import_statement) @imp
|
|
(import_from_statement) @imp
|
|
`,go:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(method_declaration name: (field_identifier) @name) @method
|
|
(type_declaration (type_spec name: (type_identifier) @name)) @tdef
|
|
(import_declaration) @imp
|
|
`,rust:`
|
|
(function_item name: (identifier) @name) @func
|
|
(struct_item name: (type_identifier) @name) @struct_def
|
|
(enum_item name: (type_identifier) @name) @enm
|
|
(trait_item name: (type_identifier) @name) @trait_def
|
|
(impl_item type: (type_identifier) @name) @impl_def
|
|
(use_declaration) @imp
|
|
`,ruby:`
|
|
(method name: (identifier) @name) @func
|
|
(class name: (constant) @name) @cls
|
|
(module name: (constant) @name) @cls
|
|
(call method: (identifier) @name) @imp
|
|
`,java:`
|
|
(method_declaration name: (identifier) @name) @method
|
|
(class_declaration name: (identifier) @name) @cls
|
|
(interface_declaration name: (identifier) @name) @iface
|
|
(enum_declaration name: (identifier) @name) @enm
|
|
(import_declaration) @imp
|
|
`,kotlin:`
|
|
(function_declaration (simple_identifier) @name) @func
|
|
(class_declaration (type_identifier) @name) @cls
|
|
(object_declaration (type_identifier) @name) @cls
|
|
(import_header) @imp
|
|
`,swift:`
|
|
(function_declaration name: (simple_identifier) @name) @func
|
|
(class_declaration name: (type_identifier) @name) @cls
|
|
(protocol_declaration name: (type_identifier) @name) @iface
|
|
(import_declaration) @imp
|
|
`,php:`
|
|
(function_definition name: (name) @name) @func
|
|
(class_declaration name: (name) @name) @cls
|
|
(interface_declaration name: (name) @name) @iface
|
|
(trait_declaration name: (name) @name) @trait_def
|
|
(method_declaration name: (name) @name) @method
|
|
(namespace_use_declaration) @imp
|
|
`,lua:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(function_declaration name: (dot_index_expression) @name) @func
|
|
(function_declaration name: (method_index_expression) @name) @func
|
|
`,scala:`
|
|
(function_definition name: (identifier) @name) @func
|
|
(class_definition name: (identifier) @name) @cls
|
|
(object_definition name: (identifier) @name) @cls
|
|
(trait_definition name: (identifier) @name) @trait_def
|
|
(import_declaration) @imp
|
|
`,bash:`
|
|
(function_definition name: (word) @name) @func
|
|
`,haskell:`
|
|
(function name: (variable) @name) @func
|
|
(type_synomym name: (name) @name) @tdef
|
|
(newtype name: (name) @name) @tdef
|
|
(data_type name: (name) @name) @tdef
|
|
(class name: (name) @name) @cls
|
|
(import) @imp
|
|
`,zig:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(test_declaration) @func
|
|
`,css:`
|
|
(rule_set (selectors) @name) @func
|
|
(media_statement) @cls
|
|
(keyframes_statement (keyframes_name) @name) @cls
|
|
(import_statement) @imp
|
|
`,scss:`
|
|
(rule_set (selectors) @name) @func
|
|
(media_statement) @cls
|
|
(keyframes_statement (keyframes_name) @name) @cls
|
|
(import_statement) @imp
|
|
(mixin_statement name: (identifier) @name) @mixin_def
|
|
(function_statement name: (identifier) @name) @func
|
|
(include_statement) @imp
|
|
`,toml:`
|
|
(table (bare_key) @name) @cls
|
|
(table (dotted_key) @name) @cls
|
|
(table_array_element (bare_key) @name) @cls
|
|
(table_array_element (dotted_key) @name) @cls
|
|
`,yaml:`
|
|
(block_mapping_pair key: (flow_node) @name) @func
|
|
`,sql:`
|
|
(create_table (object_reference) @name) @cls
|
|
(create_function (object_reference) @name) @func
|
|
(create_view (object_reference) @name) @cls
|
|
`,markdown:`
|
|
(atx_heading heading_content: (inline) @name) @heading
|
|
(setext_heading heading_content: (paragraph) @name) @heading
|
|
(fenced_code_block (info_string (language) @name)) @code_block
|
|
(fenced_code_block) @code_block
|
|
(minus_metadata) @frontmatter
|
|
(link_reference_definition (link_label) @name) @ref
|
|
`,generic:`
|
|
(function_declaration name: (identifier) @name) @func
|
|
(function_definition name: (identifier) @name) @func
|
|
(class_declaration name: (identifier) @name) @cls
|
|
(class_definition name: (identifier) @name) @cls
|
|
(import_statement) @imp
|
|
(import_declaration) @imp
|
|
`};function $S(t){switch(t){case"javascript":case"typescript":case"tsx":return"jsts";case"python":return"python";case"go":return"go";case"rust":return"rust";case"ruby":return"ruby";case"java":return"java";case"kotlin":return"kotlin";case"swift":return"swift";case"php":return"php";case"elixir":return"generic";case"lua":return"lua";case"scala":return"scala";case"bash":return"bash";case"haskell":return"haskell";case"zig":return"zig";case"css":return"css";case"scss":return"scss";case"toml":return"toml";case"yaml":return"yaml";case"sql":return"sql";case"markdown":return"markdown";default:return"generic"}}var Ni=null,zi=new Map;function ju(t){if(zi.has(t))return zi.get(t);Ni||(Ni=(0,te.mkdtempSync)((0,Z.join)((0,Ui.tmpdir)(),"smart-read-queries-")));let e=(0,Z.join)(Ni,`${t}.scm`);return(0,te.writeFileSync)(e,Lu[t]),zi.set(t,e),e}var Nr=null;function RS(){if(Nr)return Nr;try{let t=ji.resolve("tree-sitter-cli/package.json"),e=(0,Z.join)((0,Z.dirname)(t),"tree-sitter");if((0,te.existsSync)(e))return Nr=e,e}catch{}return Nr="tree-sitter",Nr}function MS(t,e,r){return qu(t,[e],r).get(e)||[]}function qu(t,e,r){if(e.length===0)return new Map;let n=RS(),s=["query","-p",r,t,...e],o;try{o=(0,Iu.execFileSync)(n,s,{encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]})}catch(i){return y.debug("WORKER",`tree-sitter query failed for ${e.length} file(s)`,void 0,i instanceof Error?i:void 0),new Map}return AS(o)}function AS(t){let e=new Map,r=null,n=null;for(let s of t.split(`
|
|
`)){if(s.length>0&&!s.startsWith(" ")&&!s.startsWith(" ")){r=s.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let o=s.match(/^\s+pattern:\s+(\d+)/);if(o){n={pattern:parseInt(o[1]),captures:[]},e.get(r).push(n);continue}let i=s.match(/^\s+capture:\s+(?:\d+\s*-\s*)?(\w+),\s*start:\s*\((\d+),\s*(\d+)\),\s*end:\s*\((\d+),\s*(\d+)\)(?:,\s*text:\s*`([^`]*)`)?/);i&&n&&n.captures.push({tag:i[1],startRow:parseInt(i[2]),startCol:parseInt(i[3]),endRow:parseInt(i[4]),endCol:parseInt(i[5]),text:i[6]})}return e}var Ou={func:"function",const_func:"function",cls:"class",method:"method",iface:"interface",tdef:"type",enm:"enum",struct_def:"struct",trait_def:"trait",impl_def:"impl",mixin_def:"mixin",heading:"section",code_block:"code",frontmatter:"metadata",ref:"reference"},OS=new Set(["class","struct","impl","trait"]);function CS(t,e,r,n=200){let o=t[e]||"";if(!o.trimEnd().endsWith("{")&&!o.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(`
|
|
`),c=i.indexOf("{");c!==-1&&c<500&&(o=i.slice(0,c).replace(/\n/g," ").replace(/\s+/g," ").trim())}return o=o.replace(/\s*[{:]\s*$/,"").trim(),o.length>n&&(o=o.slice(0,n-3)+"..."),o}function IS(t,e){let r=[],n=!1;for(let s=e-1;s>=0;s--){let o=t[s].trim();if(o===""){if(n)break;continue}if(o.startsWith("/**")||o.startsWith("*")||o.startsWith("*/")||o.startsWith("//")||o.startsWith("///")||o.startsWith("//!")||o.startsWith("#")||o.startsWith("@"))r.unshift(t[s]),n=!0;else break}return r.length>0?r.join(`
|
|
`).trim():void 0}function xS(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let s=t[n]?.trim();if(s){if(s.startsWith('"""')||s.startsWith("'''"))return s;break}}}function DS(t,e,r,n,s,o){switch(o){case"javascript":case"typescript":case"tsx":return n.some(i=>e>=i.startRow&&r<=i.endRow);case"python":return!t.startsWith("_");case"go":return t.length>0&&t[0]===t[0].toUpperCase()&&t[0]!==t[0].toLowerCase();case"rust":return s[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function Uu(t,e,r){let n=[],s=[],o=[],i=[];for(let l of t)for(let u of l.captures)u.tag==="exp"&&o.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&s.push(u.text||e[u.startRow]?.trim()||"");for(let l of t){let u=l.captures.find(w=>Ou[w.tag]),d=l.captures.find(w=>w.tag==="name");if(!u)continue;let f=u.startRow,p=u.endRow,m=Ou[u.tag],h=d?.text||"anonymous",g;if(r==="markdown"&&m==="section"){let A=(e[f]||"").match(/^(#{1,6})\s/),k=A?A[1].length:1;g=`${"#".repeat(k)} ${h}`}else if(r==="markdown"&&m==="code"){let w=h!=="anonymous"?h:"";g=w?"```"+w:"```"}else r==="markdown"&&m==="metadata"?g="---frontmatter---":r==="markdown"&&m==="reference"?g=e[f]?.trim()||h:g=CS(e,f,p);let _=r==="markdown"?void 0:IS(e,f),E=r==="python"?xS(e,f,p):void 0,S={name:h,kind:m,signature:g,jsdoc:_||E,lineStart:f,lineEnd:p,exported:DS(h,f,p,o,e,r)};OS.has(m)&&(S.children=[],i.push({sym:S,startRow:f,endRow:p})),n.push(S)}if(r==="markdown"){let l=new Map,u=new Set;for(let d of n){if(d.kind!=="code")continue;let f=`${d.lineStart}:${d.lineEnd}`,p=l.get(f);p?d.name!=="anonymous"?(u.add(p),l.set(f,d)):u.add(d):l.set(f,d)}if(u.size>0){let d=n.filter(f=>!u.has(f));n.length=0,n.push(...d)}}let c=new Set;for(let l of i)for(let u of n)u!==l.sym&&u.lineStart>l.startRow&&u.lineEnd<=l.endRow&&(u.kind==="function"&&(u.kind="method"),l.sym.children.push(u),c.add(u));return{symbols:n.filter(l=>!c.has(l)),imports:s}}function ts(t,e,r){let n=r?zr(r):qt,s=xu(e,n),o=t.split(`
|
|
`),i=zu(s,r);if(!i)return{filePath:e,language:s,symbols:[],imports:[],totalLines:o.length,foldedTokenEstimate:50};let c=Du(s,n),l=ju(c),u=e.slice(e.lastIndexOf("."))||".txt",d=(0,te.mkdtempSync)((0,Z.join)((0,Ui.tmpdir)(),"smart-src-")),f=(0,Z.join)(d,`source${u}`);(0,te.writeFileSync)(f,t);try{let p=MS(l,f,i),m=Uu(p,o,s),h=Ut({filePath:e,language:s,symbols:m.symbols,imports:m.imports,totalLines:o.length,foldedTokenEstimate:0});return{filePath:e,language:s,symbols:m.symbols,imports:m.imports,totalLines:o.length,foldedTokenEstimate:Math.ceil(h.length/4)}}finally{(0,te.rmSync)(d,{recursive:!0,force:!0})}}function Fu(t,e){let r=new Map,n=e?zr(e):qt,s=new Map;for(let o of t){let i=xu(o.relativePath,n);s.has(i)||s.set(i,[]),s.get(i).push(o)}for(let[o,i]of s){let c=zu(o,e);if(!c){for(let p of i){let m=p.content.split(`
|
|
`);r.set(p.relativePath,{filePath:p.relativePath,language:o,symbols:[],imports:[],totalLines:m.length,foldedTokenEstimate:50})}continue}let l=Du(o,n),u=ju(l),d=i.map(p=>p.absolutePath),f=qu(u,d,c);for(let p of i){let m=p.content.split(`
|
|
`),h=f.get(p.absolutePath)||[],g=Uu(h,m,o),_=Ut({filePath:p.relativePath,language:o,symbols:g.symbols,imports:g.imports,totalLines:m.length,foldedTokenEstimate:0});r.set(p.relativePath,{filePath:p.relativePath,language:o,symbols:g.symbols,imports:g.imports,totalLines:m.length,foldedTokenEstimate:Math.ceil(_.length/4)})}}return r}function Ut(t){if(t.language==="markdown")return NS(t);let e=[];if(e.push(`\u{1F4C1} ${t.filePath} (${t.language}, ${t.totalLines} lines)`),e.push(""),t.imports.length>0){e.push(` \u{1F4E6} Imports: ${t.imports.length} statements`);for(let r of t.imports.slice(0,10))e.push(` ${r}`);t.imports.length>10&&e.push(` ... +${t.imports.length-10} more`),e.push("")}for(let r of t.symbols)e.push(Hu(r," "));return e.join(`
|
|
`)}function NS(t){let e=[];e.push(`\u{1F4C4} ${t.filePath} (${t.language}, ${t.totalLines} lines)`);for(let n of t.symbols)if(n.kind==="section"){let s=n.signature.match(/^(#{1,6})\s/),o=s?s[1].length:1,i=" ".repeat(o),c=`L${n.lineStart+1}`,l=`${i}${n.signature}`;e.push(`${l.padEnd(56)}${c}`)}else if(n.kind==="code"){let s=Cu(t.symbols,n.lineStart),o=" ".repeat(s+1),i=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,c=`${o}${n.signature}`;e.push(`${c.padEnd(56)}${i}`)}else if(n.kind==="metadata"){let s=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,o=` ${n.signature}`;e.push(`${o.padEnd(56)}${s}`)}else if(n.kind==="reference"){let s=Cu(t.symbols,n.lineStart),o=" ".repeat(s+1),i=`L${n.lineStart+1}`,c=`${o}\u2197 ${n.name}`;e.push(`${c.padEnd(56)}${i}`)}return e.join(`
|
|
`)}function Cu(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart<e){let s=n.signature.match(/^(#{1,6})\s/);r=s?s[1].length:1}return r}function Hu(t,e){let r=[],n=zS(t.kind),s=t.exported?" [exported]":"",o=t.lineStart===t.lineEnd?`L${t.lineStart+1}`:`L${t.lineStart+1}-${t.lineEnd+1}`;if(r.push(`${e}${n} ${t.name}${s} (${o})`),r.push(`${e} ${t.signature}`),t.jsdoc){let c=t.jsdoc.split(`
|
|
`).find(l=>{let u=l.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").trim();return u.length>0&&!u.startsWith("/**")});if(c){let l=c.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").replace(/['"`]{3}$/,"").trim();l&&r.push(`${e} \u{1F4AC} ${l}`)}}if(t.children&&t.children.length>0)for(let i of t.children)r.push(Hu(i,e+" "));return r.join(`
|
|
`)}function zS(t){return{function:"\u0192",method:"\u0192",class:"\u25C6",interface:"\u25C7",type:"\u25C7",const:"\u25CF",variable:"\u25CB",export:"\u2192",struct:"\u25C6",enum:"\u25A3",trait:"\u25C7",impl:"\u25C8",property:"\u25CB",getter:"\u21E2",setter:"\u21E0",mixin:"\u25C8",section:"\xA7",code:"\u2318",metadata:"\u25CA",reference:"\u2197"}[t]||"\xB7"}function Wu(t,e,r){let n=ts(t,e),s=u=>{for(let d of u){if(d.name===r)return d;if(d.children){let f=s(d.children);if(f)return f}}return null},o=s(n.symbols);if(!o)return null;let i=t.split(`
|
|
`);if(n.language==="markdown"&&o.kind==="section"){let u=o.signature.match(/^(#{1,6})\s/),d=u?u[1].length:1,f=o.lineStart,p=i.length-1;for(let h of n.symbols)if(h.kind==="section"&&h.lineStart>f){let g=h.signature.match(/^(#{1,6})\s/);if((g?g[1].length:1)<=d){for(p=h.lineStart-1;p>f&&i[p].trim()==="";)p--;break}}let m=i.slice(f,p+1).join(`
|
|
`);return`<!-- \u{1F4CD} ${e} L${f+1}-${p+1} -->
|
|
${m}`}let c=o.lineStart;for(let u=o.lineStart-1;u>=0;u--){let d=i[u].trim();if(d===""||d.startsWith("*")||d.startsWith("/**")||d.startsWith("///")||d.startsWith("//")||d.startsWith("#")||d.startsWith("@")||d==="*/")c=u;else break}let l=i.slice(c,o.lineEnd+1).join(`
|
|
`);return`// \u{1F4CD} ${e} L${c+1}-${o.lineEnd+1}
|
|
${l}`}var Vu=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),jS=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),qS=512*1024;async function*Gu(t,e,r=20,n){if(r<=0)return;let s;try{s=await(0,Ft.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of s){if(o.name.startsWith(".")&&o.name!=="."||jS.has(o.name))continue;let i=(0,Lr.join)(t,o.name);if(o.isDirectory())yield*Gu(i,e,r-1,n);else if(o.isFile()){let c=o.name.slice(o.name.lastIndexOf("."));(Vu.has(c)||n&&n.has(c))&&(yield i)}}}async function US(t){try{let e=await(0,Ft.stat)(t);if(e.size>qS||e.size===0)return null;let r=await(0,Ft.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function Ku(t,e,r={}){let n=r.maxResults||20,s=e.toLowerCase(),o=s.split(/[\s_\-./]+/).filter(S=>S.length>0),i=r.projectRoot||t,c=zr(i),l=new Set;for(let S of Object.values(c.grammars))for(let w of S.extensions)Vu.has(w)||l.add(w);let u=[];for await(let S of Gu(t,t,20,l.size>0?l:void 0)){if(r.filePattern&&!(0,Lr.relative)(t,S).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let w=await US(S);w&&u.push({absolutePath:S,relativePath:(0,Lr.relative)(t,S),content:w})}let d=Fu(u,i),f=[],p=[],m=0;for(let[S,w]of d){m+=FS(w);let k=rs(S.toLowerCase(),o)>0,le=[],fe=(Wt,yt)=>{for(let W of Wt){let Ge=0,be="",Vt=rs(W.name.toLowerCase(),o);Vt>0&&(Ge+=Vt*3,be="name match"),W.signature.toLowerCase().includes(s)&&(Ge+=2,be=be?`${be} + signature`:"signature match"),W.jsdoc&&W.jsdoc.toLowerCase().includes(s)&&(Ge+=1,be=be?`${be} + jsdoc`:"jsdoc match"),Ge>0&&(k=!0,le.push({filePath:S,symbolName:yt?`${yt}.${W.name}`:W.name,kind:W.kind,signature:W.signature,jsdoc:W.jsdoc,lineStart:W.lineStart,lineEnd:W.lineEnd,matchReason:be})),W.children&&fe(W.children,W.name)}};fe(w.symbols),k&&(f.push(w),p.push(...le))}p.sort((S,w)=>{let A=rs(S.symbolName.toLowerCase(),o);return rs(w.symbolName.toLowerCase(),o)-A});let h=p.slice(0,n),g=new Set(h.map(S=>S.filePath)),_=f.filter(S=>g.has(S.filePath)).slice(0,n),E=_.reduce((S,w)=>S+w.foldedTokenEstimate,0);return{foldedFiles:_,matchingSymbols:h,totalFilesScanned:u.length,totalSymbolsFound:m,tokenEstimate:E}}function rs(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let s=0,o=0;for(let i of n){let c=t.indexOf(i,s);c!==-1&&(o++,s=c+1)}o===n.length&&(r+=1)}return r}function FS(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function Yu(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
|
|
`);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let s=n.jsdoc.split(`
|
|
`).find(o=>o.replace(/^[\s*/]+/,"").trim().length>0);s&&r.push(` \u{1F4AC} ${s.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ut(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
|
|
`)}var Hi=require("node:fs/promises"),ns=require("node:fs"),Re=require("node:path"),Zu=require("node:os"),Xu=require("node:url"),eE={},HS="12.5.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var Qu=!1,ed=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Re.dirname)((0,Xu.fileURLToPath)(eE.url))}catch{return Qu=!0,process.cwd()}})(),Wi=(0,Re.resolve)(ed,"worker-service.cjs");function WS(){Qu&&((0,ns.existsSync)(Wi)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Wi,mcpServerDir:ed}))}var Bu={search:"/api/search",timeline:"/api/timeline"};async function Fi(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[s,o]of Object.entries(e))o!=null&&r.append(s,String(o));let n=`${t}?${r}`;try{let s=await Qn(n);if(!s.ok){let i=await s.text();throw new Error(`Worker API error (${s.status}): ${i}`)}let o=await s.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),o}catch(s){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},s instanceof Error?s:new Error(String(s))),{content:[{type:"text",text:`Error calling Worker API: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}async function VS(t,e){let r=await Qn(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let s=await r.text();throw new Error(`Worker API error (${r.status}): ${s}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Ht(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await VS(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function GS(){try{return(await Qn("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function KS(){if(await GS())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),WS();try{let t=Ci(),e=await Au(t,Wi);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var td=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
NEVER fetch full details without filtering first. 10x token savings.`,inputSchema:{type:"object",properties:{}},handler:async()=>({content:[{type:"text",text:`# Memory Search Workflow
|
|
|
|
**3-Layer Pattern (ALWAYS follow this):**
|
|
|
|
1. **Search** - Get index of results with IDs
|
|
\`search(query="...", limit=20, project="...")\`
|
|
Returns: Table with IDs, titles, dates (~50-100 tokens/result)
|
|
|
|
2. **Timeline** - Get context around interesting results
|
|
\`timeline(anchor=<ID>, depth_before=3, depth_after=3)\`
|
|
Returns: Chronological context showing what was happening
|
|
|
|
3. **Fetch** - Get full details ONLY for relevant IDs
|
|
\`get_observations(ids=[...])\` # ALWAYS batch for 2+ items
|
|
Returns: Complete details (~500-1000 tokens/result)
|
|
|
|
**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},limit:{type:"number",description:"Max results (default 20)"},project:{type:"string",description:"Filter by project name"},type:{type:"string",description:"Filter by observation type"},obs_type:{type:"string",description:"Filter by obs_type field"},dateStart:{type:"string",description:"Start date filter (ISO)"},dateEnd:{type:"string",description:"End date filter (ISO)"},offset:{type:"number",description:"Pagination offset"},orderBy:{type:"string",description:"Sort order: date_desc or date_asc"}},additionalProperties:!0},handler:async t=>{let e=Bu.search;return await Fi(e,t)}},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{anchor:{type:"number",description:"Observation ID to center the timeline around"},query:{type:"string",description:"Query to find anchor automatically"},depth_before:{type:"number",description:"Items before anchor (default 3)"},depth_after:{type:"number",description:"Items after anchor (default 3)"},project:{type:"string",description:"Filter by project name"}},additionalProperties:!0},handler:async t=>{let e=Bu.timeline;return await Fi(e,t)}},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await Ht("/api/observations/batch",t)},{name:"smart_search",description:"Search codebase for symbols, functions, classes using tree-sitter AST parsing. Returns folded structural views with token counts. Use path parameter to scope the search.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search term \u2014 matches against symbol names, file names, and file content"},path:{type:"string",description:"Root directory to search (default: current working directory)"},max_results:{type:"number",description:"Maximum results to return (default: 20)"},file_pattern:{type:"string",description:'Substring filter for file paths (e.g. ".ts", "src/services")'}},required:["query"]},handler:async t=>{let e=(0,Re.resolve)(t.path||process.cwd()),r=await Ku(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:Yu(r,t.query)}]}}},{name:"smart_unfold",description:"Expand a specific symbol (function, class, method) from a file. Returns the full source code of just that symbol. Use after smart_search or smart_outline to read specific code.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"},symbol_name:{type:"string",description:"Name of the symbol to unfold (function, class, method, etc.)"}},required:["file_path","symbol_name"]},handler:async t=>{let e=(0,Re.resolve)(t.file_path),r=await(0,Hi.readFile)(e,"utf-8"),n=Wu(r,e,t.symbol_name);if(n)return{content:[{type:"text",text:n}]};let s=ts(r,e);if(s.symbols.length>0){let o=s.symbols.map(i=>` - ${i.name} (${i.kind})`).join(`
|
|
`);return{content:[{type:"text",text:`Symbol "${t.symbol_name}" not found in ${t.file_path}.
|
|
|
|
Available symbols:
|
|
${o}`}]}}return{content:[{type:"text",text:`Could not parse ${t.file_path}. File may be unsupported or empty.`}]}}},{name:"smart_outline",description:"Get structural outline of a file \u2014 shows all symbols (functions, classes, methods, types) with signatures but bodies folded. Much cheaper than reading the full file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"}},required:["file_path"]},handler:async t=>{let e=(0,Re.resolve)(t.file_path),r=await(0,Hi.readFile)(e,"utf-8"),n=ts(r,e);return n.symbols.length>0?{content:[{type:"text",text:Ut(n)}]}:{content:[{type:"text",text:`Could not parse ${t.file_path}. File may use an unsupported language or be empty.`}]}}},{name:"build_corpus",description:"Build a knowledge corpus from filtered observations. Creates a queryable knowledge agent. Params: name (required), description, project, types (comma-separated), concepts (comma-separated), files (comma-separated), query, dateStart, dateEnd, limit",inputSchema:{type:"object",properties:{name:{type:"string",description:"Corpus name (used as filename)"},description:{type:"string",description:"What this corpus is about"},project:{type:"string",description:"Filter by project"},types:{type:"string",description:"Comma-separated observation types: decision,bugfix,feature,refactor,discovery,change"},concepts:{type:"string",description:"Comma-separated concepts to filter by"},files:{type:"string",description:"Comma-separated file paths to filter by"},query:{type:"string",description:"Semantic search query"},dateStart:{type:"string",description:"Start date (ISO format)"},dateEnd:{type:"string",description:"End date (ISO format)"},limit:{type:"number",description:"Maximum observations (default 500)"}},required:["name"],additionalProperties:!0},handler:async t=>await Ht("/api/corpus",t)},{name:"list_corpora",description:"List all knowledge corpora with their stats and priming status",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>await Fi("/api/corpus",t)},{name:"prime_corpus",description:"Prime a knowledge corpus \u2014 creates an AI session loaded with the corpus knowledge. Must be called before query_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to prime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Ht(`/api/corpus/${encodeURIComponent(e)}/prime`,r)}},{name:"query_corpus",description:"Ask a question to a primed knowledge corpus. The corpus must be primed first with prime_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to query"},question:{type:"string",description:"The question to ask"}},required:["name","question"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Ht(`/api/corpus/${encodeURIComponent(e)}/query`,r)}},{name:"rebuild_corpus",description:"Rebuild a knowledge corpus from its stored filter \u2014 re-runs the search to refresh with new observations. Does not re-prime the session.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to rebuild"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Ht(`/api/corpus/${encodeURIComponent(e)}/rebuild`,r)}},{name:"reprime_corpus",description:"Create a fresh knowledge agent session for a corpus, clearing prior Q&A context. Use when conversation has drifted or after rebuilding.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to reprime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await Ht(`/api/corpus/${encodeURIComponent(e)}/reprime`,r)}}],Vi=new Vn({name:"claude-mem",version:HS},{capabilities:{tools:{}}});Vi.setRequestHandler(vs,async()=>({tools:td.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));Vi.setRequestHandler(er,async t=>{let e=td.find(r=>r.name===t.params.name);if(!e)throw new Error(`Unknown tool: ${t.params.name}`);try{return await e.handler(t.params.arguments||{})}catch(r){return y.error("SYSTEM","Tool execution failed",{tool:t.params.name},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var YS=3e4,jr=null,Ju=!1;function ss(){qr("stdio-closed")}function rd(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),qr("stdio-error")}function BS(){process.stdin.on("end",ss),process.stdin.on("close",ss),process.stdin.on("error",rd)}function JS(){process.stdin.off("end",ss),process.stdin.off("close",ss),process.stdin.off("error",rd)}function ZS(){if(process.platform==="win32")return;let t=process.ppid;jr=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),qr())},YS),jr.unref&&jr.unref()}function qr(t="shutdown"){Ju||(Ju=!0,jr&&clearInterval(jr),JS(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",qr);process.on("SIGINT",qr);function XS(){try{let t=(0,Zu.homedir)(),e=[(0,Re.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,Re.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,ns.existsSync)(i)),n=[(0,Re.resolve)(t,".claude","plugins","cache","thedotmack","claude-mem"),(0,Re.resolve)(t,".config","claude","plugins","cache","thedotmack","claude-mem")],s=n.some(i=>i&&(0,ns.existsSync)(i)),o=n[0];!r&&s&&y.error("SYSTEM","claude-mem MCP started but no marketplace directory was found at ~/.claude/plugins/marketplaces/thedotmack or the XDG equivalent. The IDE plugin loader needs that directory to fire claude-mem hooks (SessionStart, PostToolUse, Stop, etc.). Without it, MCP search will work but no new memories will be captured. To self-heal, run: node ~/.claude/plugins/cache/thedotmack/claude-mem/*/scripts/smart-install.js (or reinstall the plugin from the marketplace).",{marketplaceCandidates:e,cacheRoot:o})}catch{}}async function QS(){let t=new Kn;BS(),await Vi.connect(t),y.info("SYSTEM","Claude-mem search server started"),XS(),ZS(),setTimeout(async()=>{await KS()?y.info("SYSTEM","Worker available",void 0,{}):(y.error("SYSTEM","Worker not available",void 0,{}),y.error("SYSTEM","Tools will fail until Worker is started"),y.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}QS().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)});
|