@dimassetoid/septum-mcp 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > **Local codebase intelligence and architecture boundary guard for AI coding agents.**
4
4
 
5
- [![Version: 0.5.0](https://img.shields.io/badge/Version-0.5.0-blue)](package.json)
5
+ [![Version: 0.5.2](https://img.shields.io/badge/Version-0.5.2-blue)](package.json)
6
6
  [![Runtime: Bun](https://img.shields.io/badge/Runtime-Bun-black?logo=bun)](https://bun.sh)
7
7
  [![Protocol: Model Context Protocol](https://img.shields.io/badge/Protocol-MCP-green)](https://modelcontextprotocol.io/)
8
8
  [![Database: SQLite WAL](https://img.shields.io/badge/Database-SQLite%20(bun:sqlite)-003B57?logo=sqlite)](https://sqlite.org/)
@@ -18,6 +18,7 @@ Septum is a local static-analysis MCP server and CLI that keeps AI coding agents
18
18
  - **Bounded Symbol Context & Impact (`septum_symbol`):** Locates declarations across the codebase, retrieves bounded implementation context (deep TypeScript reference context within `budget_bytes`, or bounded polyglot source inspection), and reports static dependents and caller hints.
19
19
  - **Static Flow Tracing (`septum_slice`):** Traces static relationship chains from supported application entrypoints (`query`, `controller_file`, `max_depth`) across layers, showing relationship evidence or `unknown` for each node.
20
20
  - **Architecture Boundary Guard (`septum_boundary`):** Validates proposed file imports against domain rules before writing (`scope: "file"`), checks staged Git changes before commit (`scope: "staged"`), and audits circular or cross-domain violations (`scope: "domain"`, `scope: "all"`).
21
+ - **MCP App UI, Resources & Prompts (`septum_app`, `ui://septum/app.html`):** Ships an interactive MCP App panel (Architecture, Slice, and Boundary views) for compatible hosts, read-only `septum://` workspace resources (`domains`, `health`, `boundaries`, `apps`, `domain/{name}`), and five workflow prompts (`open-apps`, `audit-coupling`, `check-staged`, `plan-refactor`, `trace-feature`).
21
22
 
22
23
  ### Language Support & Analysis Scope
23
24
 
@@ -116,6 +117,7 @@ If your MCP client is not configured via `septum init`, add Septum to `.mcp.json
116
117
  ## Documentation
117
118
 
118
119
  - [Implemented Features & Limits](docs/feature/README.md) — Tool behaviors, language coverage, and verification scope
120
+ - [MCP Resources, Prompts & Apps](docs/feature/mcp-resources-and-prompts.md) — Workspace resources, workflow playbooks, and the Septum Architecture UI
119
121
  - [Symbol Context Contract](docs/feature/symbol-context-contract.md) — Deep context selection, byte budgets, and pagination
120
122
  - [Import Resolution](docs/feature/import-resolution.md) — Supported static targets and unresolved boundaries
121
123
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimassetoid/septum-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Deterministic Bounded-Context, Structural File Catalog & Anti-Poisoning Partition for AI Agents",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -93,13 +93,9 @@ function blockHook(db: SeptumDatabase | null, reason: string): never {
93
93
  async function runPreWriteHook(): Promise<void> {
94
94
  const callerRoot = process.cwd();
95
95
  const workspaceRoot = path.resolve(process.env.SEPTUM_HOOK_ROOT || callerRoot);
96
- const configFilePath = path.join(workspaceRoot, "septum.config.json");
97
- const hasDiskConfig = fs.existsSync(configFilePath);
98
- const config = hasDiskConfig
99
- ? ConfigLoader.loadFromDisk(configFilePath)
100
- : ConfigLoader.load(undefined, workspaceRoot);
96
+ const config = ConfigLoader.load(undefined, workspaceRoot);
101
97
  const dbPath = resolveDatabasePath(workspaceRoot, config.settings.db_path);
102
- if (!hasDiskConfig && !fs.existsSync(dbPath)) {
98
+ if (!fs.existsSync(dbPath)) {
103
99
  process.exit(0);
104
100
  }
105
101
 
@@ -133,10 +129,8 @@ async function runPreWriteHook(): Promise<void> {
133
129
  const targetFile = path.relative(workspaceRoot, path.resolve(callerRoot, edit.target)).replace(/\\/g, "/");
134
130
  const content = edit.content;
135
131
 
136
- // Zero-SQLite fast path: when septum.config.json owns policy, evaluate proposed imports
137
- // in-memory without opening SQLite on every edit.
138
- const db = hasDiskConfig ? null : new SeptumDatabase(dbPath);
139
- const repo = db ? new SeptumRepository(db.raw) : undefined;
132
+ const db = new SeptumDatabase(dbPath);
133
+ const repo = new SeptumRepository(db.raw);
140
134
  const evaluator = new BoundaryEvaluator(repo, new ModuleResolver(workspaceRoot, repo));
141
135
 
142
136
  try {
@@ -170,7 +164,7 @@ async function runPreWriteHook(): Promise<void> {
170
164
  rule: v.rule,
171
165
  source_domain: v.source_domain,
172
166
  target_domain: v.target_domain,
173
- zero_sqlite: hasDiskConfig,
167
+ zero_sqlite: false,
174
168
  },
175
169
  workspaceRoot,
176
170
  emitStderr: false,
@@ -197,7 +191,7 @@ async function runPreWriteHook(): Promise<void> {
197
191
  decision: "allow",
198
192
  coverage: edit.coverage,
199
193
  evaluated: sourceDomain ? "proposed_imports" : "unmapped_domain",
200
- zero_sqlite: hasDiskConfig,
194
+ zero_sqlite: false,
201
195
  },
202
196
  workspaceRoot,
203
197
  emitStderr: false,
@@ -18,41 +18,22 @@ export async function handleInitCommand(force: boolean = false): Promise<void> {
18
18
  if (!fs.existsSync(septumDir)) {
19
19
  fs.mkdirSync(septumDir, { recursive: true });
20
20
  }
21
- const policyFile = path.join(workspaceRoot, "septum.config.json");
22
- const diskConfig = fs.existsSync(policyFile) ? ConfigLoader.loadFromDisk(policyFile) : undefined;
23
- const dbPath = resolveDatabasePath(workspaceRoot, diskConfig?.settings.db_path);
21
+ const dbPath = resolveDatabasePath(workspaceRoot);
24
22
 
25
23
  console.log("\n\x1b[36m◆\x1b[0m \x1b[1mSeptum Architecture Guard & SSOT Initializer\x1b[0m\n\x1b[36m│\x1b[0m");
26
24
  console.log(`\x1b[36m│\x1b[0m Workspace: ${workspaceRoot}`);
27
25
 
28
- // 1. Auto-discover project topology (or sync explicit septum.config.json domains) and persist to SQLite SSOT
26
+ // 1. Auto-discover project topology and persist to SQLite SSOT
29
27
  console.log("\x1b[36m◇\x1b[0m Analyzing codebase topology, modular boundaries, and deployment infrastructure...");
30
28
  const db = new SeptumDatabase(dbPath);
31
29
  try {
32
30
  const repo = new SeptumRepository(db.raw);
33
- const hasExplicitDomains = Boolean(diskConfig && Object.keys(diskConfig.domains).length > 0);
34
- let domains: Record<string, import("../../types/index.ts").DomainConfig>;
35
- let shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }> = [];
36
- if (hasExplicitDomains) {
37
- const synced = TopologyDetector.syncExplicitConfigDomains(repo, workspaceRoot, diskConfig!.domains);
38
- domains = synced.domains;
39
- shadowedSubdomains = synced.shadowedSubdomains;
40
- console.log("\x1b[36m│\x1b[0m \x1b[33mℹ\x1b[0m Using explicit domains from septum.config.json (skipping topology auto-discovery).");
41
- } else {
42
- domains = TopologyDetector.discoverAndPersist(repo, workspaceRoot, force);
43
- }
31
+ const domains = TopologyDetector.discoverAndPersist(repo, workspaceRoot, force);
44
32
  const domainNames = Object.keys(domains);
45
- console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m ${hasExplicitDomains ? "Synchronized" : "Discovered and registered"} ${domainNames.length} domain(s) in SQLite SSOT:`);
33
+ console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m Discovered and registered ${domainNames.length} domain(s) in SQLite SSOT:`);
46
34
  for (const name of domainNames) {
47
35
  console.log(`\x1b[36m│\x1b[0m - \x1b[1m${name}\x1b[0m: root -> '${domains[name].root}'`);
48
36
  }
49
- for (const shadow of shadowedSubdomains) {
50
- const preview = shadow.detectedNames.slice(0, 6).join(", ");
51
- const suffix = shadow.detectedNames.length > 6 ? `, +${shadow.detectedNames.length - 6} more` : "";
52
- console.log(
53
- `\x1b[36m│\x1b[0m \x1b[33m⚠\x1b[0m Explicit domain '${shadow.explicitDomain}' (root: '${shadow.explicitRoot}') covers ${shadow.detectedNames.length} detected sub-domain(s) (${preview}${suffix}). Remove '${shadow.explicitDomain}' or clear 'domains' in septum.config.json to use auto-discovered layers.`
54
- );
55
- }
56
37
  const scanned = JSON.parse(repo.getMeta("scanned_folders") || "[]");
57
38
  const ignored = JSON.parse(repo.getMeta("ignored_folders") || "[]");
58
39
  if (scanned.length > 0) {
@@ -20,7 +20,7 @@ export const SEPTUM_PRE_WRITE_SCRIPT = `#!/usr/bin/env sh
20
20
  # Passes supported edit payloads to the CLI before the client writes them
21
21
 
22
22
  ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd -P)"
23
- if [ ! -f "$ROOT_DIR/.septum/septum.db" ] && [ ! -f "$ROOT_DIR/septum.config.json" ]; then
23
+ if [ ! -f "$ROOT_DIR/.septum/septum.db" ]; then
24
24
  exit 0
25
25
  fi
26
26
 
@@ -45,7 +45,7 @@ export const SEPTUM_POST_WRITE_SCRIPT = `#!/usr/bin/env sh
45
45
  # Syncs modified AST into SQLite SSOT after file mutations
46
46
 
47
47
  ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd -P)"
48
- if [ ! -f "$ROOT_DIR/.septum/septum.db" ] && [ ! -f "$ROOT_DIR/septum.config.json" ]; then
48
+ if [ ! -f "$ROOT_DIR/.septum/septum.db" ]; then
49
49
  exit 0
50
50
  fi
51
51
 
@@ -53,8 +53,8 @@ Set \`workspace_path\` when selecting among repositories. If the MCP tools are u
53
53
 
54
54
  ## Resources & Prompts
55
55
 
56
- - **MCP Resources (initial workspace):** \`septum://domains\`, \`septum://health\`, \`septum://boundaries\`, and \`septum://domain/{name}\` provide read-only JSON snapshots for the server's initial workspace; use the 4 MCP tools with \`workspace_path\` for multi-root queries.
57
- - **MCP Prompts:** \`septum-pre-edit-check\` and \`septum-architecture-audit\` provide step-by-step verification playbooks.
56
+ - **MCP Resources:** \`septum://domains\`, \`septum://health\`, \`septum://boundaries\`, \`septum://apps\`, \`ui://septum/app.html\`, and \`septum://domain/{name}\` provide workspace snapshots and the MCP App UI (append \`?workspace=\` to select a workspace; use the 4 MCP tools with \`workspace_path\` for multi-root queries).
57
+ - **MCP Prompts:** \`open-apps\`, \`audit-coupling\`, \`check-staged\`, \`plan-refactor\`, and \`trace-feature\` provide step-by-step workflow playbooks.
58
58
 
59
59
  Describe the operation and observed result. Do not promise token savings, response speed, memory savings, complete caller discovery or universal language/framework coverage.
60
60
  `;
@@ -119,6 +119,26 @@ export async function evaluateBoundary(
119
119
  if (incomplete.length || proposed.length || staleFiles.length) {
120
120
  const known = evaluator.auditCodebase(config, evidence).filter(violation => relevant(violation.file));
121
121
  known.push(...requested.flatMap(file => evaluator.evaluate(file, proposedImports, config, evidence)));
122
+ const incompleteReasons = {
123
+ target_not_fully_indexed: incomplete.filter(edge => edge.index_coverage === "partial").length,
124
+ stale_source: incomplete.filter(edge => edge.freshness !== "current").length,
125
+ unresolved_or_unsupported: incomplete.filter(edge => !["resolved", "external"].includes(edge.resolution.status)).length,
126
+ conditional_resolution: incomplete.filter(edge => edge.resolution.coverage === "conditional").length,
127
+ multiple_domains: incomplete.filter(edge => edge.target_domains.length > 1).length,
128
+ };
129
+ const reasonParts = [
130
+ incompleteReasons.target_not_fully_indexed > 0 ? `${incompleteReasons.target_not_fully_indexed} target(s) not fully indexed` : "",
131
+ incompleteReasons.stale_source > 0 ? `${incompleteReasons.stale_source} stale source import(s)` : "",
132
+ incompleteReasons.unresolved_or_unsupported > 0 ? `${incompleteReasons.unresolved_or_unsupported} unresolved/unsupported import(s)` : "",
133
+ incompleteReasons.conditional_resolution > 0 ? `${incompleteReasons.conditional_resolution} conditional import(s)` : "",
134
+ incompleteReasons.multiple_domains > 0 ? `${incompleteReasons.multiple_domains} multi-domain target(s)` : "",
135
+ proposed.length > 0 ? `${proposed.length} unresolved/conditional proposed import(s)` : "",
136
+ staleFiles.length > 0 ? `${staleFiles.length} stale indexed file(s)` : "",
137
+ ].filter(Boolean);
138
+ const reasonSummary = reasonParts.length > 0 ? reasonParts.join(", ") : "incomplete import evidence";
139
+ const message = known.length > 0
140
+ ? `${known.length} boundary violation(s) detected, and relevant import evidence is incomplete (${reasonSummary}).`
141
+ : `Boundary approval is unknown because relevant import evidence is incomplete (${reasonSummary}).`;
122
142
  return incompleteEvidence({
123
143
  status: known.length ? "rejected" : "unknown",
124
144
  scope: effectiveScope,
@@ -127,16 +147,10 @@ export async function evaluateBoundary(
127
147
  circular_dependencies: known.filter(v => v.rule === "circular_dependency"), circular_dependencies_count: known.filter(v => v.rule === "circular_dependency").length,
128
148
  relationships: incomplete.slice(0, 10), proposed_resolutions: allProposed,
129
149
  diagnostic_accounting: { total: incomplete.length, returned: Math.min(10, incomplete.length), omitted: Math.max(0, incomplete.length - 10) },
130
- incomplete_reasons: {
131
- target_not_fully_indexed: incomplete.filter(edge => edge.index_coverage === "partial").length,
132
- stale_source: incomplete.filter(edge => edge.freshness !== "current").length,
133
- unresolved_or_unsupported: incomplete.filter(edge => !["resolved", "external"].includes(edge.resolution.status)).length,
134
- conditional_resolution: incomplete.filter(edge => edge.resolution.coverage === "conditional").length,
135
- multiple_domains: incomplete.filter(edge => edge.target_domains.length > 1).length,
136
- },
150
+ incomplete_reasons: incompleteReasons,
137
151
  next: ["Inspect the listed source imports; register/index uncovered target roots or narrow scope to a file/domain. Unknown is not approval."],
138
152
  stale_files: staleFiles,
139
- message: "Relevant import resolution is incomplete; an empty graph cannot prove boundary approval.",
153
+ message,
140
154
  });
141
155
  }
142
156
  }
@@ -1,11 +1,10 @@
1
- import { existsSync, readFileSync, statSync } from "node:fs";
2
- import { join, resolve } from "node:path";
1
+ import { statSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
3
  import type { SeptumRepository } from "../database/repository.ts";
4
4
  import { IngestionPipeline, type IngestionMetrics } from "../ingestion/pipeline.ts";
5
5
  import { assertPathContained } from "../resolver/path-resolver.ts";
6
6
  import { assertUniqueDomainRoots, domainNameKey, domainRootIdentity } from "./domain-ownership.ts";
7
- import { ConfigLoader } from "./loader.ts";
8
- import { SeptumConfigSchema, type ValidatedSeptumConfig } from "./schema.ts";
7
+ import type { ValidatedSeptumConfig } from "./schema.ts";
9
8
  import type { DomainConfig } from "../../types/index.ts";
10
9
 
11
10
  export interface DomainRegistrationInput {
@@ -20,7 +19,7 @@ export interface DomainRegistrationInput {
20
19
  }
21
20
 
22
21
  export interface DomainRegistrationResult {
23
- policyOwner: "database" | "file";
22
+ policyOwner: "database";
24
23
  domainId: number;
25
24
  domain: string;
26
25
  config: ValidatedSeptumConfig["domains"][string];
@@ -73,39 +72,9 @@ export async function registerDomainPolicy(
73
72
  );
74
73
  assertUniqueDomainRoots({ ...memoryClaims, [domainName]: domainConfig }, workspaceRoot);
75
74
 
76
- const policyFile = join(workspaceRoot, "septum.config.json");
77
- const policySource = existsSync(policyFile) ? readFileSync(policyFile, "utf8") : undefined;
78
- if (policySource !== undefined) {
79
- const policy = SeptumConfigSchema.parse(JSON.parse(policySource));
80
- const existing = Object.entries(policy.domains).find(([name]) => domainNameKey(name) === domainNameKey(domainName))?.[1];
81
- domainConfig.allowed_dependencies ??= existing?.allowed_dependencies ?? [];
82
- domainConfig.forbidden_dependencies ??= existing?.forbidden_dependencies ?? [];
83
- domainConfig.archetypes ??= existing?.archetypes ?? {};
84
- domainConfig.description = args.description ?? existing?.description ?? domainConfig.description;
85
- const diskClaims = Object.fromEntries(
86
- Object.entries(policy.domains).filter(
87
- ([name, claim]) => domainNameKey(name) !== domainNameKey(domainName) && domainRootIdentity(claim.root, workspaceRoot) === proposed
88
- )
89
- );
90
- assertUniqueDomainRoots({ ...diskClaims, [domainName]: domainConfig }, workspaceRoot);
91
- }
92
-
93
75
  const domainId = repo.runInTransaction(() => {
94
76
  const id = repo.domains.upsertDomain(domainName, domainConfig, workspaceRoot);
95
77
  const stored = repo.domains.getDomainByName(domainName)!;
96
- if (policySource !== undefined) {
97
- ConfigLoader.writeDomain(
98
- workspaceRoot,
99
- stored.name,
100
- {
101
- ...domainConfig,
102
- allowed_dependencies: JSON.parse(stored.allowed_deps_json),
103
- forbidden_dependencies: JSON.parse(stored.forbidden_deps_json),
104
- archetypes: JSON.parse(stored.archetypes_json),
105
- },
106
- policySource
107
- );
108
- }
109
78
  repo.rebindFilesToDomain(stored.root_path || domainConfig.root, id);
110
79
  return id;
111
80
  }, true);
@@ -131,7 +100,7 @@ export async function registerDomainPolicy(
131
100
  }
132
101
 
133
102
  return {
134
- policyOwner: policySource === undefined ? "database" : "file",
103
+ policyOwner: "database",
135
104
  domainId,
136
105
  domain: canonicalName,
137
106
  config: finalConfig,
@@ -1,101 +1,25 @@
1
- import { closeSync, existsSync, lstatSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
- import { isAbsolute, join, resolve } from "node:path";
1
+ import { existsSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
3
  import { Database } from "bun:sqlite";
4
4
  import { SeptumConfigSchema, type ValidatedSeptumConfig } from "./schema.ts";
5
5
  import { SeptumDatabase } from "../database/client.ts";
6
6
  import { SeptumRepository } from "../database/repository.ts";
7
7
  import { resolveWorkspaceRoot } from "../resolver/path-resolver.ts";
8
- import type { DomainConfig } from "../../types/index.ts";
9
8
 
10
9
  export function resolveDatabasePath(root: string, dbPath = ".septum/septum.db"): string {
11
10
  return dbPath === ":memory:" || isAbsolute(dbPath) ? dbPath : resolve(root, dbPath);
12
11
  }
13
12
 
14
13
  export class ConfigLoader {
15
- /** Read configuration without initializing or modifying workspace state. */
14
+ /** Read configuration from SQLite SSOT (or defaults) without initializing workspace state. */
16
15
  public static load(
17
16
  dbPath?: string,
18
17
  projectRoot?: string
19
18
  ): ValidatedSeptumConfig {
20
19
  const root = resolveWorkspaceRoot(projectRoot);
21
- const configFilePath = join(root, "septum.config.json");
22
- if (existsSync(configFilePath)) {
23
- const diskConfig = ConfigLoader.loadFromDisk(configFilePath);
24
- if (dbPath) diskConfig.settings.db_path = dbPath;
25
- return diskConfig;
26
- }
27
20
  return ConfigLoader.loadFromDatabaseOrDefaults(resolveDatabasePath(root, dbPath));
28
21
  }
29
22
 
30
- /** The file owns policy when present; retain unknown user fields on updates. */
31
- public static writeDomain(root: string, name: string, domain: DomainConfig, expected: string): void {
32
- const file = join(root, "septum.config.json");
33
- const lock = `${file}.lock`;
34
- const fd = openSync(lock, "wx");
35
- const temporary = `${file}.${process.pid}.tmp`;
36
- try {
37
- if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw new Error("Policy file must be a regular file.");
38
- if (readFileSync(file, "utf8") !== expected) throw new Error("Policy changed during registration; reload and retry.");
39
- const raw = JSON.parse(expected);
40
- const domains = { ...raw.domains };
41
- const key = Object.keys(domains).find(key => key.toLowerCase() === name.toLowerCase()) ?? name;
42
- domains[key] = { ...domains[key], ...domain };
43
- const updated = { ...raw, domains };
44
- SeptumConfigSchema.parse(updated);
45
- writeFileSync(temporary, JSON.stringify(updated, null, 2) + "\n", { flag: "wx", mode: lstatSync(file).mode & 0o777 });
46
- if (readFileSync(file, "utf8") !== expected) throw new Error("Policy changed during registration; reload and retry.");
47
- renameSync(temporary, file);
48
- } finally {
49
- closeSync(fd);
50
- rmSync(temporary, { force: true });
51
- rmSync(lock, { force: true });
52
- }
53
- }
54
-
55
- public static loadFromDisk(filePath: string): ValidatedSeptumConfig {
56
- try {
57
- const raw = readFileSync(filePath, "utf-8");
58
- const parsed = JSON.parse(raw);
59
- const defaults = ConfigLoader.getDefaultConfig();
60
- const merged = {
61
- ...defaults,
62
- ...parsed,
63
- settings: {
64
- ...defaults.settings,
65
- ...(parsed.settings || {}),
66
- },
67
- domains: parsed.domains || {},
68
- };
69
- return SeptumConfigSchema.parse(merged);
70
- } catch (err: any) {
71
- throw new Error(`Failed to load configuration from '${filePath}': ${err.message || err}`);
72
- }
73
- }
74
-
75
- public static syncDiskConfigToDatabase(
76
- dbPath: string,
77
- diskConfig: ValidatedSeptumConfig,
78
- workspaceRoot?: string
79
- ): void {
80
- if (!existsSync(dbPath)) return;
81
- const septumDb = new SeptumDatabase(dbPath);
82
- const repo = new SeptumRepository(septumDb.raw);
83
- try {
84
- repo.runInTransaction(() => {
85
- repo.setMeta("settings_json", JSON.stringify(diskConfig.settings));
86
- if (diskConfig.domains && Object.keys(diskConfig.domains).length > 0) {
87
- const domainNames = Object.keys(diskConfig.domains);
88
- for (const [name, domain] of Object.entries(diskConfig.domains)) {
89
- repo.upsertDomain(name, domain, workspaceRoot);
90
- }
91
- repo.pruneDomainsNotIn(domainNames);
92
- }
93
- });
94
- } finally {
95
- septumDb.close();
96
- }
97
- }
98
-
99
23
  public static getDefaultConfig(): ValidatedSeptumConfig {
100
24
  return SeptumConfigSchema.parse({});
101
25
  }
@@ -17,7 +17,8 @@ function aggregateImportEdges(
17
17
  const byPath = new Map(files.map(file => [file.path, file]));
18
18
  const degree = new Map<string, number>();
19
19
  const edges = new Map<string, NavEdge>();
20
- const unresolved: NavUnresolved[] = [];
20
+ const incomplete: NavUnresolved[] = [];
21
+ let unresolvedCount = 0;
21
22
 
22
23
  const relationshipList = workspace
23
24
  ? repo.getImportRelationships(root)
@@ -28,12 +29,14 @@ function aggregateImportEdges(
28
29
  const targets = [...new Set(edge.resolution.targets.flatMap(target => target.files))];
29
30
  if (!paths.has(source) && !targets.some(target => paths.has(target))) continue;
30
31
 
32
+ const isUnresolved = !["resolved", "external"].includes(edge.resolution.status);
31
33
  const isIncomplete = edge.freshness !== "current" ||
32
- !["resolved", "external"].includes(edge.resolution.status) ||
34
+ isUnresolved ||
33
35
  edge.resolution.coverage === "conditional" ||
34
36
  edge.index_coverage === "partial";
37
+ if (isUnresolved) unresolvedCount++;
35
38
  if (isIncomplete) {
36
- unresolved.push({
39
+ incomplete.push({
37
40
  file: source,
38
41
  target: edge.resolution.source.target,
39
42
  reason: edge.freshness !== "current"
@@ -58,14 +61,15 @@ function aggregateImportEdges(
58
61
  }
59
62
  }
60
63
 
61
- return { byPath, degree, edges, unresolved };
64
+ return { byPath, degree, edges, incomplete, unresolvedCount };
62
65
  }
63
66
 
64
67
  /** Summarize index health and coverage diagnostics for the selected navigation scope. */
65
68
  function computeNavigationHealth(
66
69
  repo: SeptumRepository,
67
70
  domainRoot: string | undefined,
68
- unresolved: NavUnresolved[],
71
+ incomplete: NavUnresolved[],
72
+ unresolvedCount: number,
69
73
  emptyDomainsCount: number,
70
74
  totalIndexedFiles: number,
71
75
  uncoveredCount: number
@@ -79,7 +83,7 @@ function computeNavigationHealth(
79
83
  .filter(file => !prefix || file.path.startsWith(prefix)).length;
80
84
 
81
85
  const reasons = [...new Set([
82
- ...unresolved.map(item => item.reason),
86
+ ...incomplete.map(item => item.reason),
83
87
  ...(unsupported > 0 ? ["unsupported_files"] : []),
84
88
  ...(skipped > 0 ? ["skipped_files"] : []),
85
89
  ...(emptyDomainsCount > 0 ? ["empty_domains"] : []),
@@ -91,7 +95,7 @@ function computeNavigationHealth(
91
95
 
92
96
  const coverage = sync === "complete" &&
93
97
  !dirty &&
94
- unresolved.length === 0 &&
98
+ incomplete.length === 0 &&
95
99
  unsupported === 0 &&
96
100
  skipped === 0 &&
97
101
  emptyDomainsCount === 0 &&
@@ -103,7 +107,16 @@ function computeNavigationHealth(
103
107
  return {
104
108
  sync,
105
109
  dirty,
106
- health: { index: sync, sync_needed: dirty, coverage, unresolved_imports: unresolved.length, unsupported_files: unsupported, skipped_files: skipped, reasons },
110
+ health: {
111
+ index: sync,
112
+ sync_needed: dirty,
113
+ coverage,
114
+ unresolved_imports: unresolvedCount,
115
+ incomplete_imports: incomplete.length,
116
+ unsupported_files: unsupported,
117
+ skipped_files: skipped,
118
+ reasons,
119
+ },
107
120
  };
108
121
  }
109
122
 
@@ -135,7 +148,7 @@ export function buildNavigation(repo: SeptumRepository, args: NavigationQuery, r
135
148
  const paths = new Set(matching.map(file => file.path));
136
149
  const workspace = !domain && !filter && !archetype;
137
150
 
138
- const { byPath, degree, edges, unresolved } = aggregateImportEdges(repo, root, files, paths, workspace);
151
+ const { byPath, degree, edges, incomplete, unresolvedCount } = aggregateImportEdges(repo, root, files, paths, workspace);
139
152
  const entries = repo.getNavigationEntrypoints().filter(entry => entry.file && paths.has(entry.file));
140
153
  const entryFiles = new Set(entries.map(entry => entry.file));
141
154
  matching.sort((a, b) =>
@@ -222,7 +235,7 @@ export function buildNavigation(repo: SeptumRepository, args: NavigationQuery, r
222
235
  const scopedDomains = workspace ? domains : domain ? [domain] : [];
223
236
  const emptyDomainsCount = scopedDomains.filter(d => (domainCounts.get(d.name) ?? 0) === 0).length;
224
237
  const uncoveredCount = (JSON.parse(repo.getMeta("uncovered_files") || "[]") as string[]).length;
225
- const { sync, dirty, health } = computeNavigationHealth(repo, domain?.root_path, unresolved, emptyDomainsCount, files.length, uncoveredCount);
238
+ const { sync, dirty, health } = computeNavigationHealth(repo, domain?.root_path, incomplete, unresolvedCount, emptyDomainsCount, files.length, uncoveredCount);
226
239
  const end = offset + selected.length;
227
240
 
228
241
  return {
@@ -253,7 +266,7 @@ export function buildNavigation(repo: SeptumRepository, args: NavigationQuery, r
253
266
  omitted_entrypoints: entries.length - entrypoints.length,
254
267
  },
255
268
  ...(!workspace && end < matching.length ? { pagination: { next_file_offset: end, file_offset: offset } } : {}),
256
- ...(args.include_evidence ? { diagnostics: unresolved.slice(0, 5), diagnostics_omitted: Math.max(0, unresolved.length - 5) } : {}),
269
+ ...(args.include_evidence ? { diagnostics: incomplete.slice(0, 5), diagnostics_omitted: Math.max(0, incomplete.length - 5) } : {}),
257
270
  next: submodules && submodules.length > 1 && domain
258
271
  ? [
259
272
  { tool: "septum_map", args: { action: "catalog", domain: domain.name, file_filter: submodules[0]!.path } },
@@ -593,48 +593,6 @@ export class TopologyDetector {
593
593
  return this.persistMacroMetadata(repo, topology);
594
594
  }
595
595
 
596
- /**
597
- * Synchronize explicit domains from septum.config.json as the SSOT without
598
- * writing auto-discovered domains, while still updating macro metadata and
599
- * reporting any detected framework sub-domains shadowed by coarse roots.
600
- */
601
- public static syncExplicitConfigDomains(
602
- repo: SeptumRepository,
603
- projectRoot: string,
604
- explicitDomains: Record<string, DomainConfig>
605
- ): {
606
- domains: Record<string, DomainConfig>;
607
- shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }>;
608
- } {
609
- assertUniqueDomainRoots(explicitDomains, projectRoot);
610
- for (const [name, config] of Object.entries(explicitDomains)) {
611
- repo.domains.upsertDomain(name, config, projectRoot);
612
- }
613
- repo.domains.pruneDomainsNotIn(Object.keys(explicitDomains));
614
-
615
- const topology = this.detect(projectRoot);
616
- const domains = this.persistMacroMetadata(repo, topology);
617
-
618
- const shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }> = [];
619
- for (const [explicitDomain, explicitCfg] of Object.entries(explicitDomains)) {
620
- const parentAbs = path.resolve(projectRoot, explicitCfg.root);
621
- const detectedNames: string[] = [];
622
- for (const [detectedName, detectedCfg] of Object.entries(topology.domains)) {
623
- if (domainNameKey(detectedName) === domainNameKey(explicitDomain)) continue;
624
- const childAbs = path.resolve(projectRoot, detectedCfg.root);
625
- const rel = path.relative(parentAbs, childAbs);
626
- if (rel !== "" && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel)) {
627
- detectedNames.push(detectedName);
628
- }
629
- }
630
- if (detectedNames.length > 0) {
631
- shadowedSubdomains.push({ explicitDomain, explicitRoot: explicitCfg.root, detectedNames });
632
- }
633
- }
634
-
635
- return { domains, shadowedSubdomains };
636
- }
637
-
638
596
  private static persistMacroMetadata(
639
597
  repo: SeptumRepository,
640
598
  topology: DiscoveredProjectTopology
@@ -19,9 +19,12 @@ export function formatMapAsText(payload: Record<string, any>): string {
19
19
  : scope.domain ?? "workspace";
20
20
  const health = payload.health ?? {};
21
21
  const acc = payload.accounting ?? {};
22
+ const incompleteSuffix = (health.incomplete_imports ?? 0) > (health.unresolved_imports ?? 0)
23
+ ? ` incomplete=${health.incomplete_imports}`
24
+ : "";
22
25
  const lines: string[] = [
23
26
  `# Septum Map: ${headerScope} [${payload.status}]`,
24
- `Health: index=${health.index ?? "unknown"} coverage=${health.coverage ?? "unknown"} sync_needed=${Boolean(health.sync_needed)} unresolved=${health.unresolved_imports ?? 0}`,
27
+ `Health: index=${health.index ?? "unknown"} coverage=${health.coverage ?? "unknown"} sync_needed=${Boolean(health.sync_needed)} unresolved=${health.unresolved_imports ?? 0}${incompleteSuffix}`,
25
28
  ];
26
29
 
27
30
  if (Array.isArray(payload.domains) && payload.domains.length) {
@@ -1,11 +1,14 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
+ import { Database } from "bun:sqlite";
3
4
  import { McpError } from "@modelcontextprotocol/sdk/types.js";
5
+ import appHtmlPath from "./ui/app.html" with { type: "file" };
4
6
  import type { WorkspaceManager } from "./workspace-manager.ts";
5
7
  import { isWorkspaceInitialized, resolveServerWorkspace } from "./workspace-manager.ts";
6
8
  import { handleGetDomainCatalog } from "./tools/map.ts";
7
9
  import { runWorkspaceBoundary } from "./workspace-boundary.ts";
8
10
  import { RESOURCE_LIMITS } from "../core/resources/limits.ts";
11
+ import { ConfigLoader, resolveDatabasePath } from "../core/config/loader.ts";
9
12
 
10
13
  export const SEPTUM_RESOURCES = [
11
14
  {
@@ -70,6 +73,37 @@ function matchDomainResource(uri: string): string | undefined {
70
73
  function readIndexHealth(manager: WorkspaceManager, root: string) {
71
74
  const ctx = manager.peek(root);
72
75
  if (!ctx) {
76
+ try {
77
+ const config = ConfigLoader.load(undefined, root);
78
+ const dbPath = resolveDatabasePath(root, config.settings.db_path);
79
+ if (existsSync(dbPath)) {
80
+ const db = new Database(dbPath, { readonly: true });
81
+ try {
82
+ const getMeta = (key: string): string | undefined =>
83
+ db.query<{ value: string }, [string]>("SELECT value FROM repo_meta WHERE key = ?").get(key)?.value;
84
+ const syncState = getMeta("sync_state") ?? "unindexed";
85
+ const syncError = getMeta("sync_error") || undefined;
86
+ const domainsCount = db.query<{ count: number }, []>("SELECT COUNT(*) AS count FROM domains").get()?.count ?? 0;
87
+ const filesCount = db.query<{ count: number }, []>("SELECT COUNT(*) AS count FROM files").get()?.count ?? 0;
88
+ const slicesCount = db.query<{ count: number }, []>("SELECT COUNT(*) AS count FROM vertical_slices").get()?.count ?? 0;
89
+ return {
90
+ workspace_root: root,
91
+ status: syncError ? "error" : syncState,
92
+ sync_state: syncState,
93
+ sync_error: syncError,
94
+ last_sync: getMeta("last_sync"),
95
+ domains_count: domainsCount,
96
+ files_count: filesCount,
97
+ slices_count: slicesCount,
98
+ context_active: false,
99
+ };
100
+ } finally {
101
+ db.close();
102
+ }
103
+ }
104
+ } catch {
105
+ // Fall back to initialization check when DB is unreadable or unmigrated.
106
+ }
73
107
  return {
74
108
  workspace_root: root,
75
109
  status: isWorkspaceInitialized(root) ? "inactive" : "not_indexed",
@@ -154,7 +188,7 @@ function buildAppsGuide(manager: WorkspaceManager, root: string) {
154
188
  return {
155
189
  workspace_root: root,
156
190
  ui_resource: "ui://septum/app.html",
157
- open_via_tools: ["septum_map", "septum_slice", "septum_boundary"],
191
+ open_via_tools: ["septum_app"],
158
192
  antigravity_entrypoints: [
159
193
  { type: "aux_pane", title: "Septum Architecture" },
160
194
  { type: "global", title: "Septum" },
@@ -185,6 +219,7 @@ function loadSeptumAppHtml(): string {
185
219
  const envPath = process.env.SEPTUM_APP_HTML?.trim();
186
220
  const candidates = [
187
221
  ...(envPath ? [resolve(envPath)] : []),
222
+ ...(typeof appHtmlPath === "string" ? [appHtmlPath] : []),
188
223
  resolve(import.meta.dir, "ui/app.html"),
189
224
  resolve(process.cwd(), "src/mcp/ui/app.html"),
190
225
  ];
package/src/mcp/server.ts CHANGED
@@ -271,7 +271,7 @@ export function createMcpServer(manager: WorkspaceManager): Server {
271
271
  });
272
272
 
273
273
  if (!isWorkspaceInitialized(root)) {
274
- if (name === "septum_map" && (!("action" in record) || !record.action || record.action === "catalog")) {
274
+ if (parsed.name === "septum_app" || (parsed.name === "septum_map" && parsed.args.action === "catalog")) {
275
275
  const runtimeVersion = await checkRuntimeVersion();
276
276
  const diagnostic = buildUnindexedCatalog(root, runtimeVersion);
277
277
  return finish({
@@ -1,4 +1,5 @@
1
1
  import type { Tool } from "@modelcontextprotocol/sdk/types.js";
2
+ import { z } from "zod";
2
3
  import type { WorkspaceContext } from "./workspace-manager.ts";
3
4
  import { MapToolSchema, SymbolToolSchema, SliceToolSchema, BoundaryToolSchema } from "./schemas.ts";
4
5
  import { handleMapTool } from "./tools/map.ts";
@@ -31,15 +32,6 @@ export const TOOL_CATALOG = [
31
32
  name: "septum_map",
32
33
  schema: MapToolSchema,
33
34
  execute: (ctx, args, signal) => handleMapTool(ctx.repo, ctx.config, args, ctx.root, signal),
34
- _meta: {
35
- ui: { resourceUri: SEPTUM_APP_URI },
36
- "com.google.antigravity/ui": {
37
- entrypoints: [
38
- { type: "aux_pane", title: "Septum Architecture" },
39
- { type: "global", title: "Septum" },
40
- ],
41
- },
42
- },
43
35
  description:
44
36
  "Inspect workspace architecture or register domains. action='catalog' (default) returns domain topology, cross-domain import adjacency, file neighborhoods, static entrypoints, and index health. action='register' adds a bounded-context domain and optionally ingests it. Use file_filter to focus files, include_evidence=true for one file's import details, septum_symbol for declarations/source, or septum_slice for entrypoint traces. Example: {action:'catalog',domain:'mcp'}.",
45
37
  inputSchema: {
@@ -224,9 +216,6 @@ export const TOOL_CATALOG = [
224
216
  name: "septum_slice",
225
217
  schema: SliceToolSchema,
226
218
  execute: (ctx, args, signal) => handleSliceTool(ctx.repo, ctx.config, args, ctx.root, signal),
227
- _meta: {
228
- ui: { resourceUri: SEPTUM_APP_URI },
229
- },
230
219
  description:
231
220
  "Trace a cataloged static entrypoint (HTTP route, handler, job, CLI command, or event) to related nodes with relationship evidence and diagnostics. Static matches do not establish runtime execution order or complete reachability. Use septum_symbol for declarations and septum_boundary for import policy. Example: {query:'POST /orders/{id}/pay',max_depth:5} or {query:'OrderController@pay'}.",
232
221
  inputSchema: {
@@ -266,9 +255,6 @@ export const TOOL_CATALOG = [
266
255
  name: "septum_boundary",
267
256
  schema: BoundaryToolSchema,
268
257
  execute: (ctx, args, signal) => handleBoundaryTool(ctx.evaluator, ctx.config, args, ctx.repo, ctx.root),
269
- _meta: {
270
- ui: { resourceUri: SEPTUM_APP_URI },
271
- },
272
258
  description:
273
259
  "Validate proposed or staged imports against domain boundaries and circular-dependency rules. When to use: (1) scope='file' with proposed_imports BEFORE writing new import statements, (2) scope='staged' BEFORE git commit to catch cross-domain leaks, (3) scope='all' or 'domain' for codebase audits. When NOT to use: do NOT use to read source code or locate symbols. Status 'approved' confirms zero violations; 'rejected' requires refactoring. Example: {scope:'file',file_path:'src/order/service.ts',proposed_imports:['../billing/repo']}.",
274
260
  inputSchema: {
@@ -322,6 +308,35 @@ export const TOOL_CATALOG = [
322
308
  required: [],
323
309
  },
324
310
  }),
311
+ defineTool({
312
+ name: "septum_app",
313
+ schema: z.object({ workspace_path: z.string().optional() }),
314
+ execute: (ctx, _args, signal) =>
315
+ handleMapTool(ctx.repo, ctx.config, { action: "catalog", detail_level: "compact", format: "json", ingest_now: false }, ctx.root, signal),
316
+ _meta: {
317
+ ui: {
318
+ resourceUri: SEPTUM_APP_URI,
319
+ visibility: ["app"],
320
+ },
321
+ "com.google.antigravity/ui": {
322
+ entrypoints: [
323
+ { type: "aux_pane", title: "Septum Architecture" },
324
+ { type: "global", title: "Septum" },
325
+ ],
326
+ },
327
+ },
328
+ description: "Open the Septum Architecture UI panel in the side pane or sidebar.",
329
+ inputSchema: {
330
+ type: "object",
331
+ properties: {
332
+ workspace_path: {
333
+ type: "string",
334
+ description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
335
+ },
336
+ },
337
+ required: [],
338
+ },
339
+ }),
325
340
  ];
326
341
 
327
342
  export function parseToolRequest(name: string, args: unknown) {
@@ -100,9 +100,7 @@ export async function handleRegisterDomain(
100
100
  {
101
101
  status: "success",
102
102
  policy_owner: result.policyOwner,
103
- message: `Domain '${result.domain}' successfully registered in ${
104
- result.policyOwner === "database" ? "SQLite" : "septum.config.json"
105
- }.${args.ingest_now ? " Initial ingestion completed." : ""}`,
103
+ message: `Domain '${result.domain}' successfully registered in SQLite.${args.ingest_now ? " Initial ingestion completed." : ""}`,
106
104
  domain_id: result.domainId,
107
105
  domain: result.domain,
108
106
  name: result.domain,
@@ -311,7 +311,7 @@ Boolean requesting whether a visible border and background is provided by the ho
311
311
  - omitted: host decides border`)}),D9=N({method:x("ui/request-display-mode"),params:N({mode:Hc.describe("The display mode being requested.")})}),HM=N({mode:Hc.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),JM=tr([x("model"),x("app")]).describe("Tool visibility scope - who can access the tool."),U9=N({resourceUri:Te().optional(),visibility:er(JM).optional().describe(`Who can access this tool. Default: ["model", "app"]
312
312
  - "model": Tool visible to and callable by the agent
313
313
  - "app": Tool callable by the app from this server only`),csp:Lf().optional(),permissions:Lf().optional()}),F9=N({mimeTypes:er(Te()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),V9=N({method:x("ui/download-file"),params:N({contents:er(tr([nn,sn])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),B9=N({method:x("ui/message"),params:N({role:x("user").describe('Message role, currently only "user" is supported.'),content:er($r).describe("Message content blocks (text, image, etc.).")})}),H9=N({method:x("ui/notifications/sandbox-resource-ready"),params:N({html:Te().describe("HTML content to load into the inner iframe."),sandbox:Te().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Df.optional().describe("CSP configuration from resource metadata."),permissions:Uf.optional().describe("Sandbox permissions from resource metadata.")})}),KM=N({method:x("ui/notifications/tool-result"),params:xo.describe("Standard MCP tool execution result.")}),W0=N({toolInfo:N({id:sr.optional().describe("JSON-RPC id of the tools/call request."),tool:zo.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:IM.optional().describe("Current color theme preference."),styles:DM.optional().describe("Style configuration for theming the app."),displayMode:Hc.optional().describe("How the UI is currently displayed."),availableDisplayModes:er(Hc).optional().describe("Display modes the host supports."),containerDimensions:tr([N({height:Or().describe("Fixed container height in pixels.")}),N({maxHeight:tr([Or(),jf()]).optional().describe("Maximum container height in pixels.")})]).and(tr([N({width:Or().describe("Fixed container width in pixels.")}),N({maxWidth:tr([Or(),jf()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
314
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:Te().optional().describe("User's language and region preference in BCP 47 format."),timeZone:Te().optional().describe("User's timezone in IANA format."),userAgent:Te().optional().describe("Host application identifier."),platform:tr([x("web"),x("desktop"),x("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:N({touch:eo().optional().describe("Whether the device supports touch input."),hover:eo().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:N({top:Or().describe("Top safe area inset in pixels."),right:Or().describe("Right safe area inset in pixels."),bottom:Or().describe("Bottom safe area inset in pixels."),left:Or().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),WM=N({method:x("ui/notifications/host-context-changed"),params:W0.describe("Partial context update containing only changed fields.")}),J9=N({method:x("ui/update-model-context"),params:N({content:er($r).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:to(Te(),$s().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),K9=N({method:x("ui/initialize"),params:N({appInfo:xr.describe("App identification (name and version)."),appCapabilities:BM.describe("Features and capabilities this app provides."),protocolVersion:Te().describe("Protocol version this app supports.")})}),GM=N({protocolVersion:Te().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:xr.describe("Host application identification and version."),hostCapabilities:VM.describe("Features and capabilities provided by the host."),hostContext:W0.describe("Rich context about the host environment.")}).passthrough(),YM={target:"draft-2020-12"};async function V0(e,t){let r=e["~standard"];if(r.jsonSchema)return r.jsonSchema[t](YM);throw Error(`Schema (vendor: ${r.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function B0(e,t,r=""){let o=await e["~standard"].validate(t);if(o.issues){let n=o.issues.map((s)=>{let i=s.path?.map((a)=>typeof a==="object"?a.key:a).join(".");return i?`${i}: ${s.message}`:s.message}).join("; ");throw Error(r+n)}return o.value}function G0(e){let t=document.documentElement;t.setAttribute("data-theme",e),t.style.colorScheme=e}function Y0(e,t=document.documentElement){for(let[r,o]of Object.entries(e))if(o!==void 0)t.style.setProperty(r,o)}function XM(e,t){let r={...e,...t};if(t.experimental!==void 0)r.experimental={...e.experimental,...t.experimental};if(t.tools!==void 0)r.tools={...e.tools,...t.tools};return r}class Up extends jc{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new H0;_methods=new J0;setRequestHandler=(...e)=>{let[t,...r]=U0("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=U0("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:MM,toolinputpartial:jM,toolresult:KM,toolcancelled:LM,hostcontextchanged:WM};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!Up.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e))return;if(this._everHadListener.add(e),!this._initializedSent)return;let t=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(t);console.warn(t)}setEventHandler(e,t){if(t)this._assertHandlerTiming(e);this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(r)=>{let o=r;if(e==="hostcontextchanged")this._hostContext={...this._hostContext,...o};this._events.dispatch(e,o)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},r={autoResize:!0}){super(r);if(this._appInfo=e,this._appCapabilities=t,this.options=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!r.allowUnsafeEval)It({jitless:!0});this.replaceRequestHandler("ping",(o)=>(console.log("Received ping:",o.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=XM(this._appCapabilities,e)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let o=this,n=()=>{if(o._initializedSent&&o._appCapabilities.tools?.listChanged)o.sendToolListChanged()},s=t.inputSchema!==void 0,i={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(a){Object.assign(this,a),n()},remove(){if(o._registeredTools[e]!==i)return;delete o._registeredTools[e],n()},handler:async(a,c)=>{if(!i.enabled)throw Error(`Tool ${e} is disabled`);let u;if(s){let l=i.inputSchema,p=l?await B0(l,a??{},`Invalid input for tool ${e}: `):a??{};u=await r(p,c)}else u=await r(c);if(i.outputSchema&&!u.isError)u.structuredContent=await B0(i.outputSchema,u.structuredContent,`Invalid output for tool ${e}: `);return u}};if(this._registeredTools[e]=i,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),n(),i}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let r=this._registeredTools[e.name];if(!r)throw Error(`Tool ${e.name} not found`);return r.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([r,o])=>o.enabled).map(async([r,o])=>{let n={name:r,title:o.title,description:o.description,inputSchema:o.inputSchema?await V0(o.inputSchema,"input"):{type:"object",properties:{}}};if(o.outputSchema)n.outputSchema=await V0(o.outputSchema,"output");if(o.annotations)n.annotations=o.annotations;if(o._meta)n._meta=o._meta;return n}))})}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:UM.shape.params,result:FM},(t,r)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(t,r)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(t.params,r)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized("callServerTool"),typeof e==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},t)}async listServerResources(e,t){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},t)}sendMessage(e,t){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},ZM,t)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,t){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},So,t)}openLink(e,t){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},AM,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},NM,t)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,t){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},HM,t)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,t=0,r=0,o=()=>{if(e)return;e=!0,requestAnimationFrame(()=>{e=!1;let s=document.documentElement,i=s.style.height;s.style.height="max-content";let a=Math.ceil(s.getBoundingClientRect().height);s.style.height=i;let c=Math.ceil(window.innerWidth);if(c!==t||a!==r)t=c,r=a,this.sendSizeChanged({width:c,height:a})})};o();let n=new ResizeObserver(o);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(e=new K0(window.parent,window.parent),t){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let r=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:TM}},GM,t);if(r===void 0)throw Error(`Server sent invalid initialize result: ${r}`);if(this._hostCapabilities=r.hostCapabilities,this._hostInfo=r.hostInfo,this._hostContext=r.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(r){throw this.close(),r}}}var ge;(function(e){e.assertEqual=(n)=>{};function t(n){}e.assertIs=t;function r(n){throw Error()}e.assertNever=r,e.arrayToEnum=(n)=>{let s={};for(let i of n)s[i]=i;return s},e.getValidEnumValues=(n)=>{let s=e.objectKeys(n).filter((a)=>typeof n[n[a]]!=="number"),i={};for(let a of s)i[a]=n[a];return e.objectValues(i)},e.objectValues=(n)=>e.objectKeys(n).map(function(s){return n[s]}),e.objectKeys=typeof Object.keys==="function"?(n)=>Object.keys(n):(n)=>{let s=[];for(let i in n)if(Object.prototype.hasOwnProperty.call(n,i))s.push(i);return s},e.find=(n,s)=>{for(let i of n)if(s(i))return i;return},e.isInteger=typeof Number.isInteger==="function"?(n)=>Number.isInteger(n):(n)=>typeof n==="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,s=" | "){return n.map((i)=>typeof i==="string"?`'${i}'`:i).join(s)}e.joinValues=o,e.jsonStringifyReplacer=(n,s)=>{if(typeof s==="bigint")return s.toString();return s}})(ge||(ge={}));var X0;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(X0||(X0={}));var L=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ro=(e)=>{switch(typeof e){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(e)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":if(Array.isArray(e))return L.array;if(e===null)return L.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return L.promise;if(typeof Map<"u"&&e instanceof Map)return L.map;if(typeof Set<"u"&&e instanceof Set)return L.set;if(typeof Date<"u"&&e instanceof Date)return L.date;return L.object;default:return L.unknown}};var w=ge.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ft extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(n){return n.message},r={_errors:[]},o=(n)=>{for(let s of n.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(t(s));else{let i=r,a=0;while(a<s.path.length){let c=s.path[a];if(a!==s.path.length-1)i[c]=i[c]||{_errors:[]};else i[c]=i[c]||{_errors:[]},i[c]._errors.push(t(s));i=i[c],a++}}};return o(this),r}static assert(e){if(!(e instanceof Ft))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ge.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},r=[];for(let o of this.issues)if(o.path.length>0){let n=o.path[0];t[n]=t[n]||[],t[n].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Ft.create=(e)=>new Ft(e);var QM=(e,t)=>{let r;switch(e.code){case w.invalid_type:if(e.received===L.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case w.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,ge.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(e.keys,", ")}`;break;case w.invalid_union:r="Invalid input";break;case w.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(e.options)}`;break;case w.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(e.options)}, received '${e.received}'`;break;case w.invalid_arguments:r="Invalid function arguments";break;case w.invalid_return_type:r="Invalid function return type";break;case w.invalid_date:r="Invalid date";break;case w.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else ge.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case w.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case w.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case w.custom:r="Invalid input";break;case w.invalid_intersection_types:r="Intersection results could not be merged";break;case w.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case w.not_finite:r="Number must be finite";break;default:r=t.defaultError,ge.assertNever(e)}return{message:r}},Co=QM;var ej=Co;function Jc(){return ej}var Fp=(e)=>{let{data:t,path:r,errorMaps:o,issueData:n}=e,s=[...r,...n.path||[]],i={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let a="",c=o.filter((u)=>!!u).slice().reverse();for(let u of c)a=u(i,{data:t,defaultError:a}).message;return{...n,path:s,message:a}};function A(e,t){let r=Jc(),o=Fp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Co?void 0:Co].filter((n)=>!!n)});e.common.issues.push(o)}class dt{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let o of t){if(o.status==="aborted")return oe;if(o.status==="dirty")e.dirty();r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let o of t){let n=await o.key,s=await o.value;r.push({key:n,value:s})}return dt.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let o of t){let{key:n,value:s}=o;if(n.status==="aborted")return oe;if(s.status==="aborted")return oe;if(n.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(n.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet))r[n.value]=s.value}return{status:e.value,value:r}}}var oe=Object.freeze({status:"aborted"}),ks=(e)=>({status:"dirty",value:e}),bt=(e)=>({status:"valid",value:e}),Ff=(e)=>e.status==="aborted",Vf=(e)=>e.status==="dirty",_n=(e)=>e.status==="valid",Kc=(e)=>typeof Promise<"u"&&e instanceof Promise;var K;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(K||(K={}));class cr{constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Q0=(e,t)=>{if(_n(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ft(e.common.issues);return this._error=r,this._error}}}};function ce(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:o,description:n}=e;if(t&&(r||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:n};return{errorMap:(i,a)=>{let{message:c}=e;if(i.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??o??a.defaultError};if(i.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:n}}class de{get description(){return this._def.description}_getType(e){return ro(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ro(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new dt,ctx:{common:e.parent.common,data:e.data,parsedType:ro(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Kc(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ro(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Q0(r,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ro(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return _n(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>_n(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ro(e)},o=this._parse({data:e,path:r.path,parent:r}),n=await(Kc(o)?o:Promise.resolve(o));return Q0(r,n)}refine(e,t){let r=(o)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(o);else return t};return this._refinement((o,n)=>{let s=e(o),i=()=>n.addIssue({code:w.custom,...r(o)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((a)=>{if(!a)return i(),!1;else return!0});if(!s)return i(),!1;else return!0})}refinement(e,t){return this._refinement((r,o)=>{if(!e(r))return o.addIssue(typeof t==="function"?t(r,o):t),!1;else return!0})}_refinement(e){return new Zr({schema:this,typeName:ne.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return Nr.create(this,this._def)}nullable(){return Oo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ar.create(this)}promise(){return Is.create(this,this._def)}or(e){return Qc.create([this,e],this._def)}and(e){return eu.create(this,e,this._def)}transform(e){return new Zr({...ce(this._def),schema:this,typeName:ne.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new nu({...ce(this._def),innerType:this,defaultValue:t,typeName:ne.ZodDefault})}brand(){return new Kf({typeName:ne.ZodBranded,type:this,...ce(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new su({...ce(this._def),innerType:this,catchValue:t,typeName:ne.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Yp.create(this,e)}readonly(){return iu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var tj=/^c[^\s-]{8,}$/i,rj=/^[0-9a-z]+$/,oj=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nj=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sj=/^[a-z0-9_-]{21}$/i,ij=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,aj=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,cj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Bf,lj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,dj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,mj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eT="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",gj=new RegExp(`^${eT}$`);function tT(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function _j(e){return new RegExp(`^${tT(e)}$`)}function yj(e){let t=`${eT}T${tT(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function vj(e,t){if((t==="v4"||!t)&&lj.test(e))return!0;if((t==="v6"||!t)&&dj.test(e))return!0;return!1}function Sj(e,t){if(!ij.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let o=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(o));if(typeof n!=="object"||n===null)return!1;if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&n.alg!==t)return!1;return!0}catch{return!1}}function bj(e,t){if((t==="v4"||!t)&&pj.test(e))return!0;if((t==="v6"||!t)&&mj.test(e))return!0;return!1}class no extends de{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==L.string){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_type,expected:L.string,received:n.parsedType}),oe}let r=new dt,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.length<n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="max"){if(e.data.length>n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="length"){let s=e.data.length>n.value,i=e.data.length<n.value;if(s||i){if(o=this._getOrReturnCtx(e,o),s)A(o,{code:w.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});else if(i)A(o,{code:w.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});r.dirty()}}else if(n.kind==="email"){if(!cj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"email",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="emoji"){if(!Bf)Bf=new RegExp(uj,"u");if(!Bf.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"emoji",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="uuid"){if(!nj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"uuid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="nanoid"){if(!sj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"nanoid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid"){if(!tj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid2"){if(!rj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid2",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ulid"){if(!oj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"ulid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),A(o,{validation:"url",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="regex"){if(n.regex.lastIndex=0,!n.regex.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"regex",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="trim")e.data=e.data.trim();else if(n.kind==="includes"){if(!e.data.includes(n.value,n.position))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),r.dirty()}else if(n.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(n.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(n.kind==="startsWith"){if(!e.data.startsWith(n.value))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:{startsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="endsWith"){if(!e.data.endsWith(n.value))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:{endsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="datetime"){if(!yj(n).test(e.data))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:"datetime",message:n.message}),r.dirty()}else if(n.kind==="date"){if(!gj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:"date",message:n.message}),r.dirty()}else if(n.kind==="time"){if(!_j(n).test(e.data))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:"time",message:n.message}),r.dirty()}else if(n.kind==="duration"){if(!aj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"duration",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ip"){if(!vj(e.data,n.version))o=this._getOrReturnCtx(e,o),A(o,{validation:"ip",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="jwt"){if(!Sj(e.data,n.alg))o=this._getOrReturnCtx(e,o),A(o,{validation:"jwt",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cidr"){if(!bj(e.data,n.version))o=this._getOrReturnCtx(e,o),A(o,{validation:"cidr",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64"){if(!hj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"base64",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64url"){if(!fj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"base64url",code:w.invalid_string,message:n.message}),r.dirty()}else ge.assertNever(n);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((o)=>e.test(o),{validation:t,code:w.invalid_string,...K.errToObj(r)})}_addCheck(e){return new no({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...K.errToObj(e)})}url(e){return this._addCheck({kind:"url",...K.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...K.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...K.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...K.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...K.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...K.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...K.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...K.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...K.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...K.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...K.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...K.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...K.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...K.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...K.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...K.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...K.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...K.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...K.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...K.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...K.errToObj(t)})}nonempty(e){return this.min(1,K.errToObj(e))}trim(){return new no({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new no({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new no({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}no.create=(e)=>new no({checks:[],typeName:ne.ZodString,coerce:e?.coerce??!1,...ce(e)});function zj(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,s=Number.parseInt(e.toFixed(n).replace(".","")),i=Number.parseInt(t.toFixed(n).replace(".",""));return s%i/10**n}class Ps extends de{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==L.number){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_type,expected:L.number,received:n.parsedType}),oe}let r=void 0,o=new dt;for(let n of this._def.checks)if(n.kind==="int"){if(!ge.isInteger(e.data))r=this._getOrReturnCtx(e,r),A(r,{code:w.invalid_type,expected:"integer",received:"float",message:n.message}),o.dirty()}else if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(zj(e.data,n.value)!==0)r=this._getOrReturnCtx(e,r),A(r,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else if(n.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),A(r,{code:w.not_finite,message:n.message}),o.dirty()}else ge.assertNever(n);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,K.toString(t))}gt(e,t){return this.setLimit("min",e,!1,K.toString(t))}lte(e,t){return this.setLimit("max",e,!0,K.toString(t))}lt(e,t){return this.setLimit("max",e,!1,K.toString(t))}setLimit(e,t,r,o){return new Ps({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:K.toString(o)}]})}_addCheck(e){return new Ps({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:K.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:K.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&ge.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}Ps.create=(e)=>new Ps({checks:[],typeName:ne.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Ts extends de{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==L.bigint)return this._getInvalidInput(e);let r=void 0,o=new dt;for(let n of this._def.checks)if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(e.data%n.value!==BigInt(0))r=this._getOrReturnCtx(e,r),A(r,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else ge.assertNever(n);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:w.invalid_type,expected:L.bigint,received:t.parsedType}),oe}gte(e,t){return this.setLimit("min",e,!0,K.toString(t))}gt(e,t){return this.setLimit("min",e,!1,K.toString(t))}lte(e,t){return this.setLimit("max",e,!0,K.toString(t))}lt(e,t){return this.setLimit("max",e,!1,K.toString(t))}setLimit(e,t,r,o){return new Ts({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:K.toString(o)}]})}_addCheck(e){return new Ts({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Ts.create=(e)=>new Ts({checks:[],typeName:ne.ZodBigInt,coerce:e?.coerce??!1,...ce(e)});class Vp extends de{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==L.boolean){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.boolean,received:r.parsedType}),oe}return bt(e.data)}}Vp.create=(e)=>new Vp({typeName:ne.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class Gc extends de{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==L.date){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_type,expected:L.date,received:n.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_date}),oe}let r=new dt,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.getTime()<n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()}else if(n.kind==="max"){if(e.data.getTime()>n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()}else ge.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Gc({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:K.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:K.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}Gc.create=(e)=>new Gc({checks:[],coerce:e?.coerce||!1,typeName:ne.ZodDate,...ce(e)});class Bp extends de{_parse(e){if(this._getType(e)!==L.symbol){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.symbol,received:r.parsedType}),oe}return bt(e.data)}}Bp.create=(e)=>new Bp({typeName:ne.ZodSymbol,...ce(e)});class Yc extends de{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.undefined,received:r.parsedType}),oe}return bt(e.data)}}Yc.create=(e)=>new Yc({typeName:ne.ZodUndefined,...ce(e)});class Xc extends de{_parse(e){if(this._getType(e)!==L.null){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.null,received:r.parsedType}),oe}return bt(e.data)}}Xc.create=(e)=>new Xc({typeName:ne.ZodNull,...ce(e)});class Hp extends de{constructor(){super(...arguments);this._any=!0}_parse(e){return bt(e.data)}}Hp.create=(e)=>new Hp({typeName:ne.ZodAny,...ce(e)});class yn extends de{constructor(){super(...arguments);this._unknown=!0}_parse(e){return bt(e.data)}}yn.create=(e)=>new yn({typeName:ne.ZodUnknown,...ce(e)});class so extends de{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:w.invalid_type,expected:L.never,received:t.parsedType}),oe}}so.create=(e)=>new so({typeName:ne.ZodNever,...ce(e)});class Jp extends de{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.void,received:r.parsedType}),oe}return bt(e.data)}}Jp.create=(e)=>new Jp({typeName:ne.ZodVoid,...ce(e)});class Ar extends de{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==L.array)return A(t,{code:w.invalid_type,expected:L.array,received:t.parsedType}),oe;if(o.exactLength!==null){let s=t.data.length>o.exactLength.value,i=t.data.length<o.exactLength.value;if(s||i)A(t,{code:s?w.too_big:w.too_small,minimum:i?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty()}if(o.minLength!==null){if(t.data.length<o.minLength.value)A(t,{code:w.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()}if(o.maxLength!==null){if(t.data.length>o.maxLength.value)A(t,{code:w.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,i)=>o.type._parseAsync(new cr(t,s,t.path,i)))).then((s)=>dt.mergeArray(r,s));let n=[...t.data].map((s,i)=>o.type._parseSync(new cr(t,s,t.path,i)));return dt.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Ar({...this._def,minLength:{value:e,message:K.toString(t)}})}max(e,t){return new Ar({...this._def,maxLength:{value:e,message:K.toString(t)}})}length(e,t){return new Ar({...this._def,exactLength:{value:e,message:K.toString(t)}})}nonempty(e){return this.min(1,e)}}Ar.create=(e,t)=>new Ar({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ne.ZodArray,...ce(t)});function Rs(e){if(e instanceof Ke){let t={};for(let r in e.shape){let o=e.shape[r];t[r]=Nr.create(Rs(o))}return new Ke({...e._def,shape:()=>t})}else if(e instanceof Ar)return new Ar({...e._def,type:Rs(e.element)});else if(e instanceof Nr)return Nr.create(Rs(e.unwrap()));else if(e instanceof Oo)return Oo.create(Rs(e.unwrap()));else if(e instanceof io)return io.create(e.items.map((t)=>Rs(t)));else return e}class Ke extends de{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=ge.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==L.object){let c=this._getOrReturnCtx(e);return A(c,{code:w.invalid_type,expected:L.object,received:c.parsedType}),oe}let{status:r,ctx:o}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof so&&this._def.unknownKeys==="strip")){for(let c in o.data)if(!s.includes(c))i.push(c)}let a=[];for(let c of s){let u=n[c],l=o.data[c];a.push({key:{status:"valid",value:c},value:u._parse(new cr(o,l,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof so){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of i)a.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict"){if(i.length>0)A(o,{code:w.unrecognized_keys,keys:i}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of i){let l=o.data[u];a.push({key:{status:"valid",value:u},value:c._parse(new cr(o,l,o.path,u)),alwaysSet:u in o.data})}}if(o.common.async)return Promise.resolve().then(async()=>{let c=[];for(let u of a){let l=await u.key,p=await u.value;c.push({key:l,value:p,alwaysSet:u.alwaysSet})}return c}).then((c)=>dt.mergeObjectSync(r,c));else return dt.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return K.errToObj,new Ke({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let o=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:K.errToObj(e).message??o};return{message:o}}}:{}})}strip(){return new Ke({...this._def,unknownKeys:"strip"})}passthrough(){return new Ke({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ke({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ke({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ne.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ke({...this._def,catchall:e})}pick(e){let t={};for(let r of ge.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new Ke({...this._def,shape:()=>t})}omit(e){let t={};for(let r of ge.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new Ke({...this._def,shape:()=>t})}deepPartial(){return Rs(this)}partial(e){let t={};for(let r of ge.objectKeys(this.shape)){let o=this.shape[r];if(e&&!e[r])t[r]=o;else t[r]=o.optional()}return new Ke({...this._def,shape:()=>t})}required(e){let t={};for(let r of ge.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let n=this.shape[r];while(n instanceof Nr)n=n._def.innerType;t[r]=n}return new Ke({...this._def,shape:()=>t})}keyof(){return rT(ge.objectKeys(this.shape))}}Ke.create=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strip",catchall:so.create(),typeName:ne.ZodObject,...ce(t)});Ke.strictCreate=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strict",catchall:so.create(),typeName:ne.ZodObject,...ce(t)});Ke.lazycreate=(e,t)=>new Ke({shape:e,unknownKeys:"strip",catchall:so.create(),typeName:ne.ZodObject,...ce(t)});class Qc extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function o(n){for(let i of n)if(i.result.status==="valid")return i.result;for(let i of n)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let s=n.map((i)=>new Ft(i.ctx.common.issues));return A(t,{code:w.invalid_union,unionErrors:s}),oe}if(t.common.async)return Promise.all(r.map(async(n)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(o);else{let n=void 0,s=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},u=a._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;else if(u.status==="dirty"&&!n)n={result:u,ctx:c};if(c.common.issues.length)s.push(c.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let i=s.map((a)=>new Ft(a));return A(t,{code:w.invalid_union,unionErrors:i}),oe}}get options(){return this._def.options}}Qc.create=(e,t)=>new Qc({options:e,typeName:ne.ZodUnion,...ce(t)});var oo=(e)=>{if(e instanceof tu)return oo(e.schema);else if(e instanceof Zr)return oo(e.innerType());else if(e instanceof ru)return[e.value];else if(e instanceof vn)return e.options;else if(e instanceof ou)return ge.objectValues(e.enum);else if(e instanceof nu)return oo(e._def.innerType);else if(e instanceof Yc)return[void 0];else if(e instanceof Xc)return[null];else if(e instanceof Nr)return[void 0,...oo(e.unwrap())];else if(e instanceof Oo)return[null,...oo(e.unwrap())];else if(e instanceof Kf)return oo(e.unwrap());else if(e instanceof iu)return oo(e.unwrap());else if(e instanceof su)return oo(e._def.innerType);else return[]};class Jf extends de{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.object)return A(t,{code:w.invalid_type,expected:L.object,received:t.parsedType}),oe;let r=this.discriminator,o=t.data[r],n=this.optionsMap.get(o);if(!n)return A(t,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),oe;if(t.common.async)return n._parseAsync({data:t.data,path:t.path,parent:t});else return n._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let o=new Map;for(let n of t){let s=oo(n.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of s){if(o.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);o.set(i,n)}}return new Jf({typeName:ne.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...ce(r)})}}function Hf(e,t){let r=ro(e),o=ro(t);if(e===t)return{valid:!0,data:e};else if(r===L.object&&o===L.object){let n=ge.objectKeys(t),s=ge.objectKeys(e).filter((a)=>n.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=Hf(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===L.array&&o===L.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=Hf(i,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else if(r===L.date&&o===L.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class eu extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=(n,s)=>{if(Ff(n)||Ff(s))return oe;let i=Hf(n.value,s.value);if(!i.valid)return A(r,{code:w.invalid_intersection_types}),oe;if(Vf(n)||Vf(s))t.dirty();return{status:t.value,value:i.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([n,s])=>o(n,s));else return o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}eu.create=(e,t,r)=>new eu({left:e,right:t,typeName:ne.ZodIntersection,...ce(r)});class io extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.array)return A(r,{code:w.invalid_type,expected:L.array,received:r.parsedType}),oe;if(r.data.length<this._def.items.length)return A(r,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;if(!this._def.rest&&r.data.length>this._def.items.length)A(r,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let n=[...r.data].map((s,i)=>{let a=this._def.items[i]||this._def.rest;if(!a)return null;return a._parse(new cr(r,s,r.path,i))}).filter((s)=>!!s);if(r.common.async)return Promise.all(n).then((s)=>dt.mergeArray(t,s));else return dt.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new io({...this._def,rest:e})}}io.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new io({items:e,typeName:ne.ZodTuple,rest:null,...ce(t)})};class Kp extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.object)return A(r,{code:w.invalid_type,expected:L.object,received:r.parsedType}),oe;let o=[],n=this._def.keyType,s=this._def.valueType;for(let i in r.data)o.push({key:n._parse(new cr(r,i,r.path,i)),value:s._parse(new cr(r,r.data[i],r.path,i)),alwaysSet:i in r.data});if(r.common.async)return dt.mergeObjectAsync(t,o);else return dt.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof de)return new Kp({keyType:e,valueType:t,typeName:ne.ZodRecord,...ce(r)});return new Kp({keyType:no.create(),valueType:e,typeName:ne.ZodRecord,...ce(t)})}}class Wp extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.map)return A(r,{code:w.invalid_type,expected:L.map,received:r.parsedType}),oe;let o=this._def.keyType,n=this._def.valueType,s=[...r.data.entries()].map(([i,a],c)=>({key:o._parse(new cr(r,i,r.path,[c,"key"])),value:n._parse(new cr(r,a,r.path,[c,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let a of s){let c=await a.key,u=await a.value;if(c.status==="aborted"||u.status==="aborted")return oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();i.set(c.value,u.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let a of s){let{key:c,value:u}=a;if(c.status==="aborted"||u.status==="aborted")return oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();i.set(c.value,u.value)}return{status:t.value,value:i}}}}Wp.create=(e,t,r)=>new Wp({valueType:t,keyType:e,typeName:ne.ZodMap,...ce(r)});class Es extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.set)return A(r,{code:w.invalid_type,expected:L.set,received:r.parsedType}),oe;let o=this._def;if(o.minSize!==null){if(r.data.size<o.minSize.value)A(r,{code:w.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()}if(o.maxSize!==null){if(r.data.size>o.maxSize.value)A(r,{code:w.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty()}let n=this._def.valueType;function s(a){let c=new Set;for(let u of a){if(u.status==="aborted")return oe;if(u.status==="dirty")t.dirty();c.add(u.value)}return{status:t.value,value:c}}let i=[...r.data.values()].map((a,c)=>n._parse(new cr(r,a,r.path,c)));if(r.common.async)return Promise.all(i).then((a)=>s(a));else return s(i)}min(e,t){return new Es({...this._def,minSize:{value:e,message:K.toString(t)}})}max(e,t){return new Es({...this._def,maxSize:{value:e,message:K.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Es.create=(e,t)=>new Es({valueType:e,minSize:null,maxSize:null,typeName:ne.ZodSet,...ce(t)});class Wc extends de{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.function)return A(t,{code:w.invalid_type,expected:L.function,received:t.parsedType}),oe;function r(i,a){return Fp({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Jc(),Co].filter((c)=>!!c),issueData:{code:w.invalid_arguments,argumentsError:a}})}function o(i,a){return Fp({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Jc(),Co].filter((c)=>!!c),issueData:{code:w.invalid_return_type,returnTypeError:a}})}let n={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Is){let i=this;return bt(async function(...a){let c=new Ft([]),u=await i._def.args.parseAsync(a,n).catch((d)=>{throw c.addIssue(r(a,d)),c}),l=await Reflect.apply(s,this,u);return await i._def.returns._def.type.parseAsync(l,n).catch((d)=>{throw c.addIssue(o(l,d)),c})})}else{let i=this;return bt(function(...a){let c=i._def.args.safeParse(a,n);if(!c.success)throw new Ft([r(a,c.error)]);let u=Reflect.apply(s,this,c.data),l=i._def.returns.safeParse(u,n);if(!l.success)throw new Ft([o(u,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Wc({...this._def,args:io.create(e).rest(yn.create())})}returns(e){return new Wc({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Wc({args:e?e:io.create([]).rest(yn.create()),returns:t||yn.create(),typeName:ne.ZodFunction,...ce(r)})}}class tu extends de{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}tu.create=(e,t)=>new tu({getter:e,typeName:ne.ZodLazy,...ce(t)});class ru extends de{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:w.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}}ru.create=(e,t)=>new ru({value:e,typeName:ne.ZodLiteral,...ce(t)});function rT(e,t){return new vn({values:e,typeName:ne.ZodEnum,...ce(t)})}class vn extends de{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return A(t,{expected:ge.joinValues(r),received:t.parsedType,code:w.invalid_type}),oe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return A(t,{received:t.data,code:w.invalid_enum_value,options:r}),oe}return bt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return vn.create(e,{...this._def,...t})}exclude(e,t=this._def){return vn.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}vn.create=rT;class ou extends de{_parse(e){let t=ge.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==L.string&&r.parsedType!==L.number){let o=ge.objectValues(t);return A(r,{expected:ge.joinValues(o),received:r.parsedType,code:w.invalid_type}),oe}if(!this._cache)this._cache=new Set(ge.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=ge.objectValues(t);return A(r,{received:r.data,code:w.invalid_enum_value,options:o}),oe}return bt(e.data)}get enum(){return this._def.values}}ou.create=(e,t)=>new ou({values:e,typeName:ne.ZodNativeEnum,...ce(t)});class Is extends de{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.promise&&t.common.async===!1)return A(t,{code:w.invalid_type,expected:L.promise,received:t.parsedType}),oe;let r=t.parsedType===L.promise?t.data:Promise.resolve(t.data);return bt(r.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Is.create=(e,t)=>new Is({type:e,typeName:ne.ZodPromise,...ce(t)});class Zr extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ne.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,n={addIssue:(s)=>{if(A(r,s),s.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),o.type==="preprocess"){let s=o.transform(r.data,n);if(r.common.async)return Promise.resolve(s).then(async(i)=>{if(t.value==="aborted")return oe;let a=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});if(a.status==="aborted")return oe;if(a.status==="dirty")return ks(a.value);if(t.value==="dirty")return ks(a.value);return a});else{if(t.value==="aborted")return oe;let i=this._def.schema._parseSync({data:s,path:r.path,parent:r});if(i.status==="aborted")return oe;if(i.status==="dirty")return ks(i.value);if(t.value==="dirty")return ks(i.value);return i}}if(o.type==="refinement"){let s=(i)=>{let a=o.refinement(i,n);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(i.status==="aborted")return oe;if(i.status==="dirty")t.dirty();return s(i.value),{status:t.value,value:i.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(i.status==="aborted")return oe;if(i.status==="dirty")t.dirty();return s(i.value).then(()=>({status:t.value,value:i.value}))})}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_n(s))return oe;let i=o.transform(s.value,n);if(i instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(!_n(s))return oe;return Promise.resolve(o.transform(s.value,n)).then((i)=>({status:t.value,value:i}))});ge.assertNever(o)}}Zr.create=(e,t,r)=>new Zr({schema:e,typeName:ne.ZodEffects,effect:t,...ce(r)});Zr.createWithPreprocess=(e,t,r)=>new Zr({schema:t,effect:{type:"preprocess",transform:e},typeName:ne.ZodEffects,...ce(r)});class Nr extends de{_parse(e){if(this._getType(e)===L.undefined)return bt(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Nr.create=(e,t)=>new Nr({innerType:e,typeName:ne.ZodOptional,...ce(t)});class Oo extends de{_parse(e){if(this._getType(e)===L.null)return bt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Oo.create=(e,t)=>new Oo({innerType:e,typeName:ne.ZodNullable,...ce(t)});class nu extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===L.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}nu.create=(e,t)=>new nu({innerType:e,typeName:ne.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...ce(t)});class su extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(Kc(o))return o.then((n)=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Ft(r.common.issues)},input:r.data})}));else return{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ft(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}su.create=(e,t)=>new su({innerType:e,typeName:ne.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...ce(t)});class Gp extends de{_parse(e){if(this._getType(e)!==L.nan){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.nan,received:r.parsedType}),oe}return{status:"valid",value:e.data}}}Gp.create=(e)=>new Gp({typeName:ne.ZodNaN,...ce(e)});var h6=Symbol("zod_brand");class Kf extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Yp extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return oe;if(n.status==="dirty")return t.dirty(),ks(n.value);else return this._def.out._parseAsync({data:n.value,path:r.path,parent:r})})();else{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return oe;if(o.status==="dirty")return t.dirty(),{status:"dirty",value:o.value};else return this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new Yp({in:e,out:t,typeName:ne.ZodPipeline})}}class iu extends de{_parse(e){let t=this._def.innerType._parse(e),r=(o)=>{if(_n(o))o.value=Object.freeze(o.value);return o};return Kc(t)?t.then((o)=>r(o)):r(t)}unwrap(){return this._def.innerType}}iu.create=(e,t)=>new iu({innerType:e,typeName:ne.ZodReadonly,...ce(t)});var f6={object:Ke.lazycreate},ne;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ne||(ne={}));var g6=no.create,_6=Ps.create,y6=Gp.create,v6=Ts.create,xj=Vp.create,S6=Gc.create,b6=Bp.create,z6=Yc.create,x6=Xc.create,w6=Hp.create,$6=yn.create,k6=so.create,R6=Jp.create,P6=Ar.create,{create:wj,strictCreate:T6}=Ke,E6=Qc.create,I6=Jf.create,C6=eu.create,O6=io.create,A6=Kp.create,N6=Wp.create,Z6=Es.create,M6=Wc.create,j6=tu.create,L6=ru.create,q6=vn.create,D6=ou.create,U6=Is.create,F6=Zr.create,V6=Nr.create,B6=Oo.create,H6=Zr.createWithPreprocess,J6=Yp.create;var oT="0.5.0";var Qp="__default__",Rj=wj({isError:xj().optional()}).passthrough(),sT={map:[{label:"Explain architecture",prompt:"Explain the architecture and responsibilities of these domains."},{label:"Audit domain coupling",prompt:"Audit cross-domain dependencies and highlight tight coupling or risky edges."}],slice:[{label:"Trace execution flow",prompt:"Trace and explain the step-by-step execution flow of this slice."},{label:"Check bugs / validation",prompt:"Inspect this execution chain for potential bugs, missing validation, or boundary issues."}],boundary:[{label:"Fix violations",prompt:"Propose and apply clean fixes for these boundary violations without breaking domain rules."},{label:"Explain forbidden rules",prompt:"Explain why these imports violate domain policies and what the intended alternative is."}]},Pj={map:"Analyze this Septum architecture context:",slice:"Analyze this Septum execution slice:",boundary:"Analyze this Septum boundary audit and suggest remediations:"},ht=new Up({name:"Septum Architecture",version:oT}),we="map",Le,Gf,au=[],cu=new Map,uu="",ao=null,iT="",Os=!1;function U(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Tj(e){return e?.trim()||Qp}function Ej(){return{map:null,domainDetail:null,slice:null,boundary:null,selectedDomains:new Set,selectedSliceNodes:new Set,selectedViolations:new Set}}function Cs(e){let t=Tj(e),r=cu.get(t);if(!r)r=Ej(),cu.set(t,r);return r}function Ij(e){let t=e?.trim();if(!t)return;if(!au.includes(t))au.push(t);if(au.length===1&&cu.has(Qp)){let r=cu.get(Qp),o=Cs(t);o.map??=r.map,o.domainDetail??=r.domainDetail,o.slice??=r.slice,o.boundary??=r.boundary,cu.delete(Qp)}Le=t}function nT(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean);return t[t.length-1]??e}function aT(e){if(!e)return;if(e.theme)G0(e.theme);if(e.styles?.variables)Y0(e.styles.variables)}function Mr(e){iT=e;let t=document.getElementById("status-bar");if(t)t.textContent=Os?"Loading...":e}function Cj(e){if(!e||typeof e!=="object")return null;if(e.schema==="navigation/v1"||Array.isArray(e.domains)||Array.isArray(e.files))return"map";if("entrypoint"in e||Array.isArray(e.chain))return"slice";if("scope"in e&&(("total_violations"in e)||("violations"in e)||("status"in e)))return"boundary";return null}function ed(e,t){ao=null;let r=e?.structuredContent??null;if(!r&&Array.isArray(e?.content)){let i=e.content.find((a)=>a?.type==="text"&&typeof a.text==="string");if(i)try{r=JSON.parse(i.text)}catch{}}if(!r){if(e?.isError){let i=e?.content?.[0]?.text??"Tool execution failed.";ao=String(i)}Mr(""),mt();return}let o=typeof r.workspace_root==="string"&&r.workspace_root.trim()?r.workspace_root.trim():t??Gf??Le;if(o)Ij(o);Gf=void 0;let n=Cj(r),s=Cs(o??Le);if(n==="map"){if(Array.isArray(r.files)&&r.files.length>0&&!Array.isArray(r.domains))s.domainDetail=r;else s.map=r,s.domainDetail=null,s.selectedDomains.clear();we="map"}else if(n==="slice")s.slice=r,s.selectedSliceNodes.clear(),we="slice";else if(n==="boundary")s.boundary=r,s.selectedViolations.clear(),we="boundary";Mr(""),mt()}function Oj(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")?`file://${encodeURI(t)}`:`file:///${encodeURI(t)}`}async function Aj(e){if(!e)return;let t=e.startsWith("/")||!Le?e:`${Le.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`;try{if((await ht.request({method:"com.google.antigravity/toggle-aux-pane",params:{tabType:"fileView",uri:Oj(t)}},Rj))?.isError)Mr(`Cannot open side pane for ${e} on this surface.`)}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("-32601"))Mr(`Side pane navigation is unavailable in this host (${e}).`);else Mr(`Open file failed: ${o}`)}}function cT(e,t){return`${t}:${e.symbol??""}:${e.file??""}:${e.line??""}`}function uT(e,t){return`${t}:${e.rule??""}:${e.file??""}:${e.line??""}`}function lT(e,t){if(e==="map")return t.selectedDomains.size;if(e==="slice")return t.selectedSliceNodes.size;return t.selectedViolations.size}function Nj(e,t){if(e==="map")t.selectedDomains.clear();else if(e==="slice")t.selectedSliceNodes.clear();else t.selectedViolations.clear()}function Zj(e,t){let r=[];if(Le)r.push(`Workspace: ${Le}`);if(e==="map"&&t.map){let o=t.map,n=o.domains??[],s=t.selectedDomains,i=s.size>0?n.filter((l)=>s.has(String(l.name))):n,a=o.health??{};if(r.push(`# Septum Architecture (index=${a.index??o.status??"unknown"}, coverage=${a.coverage??"unknown"}, unresolved=${a.unresolved_imports??0})`),t.domainDetail){let p=t.domainDetail.files??[];r.push(`
314
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:Te().optional().describe("User's language and region preference in BCP 47 format."),timeZone:Te().optional().describe("User's timezone in IANA format."),userAgent:Te().optional().describe("Host application identifier."),platform:tr([x("web"),x("desktop"),x("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:N({touch:eo().optional().describe("Whether the device supports touch input."),hover:eo().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:N({top:Or().describe("Top safe area inset in pixels."),right:Or().describe("Right safe area inset in pixels."),bottom:Or().describe("Bottom safe area inset in pixels."),left:Or().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),WM=N({method:x("ui/notifications/host-context-changed"),params:W0.describe("Partial context update containing only changed fields.")}),J9=N({method:x("ui/update-model-context"),params:N({content:er($r).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:to(Te(),$s().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),K9=N({method:x("ui/initialize"),params:N({appInfo:xr.describe("App identification (name and version)."),appCapabilities:BM.describe("Features and capabilities this app provides."),protocolVersion:Te().describe("Protocol version this app supports.")})}),GM=N({protocolVersion:Te().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:xr.describe("Host application identification and version."),hostCapabilities:VM.describe("Features and capabilities provided by the host."),hostContext:W0.describe("Rich context about the host environment.")}).passthrough(),YM={target:"draft-2020-12"};async function V0(e,t){let r=e["~standard"];if(r.jsonSchema)return r.jsonSchema[t](YM);throw Error(`Schema (vendor: ${r.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function B0(e,t,r=""){let o=await e["~standard"].validate(t);if(o.issues){let n=o.issues.map((s)=>{let i=s.path?.map((a)=>typeof a==="object"?a.key:a).join(".");return i?`${i}: ${s.message}`:s.message}).join("; ");throw Error(r+n)}return o.value}function G0(e){let t=document.documentElement;t.setAttribute("data-theme",e),t.style.colorScheme=e}function Y0(e,t=document.documentElement){for(let[r,o]of Object.entries(e))if(o!==void 0)t.style.setProperty(r,o)}function XM(e,t){let r={...e,...t};if(t.experimental!==void 0)r.experimental={...e.experimental,...t.experimental};if(t.tools!==void 0)r.tools={...e.tools,...t.tools};return r}class Up extends jc{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new H0;_methods=new J0;setRequestHandler=(...e)=>{let[t,...r]=U0("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=U0("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:MM,toolinputpartial:jM,toolresult:KM,toolcancelled:LM,hostcontextchanged:WM};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!Up.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e))return;if(this._everHadListener.add(e),!this._initializedSent)return;let t=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(t);console.warn(t)}setEventHandler(e,t){if(t)this._assertHandlerTiming(e);this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(r)=>{let o=r;if(e==="hostcontextchanged")this._hostContext={...this._hostContext,...o};this._events.dispatch(e,o)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},r={autoResize:!0}){super(r);if(this._appInfo=e,this._appCapabilities=t,this.options=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!r.allowUnsafeEval)It({jitless:!0});this.replaceRequestHandler("ping",(o)=>(console.log("Received ping:",o.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=XM(this._appCapabilities,e)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let o=this,n=()=>{if(o._initializedSent&&o._appCapabilities.tools?.listChanged)o.sendToolListChanged()},s=t.inputSchema!==void 0,i={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(a){Object.assign(this,a),n()},remove(){if(o._registeredTools[e]!==i)return;delete o._registeredTools[e],n()},handler:async(a,c)=>{if(!i.enabled)throw Error(`Tool ${e} is disabled`);let u;if(s){let l=i.inputSchema,p=l?await B0(l,a??{},`Invalid input for tool ${e}: `):a??{};u=await r(p,c)}else u=await r(c);if(i.outputSchema&&!u.isError)u.structuredContent=await B0(i.outputSchema,u.structuredContent,`Invalid output for tool ${e}: `);return u}};if(this._registeredTools[e]=i,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),n(),i}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let r=this._registeredTools[e.name];if(!r)throw Error(`Tool ${e.name} not found`);return r.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([r,o])=>o.enabled).map(async([r,o])=>{let n={name:r,title:o.title,description:o.description,inputSchema:o.inputSchema?await V0(o.inputSchema,"input"):{type:"object",properties:{}}};if(o.outputSchema)n.outputSchema=await V0(o.outputSchema,"output");if(o.annotations)n.annotations=o.annotations;if(o._meta)n._meta=o._meta;return n}))})}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:UM.shape.params,result:FM},(t,r)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(t,r)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(t.params,r)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized("callServerTool"),typeof e==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},t)}async listServerResources(e,t){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},t)}sendMessage(e,t){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},ZM,t)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,t){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},So,t)}openLink(e,t){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},AM,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},NM,t)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,t){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},HM,t)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,t=0,r=0,o=()=>{if(e)return;e=!0,requestAnimationFrame(()=>{e=!1;let s=document.documentElement,i=s.style.height;s.style.height="max-content";let a=Math.ceil(s.getBoundingClientRect().height);s.style.height=i;let c=Math.ceil(window.innerWidth);if(c!==t||a!==r)t=c,r=a,this.sendSizeChanged({width:c,height:a})})};o();let n=new ResizeObserver(o);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(e=new K0(window.parent,window.parent),t){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let r=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:TM}},GM,t);if(r===void 0)throw Error(`Server sent invalid initialize result: ${r}`);if(this._hostCapabilities=r.hostCapabilities,this._hostInfo=r.hostInfo,this._hostContext=r.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(r){throw this.close(),r}}}var ge;(function(e){e.assertEqual=(n)=>{};function t(n){}e.assertIs=t;function r(n){throw Error()}e.assertNever=r,e.arrayToEnum=(n)=>{let s={};for(let i of n)s[i]=i;return s},e.getValidEnumValues=(n)=>{let s=e.objectKeys(n).filter((a)=>typeof n[n[a]]!=="number"),i={};for(let a of s)i[a]=n[a];return e.objectValues(i)},e.objectValues=(n)=>e.objectKeys(n).map(function(s){return n[s]}),e.objectKeys=typeof Object.keys==="function"?(n)=>Object.keys(n):(n)=>{let s=[];for(let i in n)if(Object.prototype.hasOwnProperty.call(n,i))s.push(i);return s},e.find=(n,s)=>{for(let i of n)if(s(i))return i;return},e.isInteger=typeof Number.isInteger==="function"?(n)=>Number.isInteger(n):(n)=>typeof n==="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,s=" | "){return n.map((i)=>typeof i==="string"?`'${i}'`:i).join(s)}e.joinValues=o,e.jsonStringifyReplacer=(n,s)=>{if(typeof s==="bigint")return s.toString();return s}})(ge||(ge={}));var X0;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(X0||(X0={}));var L=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ro=(e)=>{switch(typeof e){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(e)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":if(Array.isArray(e))return L.array;if(e===null)return L.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return L.promise;if(typeof Map<"u"&&e instanceof Map)return L.map;if(typeof Set<"u"&&e instanceof Set)return L.set;if(typeof Date<"u"&&e instanceof Date)return L.date;return L.object;default:return L.unknown}};var w=ge.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ft extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(n){return n.message},r={_errors:[]},o=(n)=>{for(let s of n.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(t(s));else{let i=r,a=0;while(a<s.path.length){let c=s.path[a];if(a!==s.path.length-1)i[c]=i[c]||{_errors:[]};else i[c]=i[c]||{_errors:[]},i[c]._errors.push(t(s));i=i[c],a++}}};return o(this),r}static assert(e){if(!(e instanceof Ft))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ge.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},r=[];for(let o of this.issues)if(o.path.length>0){let n=o.path[0];t[n]=t[n]||[],t[n].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Ft.create=(e)=>new Ft(e);var QM=(e,t)=>{let r;switch(e.code){case w.invalid_type:if(e.received===L.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case w.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,ge.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(e.keys,", ")}`;break;case w.invalid_union:r="Invalid input";break;case w.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(e.options)}`;break;case w.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(e.options)}, received '${e.received}'`;break;case w.invalid_arguments:r="Invalid function arguments";break;case w.invalid_return_type:r="Invalid function return type";break;case w.invalid_date:r="Invalid date";break;case w.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else ge.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case w.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case w.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case w.custom:r="Invalid input";break;case w.invalid_intersection_types:r="Intersection results could not be merged";break;case w.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case w.not_finite:r="Number must be finite";break;default:r=t.defaultError,ge.assertNever(e)}return{message:r}},Co=QM;var ej=Co;function Jc(){return ej}var Fp=(e)=>{let{data:t,path:r,errorMaps:o,issueData:n}=e,s=[...r,...n.path||[]],i={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let a="",c=o.filter((u)=>!!u).slice().reverse();for(let u of c)a=u(i,{data:t,defaultError:a}).message;return{...n,path:s,message:a}};function A(e,t){let r=Jc(),o=Fp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Co?void 0:Co].filter((n)=>!!n)});e.common.issues.push(o)}class dt{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let o of t){if(o.status==="aborted")return oe;if(o.status==="dirty")e.dirty();r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let o of t){let n=await o.key,s=await o.value;r.push({key:n,value:s})}return dt.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let o of t){let{key:n,value:s}=o;if(n.status==="aborted")return oe;if(s.status==="aborted")return oe;if(n.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(n.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet))r[n.value]=s.value}return{status:e.value,value:r}}}var oe=Object.freeze({status:"aborted"}),ks=(e)=>({status:"dirty",value:e}),bt=(e)=>({status:"valid",value:e}),Ff=(e)=>e.status==="aborted",Vf=(e)=>e.status==="dirty",_n=(e)=>e.status==="valid",Kc=(e)=>typeof Promise<"u"&&e instanceof Promise;var K;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(K||(K={}));class cr{constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Q0=(e,t)=>{if(_n(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ft(e.common.issues);return this._error=r,this._error}}}};function ce(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:o,description:n}=e;if(t&&(r||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:n};return{errorMap:(i,a)=>{let{message:c}=e;if(i.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??o??a.defaultError};if(i.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:n}}class de{get description(){return this._def.description}_getType(e){return ro(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ro(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new dt,ctx:{common:e.parent.common,data:e.data,parsedType:ro(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Kc(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ro(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Q0(r,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ro(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return _n(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>_n(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ro(e)},o=this._parse({data:e,path:r.path,parent:r}),n=await(Kc(o)?o:Promise.resolve(o));return Q0(r,n)}refine(e,t){let r=(o)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(o);else return t};return this._refinement((o,n)=>{let s=e(o),i=()=>n.addIssue({code:w.custom,...r(o)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((a)=>{if(!a)return i(),!1;else return!0});if(!s)return i(),!1;else return!0})}refinement(e,t){return this._refinement((r,o)=>{if(!e(r))return o.addIssue(typeof t==="function"?t(r,o):t),!1;else return!0})}_refinement(e){return new Zr({schema:this,typeName:ne.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return Nr.create(this,this._def)}nullable(){return Oo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ar.create(this)}promise(){return Is.create(this,this._def)}or(e){return Qc.create([this,e],this._def)}and(e){return eu.create(this,e,this._def)}transform(e){return new Zr({...ce(this._def),schema:this,typeName:ne.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new nu({...ce(this._def),innerType:this,defaultValue:t,typeName:ne.ZodDefault})}brand(){return new Kf({typeName:ne.ZodBranded,type:this,...ce(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new su({...ce(this._def),innerType:this,catchValue:t,typeName:ne.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Yp.create(this,e)}readonly(){return iu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var tj=/^c[^\s-]{8,}$/i,rj=/^[0-9a-z]+$/,oj=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nj=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sj=/^[a-z0-9_-]{21}$/i,ij=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,aj=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,cj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Bf,lj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,dj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,mj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eT="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",gj=new RegExp(`^${eT}$`);function tT(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function _j(e){return new RegExp(`^${tT(e)}$`)}function yj(e){let t=`${eT}T${tT(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function vj(e,t){if((t==="v4"||!t)&&lj.test(e))return!0;if((t==="v6"||!t)&&dj.test(e))return!0;return!1}function Sj(e,t){if(!ij.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let o=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(o));if(typeof n!=="object"||n===null)return!1;if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&n.alg!==t)return!1;return!0}catch{return!1}}function bj(e,t){if((t==="v4"||!t)&&pj.test(e))return!0;if((t==="v6"||!t)&&mj.test(e))return!0;return!1}class no extends de{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==L.string){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_type,expected:L.string,received:n.parsedType}),oe}let r=new dt,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.length<n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="max"){if(e.data.length>n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="length"){let s=e.data.length>n.value,i=e.data.length<n.value;if(s||i){if(o=this._getOrReturnCtx(e,o),s)A(o,{code:w.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});else if(i)A(o,{code:w.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});r.dirty()}}else if(n.kind==="email"){if(!cj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"email",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="emoji"){if(!Bf)Bf=new RegExp(uj,"u");if(!Bf.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"emoji",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="uuid"){if(!nj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"uuid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="nanoid"){if(!sj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"nanoid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid"){if(!tj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid2"){if(!rj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid2",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ulid"){if(!oj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"ulid",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),A(o,{validation:"url",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="regex"){if(n.regex.lastIndex=0,!n.regex.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"regex",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="trim")e.data=e.data.trim();else if(n.kind==="includes"){if(!e.data.includes(n.value,n.position))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),r.dirty()}else if(n.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(n.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(n.kind==="startsWith"){if(!e.data.startsWith(n.value))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:{startsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="endsWith"){if(!e.data.endsWith(n.value))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:{endsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="datetime"){if(!yj(n).test(e.data))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:"datetime",message:n.message}),r.dirty()}else if(n.kind==="date"){if(!gj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:"date",message:n.message}),r.dirty()}else if(n.kind==="time"){if(!_j(n).test(e.data))o=this._getOrReturnCtx(e,o),A(o,{code:w.invalid_string,validation:"time",message:n.message}),r.dirty()}else if(n.kind==="duration"){if(!aj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"duration",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ip"){if(!vj(e.data,n.version))o=this._getOrReturnCtx(e,o),A(o,{validation:"ip",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="jwt"){if(!Sj(e.data,n.alg))o=this._getOrReturnCtx(e,o),A(o,{validation:"jwt",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cidr"){if(!bj(e.data,n.version))o=this._getOrReturnCtx(e,o),A(o,{validation:"cidr",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64"){if(!hj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"base64",code:w.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64url"){if(!fj.test(e.data))o=this._getOrReturnCtx(e,o),A(o,{validation:"base64url",code:w.invalid_string,message:n.message}),r.dirty()}else ge.assertNever(n);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((o)=>e.test(o),{validation:t,code:w.invalid_string,...K.errToObj(r)})}_addCheck(e){return new no({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...K.errToObj(e)})}url(e){return this._addCheck({kind:"url",...K.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...K.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...K.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...K.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...K.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...K.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...K.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...K.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...K.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...K.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...K.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...K.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...K.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...K.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...K.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...K.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...K.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...K.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...K.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...K.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...K.errToObj(t)})}nonempty(e){return this.min(1,K.errToObj(e))}trim(){return new no({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new no({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new no({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}no.create=(e)=>new no({checks:[],typeName:ne.ZodString,coerce:e?.coerce??!1,...ce(e)});function zj(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,s=Number.parseInt(e.toFixed(n).replace(".","")),i=Number.parseInt(t.toFixed(n).replace(".",""));return s%i/10**n}class Ps extends de{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==L.number){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_type,expected:L.number,received:n.parsedType}),oe}let r=void 0,o=new dt;for(let n of this._def.checks)if(n.kind==="int"){if(!ge.isInteger(e.data))r=this._getOrReturnCtx(e,r),A(r,{code:w.invalid_type,expected:"integer",received:"float",message:n.message}),o.dirty()}else if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(zj(e.data,n.value)!==0)r=this._getOrReturnCtx(e,r),A(r,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else if(n.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),A(r,{code:w.not_finite,message:n.message}),o.dirty()}else ge.assertNever(n);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,K.toString(t))}gt(e,t){return this.setLimit("min",e,!1,K.toString(t))}lte(e,t){return this.setLimit("max",e,!0,K.toString(t))}lt(e,t){return this.setLimit("max",e,!1,K.toString(t))}setLimit(e,t,r,o){return new Ps({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:K.toString(o)}]})}_addCheck(e){return new Ps({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:K.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:K.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&ge.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}Ps.create=(e)=>new Ps({checks:[],typeName:ne.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Ts extends de{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==L.bigint)return this._getInvalidInput(e);let r=void 0,o=new dt;for(let n of this._def.checks)if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),A(r,{code:w.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(e.data%n.value!==BigInt(0))r=this._getOrReturnCtx(e,r),A(r,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else ge.assertNever(n);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:w.invalid_type,expected:L.bigint,received:t.parsedType}),oe}gte(e,t){return this.setLimit("min",e,!0,K.toString(t))}gt(e,t){return this.setLimit("min",e,!1,K.toString(t))}lte(e,t){return this.setLimit("max",e,!0,K.toString(t))}lt(e,t){return this.setLimit("max",e,!1,K.toString(t))}setLimit(e,t,r,o){return new Ts({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:K.toString(o)}]})}_addCheck(e){return new Ts({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Ts.create=(e)=>new Ts({checks:[],typeName:ne.ZodBigInt,coerce:e?.coerce??!1,...ce(e)});class Vp extends de{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==L.boolean){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.boolean,received:r.parsedType}),oe}return bt(e.data)}}Vp.create=(e)=>new Vp({typeName:ne.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class Gc extends de{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==L.date){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_type,expected:L.date,received:n.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return A(n,{code:w.invalid_date}),oe}let r=new dt,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.getTime()<n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()}else if(n.kind==="max"){if(e.data.getTime()>n.value)o=this._getOrReturnCtx(e,o),A(o,{code:w.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()}else ge.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Gc({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:K.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:K.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}Gc.create=(e)=>new Gc({checks:[],coerce:e?.coerce||!1,typeName:ne.ZodDate,...ce(e)});class Bp extends de{_parse(e){if(this._getType(e)!==L.symbol){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.symbol,received:r.parsedType}),oe}return bt(e.data)}}Bp.create=(e)=>new Bp({typeName:ne.ZodSymbol,...ce(e)});class Yc extends de{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.undefined,received:r.parsedType}),oe}return bt(e.data)}}Yc.create=(e)=>new Yc({typeName:ne.ZodUndefined,...ce(e)});class Xc extends de{_parse(e){if(this._getType(e)!==L.null){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.null,received:r.parsedType}),oe}return bt(e.data)}}Xc.create=(e)=>new Xc({typeName:ne.ZodNull,...ce(e)});class Hp extends de{constructor(){super(...arguments);this._any=!0}_parse(e){return bt(e.data)}}Hp.create=(e)=>new Hp({typeName:ne.ZodAny,...ce(e)});class yn extends de{constructor(){super(...arguments);this._unknown=!0}_parse(e){return bt(e.data)}}yn.create=(e)=>new yn({typeName:ne.ZodUnknown,...ce(e)});class so extends de{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:w.invalid_type,expected:L.never,received:t.parsedType}),oe}}so.create=(e)=>new so({typeName:ne.ZodNever,...ce(e)});class Jp extends de{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.void,received:r.parsedType}),oe}return bt(e.data)}}Jp.create=(e)=>new Jp({typeName:ne.ZodVoid,...ce(e)});class Ar extends de{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==L.array)return A(t,{code:w.invalid_type,expected:L.array,received:t.parsedType}),oe;if(o.exactLength!==null){let s=t.data.length>o.exactLength.value,i=t.data.length<o.exactLength.value;if(s||i)A(t,{code:s?w.too_big:w.too_small,minimum:i?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty()}if(o.minLength!==null){if(t.data.length<o.minLength.value)A(t,{code:w.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()}if(o.maxLength!==null){if(t.data.length>o.maxLength.value)A(t,{code:w.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,i)=>o.type._parseAsync(new cr(t,s,t.path,i)))).then((s)=>dt.mergeArray(r,s));let n=[...t.data].map((s,i)=>o.type._parseSync(new cr(t,s,t.path,i)));return dt.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Ar({...this._def,minLength:{value:e,message:K.toString(t)}})}max(e,t){return new Ar({...this._def,maxLength:{value:e,message:K.toString(t)}})}length(e,t){return new Ar({...this._def,exactLength:{value:e,message:K.toString(t)}})}nonempty(e){return this.min(1,e)}}Ar.create=(e,t)=>new Ar({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ne.ZodArray,...ce(t)});function Rs(e){if(e instanceof Ke){let t={};for(let r in e.shape){let o=e.shape[r];t[r]=Nr.create(Rs(o))}return new Ke({...e._def,shape:()=>t})}else if(e instanceof Ar)return new Ar({...e._def,type:Rs(e.element)});else if(e instanceof Nr)return Nr.create(Rs(e.unwrap()));else if(e instanceof Oo)return Oo.create(Rs(e.unwrap()));else if(e instanceof io)return io.create(e.items.map((t)=>Rs(t)));else return e}class Ke extends de{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=ge.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==L.object){let c=this._getOrReturnCtx(e);return A(c,{code:w.invalid_type,expected:L.object,received:c.parsedType}),oe}let{status:r,ctx:o}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof so&&this._def.unknownKeys==="strip")){for(let c in o.data)if(!s.includes(c))i.push(c)}let a=[];for(let c of s){let u=n[c],l=o.data[c];a.push({key:{status:"valid",value:c},value:u._parse(new cr(o,l,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof so){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of i)a.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict"){if(i.length>0)A(o,{code:w.unrecognized_keys,keys:i}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of i){let l=o.data[u];a.push({key:{status:"valid",value:u},value:c._parse(new cr(o,l,o.path,u)),alwaysSet:u in o.data})}}if(o.common.async)return Promise.resolve().then(async()=>{let c=[];for(let u of a){let l=await u.key,p=await u.value;c.push({key:l,value:p,alwaysSet:u.alwaysSet})}return c}).then((c)=>dt.mergeObjectSync(r,c));else return dt.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return K.errToObj,new Ke({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let o=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:K.errToObj(e).message??o};return{message:o}}}:{}})}strip(){return new Ke({...this._def,unknownKeys:"strip"})}passthrough(){return new Ke({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ke({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ke({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ne.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ke({...this._def,catchall:e})}pick(e){let t={};for(let r of ge.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new Ke({...this._def,shape:()=>t})}omit(e){let t={};for(let r of ge.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new Ke({...this._def,shape:()=>t})}deepPartial(){return Rs(this)}partial(e){let t={};for(let r of ge.objectKeys(this.shape)){let o=this.shape[r];if(e&&!e[r])t[r]=o;else t[r]=o.optional()}return new Ke({...this._def,shape:()=>t})}required(e){let t={};for(let r of ge.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let n=this.shape[r];while(n instanceof Nr)n=n._def.innerType;t[r]=n}return new Ke({...this._def,shape:()=>t})}keyof(){return rT(ge.objectKeys(this.shape))}}Ke.create=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strip",catchall:so.create(),typeName:ne.ZodObject,...ce(t)});Ke.strictCreate=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strict",catchall:so.create(),typeName:ne.ZodObject,...ce(t)});Ke.lazycreate=(e,t)=>new Ke({shape:e,unknownKeys:"strip",catchall:so.create(),typeName:ne.ZodObject,...ce(t)});class Qc extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function o(n){for(let i of n)if(i.result.status==="valid")return i.result;for(let i of n)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let s=n.map((i)=>new Ft(i.ctx.common.issues));return A(t,{code:w.invalid_union,unionErrors:s}),oe}if(t.common.async)return Promise.all(r.map(async(n)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(o);else{let n=void 0,s=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},u=a._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;else if(u.status==="dirty"&&!n)n={result:u,ctx:c};if(c.common.issues.length)s.push(c.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let i=s.map((a)=>new Ft(a));return A(t,{code:w.invalid_union,unionErrors:i}),oe}}get options(){return this._def.options}}Qc.create=(e,t)=>new Qc({options:e,typeName:ne.ZodUnion,...ce(t)});var oo=(e)=>{if(e instanceof tu)return oo(e.schema);else if(e instanceof Zr)return oo(e.innerType());else if(e instanceof ru)return[e.value];else if(e instanceof vn)return e.options;else if(e instanceof ou)return ge.objectValues(e.enum);else if(e instanceof nu)return oo(e._def.innerType);else if(e instanceof Yc)return[void 0];else if(e instanceof Xc)return[null];else if(e instanceof Nr)return[void 0,...oo(e.unwrap())];else if(e instanceof Oo)return[null,...oo(e.unwrap())];else if(e instanceof Kf)return oo(e.unwrap());else if(e instanceof iu)return oo(e.unwrap());else if(e instanceof su)return oo(e._def.innerType);else return[]};class Jf extends de{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.object)return A(t,{code:w.invalid_type,expected:L.object,received:t.parsedType}),oe;let r=this.discriminator,o=t.data[r],n=this.optionsMap.get(o);if(!n)return A(t,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),oe;if(t.common.async)return n._parseAsync({data:t.data,path:t.path,parent:t});else return n._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let o=new Map;for(let n of t){let s=oo(n.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of s){if(o.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);o.set(i,n)}}return new Jf({typeName:ne.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...ce(r)})}}function Hf(e,t){let r=ro(e),o=ro(t);if(e===t)return{valid:!0,data:e};else if(r===L.object&&o===L.object){let n=ge.objectKeys(t),s=ge.objectKeys(e).filter((a)=>n.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=Hf(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===L.array&&o===L.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=Hf(i,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else if(r===L.date&&o===L.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class eu extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=(n,s)=>{if(Ff(n)||Ff(s))return oe;let i=Hf(n.value,s.value);if(!i.valid)return A(r,{code:w.invalid_intersection_types}),oe;if(Vf(n)||Vf(s))t.dirty();return{status:t.value,value:i.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([n,s])=>o(n,s));else return o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}eu.create=(e,t,r)=>new eu({left:e,right:t,typeName:ne.ZodIntersection,...ce(r)});class io extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.array)return A(r,{code:w.invalid_type,expected:L.array,received:r.parsedType}),oe;if(r.data.length<this._def.items.length)return A(r,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;if(!this._def.rest&&r.data.length>this._def.items.length)A(r,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let n=[...r.data].map((s,i)=>{let a=this._def.items[i]||this._def.rest;if(!a)return null;return a._parse(new cr(r,s,r.path,i))}).filter((s)=>!!s);if(r.common.async)return Promise.all(n).then((s)=>dt.mergeArray(t,s));else return dt.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new io({...this._def,rest:e})}}io.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new io({items:e,typeName:ne.ZodTuple,rest:null,...ce(t)})};class Kp extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.object)return A(r,{code:w.invalid_type,expected:L.object,received:r.parsedType}),oe;let o=[],n=this._def.keyType,s=this._def.valueType;for(let i in r.data)o.push({key:n._parse(new cr(r,i,r.path,i)),value:s._parse(new cr(r,r.data[i],r.path,i)),alwaysSet:i in r.data});if(r.common.async)return dt.mergeObjectAsync(t,o);else return dt.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof de)return new Kp({keyType:e,valueType:t,typeName:ne.ZodRecord,...ce(r)});return new Kp({keyType:no.create(),valueType:e,typeName:ne.ZodRecord,...ce(t)})}}class Wp extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.map)return A(r,{code:w.invalid_type,expected:L.map,received:r.parsedType}),oe;let o=this._def.keyType,n=this._def.valueType,s=[...r.data.entries()].map(([i,a],c)=>({key:o._parse(new cr(r,i,r.path,[c,"key"])),value:n._parse(new cr(r,a,r.path,[c,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let a of s){let c=await a.key,u=await a.value;if(c.status==="aborted"||u.status==="aborted")return oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();i.set(c.value,u.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let a of s){let{key:c,value:u}=a;if(c.status==="aborted"||u.status==="aborted")return oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();i.set(c.value,u.value)}return{status:t.value,value:i}}}}Wp.create=(e,t,r)=>new Wp({valueType:t,keyType:e,typeName:ne.ZodMap,...ce(r)});class Es extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.set)return A(r,{code:w.invalid_type,expected:L.set,received:r.parsedType}),oe;let o=this._def;if(o.minSize!==null){if(r.data.size<o.minSize.value)A(r,{code:w.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()}if(o.maxSize!==null){if(r.data.size>o.maxSize.value)A(r,{code:w.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty()}let n=this._def.valueType;function s(a){let c=new Set;for(let u of a){if(u.status==="aborted")return oe;if(u.status==="dirty")t.dirty();c.add(u.value)}return{status:t.value,value:c}}let i=[...r.data.values()].map((a,c)=>n._parse(new cr(r,a,r.path,c)));if(r.common.async)return Promise.all(i).then((a)=>s(a));else return s(i)}min(e,t){return new Es({...this._def,minSize:{value:e,message:K.toString(t)}})}max(e,t){return new Es({...this._def,maxSize:{value:e,message:K.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Es.create=(e,t)=>new Es({valueType:e,minSize:null,maxSize:null,typeName:ne.ZodSet,...ce(t)});class Wc extends de{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.function)return A(t,{code:w.invalid_type,expected:L.function,received:t.parsedType}),oe;function r(i,a){return Fp({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Jc(),Co].filter((c)=>!!c),issueData:{code:w.invalid_arguments,argumentsError:a}})}function o(i,a){return Fp({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Jc(),Co].filter((c)=>!!c),issueData:{code:w.invalid_return_type,returnTypeError:a}})}let n={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Is){let i=this;return bt(async function(...a){let c=new Ft([]),u=await i._def.args.parseAsync(a,n).catch((d)=>{throw c.addIssue(r(a,d)),c}),l=await Reflect.apply(s,this,u);return await i._def.returns._def.type.parseAsync(l,n).catch((d)=>{throw c.addIssue(o(l,d)),c})})}else{let i=this;return bt(function(...a){let c=i._def.args.safeParse(a,n);if(!c.success)throw new Ft([r(a,c.error)]);let u=Reflect.apply(s,this,c.data),l=i._def.returns.safeParse(u,n);if(!l.success)throw new Ft([o(u,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Wc({...this._def,args:io.create(e).rest(yn.create())})}returns(e){return new Wc({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Wc({args:e?e:io.create([]).rest(yn.create()),returns:t||yn.create(),typeName:ne.ZodFunction,...ce(r)})}}class tu extends de{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}tu.create=(e,t)=>new tu({getter:e,typeName:ne.ZodLazy,...ce(t)});class ru extends de{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:w.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}}ru.create=(e,t)=>new ru({value:e,typeName:ne.ZodLiteral,...ce(t)});function rT(e,t){return new vn({values:e,typeName:ne.ZodEnum,...ce(t)})}class vn extends de{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return A(t,{expected:ge.joinValues(r),received:t.parsedType,code:w.invalid_type}),oe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return A(t,{received:t.data,code:w.invalid_enum_value,options:r}),oe}return bt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return vn.create(e,{...this._def,...t})}exclude(e,t=this._def){return vn.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}vn.create=rT;class ou extends de{_parse(e){let t=ge.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==L.string&&r.parsedType!==L.number){let o=ge.objectValues(t);return A(r,{expected:ge.joinValues(o),received:r.parsedType,code:w.invalid_type}),oe}if(!this._cache)this._cache=new Set(ge.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=ge.objectValues(t);return A(r,{received:r.data,code:w.invalid_enum_value,options:o}),oe}return bt(e.data)}get enum(){return this._def.values}}ou.create=(e,t)=>new ou({values:e,typeName:ne.ZodNativeEnum,...ce(t)});class Is extends de{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.promise&&t.common.async===!1)return A(t,{code:w.invalid_type,expected:L.promise,received:t.parsedType}),oe;let r=t.parsedType===L.promise?t.data:Promise.resolve(t.data);return bt(r.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Is.create=(e,t)=>new Is({type:e,typeName:ne.ZodPromise,...ce(t)});class Zr extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ne.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,n={addIssue:(s)=>{if(A(r,s),s.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),o.type==="preprocess"){let s=o.transform(r.data,n);if(r.common.async)return Promise.resolve(s).then(async(i)=>{if(t.value==="aborted")return oe;let a=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});if(a.status==="aborted")return oe;if(a.status==="dirty")return ks(a.value);if(t.value==="dirty")return ks(a.value);return a});else{if(t.value==="aborted")return oe;let i=this._def.schema._parseSync({data:s,path:r.path,parent:r});if(i.status==="aborted")return oe;if(i.status==="dirty")return ks(i.value);if(t.value==="dirty")return ks(i.value);return i}}if(o.type==="refinement"){let s=(i)=>{let a=o.refinement(i,n);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(i.status==="aborted")return oe;if(i.status==="dirty")t.dirty();return s(i.value),{status:t.value,value:i.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(i.status==="aborted")return oe;if(i.status==="dirty")t.dirty();return s(i.value).then(()=>({status:t.value,value:i.value}))})}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_n(s))return oe;let i=o.transform(s.value,n);if(i instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(!_n(s))return oe;return Promise.resolve(o.transform(s.value,n)).then((i)=>({status:t.value,value:i}))});ge.assertNever(o)}}Zr.create=(e,t,r)=>new Zr({schema:e,typeName:ne.ZodEffects,effect:t,...ce(r)});Zr.createWithPreprocess=(e,t,r)=>new Zr({schema:t,effect:{type:"preprocess",transform:e},typeName:ne.ZodEffects,...ce(r)});class Nr extends de{_parse(e){if(this._getType(e)===L.undefined)return bt(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Nr.create=(e,t)=>new Nr({innerType:e,typeName:ne.ZodOptional,...ce(t)});class Oo extends de{_parse(e){if(this._getType(e)===L.null)return bt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Oo.create=(e,t)=>new Oo({innerType:e,typeName:ne.ZodNullable,...ce(t)});class nu extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===L.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}nu.create=(e,t)=>new nu({innerType:e,typeName:ne.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...ce(t)});class su extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(Kc(o))return o.then((n)=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Ft(r.common.issues)},input:r.data})}));else return{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ft(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}su.create=(e,t)=>new su({innerType:e,typeName:ne.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...ce(t)});class Gp extends de{_parse(e){if(this._getType(e)!==L.nan){let r=this._getOrReturnCtx(e);return A(r,{code:w.invalid_type,expected:L.nan,received:r.parsedType}),oe}return{status:"valid",value:e.data}}}Gp.create=(e)=>new Gp({typeName:ne.ZodNaN,...ce(e)});var h6=Symbol("zod_brand");class Kf extends de{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Yp extends de{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return oe;if(n.status==="dirty")return t.dirty(),ks(n.value);else return this._def.out._parseAsync({data:n.value,path:r.path,parent:r})})();else{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return oe;if(o.status==="dirty")return t.dirty(),{status:"dirty",value:o.value};else return this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new Yp({in:e,out:t,typeName:ne.ZodPipeline})}}class iu extends de{_parse(e){let t=this._def.innerType._parse(e),r=(o)=>{if(_n(o))o.value=Object.freeze(o.value);return o};return Kc(t)?t.then((o)=>r(o)):r(t)}unwrap(){return this._def.innerType}}iu.create=(e,t)=>new iu({innerType:e,typeName:ne.ZodReadonly,...ce(t)});var f6={object:Ke.lazycreate},ne;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ne||(ne={}));var g6=no.create,_6=Ps.create,y6=Gp.create,v6=Ts.create,xj=Vp.create,S6=Gc.create,b6=Bp.create,z6=Yc.create,x6=Xc.create,w6=Hp.create,$6=yn.create,k6=so.create,R6=Jp.create,P6=Ar.create,{create:wj,strictCreate:T6}=Ke,E6=Qc.create,I6=Jf.create,C6=eu.create,O6=io.create,A6=Kp.create,N6=Wp.create,Z6=Es.create,M6=Wc.create,j6=tu.create,L6=ru.create,q6=vn.create,D6=ou.create,U6=Is.create,F6=Zr.create,V6=Nr.create,B6=Oo.create,H6=Zr.createWithPreprocess,J6=Yp.create;var oT="0.5.2";var Qp="__default__",Rj=wj({isError:xj().optional()}).passthrough(),sT={map:[{label:"Explain architecture",prompt:"Explain the architecture and responsibilities of these domains."},{label:"Audit domain coupling",prompt:"Audit cross-domain dependencies and highlight tight coupling or risky edges."}],slice:[{label:"Trace execution flow",prompt:"Trace and explain the step-by-step execution flow of this slice."},{label:"Check bugs / validation",prompt:"Inspect this execution chain for potential bugs, missing validation, or boundary issues."}],boundary:[{label:"Fix violations",prompt:"Propose and apply clean fixes for these boundary violations without breaking domain rules."},{label:"Explain forbidden rules",prompt:"Explain why these imports violate domain policies and what the intended alternative is."}]},Pj={map:"Analyze this Septum architecture context:",slice:"Analyze this Septum execution slice:",boundary:"Analyze this Septum boundary audit and suggest remediations:"},ht=new Up({name:"Septum Architecture",version:oT}),we="map",Le,Gf,au=[],cu=new Map,uu="",ao=null,iT="",Os=!1;function U(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Tj(e){return e?.trim()||Qp}function Ej(){return{map:null,domainDetail:null,slice:null,boundary:null,selectedDomains:new Set,selectedSliceNodes:new Set,selectedViolations:new Set}}function Cs(e){let t=Tj(e),r=cu.get(t);if(!r)r=Ej(),cu.set(t,r);return r}function Ij(e){let t=e?.trim();if(!t)return;if(!au.includes(t))au.push(t);if(au.length===1&&cu.has(Qp)){let r=cu.get(Qp),o=Cs(t);o.map??=r.map,o.domainDetail??=r.domainDetail,o.slice??=r.slice,o.boundary??=r.boundary,cu.delete(Qp)}Le=t}function nT(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean);return t[t.length-1]??e}function aT(e){if(!e)return;if(e.theme)G0(e.theme);if(e.styles?.variables)Y0(e.styles.variables)}function Mr(e){iT=e;let t=document.getElementById("status-bar");if(t)t.textContent=Os?"Loading...":e}function Cj(e){if(!e||typeof e!=="object")return null;if(e.schema==="navigation/v1"||Array.isArray(e.domains)||Array.isArray(e.files))return"map";if("entrypoint"in e||Array.isArray(e.chain))return"slice";if("scope"in e&&(("total_violations"in e)||("violations"in e)||("status"in e)))return"boundary";return null}function ed(e,t){ao=null;let r=e?.structuredContent??null;if(!r&&Array.isArray(e?.content)){let i=e.content.find((a)=>a?.type==="text"&&typeof a.text==="string");if(i)try{r=JSON.parse(i.text)}catch{}}if(!r){if(e?.isError){let i=e?.content?.[0]?.text??"Tool execution failed.";ao=String(i)}Mr(""),mt();return}let o=typeof r.workspace_root==="string"&&r.workspace_root.trim()?r.workspace_root.trim():t??Gf??Le;if(o)Ij(o);Gf=void 0;let n=Cj(r),s=Cs(o??Le);if(n==="map"){if(Array.isArray(r.files)&&r.files.length>0&&!Array.isArray(r.domains))s.domainDetail=r;else s.map=r,s.domainDetail=null,s.selectedDomains.clear();we="map"}else if(n==="slice")s.slice=r,s.selectedSliceNodes.clear(),we="slice";else if(n==="boundary")s.boundary=r,s.selectedViolations.clear(),we="boundary";Mr(""),mt()}function Oj(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")?`file://${encodeURI(t)}`:`file:///${encodeURI(t)}`}async function Aj(e){if(!e)return;let t=e.startsWith("/")||!Le?e:`${Le.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`;try{if((await ht.request({method:"com.google.antigravity/toggle-aux-pane",params:{tabType:"fileView",uri:Oj(t)}},Rj))?.isError)Mr(`Cannot open side pane for ${e} on this surface.`)}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("-32601"))Mr(`Side pane navigation is unavailable in this host (${e}).`);else Mr(`Open file failed: ${o}`)}}function cT(e,t){return`${t}:${e.symbol??""}:${e.file??""}:${e.line??""}`}function uT(e,t){return`${t}:${e.rule??""}:${e.file??""}:${e.line??""}`}function lT(e,t){if(e==="map")return t.selectedDomains.size;if(e==="slice")return t.selectedSliceNodes.size;return t.selectedViolations.size}function Nj(e,t){if(e==="map")t.selectedDomains.clear();else if(e==="slice")t.selectedSliceNodes.clear();else t.selectedViolations.clear()}function Zj(e,t){let r=[];if(Le)r.push(`Workspace: ${Le}`);if(e==="map"&&t.map){let o=t.map,n=o.domains??[],s=t.selectedDomains,i=s.size>0?n.filter((l)=>s.has(String(l.name))):n,a=o.health??{};if(r.push(`# Septum Architecture (index=${a.index??o.status??"unknown"}, coverage=${a.coverage??"unknown"}, unresolved=${a.unresolved_imports??0})`),t.domainDetail){let p=t.domainDetail.files??[];r.push(`
315
315
  ## Focused Domain Files (${p.length})`);for(let d of p.slice(0,30))r.push(`- ${d.path}${d.archetype?` [${d.archetype}]`:""}`);if(p.length>30)r.push(`- ... +${p.length-30} more files`)}if(i.length>0){r.push(`
316
316
  ## Domains (${s.size>0?`${i.length} selected`:i.length})`);for(let l of i){let p=l.allowed_dependencies?.length?` allow=[${l.allowed_dependencies.join(",")}]`:"",d=l.forbidden_dependencies?.length?` forbid=[${l.forbidden_dependencies.join(",")}]`:"";r.push(`- ${l.name} (${l.root}, ${l.file_count??0} files)${p}${d}`)}}let c=(o.dependencies??[]).filter((l)=>s.size===0||s.has(String(l.from))||s.has(String(l.to)));if(c.length>0){r.push(`
317
317
  ## Dependencies (${c.length})`);for(let l of c.slice(0,20))r.push(`- ${l.from} -> ${l.to} (x${l.count??1})`)}let u=o.entrypoints??[];if(u.length>0&&s.size===0){r.push(`
@@ -40,8 +40,8 @@ const PLAYBOOKS = [
40
40
  });
41
41
  return userTextMessage("Open Septum Architecture UI and inspect workspace coverage.", [
42
42
  "Open the Septum Architecture UI and inspect workspace coverage:",
43
- `1. Call \`septum_map\` with \`${mapArgs}\` to open the Septum Architecture UI and load domain topology and index health.`,
44
- "2. Check `status` and `health` (`index`, `coverage`, `sync_needed`, `unsupported_files`, `skipped_files`, `unresolved_imports`, `reasons`). Read `septum://apps` if the client supports MCP resources for partial-file samples.",
43
+ "1. Open Septum Architecture from the host's app controls when available. The host uses the app-only `septum_app` entrypoint.",
44
+ `2. Call \`septum_map\` with \`${mapArgs}\` to inspect topology and index health. Check \`status\` and \`health\`, including \`coverage\`, \`unresolved_imports\` and \`incomplete_imports\`. Read \`septum://apps\` for partial-file samples when supported.`,
45
45
  "3. If `status` is `NOT_INDEXED` or `coverage` is `partial`, list the uncovered files or conditions and give concrete next steps (`septum init`, `septum sync`, `septum_map(action='register')`, or `ignore_patterns` / alias fixes).",
46
46
  ]);
47
47
  },
@@ -52,9 +52,8 @@ export function resolveServerWorkspace(options: {workspacePath?: string; filePat
52
52
 
53
53
  export function isWorkspaceInitialized(root: string): boolean {
54
54
  try {
55
- // SV-03: Pure .septum directory without config or db is uninitialized
56
- return existsSync(join(root, "septum.config.json")) ||
57
- existsSync(join(root, ".septum", "septum.db"));
55
+ // SV-03: Pure .septum directory without db is uninitialized
56
+ return existsSync(join(root, ".septum", "septum.db"));
58
57
  } catch {
59
58
  return false;
60
59
  }
@@ -105,7 +104,13 @@ export class WorkspaceManager {
105
104
  get pendingPaths(): number { return [...this.contexts.values()].reduce((n, entry) => n + entry.context.watcher.pendingCount, 0); }
106
105
 
107
106
  /** Inspect an active context synchronously without renewing or creating it. */
108
- peek(root: string): WorkspaceContext | undefined {
107
+ peek(rawRoot: string): WorkspaceContext | undefined {
108
+ let root = rawRoot;
109
+ try {
110
+ root = realpathSync(rawRoot);
111
+ } catch {
112
+ // Keep rawRoot if path does not exist on disk yet.
113
+ }
109
114
  return this.contexts.get(root)?.context;
110
115
  }
111
116