Files
claude-mem/plugin/scripts/mcp-server.cjs
T
Alex Newman 9e2973059a UX redesign: installer + provider rename + /learn-codebase + welcome card + SessionStart hint (#2255)
* feat(ux): claude-mem UX improvements with installer enhancements

Squashed PR #2156 commits for clean rebase onto main:
- feat(installer): add provider selection, model prompt, worker auto-start
- refactor: rename *Agent provider classes to *Provider
- feat: add /learn-codebase skill and viewer welcome card
- feat(worker): inject welcome hint when project has zero observations
- fix(pr-2156): address greptile review comments
- fix(pr-2156): address coderabbit review comments
- fix(pr-2156): persist CLAUDE_MEM_PROVIDER for non-claude in non-TTY mode
- fix(pr-2156): file-backed settings reads in installer + env-first SKILL doc

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* build: rebuild plugin artifacts after rebase onto v12.4.7

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(skills): strip claude-mem internals from learn-codebase

The learn-codebase skill, install next-step copy, WelcomeCard, and
welcome-hint previously walked the primary agent through worker endpoints
and synthetic observation payloads. The PostToolUse hook already captures
every Read/Edit the agent makes — the agent should have no awareness that
the memory layer exists. Collapse the skill to one instruction ("read every
source file in full") and rephrase touchpoints to describe only what the
user observes (Claude reading files), not what happens behind the scenes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sync): preflight version mismatch + settings-aware port resolution

Two related fixes for build-and-sync's worker restart step:

1. Read CLAUDE_MEM_WORKER_PORT from ~/.claude-mem/settings.json the same
   way the worker does, instead of computing the default port from the
   uid alone. Previously, users with a custom port saw a misleading
   "Worker not running" message because the restart POST hit the wrong
   port and got ECONNREFUSED.

2. Add a preflight check that aborts the sync when the running worker's
   reported version does not match the version we are about to build.
   Claude Code's plugin loader pins the worker to a specific cache
   version per session, so syncing into a newer cache directory has no
   effect until the user runs `claude plugin update thedotmack/claude-mem`
   to bump the pin. The preflight surfaces this explicitly with the exact
   command to run; --force bypasses it for intentional cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(learn-codebase): note sed for partial reads of large files

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: strip comments codebase-wide

Removed prose comments from all tracked source. Preserved directives
(@ts-ignore, eslint-disable, biome-ignore, prettier-ignore, triple-slash
references, webpack magic, shebangs). Deleted two tests that asserted
on comment text rather than runtime behavior.

Net: 401 files, -14,587 / +389 lines, -10.4% bytes.

Verified: typecheck passes, build passes, test count unchanged from
baseline (22 pre-existing fails, all unrelated).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(installer): move runtime setup into npx, eliminate hook dead air

Smart-install ran 3 times during a fresh install — the worst run was silent,
fired by Claude Code's Setup hook after `claude plugin install`, producing
~30s of dead air that looked like the plugin was hung.

This change makes `npx claude-mem install` the single place heavy work
happens, with a visible spinner. Hooks become runtime-only.

- New `src/npx-cli/install/setup-runtime.ts` module: ensureBun, ensureUv,
  installPluginDependencies, read/writeInstallMarker, isInstallCurrent.
  Marker schema preserved exactly ({version, bun, uv, installedAt}) so
  ContextBuilder and BranchManager readers keep working.
- `npx claude-mem install`: ungated copy/register/enable for every IDE,
  inserts a "Setting up runtime" task with honest "first install can take
  ~30s" spinner. The claude-code shell-out to `claude plugin install` is
  removed — npx already populated everything Claude reads.
- New `npx claude-mem repair` command for post-`claude plugin update`
  recovery, force-reinstalls runtime.
- Setup hook now runs `plugin/scripts/version-check.js` (29ms wall) instead
  of smart-install. Mismatch prints "run: npx claude-mem repair" on stderr.
  Always exits 0 (non-blocking, per CLAUDE.md exit-code strategy).
- SessionStart loses the smart-install entry; 2 hooks remain (worker start,
  context fetch).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(installer): delete smart-install sources, retarget tests

- Delete scripts/smart-install.js + plugin/scripts/smart-install.js (both
  are source files kept in sync manually; both must go).
- Delete tests/smart-install.test.ts (covered surface is gone).
- tests/plugin-scripts-line-endings: drop smart-install.js entry.
- tests/infrastructure/plugin-distribution: retarget two assertions at
  version-check.js (the new Setup hook script).
- New tests/setup-runtime.test.ts: 9 tests covering marker read/write,
  isInstallCurrent semantics. Marker schema invariant verified.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(installer): describe npx-driven setup + version-check Setup hook

Sweep public docs and architecture notes to reflect the new flow:
npx installer does Bun/uv setup with a visible spinner; Setup hook runs
sub-100ms version-check.js; users hit `npx claude-mem repair` after a
`claude plugin update`.

- docs/architecture-overview.md: hook lifecycle table + npx flow paragraph
- docs/public/configuration.mdx: tree + hook config example
- docs/public/development.mdx: build output line
- docs/public/hooks-architecture.mdx: full rewrite of pre-hook section,
  timing table, performance table
- docs/public/architecture/{overview,hooks,worker-service}.mdx: tree
  comments, JSON config example, Bun requirement section

docs/reports/* untouched (historical incident reports).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(install): mergeSettings writes via USER_SETTINGS_PATH

Greptile P1 (#2156): `settingsFilePath()` only resolved
`process.env.CLAUDE_MEM_DATA_DIR`, while `getSetting()` reads via
`USER_SETTINGS_PATH` which `resolveDataDir()` populates from BOTH the env
var AND a `CLAUDE_MEM_DATA_DIR` entry persisted in
`~/.claude-mem/settings.json`. Result: a user with the data dir saved in
settings.json but not exported in their shell would have provider/model
settings silently written to `~/.claude-mem/settings.json` while
`getSetting()` read from `/custom/path/settings.json` — read/write split.

Drop `settingsFilePath()` and the now-unused `homedir` import; reuse the
already-imported `USER_SETTINGS_PATH` constant.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(cli): parse --provider, --model, --no-auto-start install flags

Greptile P1 (#2156): InstallOptions has fields `provider`, `model`,
`noAutoStart`, but the install case in the npx-cli switch only parsed
`--ide`. The other three flags were silently dropped — `npx claude-mem
install --provider gemini` was a no-op.

Extract a `parseInstallOptions(argv)` helper, share it between the bare
`npx claude-mem` and `npx claude-mem install` paths, and validate
`--provider` against the allowed set. Update help text accordingly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(install): pipe runtime-setup output, always show IDE multiselect

Two issues caught in a docker test of the installer:

1. The bun.sh installer, uv installer, and `bun install` were using
   stdio: 'inherit', dumping their stdout/stderr through clack's spinner
   region — visible as raw "downloading uv 0.11.8…" / "Checked 58
   installs across 38 packages…" text streaming under the spinner. Switch
   to stdio: 'pipe' and surface captured stderr only on failure (via a
   shared describeExecError() helper that includes stdout when stderr is
   empty). Spinner stays clean on the happy path.

2. promptForIDESelection() silently picked claude-code when no IDEs were
   detected, never showing the user the multiselect. On a fresh machine
   with no IDEs present yet (e.g. our docker test container), the user
   never got to choose. Now: always show the full IDE list when
   interactive; mark detected ones with [detected] hints and pre-select
   them; show a warn line if zero are detected explaining they should pick
   what they plan to use. Non-TTY callers still get the silent
   claude-code default at the call site (unchanged).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(install): skip marketplace work for claude-code-only, offer to install Claude Code

Two related UX fixes from a docker test:

**Delay between "Saved Claude model=…" and "Plugin files copied OK"**

After dropping the needsManualInstall gate, every install was unconditionally
running `copyPluginToMarketplace` (which copied the entire root node_modules
tree — thousands of files, dozens of seconds) and `runNpmInstallInMarketplace`
(npm install --production) even when only claude-code was selected. Neither
is needed for claude-code: that path uses the plugin cache dir + the
installed_plugins.json + enabledPlugins flag, all of which we already write.

- Drop `node_modules` from `copyPluginToMarketplace`'s allowed-entries list;
  the dependency-install task populates it on the destination side anyway.
- Re-introduce `needsMarketplace = selectedIDEs.some(id => id !== 'claude-code')`
  scoped *only* to `copyPluginToMarketplace`, `runNpmInstallInMarketplace`,
  and the pre-install `shutdownWorkerAndWait` (also pointless for claude-code-
  only flows since we're not overwriting the worker's running cache dir
  source). All other tasks (cache copy, register, enable, runtime setup) stay
  unconditional.

**Claude Code missing → silent install of an IDE that isn't there**

When the user picked claude-code on a machine without it (e.g. a fresh
container), the install completed but `claude` was unavailable and the only
hint was a generic warn line. Replace with an explicit pre-flight prompt:

  Claude Code is not installed. Claude-mem works best in Claude Code, but
  also works with the IDEs below.
  ? Install Claude Code now?
    ◆ Yes — install Claude Code (recommended)
    ◯ No — pick another IDE below
    ◯ Cancel installation

If the user picks "Yes", run `curl -fsSL https://claude.ai/install.sh | bash`
(or the PowerShell equivalent on Windows), then re-detect IDEs and proceed
with claude-code pre-selected. If the install fails or the user picks "No",
the multiselect still appears with claude-code visible (just unmarked
[detected]), so they can opt in or pick another IDE.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(install): detect Claude Code via `claude` CLI, not ~/.claude dir

The directory `~/.claude` can exist (e.g. mounted in Docker, or created
by tooling) without Claude Code actually being installed. Detect the
`claude` command in PATH instead so the installer correctly offers to
install Claude Code when missing.

* docs(learn-codebase): add reviewer note explaining the cost tradeoff

The skill intentionally reads every file in full to build a cognitive
cache that pays off across the rest of the project. Add a brief note
so reviewers (human or bot) understand the tradeoff before flagging
the unbounded read as a cost issue.

* fix: address Greptile P1 feedback on welcome hint and learn-codebase

- SearchRoutes: skip welcome hint when caller passes ?full=true so
  explicit full-context requests aren't intercepted by the hint.
- learn-codebase: replace `sed` instruction with the Read tool's
  offset/limit parameters, since Bash is gated in Claude Code by
  default.

* feat(install): ASCII-animated logo splash on interactive install

Plays a ~1s bloom animation of the claude-mem sunburst logomark when
the installer starts in an interactive terminal — geometrically rendered
via 12 ray curves around a center disc, in the brand orange. The
wordmark and tagline type on alongside the final frame.

Auto-skipped on non-TTY, in CI, when NO_COLOR or CLAUDE_MEM_NO_BANNER
is set, or when the terminal is too narrow.

Inspired by ghostty +boo.

* feat(banner): replace rotation frames with angular-sector bloom generator

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(banner): replace rotation frames with angular-sector bloom generator

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(banner): three-act choreography renderer with radial gradient and diff redraw

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(banner): update preview script to support small/medium/hero tier selection

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(docker): add COLORTERM=truecolor to test-installer sandbox

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(install): auto-apply PATH for Claude Code with spinner UX

The Claude Code install.sh prints a Setup notes block telling users to
manually edit "your shell config file" to add ~/.local/bin to PATH —
which left fresh installs unable to launch claude from the command line.

After a successful install, detect ~/.local/bin/claude on disk and, if
the dir is missing from PATH, append the right export line to .zshrc /
.bash_profile / .bashrc / fish config (idempotent, marked with a
comment). Also updates process.env.PATH for the current install run.

Wraps the curl|bash install in a clack spinner (interactive only) so the
~4 minute native-build download doesn't look frozen — output is captured
silently and dumped on failure for debuggability. Non-interactive mode
keeps inherited stdio for CI logs.

Verified end-to-end in the test-installer docker sandbox: spinner
animates, .bashrc gets the export, fresh login shell resolves claude.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(banner): video-frame ASCII renderer with three-act choreography

Generator switched from a single Jimp-rendered logo to pre-extracted
video frames concatenated with \x01 separators and gzip-deflated, ported
from ghostty's boo wire format. Renderer rewritten around three acts
(ignite → stagger bloom → text reveal + breathe) with adaptive sizing,
radial gradient, and diff-based redraw.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(onboarding): unify install / SessionStart / viewer around one first-success moment

Three surfaces now point at the same north-star moment — open the viewer, do
anything in Claude Code, watch an observation appear within seconds — with the
same verbatim timing and privacy lines, and a single canonical "how it works"
explainer instead of three diverging copies.

- Canonical explainer at src/services/worker/onboarding-explainer.md served via
  GET /api/onboarding/explainer; mirrored into plugin/skills/how-it-works/SKILL.md
- SessionStart welcome hint rewritten as third-person status (no imperatives
  Claude tries to execute), pinned with a default-value regression test
- Post-install Next Steps reframed as "two paths": passive default + optional
  /learn-codebase front-load; drops /mem-search and /knowledge-agent from this
  surface; adds verbatim timing + privacy lines and /how-it-works link
- /api/stats response gains firstObservationAt for the viewer stat row
- Viewer WelcomeCard branches on observationCount === 0: empty state shows live
  worker-connection dot + "waiting for activity"; has-data state shows
  observations · projects · since [date] and two example prompts. v2 dismiss key
- jimp added to package.json to fix pre-existing banner-frame build break

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(banner): play unconditionally; only honor CLAUDE_MEM_NO_BANNER

The 128-col / TTY / CI / NO_COLOR gates silently swallowed the banner in
narrower terminals, CI logs, and any non-TTY pipe — including Docker runs
where -it should preserve the experience but column width was the wrong
gate. Remove the implicit gates; keep the explicit opt-out only.

If a frame wraps in a narrow terminal, that's better than the banner
not playing at all.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* revert(banner): restore 15:33 gating logic per user request

Reverts eb6fc157. Restores isBannerEnabled to the state at commit
8e448015 (2026-04-30 15:33): TTY check, !CI, !NO_COLOR, !CLAUDE_MEM_NO_BANNER,
and cols >= BANNER.width.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(install): wrap remaining slow steps with spinners

Each IDE installer (Cursor, Gemini CLI, OpenCode, Windsurf, OpenClaw,
Codex CLI, MCP integrations) now runs inside a clack task spinner with
per-step progress messages instead of silent dynamic-import + cpSync.
Pre-overwrite worker shutdown (up to 10s) and the post-install health
probe (up to 3s) also get spinners.

Internal console.log/error/warn from each IDE installer is buffered
during the spinner; if the install fails, captured output is replayed
afterward via log.warn so users can see what broke.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(review): observation count + IDE pre-selection regressions

WelcomeCard's "no observations yet" empty state was triggered when a
project filter narrowed the feed to zero rows, even with thousands of
observations elsewhere. Source the count from global stats.database
to match firstObservationAt's scope.

Restore initialValues: [] in the IDE multiselect — pre-selecting every
detected IDE was the exact regression #2106 was filed for.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(install): trichotomy worker state + cache fallback for script path

ensureWorkerStarted now returns 'ready' | 'warming' | 'dead' instead of
boolean. The spawned-but-still-warming case (common in Docker cold
starts and slow first-time inits) was being misreported as 'did not
start', which contradicted the next-steps panel saying 'still starting
up'. Install task message and Next Steps headline now agree on the
actual state.

Also fixes the actual root cause of 'Worker did not start' on
claude-code-only installs: the worker script path was hardcoded to the
marketplace dir, which is left empty when no non-claude-code IDE is
selected. Now falls back to pluginCacheDirectory(version) when the
marketplace copy isn't present.

Verified end-to-end in docker/claude-mem with --ide claude-code,
--ide cursor, and a fresh container — install task and headline
agree on 'Worker ready at http://localhost:<port>' in all cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: align CLAUDE.md and public docs with current code

Sweep across CLAUDE.md and 10 high-traffic docs/public/ MDX files to
remove point-in-time references and align with the actual current
shape of the codebase. Highlights:

- Hardcoded port 37777 → per-user formula (37700 + uid % 100) on the
  front-door pages (introduction, installation, configuration,
  architecture/overview, architecture/worker-service, troubleshooting,
  hooks-architecture, platform-integration).
- Default model 'sonnet' → 'claude-haiku-4-5-20251001' (matches
  SettingsDefaultsManager).
- Node 18 → 20 (matches package.json engines).
- Lifecycle hook count corrected (5 events).
- Removed the nonexistent 'Smart Install' component and pre-built
  directory tree referencing files that no longer exist
  (context-hook.ts, save-hook.ts, cleanup-hook.ts, etc.); replaced
  with the real worker dispatcher shape.
- Removed CLAUDE.md '#2101' issue tag (kept the design rationale).
- Replaced obsolete hooks.json example with a description of the real
  bun-runner.js / worker-service.cjs hook event shape.

Lower-traffic doc pages still hardcode 37777 — left for a separate
global pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(scripts): land strip-comments around real parsers (postcss, remark, parse5)

Each language gets a real parser to locate comments, then we splice ranges
out of the original source. The library never serializes — that's how
remark-stringify produced 243 reformat-noise diffs in the first attempt
versus the 21 real strip targets here.

  JS/TS/JSX  -> ts.createSourceFile + getLeadingCommentRanges
  CSS/SCSS   -> postcss.parse + walkComments + node.source offsets
  MD/MDX     -> remark-parse (+ remark-mdx) + AST html / mdx-expression nodes
  HTML       -> parse5 with sourceCodeLocationInfo
  shell/py   -> kept hand-rolled hash stripper (no library worth the dep)

Preserves: shebangs, @ts-* directives, eslint-disable, biome-ignore,
prettier-ignore, triple-slash refs, webpack magic, /*! license keep,
@strip-comments-keep file marker. JS/TS handler runs a parse-roundtrip
check and refuses to write if syntax errors increased (catches the
worker-utils.ts breakage class from the 2026-04-29 attempt).

npm scripts:
  strip-comments         (apply)
  strip-comments:check   (CI-style, exits non-zero if changes needed)
  strip-comments:dry-run (list, no writes)

Verified --check on this repo: 21 changes, -4.0% bytes, no parse-error
regressions, no reformat-suspect false positives.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: strip comments codebase-wide via parser-backed tool

21 files changed, -17,550 bytes (-4.0%) of narrative comments removed
across .ts / .tsx / .js / .mjs and the .gitignore. JS/TS comments stripped
via ts.createSourceFile + getLeadingCommentRanges — same canonical lexer,
same behavior as the 2026-04-29 strip, no reformat noise.

Preexisting baseline (unchanged):
  typecheck: 16 errors at HEAD, 16 errors after strip (line numbers shift,
             no new error classes — verified via diff of sorted error lists)
  build:     fails at HEAD with CrushHooksInstaller.js unresolved import
             (preexisting, unrelated to this strip)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(install): drop Crush integration references after extract

The Crush integration was extracted to its own branch on May 1, but the
import at install.ts:280 (and the case block + ide-detection entry +
McpIntegrations config + npx-cli help text) still referenced the now-
removed CrushHooksInstaller.js, breaking the build.

Removes:
- case 'crush' block in install.ts
- crush entry in ide-detection.ts
- CRUSH_CONFIG and registration in McpIntegrations.ts
- 'crush' from the IDE Identifiers help line in index.ts

Rebuilds worker-service.cjs to match.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(banner): mark generated banner-frames.ts with @strip-comments-keep

Without this, every build/strip cycle ping-pongs five lines of doc
comments in and out of the auto-generated output. The keep-marker tells
strip-comments.ts to skip the file entirely.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(build): drop banner-frame regen from build script

generate-banner-frames.mjs requires PNG frames in /tmp/cmem-banner-frames
that only exist after the maintainer runs ffmpeg locally on the source
video. CI has neither the video nor the frames, so the build broke on
Windows. The output (src/npx-cli/banner-frames.ts) is committed, so the
regen is a one-shot dev step — not a build step. Run the script directly
when the video changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(worker): unstick the spinner — kill claim-self-lock, wake on fail, auto-broadcast

Three surgical changes that cure the stuck-spinner bug at the source.

Phase 1.1 (L9): claimNextMessage no longer self-excludes its own worker_pid.
A single UPDATE-RETURNING grabs the oldest pending row by id. Removes the
LiveWorkerPidsProvider plumbing that was never injected — Supervisor enforces
single-worker via PID file, so the multi-worker SQL was defending against a
configuration the project does not support.

Phase 1.2 (L19): SessionManager.markMessageFailed wraps PendingMessageStore.markFailed
and emits 'message' on the per-session EventEmitter. The iterator's waitForMessage
now wakes immediately on re-pend instead of parking for 3 minutes. ResponseProcessor
and SessionRoutes routed through the new wrapper.

Phase 1.3 (L24): PendingMessageStore takes an optional onMutate callback fired
from every mutator (enqueue, claimNextMessage, confirmProcessed, markFailed,
transitionMessagesTo, clearFailedOlderThan). SessionManager wires it; WorkerService
passes broadcastProcessingStatus. Ten manual broadcast calls deleted across
SessionCleanupHelper, SessionEventBroadcaster, SessionRoutes, DataRoutes, and
worker-service. Caller discipline becomes structurally impossible to forget.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(worker): delete dead code — legacy routes, processPendingQueues, decorative guards

Pure deletions. Phase 2 of kill-the-asshole-gates.

- Legacy /sessions/:sessionDbId/* routes (handleSessionInit, handleObservations,
  handleSummarize, handleSessionStatus, handleSessionDelete, handleSessionComplete)
  bypassed all five ingest gates and were a parallel write path. Folded the
  initializeSession + broadcastNewPrompt + syncUserPrompt + ensureGeneratorRunning
  + broadcastSessionStarted work into the canonical /api/sessions/init handler so
  the hook makes one round trip instead of two.
- processPendingQueues (~104 lines, zero callers) — replaced in Phase 6 by a
  one-statement startup sweep.
- spawnInProgress Map and crashRecoveryScheduled Set — decorative dedupe over
  generatorPromise and stillExists checks that already provide the real safety.
- STALE_GENERATOR_THRESHOLD_MS — pre-empted live generators and raced with the
  finally block; the 3min idle timeout already kills zombies.
- MAX_SESSION_WALL_CLOCK_MS — ran a SELECT on every observation to enforce 24h.
  Runaway-spend protection lives in the API key, not in claude-mem.
- Missing-id 400 in shared.ts ingestObservation — Zod already enforces min(1)
  on contentSessionId and toolName at the route schema.
- SessionCompletionHandler import + completionHandler field on SessionRoutes
  (orphaned after handler deletions).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(worker): SQL-backed getTotalQueueDepth — single source of truth

Was: iterate this.sessions.values() and sum getPendingCount per session.
Now: SELECT COUNT(*) FROM pending_messages WHERE status IN ('pending','processing').

The in-memory sessions Map drifted from the DB rows whenever a generator exited
without confirm/fail, leading to false-positive isProcessing in the UI. Phase 1.3's
auto-broadcast fires on every mutation, but it broadcast a stale Map count.
Reading from the DB makes the UI's spinner state match what the queue actually holds.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(worker): typed abortReason replaces wasAborted boolean

Was: a boolean wasAborted that lumped every abort together. The finally block
branched on !wasAborted, so any abort skipped restart — including idle aborts
with pending work, which is exactly the case where we DO want to restart.

Now: ActiveSession.abortReason is a typed enum 'idle' | 'shutdown' | 'overflow'
| 'restart-guard'. The finally block consumes the reason and only skips restart
for 'shutdown' and 'restart-guard'. Idle and overflow aborts fall through, so
if pending work exists they trigger restart correctly.

Dropped 'stale' and 'wall-clock' from the union — Phase 2 deleted those paths.
Natural-completion abort (post-success) intentionally has no reason; it's not
gating restart logic.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(worker): unify the two generator-exit finally blocks

Was: worker-service.ts:startSessionProcessor and SessionRoutes:ensureGeneratorRunning
each had their own ~70-line finally block with divergent restart-guard handling.
The worker-service path called terminateSession on RestartGuard trip and orphaned
pending rows (the L16 bug); the SessionRoutes path drained them. Two places to
update when rules changed.

Now: handleGeneratorExit in src/services/worker/session/GeneratorExitHandler.ts
owns the contract:
  1. Always kill the SDK subprocess if alive.
  2. Always drain processingMessageIds via sessionManager.markMessageFailed
     (which wakes the iterator — Phase 1.2).
  3. shutdown / restart-guard reasons: drain pending rows via
     transitionMessagesTo('failed'), finalize, remove from Map. Fixes L16.
  4. pendingCount=0: finalize normally and remove from Map.
  5. pendingCount>0: backoff respawn via per-session respawnTimer (no global Set;
     Phase 2.4 deleted that). RestartGuard trip drains to 'abandoned'.

Both finally blocks are now ~10-line wrappers that translate local state into the
canonical abortReason and delegate. Restored completionHandler injection into
SessionRoutes (was dropped in Phase 2 cleanup; needed by the unified helper for
finalizeSession).

Behavior change: SessionRoutes' previous "keep idle session in memory" was
deliberately replaced by the plan's "remove from Map on natural completion" —
next observation reinitializes via getMessageIterator → initializeSession.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(worker): startup orphan sweep — reset 'processing' rows at boot

When the worker dies (crash, kill, restart), any pending_messages rows it left
in 'processing' state are by definition orphans (the only worker is dead).
Single SQL UPDATE at boot resets them to 'pending' so the iterator can claim
them again. Replaces the deleted processPendingQueues function (Phase 2.2).

Runs in initializeBackground after dbManager.initialize() and before the
initializationComplete middleware releases blocked HTTP requests, so no
in-flight request can race the sweep. NOT on a periodic timer — after boot,
every 'processing' row has a live consumer and a periodic sweep would race.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(worker): simplify enqueue catch, replace memorySessionId throw with re-pend

7.1: queueObservation's catch was logging two ERROR-level messages and rethrowing.
The rethrow is correct (FK violations / disk full / schema drift should crash
loudly), but the verbose ERROR logging pretended the error was recoverable.
Reduced to one INFO line + rethrow.

7.2: ResponseProcessor's memorySessionId guard was throwing if the SDK hadn't
included session_id on the first user-yield, terminal-failing the entire batch.
Now warns and re-pends in-flight messages via sessionManager.markMessageFailed
(which wakes the iterator — Phase 1.2). The next iteration tries again with
memorySessionId hopefully captured.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sync): mirror builds to installed-version cache for hot reload

When package.json bumps past Claude Code's installed pin, sync-marketplace
wrote new code to cache/<buildVersion>/ but the worker loaded from
cache/<installedVersion>/, so worker:restart reloaded the same old code.

Replace the exit-on-mismatch preflight with a mirror step: when versions
differ, also rsync plugin/ into cache/<installedVersion>/ so worker:restart
hot-reloads new code without a Claude Code session restart. The
build-version cache still gets written for the eventual
`claude plugin update`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: delete dead barrel files and orphan utilities

- src/sdk/index.ts (re-exports parser+prompts; nothing imported the barrel)
- src/services/Context.ts (re-exports ./context/index.js; no importers)
- src/services/integrations/index.ts (no importers)
- src/services/worker/Search.ts (3-line barrel of ./search/index.js)
- src/services/infrastructure/index.ts: drop CleanupV12_4_3 re-export
- src/utils/error-messages.ts (getWorkerRestartInstructions never imported)
- src/types/transcript.ts (170 LoC of types, zero importers)
- src/npx-cli/_preview.ts (banner dev preview, no script wires it)

Build + tests still pass; observations still flowing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(parser): drop unused detectLanguage

Only the user-grammar-aware variant detectLanguageWithUserGrammars()
is actually called.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(types): drop unused SdkSessionRecord + ObservationWithContext

Both interfaces in src/types/database.ts had zero importers anywhere
in src or tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(npx-cli): drop unused getDetectedIDEs + claudeMemDataDirectory

getDetectedIDEs has no callers — install.ts uses detectInstalledIDEs
directly. claudeMemDataDirectory has no callers either.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(ProcessManager): drop dead orphan-reaper + signal-handler helpers

Each had zero callers in src/ or tests/:
  - cleanupOrphanedProcesses + enumerateOrphanedProcesses
  - ORPHAN_PROCESS_PATTERNS + ORPHAN_MAX_AGE_MINUTES
  - forceKillProcess
  - waitForProcessesExit
  - createSignalHandler
  - resetWorkerRuntimePathCache

The orphan reaper was retired in PATHFINDER Plan 02 ("OS process groups
replace hand-rolled reapers", commit 94d592f2) — these were the leftover
pieces. shutdown.ts uses the supervisor's own kill-pgid path instead.

parseElapsedTime kept (covered by tests/infrastructure/process-manager.test.ts).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(scripts): delete 11 unreferenced DX/forensic scripts

None of these are referenced by package.json npm scripts or docs/.
All last touched on Apr 29 only as part of the comment-stripping
pass — the feature code itself is older and orphaned:

  analyze-transformations-smart.js
  debug-transcript-structure.ts
  dump-transcript-readable.ts
  endless-mode-token-calculator.js
  extract-prompts-to-yaml.cjs
  extract-rich-context-examples.ts
  find-silent-failures.sh
  fix-all-timestamps.ts
  format-transcript-context.ts
  test-transcript-parser.ts
  transcript-to-markdown.ts

These are standalone tools — runtime behavior unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(scripts): delete unused extraction/ and types/ subdirs

- scripts/extraction/{extract-all-xml.py, filter-actual-xml.py, README.md}
  point at ~/Scripts/claude-mem/ — the user's pre-relocation path that no
  longer exists. Zero references in package.json, src/, or tests/.
- scripts/types/export.ts duplicates ObservationRecord etc. and has no
  importers (CodexCliInstaller imports transcripts/types, not this).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(BranchManager): drop dead getInstalledPluginPath

OpenCodeInstaller has its own (used) getInstalledPluginPath; the
BranchManager copy never had any external callers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(ChromaSyncState): unexport DocKind (used internally only)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(gemini): drop stale earliestPendingTimestamp / processingMessageIds

Both fields were removed from ActiveSession in earlier queue-engine
cleanup. Tests had been silently keeping them because the mock sessions
use 'as any' to bypass strict typing, so the dead fields rode along
without complaint.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: drop 3 unused module-level constants

- src/npx-cli/banner.ts: CURSOR_HOME, CLEAR_DOWN (banner uses
  CLEAR_SCREEN which combines clear-down + cursor-home into a single
  CSI sequence; the standalone constants were leftovers).
- src/services/worker/BranchManager.ts: DEFAULT_SHELL_TIMEOUT_MS
  (BranchManager only uses GIT_COMMAND_TIMEOUT_MS / NPM_INSTALL_TIMEOUT_MS).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(opencode-plugin): drop dead workerPost helper

Only the fire-and-forget variant (workerPostFireAndForget) is actually
called. workerPost was the await-result version with no remaining caller.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: drop 8 truly-unused interface fields

Verified each by grepping for `.field`, `"field"`, `'field'`, and
`field:` patterns across src/ + tests/ + plugin/scripts. Where the
only remaining usage was the assignment site, removed the assignments too.

- GitHubStarsData: watchers_count, forks_count (only stargazers_count read)
- TableColumnInfo: dflt_value (PRAGMA returns it but no caller reads it)
- IndexInfo: seq (PRAGMA returns it but no caller reads it)
- ObservationRecord: source_files (legacy field, no readers)
- HookResult.hookSpecificOutput: permissionDecisionReason
- WatchTarget: rescanIntervalMs (set in config, never read)
- ShutdownResult: confirmedStopped (write-only — assigned but no
  reader; updated all 3 return sites to drop it)
- ModePrompts: language_instruction (multilingual support never wired)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(npx-cli): reuse InstallOptions type instead of inline duplicate

parseInstallOptions had its return type written out inline as an
anonymous duplicate of InstallOptions. Use the canonical type
(import type — zero bundle cost).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(integrations): drop unused Platform type alias

The detectPlatform() function that returned this type was deleted earlier
in the branch (along with getScriptExtension that consumed it). The type
itself outlived its consumer; only string literals "Platform:" survive in
console.log diagnostics, which don't reference the alias.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(worker): broadcast processing_status when summarize is queued

broadcastSummarizeQueued was an empty no-op even though
handleSummarizeByClaudeId calls it after enqueueing. The PendingMessageStore
onMutate callback already fires broadcastProcessingStatus on enqueue, but
calling it explicitly from broadcastSummarizeQueued ensures the spinner
ticks on the moment a summary is requested even if the onMutate chain has
any timing race.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(worker): keep spinner on while summary generates

ClaudeProvider's SDK can pull multiple synthetic prompts (e.g.
observation + summarize) before producing responses. Each pull pushed
an ID to session.processingMessageIds. When the SDK's first
observation response came back, ResponseProcessor.confirmProcessed
deleted ALL pending message rows — including the still-in-flight
summary — so getTotalQueueDepth dropped to 0 and the spinner turned
off, even though the summary took another ~22s to actually generate.

Tag each in-flight message with its type ({id, type}) so the response
processor can pop only the FIFO message of the matching type
(observation vs summarize). The summary row stays in 'processing'
until its own response arrives, keeping the spinner lit through the
entire summary window.

Also updates Gemini/OpenRouter providers and GeneratorExitHandler for
the new shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(worker): clear summary from queue on any SDK response

Switch ResponseProcessor from type-aware FIFO matching to strict FIFO
popping (each SDK response → 1 in-flight message consumed). This way
the summary always clears when the SDK responds, even when the
response is unparseable or the summary doesn't actually generate
content — preventing stuck spinner / queue-depth-stuck-at-1.

Spinner behavior is preserved: messages enqueued after the summary
keep the queue depth elevated, and only when the SDK has responded
to every prompt does the queue drain to zero.

Also: when the consumed message is a 'summarize' and parsing fails,
treat it as best-effort and confirmProcessed (no retry) — summaries
that can't be parsed shouldn't keep retrying.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(viewer): redesign welcome card and remove source filters

The first-start welcome card now explains the three feed card types
(observation/summary/prompt) with color-coded badges, points users at
the gear icon for settings and the project dropdown for filtering, and
plugs /mem-search for recall — replacing the old two-line "ask:" prompts.

Source filter tabs (Claude/Codex/etc.) are removed from the header.
Filtering by AI provider was nonsense from a user POV; the project
dropdown is the only header filter now. Source tracking is also
stripped from useSSE, usePagination, App state, and CSS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(viewer): keep welcome card in feed column, swap rows for 3 squares

Two visible problems in the previous design: the card stretched
edge-to-edge while feed cards sit in a centered 650px column, and
the body was a stack of long horizontal rows that scanned line-by-line.

Both fixed: Feed now accepts a pinnedTop slot so the welcome card
renders inside the same .feed-content column as observation cards.
Body is now a 3-column grid of square feature blocks — Live feed,
Tune it, Recall it — each with a custom inline SVG illustration
(stacked cards with color-coded stripes, gear+sliders, magnifier
over cards). Old text-row sections (welcome-card-types,
welcome-card-tips, welcome-card-section, welcome-card-tip-icon)
are removed. Squares stack to one column under 600px.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(viewer): convert welcome card to glassy modal with stylized logo

Card now opens as a centered modal with a frosted/glass backdrop
(blur + saturate) so it doubles as a proper help dialog when reopened
from the header's question-mark button. Removed the observation count,
project count, and "since" date — those don't make sense for a
first-launch surface and felt out of place in a help context.

Header art swapped from the small webp logomark to the new
high-resolution sun/sunburst PNG (claude-mem-logo-stylized.png),
shipped as a checked-in asset in src/ui and plugin/ui.

Bigger throughout: 28px h2, 16px tagline, 88px illustrations,
26px feature padding, 1:1 aspect-ratio squares. Backdrop click and
Esc both close. Mobile collapses the grid to one column and drops
the aspect-ratio constraint.

Reverted the unused pinnedTop slot on Feed.tsx since the welcome
card is now a true overlay rather than an in-feed pinned card.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(viewer): make welcome modal actually glassy

Previous version had a 55%-opacity black backdrop that almost fully
blocked the underlying UI — the "glass" was just a dark plate.

Now the backdrop is fully transparent (no darkening at all), the
panel itself drops to 55% bg-card opacity with its existing
backdrop-filter blur(28px) saturate(170%), and the feature squares
drop to 35% bg-tertiary so they layer as glass-on-glass over the
already-blurred panel. The header and feed below now read clearly
through the modal's frosted blur.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(viewer): bulletproof square features via padding-bottom + clamp() fluid type

Squares were rendering taller than wide because aspect-ratio is treated
as a minimum — content can push the box past 1:1. Switched to the
classic padding-bottom: 100% trick: percentage padding resolves against
the parent's width, so the box is ALWAYS W × W regardless of content.
Inner content sits in an absolutely-positioned flex column that can't
push the shell taller.

Whole modal is now desktop-first and fluid via clamp() — no media-query
stair-steps for type, padding, gaps, border-radius, illustration size,
or modal width. Single mobile breakpoint at <600px collapses the grid
to one column and reverts the padding-bottom trick so each feature can
grow to natural content height.

Tightened the three feature descriptions so they fit comfortably inside
the square at the desktop size.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* style(viewer): 15% black overlay + heavier modal shadow for elevation

Backdrop goes from transparent to rgba(0,0,0,0.15) — just enough
darkening to push the modal visually forward without burying the
underlying UI. Modal shadow stacked: 40px/120px ambient + 16px/48px
contact, both deeper, plus the existing inset 1px highlight.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(build): clear pending_messages queue on build-and-sync

Rewrites scripts/clear-failed-queue.ts to talk directly to SQLite via
bun:sqlite — the previous HTTP endpoints (/api/pending-queue/*) were
removed during the queue engine rewrite, so the script was orphaned.
Wires `npm run queue:clear` into `build-and-sync` so each rebuild
starts with a clean queue.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(worker): collapse parser to binary valid/invalid + clearPendingForSession model

- Parser: { valid: true, observations, summary } | { valid: false } — drops kind/skipped enum dispatch
- ResponseProcessor: two branches only (parseable → store + clearPendingForSession; else → no-op)
- Drop processingMessageIds + per-message claim/confirm/markFailed lifecycle across 3 providers
- PendingMessageStore: 226 → 140 lines; remove markFailed/transitionMessagesTo/confirmProcessed/clearFailedOlderThan/getAllPending/peekPendingTypes... wait keep peekPendingTypes
- Schema migration v31+v32: drop retry_count, failed_at_epoch, completed_at_epoch, worker_pid columns
- SessionQueueProcessor: delete two 1s recovery sleeps (let iterator end on error)
- Server.ts/SettingsRoutes.ts: replace four magic-number setTimeout exit-flush patterns with flushResponseThen helper
- GeneratorExitHandler: 183 → 117 lines (drain in-flight loop gone)

Net: -181 lines. No more silent data loss via maxRetries=3.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pr-2255): address review comments batch 1

- install.ts: needsMarketplace true when claude-code selected (P1, was no-op)
- install.ts: throw on invalid --model so CLI exits non-zero
- install.ts: skip worker health checks + adapt next-step copy when --no-auto-start
- install.ts: repair regenerates plugin cache when missing
- index.ts: readFlag rejects missing/flag-shaped values
- index.ts: route flag-first invocations (e.g. `--provider claude`) to install
- banner.ts: fail-open if frame payload decode throws
- SearchRoutes.ts: 5s TTL cache for settings reads on hot hook path (P2)
- detect-error-handling-antipatterns.ts: trailing-brace strip whitespace-tolerant
- investigate-timestamps.ts: compute Dec 2025 epochs at runtime (was Dec 2024)
- regenerate-claude-md.ts: include workingDir in fallback walker so root is covered
- sync-marketplace.cjs: parseWorkerPort validates 1..65535 before http.request
- sync-to-marketplace.sh: resolve SOURCE_DIR from script location, not cwd
- Dockerfile.test-installer: bash --login sources .bashrc via .bash_profile
- docs/configuration.mdx: drop nonexistent .worker.port file refs, use settings.json
- docs/architecture-overview.md: dynamic port + queue model after parser collapse
- docs/architecture/worker-service.mdx: dynamic port example + drop port-file claim
- docs/platform-integration.mdx: WORKER_BASE_URL pattern, drop hardcoded 37777
- install/public/install.sh: Node 20 floor (was 18) to match docs

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pr-2255): reset claimed messages to pending on early-return paths

ResponseProcessor returns early in two cases:
- parser invalid (unparseable response)
- memorySessionId not yet captured

Both paths previously left the just-claimed message in `status='processing'`,
which counts toward `getPendingCount`. The generator-exit handler then sees
`pendingCount > 0` and respawns the generator, looping until the restart
guard trips and `clearPendingForSession` deletes the message — silent data
loss.

Calling `resetProcessingToPending` on these paths lets the next generator
pass re-claim the message and try again, instead of burning the restart
budget on no-op respawns.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pr-2255): swebench fallback row + troubleshooting port path

- evals/swebench/run-batch.py: append fallback prediction row when
  orchestrator future raises, preserving "never drop an instance" guarantee
- docs/troubleshooting.mdx: drop nonexistent .worker.port / worker.port file
  references; use settings.json + /api/health for port discovery

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pr-2255): memoize per-project observation count for welcome-hint hot path

handleContextInject runs on every PostToolUse hook (after every Read/Edit).
The welcome-hint block ran a COUNT(*) on observations for every call once
CLAUDE_MEM_WELCOME_HINT_ENABLED was true. Observation counts are
monotonically increasing — once a project has any observations it always
will — so cache the positive result in a Set and skip the COUNT(*) on
subsequent requests.

Combined with the 5s settings TTL added earlier, the steady-state cost on
the hook hot path drops to a Set lookup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pr-2255): use clearProcessingForSession on AI-success path

clearPendingForSession deletes ALL rows for the session. On the success
path of processAgentResponse, that's wrong: messages that arrived as
'pending' during the (1-5s) AI response latency get deleted along with
the 'processing' row we just consumed. In a hook burst (three quick
PostToolUse hooks), B and C land while A is in flight; A's success then
nukes B and C — silent data loss.

Add a status-scoped clearProcessingForSession to PendingMessageStore +
SessionManager, and use it in ResponseProcessor's success path. The
unconditional clearPendingForSession remains correct in
GeneratorExitHandler for hard-stop / restart-guard-trip paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Revert "fix(pr-2255): use clearProcessingForSession on AI-success path"

This reverts commit a08995299c30cbad36bddc3e5bddda7af8604b35.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 16:05:56 -07:00

177 lines
231 KiB
JavaScript
Executable File

#!/usr/bin/env node
"use strict";var ad=Object.create;var Bi=Object.defineProperty;var cd=Object.getOwnPropertyDescriptor;var ld=Object.getOwnPropertyNames;var ud=Object.getPrototypeOf,dd=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var fd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ld(e))!dd.call(t,s)&&s!==r&&Bi(t,s,{get:()=>e[s],enumerable:!(n=cd(e,s))||n.enumerable});return t};var ne=(t,e,r)=>(r=t!=null?ad(ud(t)):{},fd(e||!t||!t.__esModule?Bi(r,"default",{value:t,enumerable:!0}):r,t));var cr=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.regexpCode=N.getEsmExportName=N.getProperty=N.safeStringify=N.stringify=N.strConcat=N.addCodeArg=N.str=N._=N.nil=N._Code=N.Name=N.IDENTIFIER=N._CodeOrName=void 0;var ir=class{};N._CodeOrName=ir;N.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var it=class extends ir{constructor(e){if(super(),!N.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}}};N.Name=it;var he=class extends ir{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 it&&(r[n.str]=(r[n.str]||0)+1),r),{})}};N._Code=he;N.nil=new he("");function ya(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ms(r,e[n]),r.push(t[++n]);return new he(r)}N._=ya;var Rs=new he("+");function _a(t,...e){let r=[ar(t[0])],n=0;for(;n<e.length;)r.push(Rs),Ms(r,e[n]),r.push(Rs,ar(t[++n]));return np(r),new he(r)}N.str=_a;function Ms(t,e){e instanceof he?t.push(...e._items):e instanceof it?t.push(e):t.push(ip(e))}N.addCodeArg=Ms;function np(t){let e=1;for(;e<t.length-1;){if(t[e]===Rs){let r=sp(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function sp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof it||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 it))return`"${t}${e.slice(1)}`}function op(t,e){return e.emptyStr()?t:t.emptyStr()?e:_a`${t}${e}`}N.strConcat=op;function ip(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ar(Array.isArray(t)?t.join(","):t)}function ap(t){return new he(ar(t))}N.stringify=ap;function ar(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}N.safeStringify=ar;function cp(t){return typeof t=="string"&&N.IDENTIFIER.test(t)?new he(`.${t}`):ya`[${t}]`}N.getProperty=cp;function lp(t){if(typeof t=="string"&&N.IDENTIFIER.test(t))return new he(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}N.getEsmExportName=lp;function up(t){return new he(t.toString())}N.regexpCode=up});var Os=b(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.ValueScope=oe.ValueScopeName=oe.Scope=oe.varKinds=oe.UsedValueState=void 0;var se=cr(),As=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ln;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ln||(oe.UsedValueState=ln={}));oe.varKinds={const:new se.Name("const"),let:new se.Name("let"),var:new se.Name("var")};var un=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=un;var dn=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=dn;var dp=(0,se._)`\n`,Cs=class extends un{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?dp:se.nil}}get(){return this._scope}name(e){return new dn(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,ln.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 As(u);l.set(u,ln.Completed)})}return o}};oe.ValueScope=Cs});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=cr(),we=Os(),Je=cr();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 hn=Os();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return hn.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return hn.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return hn.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return hn.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 qe=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Is=class extends qe{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?we.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=kt(this.rhs,e,r)),this}get names(){return this.rhs instanceof I._CodeOrName?this.rhs.names:{}}},fn=class extends qe{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=kt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof I.Name?{}:{...this.lhs.names};return mn(e,this.rhs)}},xs=class extends fn{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ds=class extends qe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ns=class extends qe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},zs=class extends qe{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ls=class extends qe{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=kt(this.code,e,r),this}get names(){return this.code instanceof I._CodeOrName?this.code.names:{}}},lr=class extends qe{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)||(fp(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>lt(e,r.names),{})}},Ue=class extends lr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},js=class extends lr{},vt=class extends Ue{};vt.kind="else";var at=class t extends Ue{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 vt(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Sa(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=kt(this.condition,e,r),this}get names(){let e=super.names;return mn(e,this.condition),this.else&&lt(e,this.else.names),e}};at.kind="if";var ct=class extends Ue{};ct.kind="for";var qs=class extends ct{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=kt(this.iteration,e,r),this}get names(){return lt(super.names,this.iteration.names)}},Us=class extends ct{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?we.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=mn(super.names,this.from);return mn(e,this.to)}},pn=class extends ct{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=kt(this.iterable,e,r),this}get names(){return lt(super.names,this.iterable.names)}},ur=class extends Ue{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)}};ur.kind="func";var dr=class extends lr{render(e){return"return "+super.render(e)}};dr.kind="return";var Fs=class extends Ue{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&&lt(e,this.catch.names),this.finally&&lt(e,this.finally.names),e}},fr=class extends Ue{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fr.kind="catch";var pr=class extends Ue{render(e){return"finally"+super.render(e)}};pr.kind="finally";var Hs=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
`:""},this._extScope=e,this._scope=new we.Scope({parent:e}),this._nodes=[new js]}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 Is(e,o,n)),o}const(e,r,n){return this._def(we.varKinds.const,e,r,n)}let(e,r,n){return this._def(we.varKinds.let,e,r,n)}var(e,r,n){return this._def(we.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new fn(e,r,n))}add(e,r){return this._leafNode(new xs(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==I.nil&&this._leafNode(new Ls(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 at(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 at(e))}else(){return this._elseNode(new vt)}endIf(){return this._endBlockNode(at,vt)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new qs(e),r)}forRange(e,r,n,s,o=this.opts.es5?we.varKinds.var:we.varKinds.let){let i=this._scope.toName(e);return this._for(new Us(o,i,r,n),()=>s(i))}forOf(e,r,n,s=we.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 pn("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?we.varKinds.var:we.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 pn("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(ct)}label(e){return this._leafNode(new Ds(e))}break(e){return this._leafNode(new Ns(e))}return(e){let r=new dr;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(dr)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Fs;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new fr(o),r(o)}return n&&(this._currNode=s.finally=new pr,this.code(n)),this._endBlockNode(fr,pr)}throw(e){return this._leafNode(new zs(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 ur(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(ur)}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 at))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=Hs;function lt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function mn(t,e){return e instanceof I._CodeOrName?lt(t,e.names):t}function kt(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 fp(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Sa(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,I._)`!${Ws(t)}`}M.not=Sa;var pp=Ea(M.operators.AND);function mp(...t){return t.reduce(pp)}M.and=mp;var hp=Ea(M.operators.OR);function gp(...t){return t.reduce(hp)}M.or=gp;function Ea(t){return(e,r)=>e===I.nil?r:r===I.nil?e:(0,I._)`${Ws(e)} ${t} ${Ws(r)}`}function Ws(t){return t instanceof I.Name?t:(0,I._)`(${t})`}});var x=b(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var L=R(),yp=cr();function _p(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=_p;function Sp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(va(t,e),!ka(e,t.self.RULES.all))}C.alwaysValidSchema=Sp;function va(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]||$a(t,`unknown keyword: "${o}"`)}C.checkUnknownRules=va;function ka(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=ka;function Ep(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=Ep;function wp({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,L._)`${r}`}return(0,L._)`${t}${e}${(0,L.getProperty)(n)}`}C.schemaRefOrVal=wp;function bp(t){return Ta(decodeURIComponent(t))}C.unescapeFragment=bp;function vp(t){return encodeURIComponent(Gs(t))}C.escapeFragment=vp;function Gs(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=Gs;function Ta(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=Ta;function kp(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=kp;function wa({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,c)=>{let l=i===void 0?o:i instanceof L.Name?(o instanceof L.Name?t(s,o,i):e(s,o,i),i):o instanceof L.Name?(e(s,i,o),o):r(o,i);return c===L.Name&&!(l instanceof L.Name)?n(s,l):l}}C.mergeEvaluated={props:wa({mergeNames:(t,e,r)=>t.if((0,L._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,L._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,L._)`${r} || {}`).code((0,L._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,L._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,L._)`${r} || {}`),Ks(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pa}),items:wa({mergeNames:(t,e,r)=>t.if((0,L._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,L._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,L._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,L._)`${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,L._)`{}`);return e!==void 0&&Ks(t,r,e),r}C.evaluatedPropsToName=Pa;function Ks(t,e,r){Object.keys(r).forEach(n=>t.assign((0,L._)`${e}${(0,L.getProperty)(n)}`,!0))}C.setEvaluated=Ks;var ba={};function Tp(t,e){return t.scopeValue("func",{ref:e,code:ba[e.code]||(ba[e.code]=new yp._Code(e.code))})}C.useFunc=Tp;var Vs;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Vs||(C.Type=Vs={}));function Pp(t,e,r){if(t instanceof L.Name){let n=e===Vs.Num;return r?n?(0,L._)`"[" + ${t} + "]"`:(0,L._)`"['" + ${t} + "']"`:n?(0,L._)`"/" + ${t}`:(0,L._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,L.getProperty)(t).toString():"/"+Gs(t)}C.getErrorPath=Pp;function $a(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}C.checkStrictMode=$a});var Fe=b(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var Z=R(),$p={data:new Z.Name("data"),valCxt:new Z.Name("valCxt"),instancePath:new Z.Name("instancePath"),parentData:new Z.Name("parentData"),parentDataProperty:new Z.Name("parentDataProperty"),rootData:new Z.Name("rootData"),dynamicAnchors:new Z.Name("dynamicAnchors"),vErrors:new Z.Name("vErrors"),errors:new Z.Name("errors"),this:new Z.Name("this"),self:new Z.Name("self"),scope:new Z.Name("scope"),json:new Z.Name("json"),jsonPos:new Z.Name("jsonPos"),jsonLen:new Z.Name("jsonLen"),jsonPart:new Z.Name("jsonPart")};Ys.default=$p});var mr=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.extendErrors=X.resetErrorsCount=X.reportExtraError=X.reportError=X.keyword$DataError=X.keywordError=void 0;var D=R(),gn=x(),te=Fe();X.keywordError={message:({keyword:t})=>(0,D.str)`must pass "${t}" keyword validation`};X.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,D.str)`"${t}" keyword must be ${e} ($data)`:(0,D.str)`"${t}" keyword is invalid ($data)`};function Rp(t,e=X.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:c}=s,l=Aa(t,e,r);n??(i||c)?Ra(o,l):Ma(s,(0,D._)`[${l}]`)}X.reportError=Rp;function Mp(t,e=X.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,c=Aa(t,e,r);Ra(s,c),o||i||Ma(n,te.default.vErrors)}X.reportExtraError=Mp;function Ap(t,e){t.assign(te.default.errors,e),t.if((0,D._)`${te.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,D._)`${te.default.vErrors}.length`,e),()=>t.assign(te.default.vErrors,null)))}X.resetErrorsCount=Ap;function Cp({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,te.default.errors,c=>{t.const(i,(0,D._)`${te.default.vErrors}[${c}]`),t.if((0,D._)`${i}.instancePath === undefined`,()=>t.assign((0,D._)`${i}.instancePath`,(0,D.strConcat)(te.default.instancePath,o.errorPath))),t.assign((0,D._)`${i}.schemaPath`,(0,D.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,D._)`${i}.schema`,r),t.assign((0,D._)`${i}.data`,n))})}X.extendErrors=Cp;function Ra(t,e){let r=t.const("err",e);t.if((0,D._)`${te.default.vErrors} === null`,()=>t.assign(te.default.vErrors,(0,D._)`[${r}]`),(0,D._)`${te.default.vErrors}.push(${r})`),t.code((0,D._)`${te.default.errors}++`)}function Ma(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,D._)`new ${t.ValidationError}(${e})`):(r.assign((0,D._)`${n}.errors`,e),r.return(!1))}var ut={keyword:new D.Name("keyword"),schemaPath:new D.Name("schemaPath"),params:new D.Name("params"),propertyName:new D.Name("propertyName"),message:new D.Name("message"),schema:new D.Name("schema"),parentSchema:new D.Name("parentSchema")};function Aa(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,D._)`{}`:Op(t,e,r)}function Op(t,e,r={}){let{gen:n,it:s}=t,o=[Ip(s,r),xp(t,r)];return Dp(t,e,o),n.object(...o)}function Ip({errorPath:t},{instancePath:e}){let r=e?(0,D.str)`${t}${(0,gn.getErrorPath)(e,gn.Type.Str)}`:t;return[te.default.instancePath,(0,D.strConcat)(te.default.instancePath,r)]}function xp({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,D.str)`${e}/${t}`;return r&&(s=(0,D.str)`${s}${(0,gn.getErrorPath)(r,gn.Type.Str)}`),[ut.schemaPath,s]}function Dp(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([ut.keyword,s],[ut.params,typeof e=="function"?e(t):e||(0,D._)`{}`]),l.messages&&n.push([ut.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([ut.schema,i],[ut.parentSchema,(0,D._)`${d}${f}`],[te.default.data,o]),u&&n.push([ut.propertyName,u])}});var Oa=b(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.boolOrEmptySchema=Tt.topBoolOrEmptySchema=void 0;var Np=mr(),zp=R(),Lp=Fe(),jp={message:"boolean schema is false"};function qp(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ca(t,!1):typeof r=="object"&&r.$async===!0?e.return(Lp.default.data):(e.assign((0,zp._)`${n}.errors`,null),e.return(!0))}Tt.topBoolOrEmptySchema=qp;function Up(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ca(t)):r.var(e,!0)}Tt.boolOrEmptySchema=Up;function Ca(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,Np.reportError)(s,jp,void 0,e)}});var Bs=b(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getRules=Pt.isJSONType=void 0;var Fp=["string","number","integer","boolean","null","object","array"],Hp=new Set(Fp);function Wp(t){return typeof t=="string"&&Hp.has(t)}Pt.isJSONType=Wp;function Vp(){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=Vp});var Js=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.shouldUseRule=Ze.shouldUseGroup=Ze.schemaHasRulesForType=void 0;function Gp({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ia(t,n)}Ze.schemaHasRulesForType=Gp;function Ia(t,e){return e.rules.some(r=>xa(t,r))}Ze.shouldUseGroup=Ia;function xa(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=xa});var hr=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.reportTypeError=Q.checkDataTypes=Q.checkDataType=Q.coerceAndCheckDataType=Q.getJSONTypes=Q.getSchemaTypes=Q.DataType=void 0;var Kp=Bs(),Yp=Js(),Bp=mr(),$=R(),Da=x(),$t;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})($t||(Q.DataType=$t={}));function Jp(t){let e=Na(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}Q.getSchemaTypes=Jp;function Na(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Kp.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Q.getJSONTypes=Na;function Zp(t,e){let{gen:r,data:n,opts:s}=t,o=Xp(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,Yp.schemaHasRulesForType)(t,e[0]));if(i){let c=Xs(e,n,s.strictNumbers,$t.Wrong);r.if(c,()=>{o.length?Qp(t,e,o):Qs(t)})}return i}Q.coerceAndCheckDataType=Zp;var za=new Set(["string","number","integer","boolean","null"]);function Xp(t,e){return e?t.filter(r=>za.has(r)||e==="array"&&r==="array"):[]}function Qp(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,$._)`typeof ${s}`),c=n.let("coerced",(0,$._)`undefined`);o.coerceTypes==="array"&&n.if((0,$._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,$._)`${s}[0]`).assign(i,(0,$._)`typeof ${s}`).if(Xs(e,s,o.strictNumbers),()=>n.assign(c,s))),n.if((0,$._)`${c} !== undefined`);for(let u of r)(za.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);n.else(),Qs(t),n.endIf(),n.if((0,$._)`${c} !== undefined`,()=>{n.assign(s,c),em(t,c)});function l(u){switch(u){case"string":n.elseIf((0,$._)`${i} == "number" || ${i} == "boolean"`).assign(c,(0,$._)`"" + ${s}`).elseIf((0,$._)`${s} === null`).assign(c,(0,$._)`""`);return;case"number":n.elseIf((0,$._)`${i} == "boolean" || ${s} === null
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(c,(0,$._)`+${s}`);return;case"integer":n.elseIf((0,$._)`${i} === "boolean" || ${s} === null
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(c,(0,$._)`+${s}`);return;case"boolean":n.elseIf((0,$._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(c,!1).elseIf((0,$._)`${s} === "true" || ${s} === 1`).assign(c,!0);return;case"null":n.elseIf((0,$._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(c,null);return;case"array":n.elseIf((0,$._)`${i} === "string" || ${i} === "number"
|| ${i} === "boolean" || ${s} === null`).assign(c,(0,$._)`[${s}]`)}}}function em({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,$._)`${e} !== undefined`,()=>t.assign((0,$._)`${e}[${r}]`,n))}function Zs(t,e,r,n=$t.Correct){let s=n===$t.Correct?$.operators.EQ:$.operators.NEQ,o;switch(t){case"null":return(0,$._)`${e} ${s} null`;case"array":o=(0,$._)`Array.isArray(${e})`;break;case"object":o=(0,$._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,$._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,$._)`typeof ${e} ${s} ${t}`}return n===$t.Correct?o:(0,$.not)(o);function i(c=$.nil){return(0,$.and)((0,$._)`typeof ${e} == "number"`,c,r?(0,$._)`isFinite(${e})`:$.nil)}}Q.checkDataType=Zs;function Xs(t,e,r,n){if(t.length===1)return Zs(t[0],e,r,n);let s,o=(0,Da.toHash)(t);if(o.array&&o.object){let i=(0,$._)`typeof ${e} != "object"`;s=o.null?i:(0,$._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=$.nil;o.number&&delete o.integer;for(let i in o)s=(0,$.and)(s,Zs(i,e,r,n));return s}Q.checkDataTypes=Xs;var tm={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,$._)`{type: ${t}}`:(0,$._)`{type: ${e}}`};function Qs(t){let e=rm(t);(0,Bp.reportError)(e,tm)}Q.reportTypeError=Qs;function rm(t){let{gen:e,data:r,schema:n}=t,s=(0,Da.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var ja=b(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.assignDefaults=void 0;var Rt=R(),nm=x();function sm(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)La(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>La(t,o,s.default))}yn.assignDefaults=sm;function La(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let c=(0,Rt._)`${o}${(0,Rt.getProperty)(e)}`;if(s){(0,nm.checkStrictMode)(t,`default is ignored for: ${c}`);return}let l=(0,Rt._)`${c} === undefined`;i.useDefaults==="empty"&&(l=(0,Rt._)`${l} || ${c} === null || ${c} === ""`),n.if(l,(0,Rt._)`${c} = ${(0,Rt.stringify)(r)}`)}});var ge=b(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.validateUnion=z.validateArray=z.usePattern=z.callValidateCode=z.schemaProperties=z.allSchemaProperties=z.noPropertyInData=z.propertyInData=z.isOwnProperty=z.hasPropFunc=z.reportMissingProp=z.checkMissingProp=z.checkReportMissingProp=void 0;var j=R(),eo=x(),Xe=Fe(),om=x();function im(t,e){let{gen:r,data:n,it:s}=t;r.if(ro(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,j._)`${e}`},!0),t.error()})}z.checkReportMissingProp=im;function am({gen:t,data:e,it:{opts:r}},n,s){return(0,j.or)(...n.map(o=>(0,j.and)(ro(t,e,o,r.ownProperties),(0,j._)`${s} = ${o}`)))}z.checkMissingProp=am;function cm(t,e){t.setParams({missingProperty:e},!0),t.error()}z.reportMissingProp=cm;function qa(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,j._)`Object.prototype.hasOwnProperty`})}z.hasPropFunc=qa;function to(t,e,r){return(0,j._)`${qa(t)}.call(${e}, ${r})`}z.isOwnProperty=to;function lm(t,e,r,n){let s=(0,j._)`${e}${(0,j.getProperty)(r)} !== undefined`;return n?(0,j._)`${s} && ${to(t,e,r)}`:s}z.propertyInData=lm;function ro(t,e,r,n){let s=(0,j._)`${e}${(0,j.getProperty)(r)} === undefined`;return n?(0,j.or)(s,(0,j.not)(to(t,e,r))):s}z.noPropertyInData=ro;function Ua(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}z.allSchemaProperties=Ua;function um(t,e){return Ua(e).filter(r=>!(0,eo.alwaysValidSchema)(t,e[r]))}z.schemaProperties=um;function dm({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},c,l,u){let d=u?(0,j._)`${t}, ${e}, ${n}${s}`:e,f=[[Xe.default.instancePath,(0,j.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,j._)`${d}, ${r.object(...f)}`;return l!==j.nil?(0,j._)`${c}.call(${l}, ${p})`:(0,j._)`${c}(${p})`}z.callValidateCode=dm;var fm=(0,j._)`new RegExp`;function pm({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,j._)`${s.code==="new RegExp"?fm:(0,om.useFunc)(t,s)}(${r}, ${n})`})}z.usePattern=pm;function mm(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,j._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:eo.Type.Num},o),e.if((0,j.not)(o),c)})}}z.validateArray=mm;function hm(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,eo.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,j._)`${i} || ${c}`),t.mergeValidEvaluated(d,c)||e.if((0,j.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}z.validateUnion=hm});var Wa=b($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.validateKeywordUsage=$e.validSchemaType=$e.funcKeywordCode=$e.macroKeywordCode=void 0;var re=R(),dt=Fe(),gm=ge(),ym=mr();function _m(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,c=e.macro.call(i.self,s,o,i),l=Ha(r,n,c);i.opts.validateSchema!==!1&&i.self.validateSchema(c,!0);let u=r.name("valid");t.subschema({schema:c,schemaPath:re.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}$e.macroKeywordCode=_m;function Sm(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:c,it:l}=t;wm(l,e);let u=!c&&e.compile?e.compile.call(l.self,o,i,l):e.validate,d=Ha(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&&Fa(t),_(()=>t.error());else{let E=e.async?m():h();e.modifying&&Fa(t),_(()=>Em(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>g((0,re._)`await `),S=>n.assign(f,!1).if((0,re._)`${S} instanceof ${l.ValidationError}`,()=>n.assign(E,(0,re._)`${S}.errors`),()=>n.throw(S))),E}function h(){let E=(0,re._)`${d}.errors`;return n.assign(E,null),g(re.nil),E}function g(E=e.async?(0,re._)`await `:re.nil){let S=l.opts.passContext?dt.default.this:dt.default.self,w=!("compile"in e&&!c||e.schema===!1);n.assign(f,(0,re._)`${E}${(0,gm.callValidateCode)(t,d,S,w)}`,e.modifying)}function _(E){var S;n.if((0,re.not)((S=e.valid)!==null&&S!==void 0?S:f),E)}}$e.funcKeywordCode=Sm;function Fa(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,re._)`${n.parentData}[${n.parentDataProperty}]`))}function Em(t,e){let{gen:r}=t;r.if((0,re._)`Array.isArray(${e})`,()=>{r.assign(dt.default.vErrors,(0,re._)`${dt.default.vErrors} === null ? ${e} : ${dt.default.vErrors}.concat(${e})`).assign(dt.default.errors,(0,re._)`${dt.default.vErrors}.length`),(0,ym.extendErrors)(t)},()=>t.error())}function wm({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ha(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,re.stringify)(r)})}function bm(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")}$e.validSchemaType=bm;function vm({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)}}$e.validateKeywordUsage=vm});var Ga=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.extendSubschemaMode=Qe.extendSubschemaData=Qe.getSubschema=void 0;var Re=R(),Va=x();function km(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,Re._)`${t.schemaPath}${(0,Re.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:c[r],schemaPath:(0,Re._)`${t.schemaPath}${(0,Re.getProperty)(e)}${(0,Re.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Va.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=km;function Tm(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,Re._)`${e.data}${(0,Re.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Re.str)`${u}${(0,Va.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Re._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Re.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=Tm;function Pm(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=Pm});var no=b((lv,Ka)=>{"use strict";Ka.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 Ba=b((uv,Ya)=>{"use strict";var et=Ya.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(){};_n(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 _n(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++)_n(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)_n(t,e,r,f[m],s+"/"+d+"/"+$m(m),o,s,d,n,m)}else(d in et.keywords||t.allKeys&&!(d in et.skipKeywords))&&_n(t,e,r,f,s+"/"+d,o,s,d,n)}r(n,s,o,i,c,l,u)}}function $m(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gr=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 Rm=x(),Mm=no(),Am=Ba(),Cm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Om(t,e=!0){return typeof t=="boolean"?!0:e===!0?!so(t):e?Ja(t)<=e:!1}ie.inlineRef=Om;var Im=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function so(t){for(let e in t){if(Im.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(so)||typeof r=="object"&&so(r))return!0}return!1}function Ja(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Cm.has(r)&&(typeof t[r]=="object"&&(0,Rm.eachItem)(t[r],n=>e+=Ja(n)),e===1/0))return 1/0}return e}function Za(t,e="",r){r!==!1&&(e=Mt(e));let n=t.parse(e);return Xa(t,n)}ie.getFullPath=Za;function Xa(t,e){return t.serialize(e).split("#")[0]+"#"}ie._getFullPath=Xa;var xm=/#\/?$/;function Mt(t){return t?t.replace(xm,""):""}ie.normalizeId=Mt;function Dm(t,e,r){return r=Mt(r),t.resolve(e,r)}ie.resolveUrl=Dm;var Nm=/^[a-z_][-a-z0-9._]*$/i;function zm(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Mt(t[r]||e),o={"":s},i=Za(n,s,!1),c={},l=new Set;return Am(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=Mt(_?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!==Mt(g)&&(w[0]==="#"?(u(f,c[w],w),c[w]=f):this.refs[w]=g),w}function S(w){if(typeof w=="string"){if(!Nm.test(w))throw new Error(`invalid anchor "${w}"`);E.call(this,`#${w}`)}}}),c;function u(f,p,m){if(p!==void 0&&!Mm(f,p))throw d(m)}function d(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ie.getSchemaRefs=zm});var Sr=b(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.getData=tt.KeywordCxt=tt.validateFunctionCode=void 0;var nc=Oa(),Qa=hr(),io=Js(),Sn=hr(),Lm=ja(),_r=Wa(),oo=Ga(),v=R(),T=Fe(),jm=gr(),He=x(),yr=mr();function qm(t){if(ic(t)&&(ac(t),oc(t))){Hm(t);return}sc(t,()=>(0,nc.topBoolOrEmptySchema)(t))}tt.validateFunctionCode=qm;function sc({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,v._)`${T.default.data}, ${T.default.valCxt}`,n.$async,()=>{t.code((0,v._)`"use strict"; ${ec(r,s)}`),Fm(t,s),t.code(o)}):t.func(e,(0,v._)`${T.default.data}, ${Um(s)}`,n.$async,()=>t.code(ec(r,s)).code(o))}function Um(t){return(0,v._)`{${T.default.instancePath}="", ${T.default.parentData}, ${T.default.parentDataProperty}, ${T.default.rootData}=${T.default.data}${t.dynamicRef?(0,v._)`, ${T.default.dynamicAnchors}={}`:v.nil}}={}`}function Fm(t,e){t.if(T.default.valCxt,()=>{t.var(T.default.instancePath,(0,v._)`${T.default.valCxt}.${T.default.instancePath}`),t.var(T.default.parentData,(0,v._)`${T.default.valCxt}.${T.default.parentData}`),t.var(T.default.parentDataProperty,(0,v._)`${T.default.valCxt}.${T.default.parentDataProperty}`),t.var(T.default.rootData,(0,v._)`${T.default.valCxt}.${T.default.rootData}`),e.dynamicRef&&t.var(T.default.dynamicAnchors,(0,v._)`${T.default.valCxt}.${T.default.dynamicAnchors}`)},()=>{t.var(T.default.instancePath,(0,v._)`""`),t.var(T.default.parentData,(0,v._)`undefined`),t.var(T.default.parentDataProperty,(0,v._)`undefined`),t.var(T.default.rootData,T.default.data),e.dynamicRef&&t.var(T.default.dynamicAnchors,(0,v._)`{}`)})}function Hm(t){let{schema:e,opts:r,gen:n}=t;sc(t,()=>{r.$comment&&e.$comment&&lc(t),Ym(t),n.let(T.default.vErrors,null),n.let(T.default.errors,0),r.unevaluated&&Wm(t),cc(t),Zm(t)})}function Wm(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 ec(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 Vm(t,e){if(ic(t)&&(ac(t),oc(t))){Gm(t,e);return}(0,nc.boolOrEmptySchema)(t,e)}function oc({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 ic(t){return typeof t.schema!="boolean"}function Gm(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&lc(t),Bm(t),Jm(t);let o=n.const("_errs",T.default.errors);cc(t,o),n.var(e,(0,v._)`${o} === ${T.default.errors}`)}function ac(t){(0,He.checkUnknownRules)(t),Km(t)}function cc(t,e){if(t.opts.jtd)return tc(t,[],!1,e);let r=(0,Qa.getSchemaTypes)(t.schema),n=(0,Qa.coerceAndCheckDataType)(t,r);tc(t,r,!n,e)}function Km(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,He.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Ym(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,He.checkStrictMode)(t,"default is ignored in the schema root")}function Bm(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,jm.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Jm(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function lc({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,v._)`${T.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._)`${T.default.self}.opts.$comment(${o}, ${i}, ${c}.schema)`)}}function Zm(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,v._)`${T.default.errors} === 0`,()=>e.return(T.default.data),()=>e.throw((0,v._)`new ${s}(${T.default.vErrors})`)):(e.assign((0,v._)`${n}.errors`,T.default.vErrors),o.unevaluated&&Xm(t),e.return((0,v._)`${T.default.errors} === 0`))}function Xm({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 tc(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,He.schemaHasRulesButRef)(o,d))){s.block(()=>dc(t,"$ref",d.all.$ref.definition));return}l.jtd||Qm(t,e),s.block(()=>{for(let p of d.rules)f(p);f(d.post)});function f(p){(0,io.shouldUseGroup)(o,p)&&(p.type?(s.if((0,Sn.checkDataType)(p.type,i,l.strictNumbers)),rc(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,Sn.reportTypeError)(t)),s.endIf()):rc(t,p),c||s.if((0,v._)`${T.default.errors} === ${n||0}`))}}function rc(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,Lm.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,io.shouldUseRule)(n,o)&&dc(t,o.keyword,o.definition,e.type)})}function Qm(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(eh(t,e),t.opts.allowUnionTypes||th(t,e),rh(t,t.dataTypes))}function eh(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{uc(t.dataTypes,r)||ao(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),sh(t,e)}}function th(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ao(t,"use allowUnionTypes to allow union type keyword")}function rh(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,io.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>nh(e,i))&&ao(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function nh(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function uc(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function sh(t,e){let r=[];for(let n of t.dataTypes)uc(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ao(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,He.checkStrictMode)(t,e,t.opts.strictTypes)}var En=class{constructor(e,r,n){if((0,_r.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,He.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",fc(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,_r.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",T.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?yr.reportExtraError:yr.reportError)(this,this.def.error,r)}$dataError(){(0,yr.reportError)(this,this.def.$dataError||yr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yr.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,Sn.checkDataTypes)(l,r,o.opts.strictNumbers,Sn.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,oo.getSubschema)(this.it,e);(0,oo.extendSubschemaData)(n,this.it,e),(0,oo.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return Vm(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=He.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=He.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=En;function dc(t,e,r,n){let s=new En(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,_r.funcKeywordCode)(s,r):"macro"in r?(0,_r.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,_r.funcKeywordCode)(s,r)}var oh=/^\/(?:[^~]|~0|~1)*$/,ih=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fc(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return T.default.rootData;if(t[0]==="/"){if(!oh.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=T.default.rootData}else{let u=ih.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,He.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=fc});var wn=b(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});var co=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};lo.default=co});var Er=b(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});var uo=gr(),fo=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,uo.resolveUrl)(e,r,n),this.missingSchema=(0,uo.normalizeId)((0,uo.getFullPath)(e,this.missingRef))}};po.default=fo});var vn=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.resolveSchema=ye.getCompilingSchema=ye.resolveRef=ye.compileSchema=ye.SchemaEnv=void 0;var be=R(),ah=wn(),ft=Fe(),ve=gr(),pc=x(),ch=Sr(),At=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,ve.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ye.SchemaEnv=At;function ho(t){let e=mc.call(this,t);if(e)return e;let r=(0,ve.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new be.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),c;t.$async&&(c=i.scopeValue("Error",{ref:ah.default,code:(0,be._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:ft.default.data,parentData:ft.default.parentData,parentDataProperty:ft.default.parentDataProperty,dataNames:[ft.default.data],dataPathArr:[be.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,be.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:c,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:be.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,be._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,ch.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();d=`${i.scopeRefs(ft.default.scope)}return ${f}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let m=new Function(`${ft.default.self}`,`${ft.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 be.Name?void 0:h,items:g instanceof be.Name?void 0:g,dynamicProps:h instanceof be.Name,dynamicItems:g instanceof be.Name},m.source&&(m.source.evaluated=(0,be.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)}}ye.compileSchema=ho;function lh(t,e,r){var n;r=(0,ve.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=fh.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 At({schema:i,schemaId:c,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=uh.call(this,o)}ye.resolveRef=lh;function uh(t){return(0,ve.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ho.call(this,t)}function mc(t){for(let e of this._compilations)if(dh(e,t))return e}ye.getCompilingSchema=mc;function dh(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function fh(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||bn.call(this,t,e)}function bn(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ve._getFullPath)(this.opts.uriResolver,r),s=(0,ve.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return mo.call(this,r,t);let o=(0,ve.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let c=bn.call(this,t,i);return typeof c?.schema!="object"?void 0:mo.call(this,r,c)}if(typeof i?.schema=="object"){if(i.validate||ho.call(this,i),o===(0,ve.normalizeId)(e)){let{schema:c}=i,{schemaId:l}=this.opts,u=c[l];return u&&(s=(0,ve.resolveUrl)(this.opts.uriResolver,s,u)),new At({schema:c,schemaId:l,root:t,baseId:s})}return mo.call(this,r,i)}}ye.resolveSchema=bn;var ph=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function mo(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,pc.unescapeFragment)(c)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!ph.has(c)&&u&&(e=(0,ve.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,pc.schemaHasRulesButRef)(r,this.RULES)){let c=(0,ve.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=bn.call(this,n,c)}let{schemaId:i}=this.opts;if(o=o||new At({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var hc=b((gv,mh)=>{mh.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 yo=b((yv,Sc)=>{"use strict";var hh=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),yc=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 go(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 gh=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function gc(t){return t.length=0,!0}function yh(t,e,r){if(t.length){let n=go(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function _h(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,c=yh;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=gc}else{s.push(u);continue}}return s.length&&(c===gc?r.zone=s.join(""):i?n.push(s.join("")):n.push(go(s))),r.address=n.join(""),r}function _c(t){if(Sh(t,":")<2)return{host:t,isIPV6:!1};let e=_h(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 Sh(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Eh(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 wh(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 bh(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!yc(r)){let n=_c(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}Sc.exports={nonSimpleDomain:gh,recomposeAuthority:bh,normalizeComponentEncoding:wh,removeDotSegments:Eh,isIPv4:yc,isUUID:hh,normalizeIPv6:_c,stringArrayToHexStripped:go}});var kc=b((_v,vc)=>{"use strict";var{isUUID:vh}=yo(),kh=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Th=["http","https","ws","wss","urn","urn:uuid"];function Ph(t){return Th.indexOf(t)!==-1}function _o(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 Ec(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function wc(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 $h(t){return t.secure=_o(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Rh(t){if((t.port===(_o(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 Mh(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(kh);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=So(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Ah(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=So(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 Ch(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!vh(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Oh(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var bc={scheme:"http",domainHost:!0,parse:Ec,serialize:wc},Ih={scheme:"https",domainHost:bc.domainHost,parse:Ec,serialize:wc},kn={scheme:"ws",domainHost:!0,parse:$h,serialize:Rh},xh={scheme:"wss",domainHost:kn.domainHost,parse:kn.parse,serialize:kn.serialize},Dh={scheme:"urn",parse:Mh,serialize:Ah,skipNormalize:!0},Nh={scheme:"urn:uuid",parse:Ch,serialize:Oh,skipNormalize:!0},Tn={http:bc,https:Ih,ws:kn,wss:xh,urn:Dh,"urn:uuid":Nh};Object.setPrototypeOf(Tn,null);function So(t){return t&&(Tn[t]||Tn[t.toLowerCase()])||void 0}vc.exports={wsIsSecure:_o,SCHEMES:Tn,isValidSchemeName:Ph,getSchemeHandler:So}});var $c=b((Sv,$n)=>{"use strict";var{normalizeIPv6:zh,removeDotSegments:wr,recomposeAuthority:Lh,normalizeComponentEncoding:Pn,isIPv4:jh,nonSimpleDomain:qh}=yo(),{SCHEMES:Uh,getSchemeHandler:Tc}=kc();function Fh(t,e){return typeof t=="string"?t=Me(We(t,e),e):typeof t=="object"&&(t=We(Me(t,e),e)),t}function Hh(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Pc(We(t,n),We(e,n),n,!0);return n.skipEscape=!0,Me(s,n)}function Pc(t,e,r,n){let s={};return n||(t=We(Me(t,r),r),e=We(Me(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=wr(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=wr(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=wr(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=wr(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 Wh(t,e,r){return typeof t=="string"?(t=unescape(t),t=Me(Pn(We(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Me(Pn(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Me(Pn(We(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Me(Pn(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Me(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=Tc(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=Lh(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=wr(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 Vh=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function We(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(Vh);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(jh(n.host)===!1){let l=zh(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=Tc(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&qh(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 Eo={SCHEMES:Uh,normalize:Fh,resolve:Hh,resolveComponent:Pc,equal:Wh,serialize:Me,parse:We};$n.exports=Eo;$n.exports.default=Eo;$n.exports.fastUri=Eo});var Mc=b(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});var Rc=$c();Rc.code='require("ajv/dist/runtime/uri").default';wo.default=Rc});var zc=b(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.CodeGen=Y.Name=Y.nil=Y.stringify=Y.str=Y._=Y.KeywordCxt=void 0;var Gh=Sr();Object.defineProperty(Y,"KeywordCxt",{enumerable:!0,get:function(){return Gh.KeywordCxt}});var Ct=R();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Ct._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Ct.str}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Ct.stringify}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Ct.nil}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Ct.Name}});Object.defineProperty(Y,"CodeGen",{enumerable:!0,get:function(){return Ct.CodeGen}});var Kh=wn(),xc=Er(),Yh=Bs(),br=vn(),Bh=R(),vr=gr(),Rn=hr(),vo=x(),Ac=hc(),Jh=Mc(),Dc=(t,e)=>new RegExp(t,e);Dc.code="new RegExp";var Zh=["removeAdditional","useDefaults","coerceTypes"],Xh=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Qh={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."},eg={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Cc=200;function tg(t){var e,r,n,s,o,i,c,l,u,d,f,p,m,h,g,_,E,S,w,A,k,le,fe,Vt,yt;let H=t.strict,Ge=(e=t.code)===null||e===void 0?void 0:e.optimize,Ee=Ge===!0||Ge===void 0?1:Ge||0,Gt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Dc,id=(s=t.uriResolver)!==null&&s!==void 0?s:Jh.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:H)!==null&&i!==void 0?i:!0,strictNumbers:(l=(c=t.strictNumbers)!==null&&c!==void 0?c:H)!==null&&l!==void 0?l:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:H)!==null&&d!==void 0?d:"log",strictTuples:(p=(f=t.strictTuples)!==null&&f!==void 0?f:H)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:H)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Ee,regExp:Gt}:{optimize:Ee,regExp:Gt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Cc,loopEnum:(_=t.loopEnum)!==null&&_!==void 0?_:Cc,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:(Vt=t.unicodeRegExp)!==null&&Vt!==void 0?Vt:!0,int32range:(yt=t.int32range)!==null&&yt!==void 0?yt:!0,uriResolver:id}}var kr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...tg(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Bh.ValueScope({scope:{},prefixes:Xh,es5:r,lines:n}),this.logger=ag(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Yh.getRules)(),Oc.call(this,Qh,e,"NOT SUPPORTED"),Oc.call(this,eg,e,"DEPRECATED","warn"),this._metaOpts=og.call(this),e.formats&&ng.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&sg.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),rg.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Ac;n==="id"&&(s={...Ac},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 xc.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,vr.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=Ic.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new br.SchemaEnv({schema:{},schemaId:n});if(r=br.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=Ic.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,vr.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(lg.call(this,n,r),!r)return(0,vo.eachItem)(n,o=>bo.call(this,o)),this;dg.call(this,r);let s={...r,type:(0,Rn.getJSONTypes)(r.type),schemaType:(0,Rn.getJSONTypes)(r.schemaType)};return(0,vo.eachItem)(n,s.type.length===0?o=>bo.call(this,o,s):o=>s.type.forEach(i=>bo.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]=Nc(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,vr.normalizeId)(i||n);let u=vr.getSchemaRefs.call(this,e,n);return l=new br.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):br.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{br.compileSchema.call(this,e)}finally{this.opts=r}}};kr.ValidationError=Kh.default;kr.MissingRefError=xc.default;Y.default=kr;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 Ic(t){return t=(0,vr.normalizeId)(t),this.schemas[t]||this.refs[t]}function rg(){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 ng(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function sg(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 og(){let t={...this.opts};for(let e of Zh)delete t[e];return t}var ig={log(){},warn(){},error(){}};function ag(t){if(t===!1)return ig;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 cg=/^[a-z_$][a-z0-9_$:-]*$/i;function lg(t,e){let{RULES:r}=this;if((0,vo.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!cg.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 bo(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,Rn.getJSONTypes)(e.type),schemaType:(0,Rn.getJSONTypes)(e.schemaType)}};e.before?ug.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 ug(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 dg(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Nc(e)),t.validateSchema=this.compile(e,!0))}var fg={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Nc(t){return{anyOf:[t,fg]}}});var Lc=b(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});var pg={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ko.default=pg});var Fc=b(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.callRef=pt.getValidate=void 0;var mg=Er(),jc=ge(),ae=R(),Ot=Fe(),qc=vn(),Mn=x(),hg={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=qc.resolveRef.call(l,u,s,r);if(d===void 0)throw new mg.default(n.opts.uriResolver,s,r);if(d instanceof qc.SchemaEnv)return p(d);return m(d);function f(){if(o===u)return An(t,i,o,o.$async);let h=e.scopeValue("root",{ref:u});return An(t,(0,ae._)`${h}.validate`,u,u.$async)}function p(h){let g=Uc(t,h);An(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 Uc(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ae._)`${r.scopeValue("wrapper",{ref:e})}.validate`}pt.getValidate=Uc;function An(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,jc.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,jc.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=Mn.mergeEvaluated.props(s,_.props,o.props));else{let E=s.var("props",(0,ae._)`${h}.evaluated.props`);o.props=Mn.mergeEvaluated.props(s,E,o.props,ae.Name)}if(o.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(o.items=Mn.mergeEvaluated.items(s,_.items,o.items));else{let E=s.var("items",(0,ae._)`${h}.evaluated.items`);o.items=Mn.mergeEvaluated.items(s,E,o.items,ae.Name)}}}pt.callRef=An;pt.default=hg});var Hc=b(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var gg=Lc(),yg=Fc(),_g=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gg.default,yg.default];To.default=_g});var Wc=b(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});var Cn=R(),rt=Cn.operators,On={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}},Sg={message:({keyword:t,schemaCode:e})=>(0,Cn.str)`must be ${On[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Cn._)`{comparison: ${On[t].okStr}, limit: ${e}}`},Eg={keyword:Object.keys(On),type:"number",schemaType:"number",$data:!0,error:Sg,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Cn._)`${r} ${On[e].fail} ${n} || isNaN(${r})`)}};Po.default=Eg});var Vc=b($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var Tr=R(),wg={message:({schemaCode:t})=>(0,Tr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Tr._)`{multipleOf: ${t}}`},bg={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wg,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),c=o?(0,Tr._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Tr._)`${i} !== parseInt(${i})`;t.fail$data((0,Tr._)`(${n} === 0 || (${i} = ${r}/${n}, ${c}))`)}};$o.default=bg});var Kc=b(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});function Gc(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}Ro.default=Gc;Gc.code='require("ajv/dist/runtime/ucs2length").default'});var Yc=b(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var mt=R(),vg=x(),kg=Kc(),Tg={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,mt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,mt._)`{limit: ${t}}`},Pg={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Tg,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?mt.operators.GT:mt.operators.LT,i=s.opts.unicode===!1?(0,mt._)`${r}.length`:(0,mt._)`${(0,vg.useFunc)(t.gen,kg.default)}(${r})`;t.fail$data((0,mt._)`${i} ${o} ${n}`)}};Mo.default=Pg});var Bc=b(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});var $g=ge(),Rg=x(),It=R(),Mg={message:({schemaCode:t})=>(0,It.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,It._)`{pattern: ${t}}`},Ag={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Mg,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,c=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,It._)`new RegExp`:(0,Rg.useFunc)(e,l),d=e.let("valid");e.try(()=>e.assign(d,(0,It._)`${u}(${o}, ${c}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,It._)`!${d}`)}else{let l=(0,$g.usePattern)(t,s);t.fail$data((0,It._)`!${l}.test(${r})`)}}};Ao.default=Ag});var Jc=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var Pr=R(),Cg={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Pr.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Pr._)`{limit: ${t}}`},Og={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Cg,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Pr.operators.GT:Pr.operators.LT;t.fail$data((0,Pr._)`Object.keys(${r}).length ${s} ${n}`)}};Co.default=Og});var Zc=b(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var $r=ge(),Rr=R(),Ig=x(),xg={message:({params:{missingProperty:t}})=>(0,Rr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Rr._)`{missingProperty: ${t}}`},Dg={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xg,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,Ig.checkStrictMode)(i,E,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(Rr.nil,f);else for(let m of r)(0,$r.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,$r.checkMissingProp)(t,r,m)),(0,$r.reportMissingProp)(t,m),e.else()}function f(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,$r.noPropertyInData)(e,s,m,c.ownProperties),()=>t.error())})}function p(m,h){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(h,(0,$r.propertyInData)(e,s,m,c.ownProperties)),e.if((0,Rr.not)(h),()=>{t.error(),e.break()})},Rr.nil)}}};Oo.default=Dg});var Xc=b(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var Mr=R(),Ng={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Mr.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Mr._)`{limit: ${t}}`},zg={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Ng,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Mr.operators.GT:Mr.operators.LT;t.fail$data((0,Mr._)`${r}.length ${s} ${n}`)}};Io.default=zg});var In=b(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var Qc=no();Qc.code='require("ajv/dist/runtime/equal").default';xo.default=Qc});var el=b(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});var Do=hr(),B=R(),Lg=x(),jg=In(),qg={message:({params:{i:t,j:e}})=>(0,B.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,B._)`{i: ${t}, j: ${e}}`},Ug={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:qg,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,Do.getSchemaTypes)(o.items):[];t.block$data(l,d,(0,B._)`${i} === false`),t.ok(l);function d(){let h=e.let("i",(0,B._)`${r}.length`),g=e.let("j");t.setParams({i:h,j:g}),e.assign(l,!0),e.if((0,B._)`${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,Do.checkDataTypes)(u,_,c.opts.strictNumbers,Do.DataType.Wrong),S=e.const("indices",(0,B._)`{}`);e.for((0,B._)`;${h}--;`,()=>{e.let(_,(0,B._)`${r}[${h}]`),e.if(E,(0,B._)`continue`),u.length>1&&e.if((0,B._)`typeof ${_} == "string"`,(0,B._)`${_} += "_"`),e.if((0,B._)`typeof ${S}[${_}] == "number"`,()=>{e.assign(g,(0,B._)`${S}[${_}]`),t.error(),e.assign(l,!1).break()}).code((0,B._)`${S}[${_}] = ${h}`)})}function m(h,g){let _=(0,Lg.useFunc)(e,jg.default),E=e.name("outer");e.label(E).for((0,B._)`;${h}--;`,()=>e.for((0,B._)`${g} = ${h}; ${g}--;`,()=>e.if((0,B._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{t.error(),e.assign(l,!1).break(E)})))}}};No.default=Ug});var tl=b(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});var zo=R(),Fg=x(),Hg=In(),Wg={message:"must be equal to constant",params:({schemaCode:t})=>(0,zo._)`{allowedValue: ${t}}`},Vg={keyword:"const",$data:!0,error:Wg,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,zo._)`!${(0,Fg.useFunc)(e,Hg.default)}(${r}, ${s})`):t.fail((0,zo._)`${o} !== ${r}`)}};Lo.default=Vg});var rl=b(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});var Ar=R(),Gg=x(),Kg=In(),Yg={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ar._)`{allowedValues: ${t}}`},Bg={keyword:"enum",schemaType:"array",$data:!0,error:Yg,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,Gg.useFunc)(e,Kg.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,Ar.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,Ar._)`${u()}(${r}, ${m})`,()=>e.assign(d,!0).break()))}function p(m,h){let g=s[h];return typeof g=="object"&&g!==null?(0,Ar._)`${u()}(${r}, ${m}[${h}])`:(0,Ar._)`${r} === ${g}`}}};jo.default=Bg});var nl=b(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});var Jg=Wc(),Zg=Vc(),Xg=Yc(),Qg=Bc(),ey=Jc(),ty=Zc(),ry=Xc(),ny=el(),sy=tl(),oy=rl(),iy=[Jg.default,Zg.default,Xg.default,Qg.default,ey.default,ty.default,ry.default,ny.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},sy.default,oy.default];qo.default=iy});var Fo=b(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.validateAdditionalItems=void 0;var ht=R(),Uo=x(),ay={message:({params:{len:t}})=>(0,ht.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ht._)`{limit: ${t}}`},cy={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:ay,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Uo.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}sl(t,n)}};function sl(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let c=r.const("len",(0,ht._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ht._)`${c} <= ${e.length}`);else if(typeof n=="object"&&!(0,Uo.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,ht._)`${c} <= ${e.length}`);r.if((0,ht.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,c,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:Uo.Type.Num},u),i.allErrors||r.if((0,ht.not)(u),()=>r.break())})}}Cr.validateAdditionalItems=sl;Cr.default=cy});var Ho=b(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.validateTuple=void 0;var ol=R(),xn=x(),ly=ge(),uy={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return il(t,"additionalItems",e);r.items=!0,!(0,xn.alwaysValidSchema)(r,e)&&t.ok((0,ly.validateArray)(t))}};function il(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=xn.mergeEvaluated.items(n,r.length,c.items));let l=n.name("valid"),u=n.const("len",(0,ol._)`${o}.length`);r.forEach((f,p)=>{(0,xn.alwaysValidSchema)(c,f)||(n.if((0,ol._)`${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,xn.checkStrictMode)(c,_,p.strictTuples)}}}Or.validateTuple=il;Or.default=uy});var al=b(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});var dy=Ho(),fy={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,dy.validateTuple)(t,"items")};Wo.default=fy});var ll=b(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});var cl=R(),py=x(),my=ge(),hy=Fo(),gy={message:({params:{len:t}})=>(0,cl.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,cl._)`{limit: ${t}}`},yy={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gy,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,py.alwaysValidSchema)(n,e)&&(s?(0,hy.validateAdditionalItems)(t,s):t.ok((0,my.validateArray)(t)))}};Vo.default=yy});var ul=b(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});var _e=R(),Dn=x(),_y={message:({params:{min:t,max:e}})=>e===void 0?(0,_e.str)`must contain at least ${t} valid item(s)`:(0,_e.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_e._)`{minContains: ${t}}`:(0,_e._)`{minContains: ${t}, maxContains: ${e}}`},Sy={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:_y,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,_e._)`${s}.length`);if(t.setParams({min:i,max:c}),c===void 0&&i===0){(0,Dn.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&i>c){(0,Dn.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Dn.alwaysValidSchema)(o,r)){let g=(0,_e._)`${d} >= ${i}`;c!==void 0&&(g=(0,_e._)`${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,_e._)`${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:Dn.Type.Num,compositeRule:!0},g),_()})}function h(g){e.code((0,_e._)`${g}++`),c===void 0?e.if((0,_e._)`${g} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,_e._)`${g} > ${c}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,_e._)`${g} >= ${i}`,()=>e.assign(f,!0)))}}};Go.default=Sy});var pl=b(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.validateSchemaDeps=Ae.validatePropertyDeps=Ae.error=void 0;var Ko=R(),Ey=x(),Ir=ge();Ae.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ko.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ko._)`{property: ${t},
missingProperty: ${n},
depsCount: ${e},
deps: ${r}}`};var wy={keyword:"dependencies",type:"object",schemaType:"object",error:Ae.error,code(t){let[e,r]=by(t);dl(t,e),fl(t,r)}};function by({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 dl(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,Ir.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,Ir.checkReportMissingProp)(t,u)}):(r.if((0,Ko._)`${l} && (${(0,Ir.checkMissingProp)(t,c,o)})`),(0,Ir.reportMissingProp)(t,o),r.else())}}Ae.validatePropertyDeps=dl;function fl(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let c in e)(0,Ey.alwaysValidSchema)(o,e[c])||(r.if((0,Ir.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))}Ae.validateSchemaDeps=fl;Ae.default=wy});var hl=b(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var ml=R(),vy=x(),ky={message:"property name must be valid",params:({params:t})=>(0,ml._)`{propertyName: ${t.propertyName}}`},Ty={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ky,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,vy.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,ml.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Yo.default=Ty});var Jo=b(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});var Nn=ge(),ke=R(),Py=Fe(),zn=x(),$y={message:"must NOT have additional properties",params:({params:t})=>(0,ke._)`{additionalProperty: ${t.additionalProperty}}`},Ry={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$y,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,zn.alwaysValidSchema)(i,r))return;let u=(0,Nn.allSchemaProperties)(n.properties),d=(0,Nn.allSchemaProperties)(n.patternProperties);f(),t.ok((0,ke._)`${o} === ${Py.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,zn.schemaRefOrVal)(i,n.properties,"properties");E=(0,Nn.isOwnProperty)(e,S,_)}else u.length?E=(0,ke.or)(...u.map(S=>(0,ke._)`${_} === ${S}`)):E=ke.nil;return d.length&&(E=(0,ke.or)(E,...d.map(S=>(0,ke._)`${(0,Nn.usePattern)(t,S)}.test(${_})`))),(0,ke.not)(E)}function m(_){e.code((0,ke._)`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,zn.alwaysValidSchema)(i,r)){let E=e.name("valid");l.removeAdditional==="failing"?(g(_,E,!1),e.if((0,ke.not)(E),()=>{t.reset(),m(_)})):(g(_,E),c||e.if((0,ke.not)(E),()=>e.break()))}}function g(_,E,S){let w={keyword:"additionalProperties",dataProp:_,dataPropType:zn.Type.Str};S===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,E)}}};Bo.default=Ry});var _l=b(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});var My=Sr(),gl=ge(),Zo=x(),yl=Jo(),Ay={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&&yl.default.code(new My.KeywordCxt(o,yl.default,"additionalProperties"));let i=(0,gl.allSchemaProperties)(r);for(let f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Zo.mergeEvaluated.props(e,(0,Zo.toHash)(i),o.props));let c=i.filter(f=>!(0,Zo.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,gl.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)}}};Xo.default=Ay});var bl=b(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var Sl=ge(),Ln=R(),El=x(),wl=x(),Cy={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,Sl.allSchemaProperties)(r),l=c.filter(g=>(0,El.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 Ln.Name)&&(o.props=(0,wl.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,El.checkStrictMode)(o,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",n,_=>{e.if((0,Ln._)`${(0,Sl.usePattern)(t,g)}.test(${_})`,()=>{let E=l.includes(g);E||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:wl.Type.Str},d),o.opts.unevaluated&&f!==!0?e.assign((0,Ln._)`${f}[${_}]`,!0):!E&&!o.allErrors&&e.if((0,Ln.not)(d),()=>e.break())})})}}};Qo.default=Cy});var vl=b(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var Oy=x(),Iy={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Oy.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"}};ei.default=Iy});var kl=b(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var xy=ge(),Dy={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xy.validateUnion,error:{message:"must match a schema in anyOf"}};ti.default=Dy});var Tl=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var jn=R(),Ny=x(),zy={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,jn._)`{passingSchemas: ${t.passing}}`},Ly={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:zy,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,Ny.alwaysValidSchema)(s,d)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,jn._)`${l} && ${i}`).assign(i,!1).assign(c,(0,jn._)`[${c}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(c,f),p&&t.mergeEvaluated(p,jn.Name)})})}}};ri.default=Ly});var Pl=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});var jy=x(),qy={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,jy.alwaysValidSchema)(n,o))return;let c=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(c)})}};ni.default=qy});var Ml=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});var qn=R(),Rl=x(),Uy={message:({params:t})=>(0,qn.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,qn._)`{failingKeyword: ${t.ifClause}}`},Fy={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Uy,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Rl.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=$l(n,"then"),o=$l(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,qn.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,qn._)`${d}`):t.setParams({ifClause:d})}}}};function $l(t,e){let r=t.schema[e];return r!==void 0&&!(0,Rl.alwaysValidSchema)(t,r)}si.default=Fy});var Al=b(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var Hy=x(),Wy={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Hy.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};oi.default=Wy});var Cl=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});var Vy=Fo(),Gy=al(),Ky=Ho(),Yy=ll(),By=ul(),Jy=pl(),Zy=hl(),Xy=Jo(),Qy=_l(),e_=bl(),t_=vl(),r_=kl(),n_=Tl(),s_=Pl(),o_=Ml(),i_=Al();function a_(t=!1){let e=[t_.default,r_.default,n_.default,s_.default,o_.default,i_.default,Zy.default,Xy.default,Jy.default,Qy.default,e_.default];return t?e.push(Gy.default,Yy.default):e.push(Vy.default,Ky.default),e.push(By.default),e}ii.default=a_});var Ol=b(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});var U=R(),c_={message:({schemaCode:t})=>(0,U.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,U._)`{format: ${t}}`},l_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:c_,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,U._)`${h}[${i}]`),_=r.let("fType"),E=r.let("format");r.if((0,U._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,U._)`${g}.type || "string"`).assign(E,(0,U._)`${g}.validate`),()=>r.assign(_,(0,U._)`"string"`).assign(E,g)),t.fail$data((0,U.or)(S(),w()));function S(){return l.strictSchema===!1?U.nil:(0,U._)`${i} && !${E}`}function w(){let A=d.$async?(0,U._)`(${g}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,U._)`${E}(${n})`,k=(0,U._)`(typeof ${E} == "function" ? ${A} : ${E}.test(${n}))`;return(0,U._)`${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,U.regexpCode)(k):l.code.formats?(0,U._)`${l.code.formats}${(0,U.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,U._)`${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,U._)`await ${E}(${n})`}return typeof _=="function"?(0,U._)`${E}(${n})`:(0,U._)`${E}.test(${n})`}}}};ai.default=l_});var Il=b(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});var u_=Ol(),d_=[u_.default];ci.default=d_});var xl=b(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.contentVocabulary=xt.metadataVocabulary=void 0;xt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Nl=b(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});var f_=Hc(),p_=nl(),m_=Cl(),h_=Il(),Dl=xl(),g_=[f_.default,p_.default,(0,m_.default)(),h_.default,Dl.metadataVocabulary,Dl.contentVocabulary];li.default=g_});var Ll=b(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.DiscrError=void 0;var zl;(function(t){t.Tag="tag",t.Mapping="mapping"})(zl||(Un.DiscrError=zl={}))});var ql=b(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var Dt=R(),ui=Ll(),jl=vn(),y_=Er(),__=x(),S_={message:({params:{discrError:t,tagName:e}})=>t===ui.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Dt._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},E_={keyword:"discriminator",type:"object",schemaType:"object",error:S_,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,Dt._)`${r}${(0,Dt.getProperty)(c)}`);e.if((0,Dt._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:ui.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,Dt._)`${u} === ${h}`),e.assign(l,f(m[h]));e.else(),t.error(!1,{discrError:ui.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,Dt.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,__.schemaHasRulesButRef)(k,o.self.RULES)){let fe=k.$ref;if(k=jl.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,fe),k instanceof jl.SchemaEnv&&(k=k.schema),k===void 0)throw new y_.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}}}};di.default=E_});var Ul=b((ak,w_)=>{w_.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 pi=b((q,fi)=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.MissingRefError=q.ValidationError=q.CodeGen=q.Name=q.nil=q.stringify=q.str=q._=q.KeywordCxt=q.Ajv=void 0;var b_=zc(),v_=Nl(),k_=ql(),Fl=Ul(),T_=["/properties"],Fn="http://json-schema.org/draft-07/schema",Nt=class extends b_.default{_addVocabularies(){super._addVocabularies(),v_.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(k_.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Fl,T_):Fl;this.addMetaSchema(e,Fn,!1),this.refs["http://json-schema.org/schema"]=Fn}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Fn)?Fn:void 0)}};q.Ajv=Nt;fi.exports=q=Nt;fi.exports.Ajv=Nt;Object.defineProperty(q,"__esModule",{value:!0});q.default=Nt;var P_=Sr();Object.defineProperty(q,"KeywordCxt",{enumerable:!0,get:function(){return P_.KeywordCxt}});var zt=R();Object.defineProperty(q,"_",{enumerable:!0,get:function(){return zt._}});Object.defineProperty(q,"str",{enumerable:!0,get:function(){return zt.str}});Object.defineProperty(q,"stringify",{enumerable:!0,get:function(){return zt.stringify}});Object.defineProperty(q,"nil",{enumerable:!0,get:function(){return zt.nil}});Object.defineProperty(q,"Name",{enumerable:!0,get:function(){return zt.Name}});Object.defineProperty(q,"CodeGen",{enumerable:!0,get:function(){return zt.CodeGen}});var $_=wn();Object.defineProperty(q,"ValidationError",{enumerable:!0,get:function(){return $_.default}});var R_=Er();Object.defineProperty(q,"MissingRefError",{enumerable:!0,get:function(){return R_.default}})});var Jl=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.formatNames=Oe.fastFormats=Oe.fullFormats=void 0;function Ce(t,e){return{validate:t,compare:e}}Oe.fullFormats={date:Ce(Gl,yi),time:Ce(hi(!0),_i),"date-time":Ce(Hl(!0),Yl),"iso-time":Ce(hi(),Kl),"iso-date-time":Ce(Hl(),Bl),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:x_,"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:U_,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:D_,int32:{type:"number",validate:L_},int64:{type:"number",validate:j_},float:{type:"number",validate:Vl},double:{type:"number",validate:Vl},password:!0,binary:!0};Oe.fastFormats={...Oe.fullFormats,date:Ce(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,yi),time:Ce(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,_i),"date-time":Ce(/^\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,Yl),"iso-time":Ce(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Kl),"iso-date-time":Ce(/^\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,Bl),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};Oe.formatNames=Object.keys(Oe.fullFormats);function M_(t){return t%4===0&&(t%100!==0||t%400===0)}var A_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,C_=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Gl(t){let e=A_.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&&M_(r)?29:C_[n])}function yi(t,e){if(t&&e)return t>e?1:t<e?-1:0}var mi=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function hi(t){return function(r){let n=mi.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 _i(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 Kl(t,e){if(!(t&&e))return;let r=mi.exec(t),n=mi.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 gi=/t|\s/i;function Hl(t){let e=hi(t);return function(n){let s=n.split(gi);return s.length===2&&Gl(s[0])&&e(s[1])}}function Yl(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Bl(t,e){if(!(t&&e))return;let[r,n]=t.split(gi),[s,o]=e.split(gi),i=yi(r,s);if(i!==void 0)return i||_i(n,o)}var O_=/\/|:/,I_=/^(?:[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 x_(t){return O_.test(t)&&I_.test(t)}var Wl=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function D_(t){return Wl.lastIndex=0,Wl.test(t)}var N_=-(2**31),z_=2**31-1;function L_(t){return Number.isInteger(t)&&t<=z_&&t>=N_}function j_(t){return Number.isInteger(t)}function Vl(){return!0}var q_=/[^\\]\\Z/;function U_(t){if(q_.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Zl=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.formatLimitDefinition=void 0;var F_=pi(),Te=R(),nt=Te.operators,Hn={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}},H_={message:({keyword:t,schemaCode:e})=>(0,Te.str)`should be ${Hn[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Te._)`{comparison: ${Hn[t].okStr}, limit: ${e}}`};Lt.formatLimitDefinition={keyword:Object.keys(Hn),type:"string",schemaType:"string",$data:!0,error:H_,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 F_.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,Te._)`${p}[${l.schemaCode}]`);t.fail$data((0,Te.or)((0,Te._)`typeof ${m} != "object"`,(0,Te._)`${m} instanceof RegExp`,(0,Te._)`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,Te._)`${i.code.formats}${(0,Te.getProperty)(p)}`:void 0});t.fail$data(f(h))}function f(p){return(0,Te._)`${p}.compare(${r}, ${n}) ${Hn[s].fail} 0`}},dependencies:["format"]};var W_=t=>(t.addKeyword(Lt.formatLimitDefinition),t);Lt.default=W_});var tu=b((xr,eu)=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});var jt=Jl(),V_=Zl(),Si=R(),Xl=new Si.Name("fullFormats"),G_=new Si.Name("fastFormats"),Ei=(t,e={keywords:!0})=>{if(Array.isArray(e))return Ql(t,e,jt.fullFormats,Xl),t;let[r,n]=e.mode==="fast"?[jt.fastFormats,G_]:[jt.fullFormats,Xl],s=e.formats||jt.formatNames;return Ql(t,s,r,n),e.keywords&&(0,V_.default)(t),t};Ei.get=(t,e="full")=>{let n=(e==="fast"?jt.fastFormats:jt.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Ql(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Si._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}eu.exports=xr=Ei;Object.defineProperty(xr,"__esModule",{value:!0});xr.default=Ei});var Le=require("fs"),Kt=require("path"),Zi=require("os"),is=(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))(is||{}),Ji=(0,Kt.join)((0,Zi.homedir)(),".claude-mem"),as=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=(0,Kt.join)(Ji,"logs");(0,Le.existsSync)(e)||(0,Le.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Kt.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=(0,Kt.join)(Ji,"settings.json");if((0,Le.existsSync)(e)){let r=(0,Le.readFileSync)(e,"utf-8"),s=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=is[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=is[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,Le.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 as;var pd=ne(require("zod/v3"),1),Vr=ne(require("zod/v4-mini"),1);function _t(t){return!!t._zod}function Ke(t,e){return _t(t)?Vr.safeParse(t,e):t.safeParse(e)}function Gr(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 Xi(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=ne(require("zod/v4"),1),ls="2025-11-25";var Qi=[ls,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ye="io.modelcontextprotocol/related-task",Yr="2.0",W=a.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ea=a.union([a.string(),a.number().int()]),ta=a.string(),aE=a.looseObject({ttl:a.number().optional(),pollInterval:a.number().optional()}),md=a.object({ttl:a.number().optional()}),hd=a.object({taskId:a.string()}),us=a.looseObject({progressToken:ea.optional(),[Ye]:hd.optional()}),ue=a.object({_meta:us.optional()}),Yt=ue.extend({task:md.optional()}),ra=t=>Yt.safeParse(t).success,V=a.object({method:a.string(),params:ue.loose().optional()}),pe=a.object({_meta:us.optional()}),me=a.object({method:a.string(),params:pe.loose().optional()}),G=a.looseObject({_meta:us.optional()}),Br=a.union([a.string(),a.number().int()]),na=a.object({jsonrpc:a.literal(Yr),id:Br,...V.shape}).strict(),ds=t=>na.safeParse(t).success,sa=a.object({jsonrpc:a.literal(Yr),...me.shape}).strict(),oa=t=>sa.safeParse(t).success,fs=a.object({jsonrpc:a.literal(Yr),id:Br,result:G}).strict(),Bt=t=>fs.safeParse(t).success;var O;(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"})(O||(O={}));var ps=a.object({jsonrpc:a.literal(Yr),id:Br.optional(),error:a.object({code:a.number().int(),message:a.string(),data:a.unknown().optional()})}).strict();var ia=t=>ps.safeParse(t).success;var aa=a.union([na,sa,fs,ps]),cE=a.union([fs,ps]),Jr=G.strict(),gd=pe.extend({requestId:Br.optional(),reason:a.string().optional()}),Zr=me.extend({method:a.literal("notifications/cancelled"),params:gd}),yd=a.object({src:a.string(),mimeType:a.string().optional(),sizes:a.array(a.string()).optional(),theme:a.enum(["light","dark"]).optional()}),Jt=a.object({icons:a.array(yd).optional()}),St=a.object({name:a.string(),title:a.string().optional()}),ca=St.extend({...St.shape,...Jt.shape,version:a.string(),websiteUrl:a.string().optional(),description:a.string().optional()}),_d=a.intersection(a.object({applyDefaults:a.boolean().optional()}),a.record(a.string(),a.unknown())),Sd=a.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,a.intersection(a.object({form:_d.optional(),url:W.optional()}),a.record(a.string(),a.unknown()).optional())),Ed=a.looseObject({list:W.optional(),cancel:W.optional(),requests:a.looseObject({sampling:a.looseObject({createMessage:W.optional()}).optional(),elicitation:a.looseObject({create:W.optional()}).optional()}).optional()}),wd=a.looseObject({list:W.optional(),cancel:W.optional(),requests:a.looseObject({tools:a.looseObject({call:W.optional()}).optional()}).optional()}),bd=a.object({experimental:a.record(a.string(),W).optional(),sampling:a.object({context:W.optional(),tools:W.optional()}).optional(),elicitation:Sd.optional(),roots:a.object({listChanged:a.boolean().optional()}).optional(),tasks:Ed.optional(),extensions:a.record(a.string(),W).optional()}),vd=ue.extend({protocolVersion:a.string(),capabilities:bd,clientInfo:ca}),ms=V.extend({method:a.literal("initialize"),params:vd});var kd=a.object({experimental:a.record(a.string(),W).optional(),logging:W.optional(),completions:W.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:wd.optional(),extensions:a.record(a.string(),W).optional()}),Td=G.extend({protocolVersion:a.string(),capabilities:kd,serverInfo:ca,instructions:a.string().optional()}),hs=me.extend({method:a.literal("notifications/initialized"),params:pe.optional()});var Xr=V.extend({method:a.literal("ping"),params:ue.optional()}),Pd=a.object({progress:a.number(),total:a.optional(a.number()),message:a.optional(a.string())}),$d=a.object({...pe.shape,...Pd.shape,progressToken:ea}),Qr=me.extend({method:a.literal("notifications/progress"),params:$d}),Rd=ue.extend({cursor:ta.optional()}),Zt=V.extend({params:Rd.optional()}),Xt=G.extend({nextCursor:ta.optional()}),Md=a.enum(["working","input_required","completed","failed","cancelled"]),Qt=a.object({taskId:a.string(),status:Md,ttl:a.union([a.number(),a.null()]),createdAt:a.string(),lastUpdatedAt:a.string(),pollInterval:a.optional(a.number()),statusMessage:a.optional(a.string())}),Et=G.extend({task:Qt}),Ad=pe.merge(Qt),er=me.extend({method:a.literal("notifications/tasks/status"),params:Ad}),en=V.extend({method:a.literal("tasks/get"),params:ue.extend({taskId:a.string()})}),tn=G.merge(Qt),rn=V.extend({method:a.literal("tasks/result"),params:ue.extend({taskId:a.string()})}),lE=G.loose(),nn=Zt.extend({method:a.literal("tasks/list")}),sn=Xt.extend({tasks:a.array(Qt)}),on=V.extend({method:a.literal("tasks/cancel"),params:ue.extend({taskId:a.string()})}),la=G.merge(Qt),ua=a.object({uri:a.string(),mimeType:a.optional(a.string()),_meta:a.record(a.string(),a.unknown()).optional()}),da=ua.extend({text:a.string()}),gs=a.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),fa=ua.extend({blob:gs}),tr=a.enum(["user","assistant"]),wt=a.object({audience:a.array(tr).optional(),priority:a.number().min(0).max(1).optional(),lastModified:a.iso.datetime({offset:!0}).optional()}),pa=a.object({...St.shape,...Jt.shape,uri:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),size:a.optional(a.number()),annotations:wt.optional(),_meta:a.optional(a.looseObject({}))}),Cd=a.object({...St.shape,...Jt.shape,uriTemplate:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:wt.optional(),_meta:a.optional(a.looseObject({}))}),Od=Zt.extend({method:a.literal("resources/list")}),Id=Xt.extend({resources:a.array(pa)}),xd=Zt.extend({method:a.literal("resources/templates/list")}),Dd=Xt.extend({resourceTemplates:a.array(Cd)}),ys=ue.extend({uri:a.string()}),Nd=ys,zd=V.extend({method:a.literal("resources/read"),params:Nd}),Ld=G.extend({contents:a.array(a.union([da,fa]))}),jd=me.extend({method:a.literal("notifications/resources/list_changed"),params:pe.optional()}),qd=ys,Ud=V.extend({method:a.literal("resources/subscribe"),params:qd}),Fd=ys,Hd=V.extend({method:a.literal("resources/unsubscribe"),params:Fd}),Wd=pe.extend({uri:a.string()}),Vd=me.extend({method:a.literal("notifications/resources/updated"),params:Wd}),Gd=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}),Kd=a.object({...St.shape,...Jt.shape,description:a.optional(a.string()),arguments:a.optional(a.array(Gd)),_meta:a.optional(a.looseObject({}))}),Yd=Zt.extend({method:a.literal("prompts/list")}),Bd=Xt.extend({prompts:a.array(Kd)}),Jd=ue.extend({name:a.string(),arguments:a.record(a.string(),a.string()).optional()}),Zd=V.extend({method:a.literal("prompts/get"),params:Jd}),_s=a.object({type:a.literal("text"),text:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Ss=a.object({type:a.literal("image"),data:gs,mimeType:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Es=a.object({type:a.literal("audio"),data:gs,mimeType:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Xd=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()}),Qd=a.object({type:a.literal("resource"),resource:a.union([da,fa]),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),ef=pa.extend({type:a.literal("resource_link")}),ws=a.union([_s,Ss,Es,ef,Qd]),tf=a.object({role:tr,content:ws}),rf=G.extend({description:a.string().optional(),messages:a.array(tf)}),nf=me.extend({method:a.literal("notifications/prompts/list_changed"),params:pe.optional()}),sf=a.object({title:a.string().optional(),readOnlyHint:a.boolean().optional(),destructiveHint:a.boolean().optional(),idempotentHint:a.boolean().optional(),openWorldHint:a.boolean().optional()}),of=a.object({taskSupport:a.enum(["required","optional","forbidden"]).optional()}),ma=a.object({...St.shape,...Jt.shape,description:a.string().optional(),inputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),W).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()),outputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),W).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()).optional(),annotations:sf.optional(),execution:of.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),bs=Zt.extend({method:a.literal("tools/list")}),af=Xt.extend({tools:a.array(ma)}),an=G.extend({content:a.array(ws).default([]),structuredContent:a.record(a.string(),a.unknown()).optional(),isError:a.boolean().optional()}),uE=an.or(G.extend({toolResult:a.unknown()})),cf=Yt.extend({name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),rr=V.extend({method:a.literal("tools/call"),params:cf}),lf=me.extend({method:a.literal("notifications/tools/list_changed"),params:pe.optional()}),dE=a.object({autoRefresh:a.boolean().default(!0),debounceMs:a.number().int().nonnegative().default(300)}),nr=a.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),uf=ue.extend({level:nr}),vs=V.extend({method:a.literal("logging/setLevel"),params:uf}),df=pe.extend({level:nr,logger:a.string().optional(),data:a.unknown()}),ff=me.extend({method:a.literal("notifications/message"),params:df}),pf=a.object({name:a.string().optional()}),mf=a.object({hints:a.array(pf).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()}),hf=a.object({mode:a.enum(["auto","required","none"]).optional()}),gf=a.object({type:a.literal("tool_result"),toolUseId:a.string().describe("The unique identifier for the corresponding tool call."),content:a.array(ws).default([]),structuredContent:a.object({}).loose().optional(),isError:a.boolean().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),yf=a.discriminatedUnion("type",[_s,Ss,Es]),Kr=a.discriminatedUnion("type",[_s,Ss,Es,Xd,gf]),_f=a.object({role:tr,content:a.union([Kr,a.array(Kr)]),_meta:a.record(a.string(),a.unknown()).optional()}),Sf=Yt.extend({messages:a.array(_f),modelPreferences:mf.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:W.optional(),tools:a.array(ma).optional(),toolChoice:hf.optional()}),Ef=V.extend({method:a.literal("sampling/createMessage"),params:Sf}),sr=G.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens"]).or(a.string())),role:tr,content:yf}),ks=G.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(a.string())),role:tr,content:a.union([Kr,a.array(Kr)])}),wf=a.object({type:a.literal("boolean"),title:a.string().optional(),description:a.string().optional(),default:a.boolean().optional()}),bf=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()}),vf=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()}),kf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),default:a.string().optional()}),Tf=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()}),Pf=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()}),$f=a.union([kf,Tf]),Rf=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()}),Mf=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()}),Af=a.union([Rf,Mf]),Cf=a.union([Pf,$f,Af]),Of=a.union([Cf,wf,bf,vf]),If=Yt.extend({mode:a.literal("form").optional(),message:a.string(),requestedSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),Of),required:a.array(a.string()).optional()})}),xf=Yt.extend({mode:a.literal("url"),message:a.string(),elicitationId:a.string(),url:a.string().url()}),Df=a.union([If,xf]),Nf=V.extend({method:a.literal("elicitation/create"),params:Df}),zf=pe.extend({elicitationId:a.string()}),Lf=me.extend({method:a.literal("notifications/elicitation/complete"),params:zf}),bt=G.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())}),jf=a.object({type:a.literal("ref/resource"),uri:a.string()});var qf=a.object({type:a.literal("ref/prompt"),name:a.string()}),Uf=ue.extend({ref:a.union([qf,jf]),argument:a.object({name:a.string(),value:a.string()}),context:a.object({arguments:a.record(a.string(),a.string()).optional()}).optional()}),Ff=V.extend({method:a.literal("completion/complete"),params:Uf});var Hf=G.extend({completion:a.looseObject({values:a.array(a.string()).max(100),total:a.optional(a.number().int()),hasMore:a.optional(a.boolean())})}),Wf=a.object({uri:a.string().startsWith("file://"),name:a.string().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Vf=V.extend({method:a.literal("roots/list"),params:ue.optional()}),Ts=G.extend({roots:a.array(Wf)}),Gf=me.extend({method:a.literal("notifications/roots/list_changed"),params:pe.optional()}),fE=a.union([Xr,ms,Ff,vs,Zd,Yd,Od,xd,zd,Ud,Hd,rr,bs,en,rn,nn,on]),pE=a.union([Zr,Qr,hs,Gf,er]),mE=a.union([Jr,sr,ks,bt,Ts,tn,sn,Et]),hE=a.union([Xr,Ef,Nf,Vf,en,rn,nn,on]),gE=a.union([Zr,Qr,ff,Vd,jd,lf,nf,er,Lf]),yE=a.union([Jr,Td,Hf,rf,Bd,Id,Dd,Ld,an,af,tn,sn,Et]),P=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===O.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new cs(s.elicitations,r)}return new t(e,r,n)}},cs=class extends P{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Be(t){return t==="completed"||t==="failed"||t==="cancelled"}var tp=ne(require("zod/v4-mini"),1);var Qf=require("zod/v3");var Yf=require("zod/v3");var Zf=require("zod/v3");var JE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ps(t){let r=Gr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Xi(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $s(t,e){let r=Ke(t,e);if(!r.success)throw r.error;return r.data}var rp=6e4,cn=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(Zr,r=>{this._oncancel(r)}),this.setNotificationHandler(Qr,r=>{this._onprogress(r)}),this.setRequestHandler(Xr,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(en,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new P(O.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(rn,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 P(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 P(O.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(nn,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 P(O.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(on,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new P(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(Be(s.status))throw new P(O.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 P(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof P?s:new P(O.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),P.fromError(O.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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");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),Bt(o)||ia(o)?this._onresponse(o):ds(o)?this._onrequest(o,i):oa(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();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=P.fromError(O.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:O.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=ra(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=>{if(i.signal.aborted)return;let f={relatedRequestId:e.id};o&&(f.relatedTask={taskId:o}),await this.notification(d,f)},sendRequest:async(d,f,p)=>{if(i.signal.aborted)throw new P(O.ConnectionClosed,"Request was cancelled");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:O.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.get(e.id)===i&&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),Bt(e))n(e);else{let i=new P(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(Bt(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),Bt(e))s(e);else{let i=P.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 P?i:new P(O.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 P(O.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 P(O.InternalError,`Task ${o} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new P(O.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 P?i:new P(O.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 P?S:new P(O.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??rp,_=()=>h(P.fromError(O.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},tn,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},sn,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},la,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=Ps(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=$s(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=Ps(e);this._notificationHandlers.set(n,s=>{let o=$s(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"&&ds(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new P(O.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 P(O.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new P(O.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 P(O.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=er.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 P(O.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Be(c.status))throw new P(O.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=er.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Be(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function ha(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ga(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];ha(i)&&ha(o)?r[s]={...i,...o}:r[s]=o}return r}var ru=ne(pi(),1),nu=ne(tu(),1);function K_(){let t=new ru.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,nu.default)(t),t}var Wn=class{constructor(e){this._ajv=e??K_()}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 Vn=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.type==="tool_result"),c=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=c?Array.isArray(c.content)?c.content:[c.content]:[],u=l.some(d=>d.type==="tool_use");if(i){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(l.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==f.size||![...d].every(p=>f.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},sr,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},bt,r)}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 su(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 ou(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 Gn=class extends cn{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(nr.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 Wn,this.setRequestHandler(ms,n=>this._oninitialize(n)),this.setNotificationHandler(hs,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(vs,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,c=nr.safeParse(i);return c.success&&this._loggingLevels.set(o,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Vn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ga(this._capabilities,e)}setRequestHandler(e,r){let s=Gr(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(rr,l);if(!d.success){let h=d.error instanceof Error?d.error.message:String(d.error);throw new P(O.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 P(O.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let m=Ke(an,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new P(O.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){ou(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&su(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:Qi.includes(r)?r:ls,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"},Jr)}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},ks,r):this.request({method:"sampling/createMessage",params:e},sr,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},bt,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},bt,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!c.valid)throw new P(O.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(i){throw i instanceof P?i:new P(O.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},Ts,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 wi=ne(require("node:process"),1);var Kn=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),Y_(r)}clear(){this._buffer=void 0}};function Y_(t){return aa.parse(JSON.parse(t))}function iu(t){return JSON.stringify(t)+`
`}var Yn=class{constructor(e=wi.default.stdin,r=wi.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Kn,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=iu(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Ii=ne(require("path"),1);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 Ie=require("fs"),Dr=require("path"),bi=require("os"),xe=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,Dr.join)((0,bi.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,Dr.join)((0,bi.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,Ie.existsSync)(e)){let i=this.getAllDefaults();try{let c=(0,Dr.dirname)(e);(0,Ie.existsSync)(c)||(0,Ie.mkdirSync)(c,{recursive:!0}),(0,Ie.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,Ie.readFileSync)(e,"utf-8"),n=JSON.parse(r),s=n;if(n.env&&typeof n.env=="object"){s=n.env;try{(0,Ie.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 F=require("path"),vi=require("os"),ki=require("fs");var cu=require("url");var Q_={};function B_(){return typeof __dirname<"u"?__dirname:(0,F.dirname)((0,cu.fileURLToPath)(Q_.url))}var Mk=B_();function J_(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,F.join)((0,vi.homedir)(),".claude-mem"),e=(0,F.join)(t,"settings.json");try{if((0,ki.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 De=J_(),Bn=process.env.CLAUDE_CONFIG_DIR||(0,F.join)((0,vi.homedir)(),".claude"),lu=(0,F.join)(Bn,"plugins","marketplaces","thedotmack"),Ak=(0,F.join)(De,"archives"),Ck=(0,F.join)(De,"logs"),Ok=(0,F.join)(De,"trash"),Ik=(0,F.join)(De,"backups"),xk=(0,F.join)(De,"modes"),Z_=(0,F.join)(De,"settings.json"),Dk=(0,F.join)(De,"claude-mem.db"),Nk=(0,F.join)(De,"vector-db"),X_=(0,F.join)(De,"observer-sessions"),zk=(0,F.basename)(X_),Lk=(0,F.join)(Bn,"settings.json"),jk=(0,F.join)(Bn,"commands"),qk=(0,F.join)(Bn,"CLAUDE.md");var gt=require("fs"),bu=require("os"),Oi=ne(require("path"),1);var Ri=require("child_process"),ze=require("fs"),uu=require("os"),Nr=ne(require("path"),1);var eS=["CLAUDECODE_","CLAUDE_CODE_"],tS=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),rS=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"]),nS=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 Ti(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(nS.has(r)){e[r]=n;continue}tS.has(r)||rS.has(r)||eS.some(s=>r.startsWith(s))||(e[r]=n)}return e}var sS=5e3,oS=1e3,iS=Nr.default.join((0,uu.homedir)(),".claude-mem"),aS=Nr.default.join(iS,"supervisor.json");function Ne(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 du(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,ze.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,Ri.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||!Ne(t.pid))return!1;if(!t.startToken)return!0;let e=du(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 $i=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,ze.mkdirSync)(Nr.default.dirname(this.registryPath),{recursive:!0}),!(0,ze.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,ze.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)Ne(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=>Ne(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()+sS;for(;Date.now()<o&&s.filter(l=>Ne(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let i=s.filter(c=>Ne(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()+oS;for(;Date.now()<c&&i.filter(u=>Ne(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,ze.mkdirSync)(Nr.default.dirname(this.registryPath),{recursive:!0}),(0,ze.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Pi=null;function Jn(){return Pi||(Pi=new $i),Pi}var mu=require("child_process"),hu=require("fs"),gu=require("os"),Ai=ne(require("path"),1),yu=require("util");var cS=(0,yu.promisify)(mu.execFile),lS=Ai.default.join((0,gu.homedir)(),".claude-mem"),uS=Ai.default.join(lS,"worker.pid");async function _u(t){let e=t.currentPid??process.pid,r=t.pidFilePath??uS,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(!Ne(i.pid)){t.registry.unregister(i.id);continue}try{await pu(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 fu(s,5e3);let o=s.filter(i=>Ne(i.pid));for(let i of o)try{await pu(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 fu(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,hu.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 fu(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.filter(s=>Ne(s.pid)).length===0)return;await new Promise(s=>setTimeout(s,100))}}async function pu(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 dS();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 dS(){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 Su=3e4,qt=null;function fS(){let e=Jn().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Eu(){qt===null&&(qt=setInterval(fS,Su),qt.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:Su}))}function wu(){qt!==null&&(clearInterval(qt),qt=null,y.debug("SYSTEM","Health checker stopped"))}var pS=Oi.default.join((0,bu.homedir)(),".claude-mem"),mS=Oi.default.join(pS,"worker.pid"),Ci=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(),Zn({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Eu()}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}wu(),this.stopPromise=_u({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}},hS=new Ci(Jn());function vu(){return hS}function Zn(t={}){let e=t.pidFilePath??mS;if(!(0,gt.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,gt.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,gt.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,gt.rmSync)(e,{force:!0}),"stale")}var gS=(()=>{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 yS(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 Xn=null,Qn=null;function xi(){if(Xn!==null)return Xn;let t=Ii.default.join(xe.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=xe.loadFromFile(t);return Xn=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Xn}function _S(){if(Qn!==null)return Qn;let t=Ii.default.join(xe.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return Qn=xe.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,Qn}function SS(t){return`http://${_S()}:${xi()}${t}`}function es(t,e={}){let r=e.method??"GET",n=e.timeoutMs??gS,s=SS(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),n>0?yS(s,o,n):fetch(s,o)}var zi=ne(require("path"),1),Se=require("fs");var Ve=ne(require("path"),1),Ni=require("os"),de=require("fs"),st=require("child_process"),Pu=require("util");var wT=(0,Pu.promisify)(st.exec),ES=Ve.default.join((0,Ni.homedir)(),".claude-mem"),ku=Ve.default.join(ES,"worker.pid");function Tu(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function wS(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,st.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 Di;function bS(t={}){let e=Object.keys(t).length===0;if(e&&Di!==void 0)return Di;let r=vS(t);return e&&r!==null&&(Di=r),r}function vS(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Tu(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,Ni.homedir)(),o=t.pathExists??de.existsSync,i=t.lookupInPath??wS,c=e==="win32"?[n.BUN,n.BUN_PATH,Ve.default.join(s,".bun","bin","bun.exe"),Ve.default.join(s,".bun","bin","bun"),n.USERPROFILE?Ve.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Ve.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Ve.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,Ve.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&&(Tu(u)&&o(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function ot(t){return process.platform==="win32"?Math.round(t*2):t}function $u(t,e,r={}){vu().assertCanSpawn("worker daemon");let n=Ti({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=bS();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,st.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=(0,st.spawn)(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 Ru(){try{if(!(0,de.existsSync)(ku))return;let t=new Date;(0,de.utimesSync)(ku,t,t)}catch{}}function Mu(){return Zn({logAlive:!1})}var Au=ne(require("net"),1);async function kS(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 Cu(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=Au.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 Ou(t,e,r,n){let s=Date.now();for(;Date.now()-s<r;){try{if((await kS(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 zr(t,e=3e4){return Ou(t,"/api/health",e,"Service not ready yet, will retry")}function Lr(t,e=3e4){return Ou(t,"/api/readiness",e,"Worker not ready yet, will retry")}var TS=120*1e3;function Li(){return zi.default.join(xe.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function PS(){if(process.platform!=="win32")return!1;let t=Li();if(!(0,Se.existsSync)(t))return!1;try{let e=(0,Se.statSync)(t).mtimeMs;return Date.now()-e<TS}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 $S(){if(process.platform==="win32")try{let t=Li();(0,Se.mkdirSync)(zi.default.dirname(t),{recursive:!0}),(0,Se.writeFileSync)(t,"","utf-8")}catch{}}function ts(){if(process.platform==="win32")try{let t=Li();(0,Se.existsSync)(t)&&(0,Se.unlinkSync)(t)}catch{}}async function Iu(t,e){if(!e)return y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,Se.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(Mu()==="alive"){if(y.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await zr(t,ot(ce.PORT_IN_USE_WAIT))){ts();let l=await Lr(t,ot(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 zr(t,1e3)){ts();let c=await Lr(t,ot(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 Cu(t)){if(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await zr(t,ot(ce.PORT_IN_USE_WAIT))){ts();let l=await Lr(t,ot(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(PS())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}),$S(),$u(e,t)===void 0)return y.error("SYSTEM","Failed to spawn worker daemon"),"dead";if(!await zr(t,ot(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 Lr(t,ot(ce.READINESS_WAIT));return i||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),ts(),Ru(),y.info("SYSTEM","Worker started successfully"),i?"ready":"warming"}var Ht=require("node:fs/promises"),Fr=require("node:path");var Nu=require("node:child_process"),ee=require("node:fs"),J=require("node:path"),Wi=require("node:os"),Ui=require("node:module");var US={},Fi=typeof __filename<"u"?(0,Ui.createRequire)(__filename):(0,Ui.createRequire)(US.url),Hi={".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 zu(t,e){let r=t.slice(t.lastIndexOf("."));return Hi[r]?Hi[r]:e.extensionToLanguage[r]?e.extensionToLanguage[r]:"unknown"}function Lu(t,e){return e.languageToQueryKey[t]?e.languageToQueryKey[t]:AS(t)}var jr=new Map,Ut={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};function Ur(t){if(jr.has(t))return jr.get(t);let e=(0,J.join)(t,".claude-mem.json"),r;try{let o=(0,ee.readFileSync)(e,"utf-8");r=JSON.parse(o)}catch{return jr.set(t,Ut),Ut}let n=r.grammars;if(!n||typeof n!="object"||Array.isArray(n))return jr.set(t,Ut),Ut;let s={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};for(let[o,i]of Object.entries(n)){if(ju[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)Hi[f]||(s.extensionToLanguage[f]=o);if(typeof d=="string"){let f=(0,J.join)(t,d);try{let p=(0,ee.readFileSync)(f,"utf-8"),m=`user_${o}`;Uu[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 jr.set(t,s),s}var ju={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"},RS={markdown:"tree-sitter-markdown"};function MS(t){let e=ju[t];if(!e)return null;let r=RS[t];if(r){try{let n=Fi.resolve(e+"/package.json"),s=(0,J.join)((0,J.dirname)(n),r);if((0,ee.existsSync)((0,J.join)(s,"src")))return s}catch{}return null}try{let n=Fi.resolve(e+"/package.json");return(0,J.dirname)(n)}catch{return null}}function qu(t,e){let r=MS(t);if(r)return r;if(!e)return null;let s=Ur(e).grammars[t];if(!s)return null;try{let o=(0,J.join)(e,"node_modules",s.package,"package.json");if((0,ee.existsSync)(o)){let i=(0,J.dirname)(o);if((0,ee.existsSync)((0,J.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 Uu={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 AS(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 ji=null,qi=new Map;function Fu(t){if(qi.has(t))return qi.get(t);ji||(ji=(0,ee.mkdtempSync)((0,J.join)((0,Wi.tmpdir)(),"smart-read-queries-")));let e=(0,J.join)(ji,`${t}.scm`);return(0,ee.writeFileSync)(e,Uu[t]),qi.set(t,e),e}var qr=null;function CS(){if(qr)return qr;try{let t=Fi.resolve("tree-sitter-cli/package.json"),e=(0,J.join)((0,J.dirname)(t),"tree-sitter");if((0,ee.existsSync)(e))return qr=e,e}catch{}return qr="tree-sitter",qr}function OS(t,e,r){return Hu(t,[e],r).get(e)||[]}function Hu(t,e,r){if(e.length===0)return new Map;let n=CS(),s=["query","-p",r,t,...e],o;try{o=(0,Nu.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 IS(o)}function IS(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 xu={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"},xS=new Set(["class","struct","impl","trait"]);function DS(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 NS(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 zS(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 LS(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 Wu(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=>xu[w.tag]),d=l.captures.find(w=>w.tag==="name");if(!u)continue;let f=u.startRow,p=u.endRow,m=xu[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=DS(e,f,p);let _=r==="markdown"?void 0:NS(e,f),E=r==="python"?zS(e,f,p):void 0,S={name:h,kind:m,signature:g,jsdoc:_||E,lineStart:f,lineEnd:p,exported:LS(h,f,p,o,e,r)};xS.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 rs(t,e,r){let n=r?Ur(r):Ut,s=zu(e,n),o=t.split(`
`),i=qu(s,r);if(!i)return{filePath:e,language:s,symbols:[],imports:[],totalLines:o.length,foldedTokenEstimate:50};let c=Lu(s,n),l=Fu(c),u=e.slice(e.lastIndexOf("."))||".txt",d=(0,ee.mkdtempSync)((0,J.join)((0,Wi.tmpdir)(),"smart-src-")),f=(0,J.join)(d,`source${u}`);(0,ee.writeFileSync)(f,t);try{let p=OS(l,f,i),m=Wu(p,o,s),h=Ft({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,ee.rmSync)(d,{recursive:!0,force:!0})}}function Vu(t,e){let r=new Map,n=e?Ur(e):Ut,s=new Map;for(let o of t){let i=zu(o.relativePath,n);s.has(i)||s.set(i,[]),s.get(i).push(o)}for(let[o,i]of s){let c=qu(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=Lu(o,n),u=Fu(l),d=i.map(p=>p.absolutePath),f=Hu(u,d,c);for(let p of i){let m=p.content.split(`
`),h=f.get(p.absolutePath)||[],g=Wu(h,m,o),_=Ft({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 Ft(t){if(t.language==="markdown")return jS(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(Gu(r," "));return e.join(`
`)}function jS(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=Du(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=Du(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 Du(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 Gu(t,e){let r=[],n=qS(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(Gu(i,e+" "));return r.join(`
`)}function qS(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 Ku(t,e,r){let n=rs(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 Yu=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"]),FS=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),HS=512*1024;async function*Bu(t,e,r=20,n){if(r<=0)return;let s;try{s=await(0,Ht.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!=="."||FS.has(o.name))continue;let i=(0,Fr.join)(t,o.name);if(o.isDirectory())yield*Bu(i,e,r-1,n);else if(o.isFile()){let c=o.name.slice(o.name.lastIndexOf("."));(Yu.has(c)||n&&n.has(c))&&(yield i)}}}async function WS(t){try{let e=await(0,Ht.stat)(t);if(e.size>HS||e.size===0)return null;let r=await(0,Ht.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 Ju(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=Ur(i),l=new Set;for(let S of Object.values(c.grammars))for(let w of S.extensions)Yu.has(w)||l.add(w);let u=[];for await(let S of Bu(t,t,20,l.size>0?l:void 0)){if(r.filePattern&&!(0,Fr.relative)(t,S).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let w=await WS(S);w&&u.push({absolutePath:S,relativePath:(0,Fr.relative)(t,S),content:w})}let d=Vu(u,i),f=[],p=[],m=0;for(let[S,w]of d){m+=VS(w);let k=ns(S.toLowerCase(),o)>0,le=[],fe=(Vt,yt)=>{for(let H of Vt){let Ge=0,Ee="",Gt=ns(H.name.toLowerCase(),o);Gt>0&&(Ge+=Gt*3,Ee="name match"),H.signature.toLowerCase().includes(s)&&(Ge+=2,Ee=Ee?`${Ee} + signature`:"signature match"),H.jsdoc&&H.jsdoc.toLowerCase().includes(s)&&(Ge+=1,Ee=Ee?`${Ee} + jsdoc`:"jsdoc match"),Ge>0&&(k=!0,le.push({filePath:S,symbolName:yt?`${yt}.${H.name}`:H.name,kind:H.kind,signature:H.signature,jsdoc:H.jsdoc,lineStart:H.lineStart,lineEnd:H.lineEnd,matchReason:Ee})),H.children&&fe(H.children,H.name)}};fe(w.symbols),k&&(f.push(w),p.push(...le))}p.sort((S,w)=>{let A=ns(S.symbolName.toLowerCase(),o);return ns(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 ns(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 VS(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function Zu(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(Ft(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 Gi=require("node:fs/promises"),ss=require("node:fs"),Pe=require("node:path"),ed=require("node:os"),td=require("node:url"),nE={},GS="12.4.9";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var rd=!1,nd=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Pe.dirname)((0,td.fileURLToPath)(nE.url))}catch{return rd=!0,process.cwd()}})(),Ki=(0,Pe.resolve)(nd,"worker-service.cjs");function KS(){rd&&((0,ss.existsSync)(Ki)||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:Ki,mcpServerDir:nd}))}var Xu={search:"/api/search",timeline:"/api/timeline"};async function Vi(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 es(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 YS(t,e){let r=await es(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 Wt(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await YS(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 BS(){try{return(await es("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function JS(){if(await BS())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),KS();try{let t=xi(),e=await Iu(t,Ki);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 sd=[{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=Xu.search;return await Vi(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=Xu.timeline;return await Vi(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 Wt("/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,Pe.resolve)(t.path||process.cwd()),r=await Ju(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:Zu(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,Pe.resolve)(t.file_path),r=await(0,Gi.readFile)(e,"utf-8"),n=Ku(r,e,t.symbol_name);if(n)return{content:[{type:"text",text:n}]};let s=rs(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,Pe.resolve)(t.file_path),r=await(0,Gi.readFile)(e,"utf-8"),n=rs(r,e);return n.symbols.length>0?{content:[{type:"text",text:Ft(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 Wt("/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 Vi("/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 Wt(`/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 Wt(`/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 Wt(`/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 Wt(`/api/corpus/${encodeURIComponent(e)}/reprime`,r)}}],Yi=new Gn({name:"claude-mem",version:GS},{capabilities:{tools:{}}});Yi.setRequestHandler(bs,async()=>({tools:sd.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));Yi.setRequestHandler(rr,async t=>{let e=sd.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 ZS=3e4,Hr=null,Qu=!1;function os(){Wr("stdio-closed")}function od(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),Wr("stdio-error")}function XS(){process.stdin.on("end",os),process.stdin.on("close",os),process.stdin.on("error",od)}function QS(){process.stdin.off("end",os),process.stdin.off("close",os),process.stdin.off("error",od)}function eE(){if(process.platform==="win32")return;let t=process.ppid;Hr=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),Wr())},ZS),Hr.unref&&Hr.unref()}function Wr(t="shutdown"){Qu||(Qu=!0,Hr&&clearInterval(Hr),QS(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",Wr);process.on("SIGINT",Wr);function tE(){try{let t=(0,ed.homedir)(),e=[(0,Pe.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,Pe.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,ss.existsSync)(i)),n=[(0,Pe.resolve)(t,".claude","plugins","cache","thedotmack","claude-mem"),(0,Pe.resolve)(t,".config","claude","plugins","cache","thedotmack","claude-mem")],s=n.some(i=>i&&(0,ss.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 rE(){let t=new Yn;XS(),await Yi.connect(t),y.info("SYSTEM","Claude-mem search server started"),tE(),eE(),setTimeout(async()=>{await JS()?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)}rE().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)});