Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
security: harden x402 payments, MCP bridges, and workers
nirholas9cafba301896
diff --git a/agent-payments-sdk/docs/x402.md b/agent-payments-sdk/docs/x402.mdindex 17f1d8ade..a1876f229 100644--- a/agent-payments-sdk/docs/x402.md+++ b/agent-payments-sdk/docs/x402.md@@ -123,9 +123,14 @@ These encode/decode the three protocol headers as base64 JSON:| Header constant | Value ||---|---|-| `X402_HEADER_PAYMENT_REQUIRED` | `"PAYMENT-REQUIRED"` |-| `X402_HEADER_PAYMENT_SIGNATURE` | `"PAYMENT-SIGNATURE"` |-| `X402_HEADER_PAYMENT_RESPONSE` | `"PAYMENT-RESPONSE"` |+| `X402_HEADER_PAYMENT` | `"X-PAYMENT"` |+| `X402_HEADER_PAYMENT_REQUIRED` | `"payment-required"` |+| `X402_HEADER_PAYMENT_RESPONSE` | `"X-PAYMENT-RESPONSE"` |++The client sends its signed proof in the **`X-PAYMENT`** request header; the+server advertises requirements on the 402 via **`payment-required`** and returns+the settlement receipt in **`X-PAYMENT-RESPONSE`**. (There is no+`PAYMENT-SIGNATURE` header — that was an earlier draft name.)---@@ -135,17 +140,17 @@ These encode/decode the three protocol headers as base64 JSON:Client Server Facilitator│ │ ││── GET /resource ─────────────►│ │- │◄── 402 PAYMENT-REQUIRED ──────│ │+ │◄── 402 payment-required ──────│ ││ { accepts: [...] } │ ││ │ ││ (build + sign + send tx) │ ││ │ ││── GET /resource ─────────────►│ │- │ PAYMENT-SIGNATURE: <proof> │── verify(payload, req) ──────►│+ │ X-PAYMENT: <proof> │── verify(payload, req) ──────►││ │◄── { isValid: true } ─────────││ │── settle(payload, req) ───────►││ │◄── { success: true, tx } ─────│- │◄── 200 PAYMENT-RESPONSE ──────│ │+ │◄── 200 X-PAYMENT-RESPONSE ────│ │```---diff --git a/agent-payments-sdk/src/solana/PumpAgent.ts b/agent-payments-sdk/src/solana/PumpAgent.tsindex 994031d38..4736e45c0 100644--- a/agent-payments-sdk/src/solana/PumpAgent.ts+++ b/agent-payments-sdk/src/solana/PumpAgent.ts@@ -377,8 +377,12 @@ export class PumpAgent extends PumpAgentOffline {async validateInvoicePayment(params: {user: PublicKey;currencyMint: PublicKey;- amount: number;- memo: number;+ // Accept string/BN as well as number: USDC atomic amounts and the+ // timestamp-derived memo both routinely exceed 2^53, so a `number` here+ // silently loses precision and the invoice PDA fails to match. BN() takes+ // a decimal string losslessly — pass the raw requirement string through.+ amount: number | string | BN;+ memo: number | string | BN;startTime: number;endTime: number;}): Promise<boolean> {diff --git a/agent-payments-sdk/src/solana/x402/client.ts b/agent-payments-sdk/src/solana/x402/client.tsindex 9828d02e3..8fe79a020 100644--- a/agent-payments-sdk/src/solana/x402/client.ts+++ b/agent-payments-sdk/src/solana/x402/client.ts@@ -55,7 +55,7 @@ const SIWX_HEADER = "SIGN-IN-WITH-X";/*** Create a fetch function that automatically handles HTTP 402 responses* by building a payment transaction, signing, sending, and retrying- * the original request with payment proof in the PAYMENT-SIGNATURE header.+ * the original request with payment proof in the X-PAYMENT header.** @example* ```tsdiff --git a/agent-payments-sdk/src/solana/x402/facilitator.ts b/agent-payments-sdk/src/solana/x402/facilitator.tsindex 4017a4513..6284cbea5 100644--- a/agent-payments-sdk/src/solana/x402/facilitator.ts+++ b/agent-payments-sdk/src/solana/x402/facilitator.ts@@ -43,6 +43,24 @@ import {USDC_MAINNET,} from "./types";+// ─── Replay protection ──────────────────────────────────────────────────────++/**+ * Pluggable consumed-signature store for replay protection.+ *+ * The default {@link SettlementCache} is an in-process Map and therefore only+ * deduplicates within a single process — it does NOT survive a restart or+ * coordinate across replicas/serverless instances. A production resource server+ * that runs more than one instance MUST pass a durable, atomically-claiming+ * store (Redis `SET NX`, a Postgres `INSERT … ON CONFLICT`, etc.) so the same+ * signature can't be redeemed twice across instances. `claim()` returns true+ * exactly once per key: true = this caller won the claim (proceed), false =+ * already consumed (reject as duplicate).+ */+export interface ReplayStore {+ claim(key: string): boolean | Promise<boolean>;+}+// ─── Settlement Cache ───────────────────────────────────────────────────────class SettlementCache {@@ -74,6 +92,13 @@ class SettlementCache {}}}++ // Atomic check-and-set: true exactly once per key (single-process only).+ claim(key: string): boolean {+ if (this.has(key)) return false;+ this.set(key);+ return true;+ }}// ─── Invoice Memo Generation ────────────────────────────────────────────────@@ -93,6 +118,13 @@ export interface PumpAgentFacilitatorConfig {connection: Connection;/** CAIP-2 network (default: SOLANA_MAINNET) */network?: string;+ /**+ * Durable replay store. Defaults to an in-process cache that only+ * deduplicates within a single process — pass a Redis/Postgres-backed+ * {@link ReplayStore} in any multi-instance / serverless deployment so a+ * signature can't be settled twice across instances. See {@link ReplayStore}.+ */+ replayStore?: ReplayStore;}/**@@ -104,11 +136,12 @@ export interface PumpAgentFacilitatorConfig {export class PumpAgentFacilitator implements FacilitatorClient {private connection: Connection;private network: string;- private settlementCache = new SettlementCache();+ private replayStore: ReplayStore;constructor(config: PumpAgentFacilitatorConfig) {this.connection = config.connection;this.network = config.network ?? SOLANA_MAINNET;+ this.replayStore = config.replayStore ?? new SettlementCache();}async verify(@@ -132,19 +165,14 @@ export class PumpAgentFacilitator implements FacilitatorClient {return { isValid: false, invalidReason: "Missing signature or payer" };}- // Duplicate check- if (this.settlementCache.has(signature)) {- return { isValid: false, invalidReason: "Duplicate payment" };- }-- // Verify amount matches- if (- payload.accepted.amount !== requirements.amount ||- payload.accepted.asset !== requirements.asset- ) {- return { isValid: false, invalidReason: "Amount or asset mismatch" };- }-+ // NOTE: we deliberately do NOT compare the client-supplied+ // `payload.accepted` against `requirements` — that block is attacker-+ // controlled and proves nothing. The authoritative amount/asset/recipient+ // binding is the on-chain invoice check below, which is driven entirely by+ // the trusted `req` (server-issued requirements): the invoice PDA is derived+ // from (agentMint, currencyMint=req.asset, amount=req.amount, memo, window),+ // and the program only emits the matched payment event when funds reach the+ // agent's canonical vault — so agentMint binds the recipient.try {const agent = new PumpAgent(new PublicKey(req.extra.agentMint),@@ -155,8 +183,10 @@ export class PumpAgentFacilitator implements FacilitatorClient {const valid = await agent.validateInvoicePayment({user: new PublicKey(payer),currencyMint: new PublicKey(req.asset),- amount: Number(req.amount),- memo: Number(req.extra.memo),+ // Pass the raw decimal strings — Number() would lose precision on+ // atomic USDC amounts and the timestamp-derived memo (both > 2^53).+ amount: req.amount,+ memo: String(req.extra.memo),startTime: req.extra.startTime,endTime: req.extra.endTime,});@@ -192,7 +222,13 @@ export class PumpAgentFacilitator implements FacilitatorClient {const signature = proof.signature as string;const payer = proof.payer as string;- this.settlementCache.set(signature);+ // Atomically consume the signature — true exactly once. With a durable+ // ReplayStore this is the cross-instance double-spend guard; with the+ // in-memory default it only protects within a single process.+ const claimed = await this.replayStore.claim(signature);+ if (!claimed) {+ return { success: false, errorReason: "Duplicate payment", payer };+ }return {success: true,diff --git a/agent-payments-sdk/src/x402/evm-facilitator.ts b/agent-payments-sdk/src/x402/evm-facilitator.tsindex ce62b2b72..2c72e29f6 100644--- a/agent-payments-sdk/src/x402/evm-facilitator.ts+++ b/agent-payments-sdk/src/x402/evm-facilitator.ts@@ -15,6 +15,17 @@ export interface EvmPaymentProof {memo: string;}+/**+ * Durable replay guard for cross-chain deposits. `claim()` returns true exactly+ * once per key (the `chainId:txHash` pair) — true = first redemption (proceed),+ * false = already redeemed (reject). Back it with Redis `SET NX` or a Postgres+ * `INSERT … ON CONFLICT` in production; without it the same EVM deposit txHash+ * can be replayed to unlock the paid resource repeatedly.+ */+export interface EvmReplayStore {+ claim(key: string): boolean | Promise<boolean>;+}+export interface VerifyEvmPaymentParams {/** Decoded proof from the X-Payment header */proof: EvmPaymentProof;@@ -30,6 +41,17 @@ export interface VerifyEvmPaymentParams {* Solana arrival asynchronously (webhook / queue).*/waitForSolana?: boolean;+ /**+ * Durable consumed-txHash store. STRONGLY recommended in production: without+ * it a confirmed deposit `txHash` can be presented repeatedly to unlock the+ * resource for free. See {@link EvmReplayStore}.+ *+ * Note: this facilitator trusts the Pump.fun cross-chain deposit API as its+ * oracle for the deposit's amount + agent binding; it does not independently+ * re-verify the EVM transaction on-chain. Consumers needing a trustless path+ * should additionally confirm the tx `to`/value against an EVM RPC.+ */+ replayStore?: EvmReplayStore;}export interface EvmPaymentVerificationResult {@@ -106,6 +128,20 @@ export async function verifyEvmPayment(error: `Insufficient amount: got ${confirmedAmount}, need ${minAmountUsdc}`,};}++ // Atomically consume the deposit txHash so it can't be redeemed twice.+ if (params.replayStore) {+ const claimed = await params.replayStore.claim(+ `${proof.chainId}:${proof.txHash}`,+ );+ if (!claimed) {+ return {+ valid: false,+ depositId,+ error: "Duplicate payment: this EVM deposit was already redeemed",+ };+ }+ }} catch (err) {return {valid: false,diff --git a/api/_lib/auth.js b/api/_lib/auth.jsindex f94639f0f..ffb0cd326 100644--- a/api/_lib/auth.js+++ b/api/_lib/auth.js@@ -288,6 +288,11 @@ export async function authenticateBearer(token, { audience } = {}) {// Otherwise treat as JWT access token.try {const payload = await verifyAccessToken(token, { audience });+ // Only ACCESS tokens authorize API calls. Refresh tokens are opaque (never+ // JWTs) so this is belt-and-suspenders, but rejecting any non-'access'+ // token_use prevents a future token type (e.g. an id/refresh JWT) from+ // being replayed against resource endpoints.+ if (payload.token_use !== 'access') return null;return {userId: payload.sub,scope: payload.scope || '',diff --git a/api/_lib/crypto.js b/api/_lib/crypto.jsindex a36531aa2..342ebd18c 100644--- a/api/_lib/crypto.js+++ b/api/_lib/crypto.js@@ -25,10 +25,21 @@ export async function sha256Base64Url(input) {return base64url(new Uint8Array(hash));}+// Length-independent constant-time string compare. We deliberately do NOT+// early-return on a length mismatch — that branch is a timing oracle that+// leaks the secret's length. Instead we fold the length difference into the+// accumulator and iterate over the longer string, reading 0 past the end of+// either operand so the loop count never reveals which side is the secret.export function constantTimeEquals(a, b) {- if (a.length !== b.length) return false;- let r = 0;- for (let i = 0; i < a.length; i++) r |= a.charCodeAt(i) ^ b.charCodeAt(i);+ const aStr = String(a);+ const bStr = String(b);+ let r = aStr.length ^ bStr.length;+ const len = aStr.length > bStr.length ? aStr.length : bStr.length;+ for (let i = 0; i < len; i++) {+ const ca = i < aStr.length ? aStr.charCodeAt(i) : 0;+ const cb = i < bStr.length ? bStr.charCodeAt(i) : 0;+ r |= ca ^ cb;+ }return r === 0;}diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 7e136eb1e..36a4deba0 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -21,6 +21,17 @@ export const env = {return trimSlash(opt('PUBLIC_APP_ORIGIN', 'https://three.ws/'));},+ // Runtime environment signals. NODE_ENV is set to 'production' by Vercel's+ // build/runtime; VERCEL_ENV is 'production' | 'preview' | 'development' on+ // Vercel deployments. Tests and local dev leave both unset, so prod-only+ // behavior (e.g. fail-closed rate limiting) never trips in CI or dev.+ get NODE_ENV() {+ return opt('NODE_ENV');+ },+ get VERCEL_ENV() {+ return opt('VERCEL_ENV');+ },+get DATABASE_URL() {return req('DATABASE_URL');},@@ -245,14 +256,16 @@ export const env = {// Falls back to public RPC nodes when unset; set Alchemy/Infura URLs for production.// ── x402 (HTTP 402 micropayments) ───────────────────────────────────────// Per-network payTo wallets that receive USDC for paid /api/mcp calls.+ // NO hardcoded default: an unset receiver fails closed — buildRequirements()+ // stops advertising that network — rather than silently routing real USDC to+ // a baked-in address if a fork or misconfigured deploy forgets to set it.+ // Asset/mint addresses below keep their public-constant defaults; only the+ // money-routing receivers (payTo + feePayer) are required-by-config.get X402_PAY_TO_SOLANA() {- return opt(- 'X402_PAY_TO_SOLANA',- opt('X402_PAY_TO', 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV'),- );+ return opt('X402_PAY_TO_SOLANA', opt('X402_PAY_TO'));},get X402_PAY_TO_BASE() {- return opt('X402_PAY_TO_BASE', '0x4022de2d36c334e73c7a108805cea11c0564f402');+ return opt('X402_PAY_TO_BASE');},// USDC asset addresses per network.get X402_ASSET_MINT_SOLANA() {@@ -321,7 +334,9 @@ export const env = {// facilitator co-signs on /settle. Must match whatever facilitator.payai.network// returns at /supported for `network:"solana"`.get X402_FEE_PAYER_SOLANA() {- return opt('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');+ // No hardcoded default — see X402_PAY_TO_SOLANA. Without a fee payer the+ // Solana accept can't be co-signed, so it must come from config.+ return opt('X402_FEE_PAYER_SOLANA');},// ERC-8021 builder-code app identifier. When set, every 402 challenge@@ -385,7 +400,9 @@ export const env = {// (1000 base units = $0.001) and emits Payment(payer, amount, ref).// Source + deploy tx: contracts/DEPLOYMENTS.mdget X402_PAY_TO_BSC() {- return opt('X402_PAY_TO_BSC', '0x00000000381f09742a30a5a49975514AeC1B72Cc');+ // No hardcoded default — see X402_PAY_TO_SOLANA. The ThreeWSPayments+ // receiver contract address must be set explicitly per deploy.+ return opt('X402_PAY_TO_BSC');},// ── AWS Marketplace ──────────────────────────────────────────────────────// IAM credentials with marketplaceMetering:ResolveCustomer,diff --git a/api/_lib/fetch-model.js b/api/_lib/fetch-model.jsindex 928bc3814..78a8150b6 100644--- a/api/_lib/fetch-model.js+++ b/api/_lib/fetch-model.js@@ -12,6 +12,7 @@// 5. Timeout — total request + streaming is bounded.import { lookup } from 'node:dns/promises';+import { Agent } from 'undici';import { env } from './env.js';const DEFAULT_MAX_BYTES = 50 * 1024 * 1024; // 50 MB@@ -58,7 +59,19 @@ function isPrivateIPv6(ip) {return false;}-async function assertPublicHost(host) {+function isPrivateAddress(address, family) {+ if (family === 4) return isPrivateIPv4(address);+ if (family === 6) return isPrivateIPv6(address);+ // Unknown family — treat as unsafe.+ return true;+}++// Resolve `host` once, reject if ANY resolved address is private, and return the+// validated address list. The caller pins the connection to exactly these+// addresses (via a custom undici `lookup`) so a DNS-rebinding attacker who+// returns a public IP at validation time and a private IP at connect time+// cannot reach internal services — we never re-resolve through the OS.+async function resolvePublicHost(host) {if (!host) throw new FetchModelError('missing host', 'invalid_url');let resolved;try {@@ -67,20 +80,42 @@ async function assertPublicHost(host) {throw new FetchModelError(`DNS lookup failed for ${host}`, 'dns_failed');}const addrs = Array.isArray(resolved) ? resolved : [resolved];+ if (!addrs.length) throw new FetchModelError(`DNS lookup failed for ${host}`, 'dns_failed');for (const { address, family } of addrs) {- if (family === 4 && isPrivateIPv4(address)) {- throw new FetchModelError(- `host resolves to private address: ${address}`,- 'private_address',- );- }- if (family === 6 && isPrivateIPv6(address)) {+ if (isPrivateAddress(address, family)) {throw new FetchModelError(`host resolves to private address: ${address}`,'private_address',);}}+ return addrs;+}++// Build an undici Agent whose DNS `lookup` only ever yields the pre-validated+// addresses for `expectedHost`. Any connect attempt to a different host (e.g.+// after an internal redirect we didn't re-pin) or with no validated address is+// refused. This closes the check-then-connect TOCTOU: the address the socket+// connects to is byte-for-byte one we already asserted is public.+function pinnedAgent(expectedHost, addrs) {+ return new Agent({+ connect: {+ lookup(hostname, _opts, cb) {+ if (hostname !== expectedHost) {+ cb(new FetchModelError(`unexpected connect host: ${hostname}`, 'host_pin_mismatch'));+ return;+ }+ // undici accepts an array of { address, family } entries. Re-assert+ // here as defense-in-depth in case a resolver returned mixed records.+ const safe = addrs.filter((a) => !isPrivateAddress(a.address, a.family));+ if (!safe.length) {+ cb(new FetchModelError('no public address to connect to', 'private_address'));+ return;+ }+ cb(null, safe.map((a) => ({ address: a.address, family: a.family })));+ },+ },+ });}function validateUrl(rawUrl) {@@ -112,14 +147,21 @@ export async function fetchModel(rawUrl, opts = {}) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), timeoutMs);+ let agent = null;try {while (true) {- await assertPublicHost(currentUrl.hostname);+ // Resolve + validate on THIS hop, then pin the connection to exactly+ // those addresses. Re-done every redirect so a redirect target that+ // rebinds to a private IP is caught and refused.+ const addrs = await resolvePublicHost(currentUrl.hostname);+ if (agent) await agent.close().catch(() => {});+ agent = pinnedAgent(currentUrl.hostname, addrs);const res = await fetch(currentUrl, {method: 'GET',redirect: 'manual',signal: controller.signal,+ dispatcher: agent,headers: {'user-agent': '3d-agent-mcp/1.0 (+https://three.ws/)',accept: 'model/gltf-binary, model/gltf+json, application/octet-stream, */*;q=0.5',@@ -187,5 +229,6 @@ export async function fetchModel(rawUrl, opts = {}) {}} finally {clearTimeout(timer);+ if (agent) await agent.close().catch(() => {});}}diff --git a/api/_lib/http.js b/api/_lib/http.jsindex 7defdb9f7..ec3b79d3c 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -1,5 +1,6 @@// HTTP helpers for Vercel Node handlers. Keeps handlers small + consistent.+import { webcrypto } from 'node:crypto';import { env } from './env.js';import { captureException } from './sentry.js';import { instrument as zauthInstrument, drain as zauthDrain } from './zauth.js';@@ -30,6 +31,45 @@ export function error(res, status, code, message, extra = {}) {return json(res, status, { error: code, error_description: message, ...extra });}+// Short, URL-safe correlation id for tying a sanitized 5xx response back to the+// full server-side log line. Not security-sensitive — just needs to be unique.+function correlationId() {+ const b = new Uint8Array(8);+ (globalThis.crypto || webcrypto).getRandomValues(b);+ return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');+}++// Emit a 5xx WITHOUT leaking internal error detail to the client. The real+// message (which may carry RPC URLs, wallet addresses, or stack-derived text)+// is logged + captured server-side under a correlation id the caller can quote+// to support; the client only sees a generic description + the ref.+export function serverError(res, status, code, err, extra = {}) {+ const ref = correlationId();+ const detail = err?.message || String(err ?? 'unknown error');+ console.error(`[server-error ${ref}] ${code} (${status}): ${detail}`);+ try {+ captureException(err instanceof Error ? err : new Error(detail), { ref, code, status });+ } catch {+ /* sentry best-effort; never mask the original failure */+ }+ return json(res, status, {+ error: code,+ error_description: `internal error — quote ref ${ref} to support`,+ ref,+ ...extra,+ });+}++// Dispatch: client-fault (4xx) keep their descriptive message; server-fault+// (5xx) are sanitized via serverError. Use this in catch blocks where the+// status is derived from `err.status` and may be either class.+export function respondError(res, status, code, err, extra = {}) {+ if (status < 500) {+ return error(res, status, code, err?.message || code, extra);+ }+ return serverError(res, status, code, err, extra);+}+// Response shape used for zod validation errors so clients can render// field-level feedback. Mirrors RFC 9457-style problem details (lite).export function validationError(res, err) {diff --git a/api/_lib/mcp-dispatch.js b/api/_lib/mcp-dispatch.jsindex 8fbcff7ac..497f5389e 100644--- a/api/_lib/mcp-dispatch.js+++ b/api/_lib/mcp-dispatch.js@@ -5,6 +5,7 @@// usage accounting, and the MCP error conventions.import { hasScope } from './auth.js';import { recordEvent, logger } from './usage.js';+import { sanitizeToolError } from './mcp-error-sanitize.js';export const PROTOCOL_VERSION = '2025-06-18';@@ -74,8 +75,12 @@ export function makeDispatcher({ serverInfo, instructions, catalog, tools, logNameta: { error: err.message, server: logName },});if (err.code && typeof err.code === 'number') throw err;+ // Shared sanitizer: suppress pg/driver internals + internal+ // hostnames, log full detail to stderr with a log id, and pass+ // safe handler-authored messages through unchanged.+ const { message } = sanitizeToolError(err, { tool: name, server: logName, log });return {- content: [{ type: 'text', text: `Error: ${err.message || 'tool call failed'}` }],+ content: [{ type: 'text', text: `Error: ${message}` }],isError: true,};}diff --git a/api/_lib/mcp-error-sanitize.js b/api/_lib/mcp-error-sanitize.jsnew file mode 100644index 000000000..4f9e91704--- /dev/null+++ b/api/_lib/mcp-error-sanitize.js@@ -0,0 +1,81 @@+// Shared sanitizer for uncaught MCP tool errors.+//+// Tool handlers reach out to Postgres, internal RPC nodes, and other services.+// When one of those throws, the raw `err.message` frequently carries internals+// we must never echo to an untrusted MCP caller: Postgres driver text + SQLSTATE+// codes, connection strings, internal hostnames/IPs, or stack-derived paths.+//+// `sanitizeToolError` returns a generic, caller-safe message plus a short log id+// that ties the response back to the full detail we write to stderr. Both the+// main /api/mcp dispatcher and the shared payment-free dispatcher+// (mcp-3d / mcp-bazaar) funnel uncaught tool errors through this so the two can+// never diverge in what they leak.++import { randomBytes } from 'node:crypto';++// Postgres driver errors carry a `severity` and/or SQLSTATE-ish `code` plus+// fields like `schema`, `table`, `column`, `routine`. Treat anything with those+// markers as a DB error whose message must be suppressed wholesale.+function isPostgresError(err) {+ if (!err || typeof err !== 'object') return false;+ if (err.severity !== undefined || err.schema !== undefined) return true;+ if (err.routine !== undefined || err.table !== undefined || err.column !== undefined)+ return true;+ // SQLSTATE codes are 5-char alphanumeric strings (e.g. '42P01', '23505').+ if (typeof err.code === 'string' && /^[0-9A-Z]{5}$/.test(err.code)) return true;+ return false;+}++// Internal hostnames / connection strings that must never leave the server,+// even when an error message is otherwise handler-authored. If a tool error's+// message contains one of these markers we suppress it wholesale.+const INTERNAL_LEAK = [+ /postgres(?:ql)?:\/\//i,+ /redis:\/\//i,+ /\b(?:127\.0\.0\.1|localhost)\b/i,+ /\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/, // RFC1918 10/8+ /\b192\.168\.\d{1,3}\.\d{1,3}\b/, // RFC1918 192.168/16+ /\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/, // RFC1918 172.16/12+ /\.internal\b/i,+ /ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|ENOTFOUND/,+];++function leaksInternalText(message) {+ if (!message) return false;+ return INTERNAL_LEAK.some((re) => re.test(message));+}++/**+ * Decide whether an uncaught tool error's own message is safe to surface, log+ * the full detail to stderr keyed by a short id, and return a caller-safe+ * payload.+ *+ * Returns `{ message }` where `message` is the text safe to send to the MCP+ * caller. Postgres/driver errors and any message containing internal markers+ * are replaced with a generic `… (ref <logId>)` string; handler-authored+ * messages that are already safe (e.g. `fetch failed: … (private_address)`)+ * pass through unchanged so existing tool contracts hold.+ *+ * @param {unknown} err the thrown error+ * @param {object} ctx+ * @param {string} ctx.tool tool name (for the log line)+ * @param {string} ctx.server server/log namespace (for the log line)+ * @param {{ error: Function }} [ctx.log] logger; falls back to console.error+ * @returns {{ message: string, logId: string }}+ */+export function sanitizeToolError(err, { tool, server, log } = {}) {+ const logId = randomBytes(6).toString('hex');+ const rawMessage = err?.message || String(err);+ const detail = err?.stack || rawMessage;+ const meta = { tool, server, log_id: logId, pg_code: err?.code, detail };+ if (log && typeof log.error === 'function') log.error('tool_error', meta);+ else console.error(`[${server || 'mcp'}] tool_error`, meta);++ if (isPostgresError(err) || leaksInternalText(rawMessage)) {+ return { message: `internal error (ref ${logId})`, logId };+ }+ // Handler-authored messages reach here already safe (they are written for+ // callers, not derived from driver internals). Surface them verbatim so the+ // existing tool error contracts (e.g. `fetch failed: …`) are preserved.+ return { message: rawMessage || `tool call failed (ref ${logId})`, logId };+}diff --git a/api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql b/api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sqlnew file mode 100644index 000000000..297382ad9--- /dev/null+++ b/api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql@@ -0,0 +1,19 @@+-- Harden plan_payment_intents against payment replay.+--+-- Before this, the EVM confirm path accepted any USDC transfer to the shared+-- treasury of >= the plan price, with no uniqueness on tx_hash. An attacker+-- could observe any public transfer to the treasury and confirm it against+-- their own intent (free upgrade), and the same tx could be replayed across+-- many intents. This index makes a single on-chain tx confirmable at most once.+--+-- Idempotent.++BEGIN;++-- A confirmed tx_hash may back at most one intent. Pending rows have+-- tx_hash = NULL and are unaffected (NULLs are distinct in a unique index).+CREATE UNIQUE INDEX IF NOT EXISTS payment_intents_tx_hash_unique+ ON plan_payment_intents (chain_type, tx_hash)+ WHERE tx_hash IS NOT NULL;++COMMIT;diff --git a/api/_lib/migrations/20260603130000_pump_agent_payments_tx_unique.sql b/api/_lib/migrations/20260603130000_pump_agent_payments_tx_unique.sqlnew file mode 100644index 000000000..4ee06f655--- /dev/null+++ b/api/_lib/migrations/20260603130000_pump_agent_payments_tx_unique.sql@@ -0,0 +1,17 @@+-- One on-chain tx may confirm at most one agent-payment invoice.+--+-- Before this, accept-payment-confirm only checked that the agent mint appeared+-- in the tx account keys — it never verified the amount, the recipient vault, or+-- that the signature was previously unused. A single cheap tx could confirm any+-- number of invoices. This index plus the rewritten verifier (vault credit ++-- payer + amount) closes that.+--+-- Idempotent.++BEGIN;++CREATE UNIQUE INDEX IF NOT EXISTS pump_agent_payments_tx_signature_unique+ ON pump_agent_payments (tx_signature)+ WHERE tx_signature IS NOT NULL;++COMMIT;diff --git a/api/_lib/pump-pricing.js b/api/_lib/pump-pricing.jsindex 389c7421b..406d004d8 100644--- a/api/_lib/pump-pricing.js+++ b/api/_lib/pump-pricing.js@@ -32,6 +32,29 @@ export function isFreeTool(toolName) {return !TOOL_PRICING[toolName];}+// USDC (and our other supported stables) are 6-decimal. The x402 wire `amount`+// is an atomic-unit string; convert a human `amount_usdc` to that. Rounds to the+// nearest atomic unit so fractional-cent prices (e.g. 0.005) map exactly.+const USDC_DECIMALS = 6;+export function usdcToAtomicString(amountUsdc) {+ const atomic = Math.round(Number(amountUsdc) * 10 ** USDC_DECIMALS);+ return String(atomic);+}++/**+ * The x402 `amount` (atomic-unit string) to charge for a given MCP tools/call.+ * Derived from the advertised per-tool price so the 402 challenge and the+ * settled charge agree. Returns null for free tools (no charge).+ *+ * @param {string} toolName+ * @returns {string|null}+ */+export function x402AmountForTool(toolName) {+ const price = priceFor(toolName);+ if (!price || !(price.amount_usdc > 0)) return null;+ return usdcToAtomicString(price.amount_usdc);+}+/*** Returns the active subscription row for (mint, payerWallet, toolName) if one* exists and has not expired. `toolName=null` matches any unrestricteddiff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex cd02dd3aa..cdb52e636 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -9,14 +9,59 @@ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {redis = new Redis({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN });}+// Prod signal: real deployments set NODE_ENV=production (Vercel does). Tests and+// local dev never do, so the in-memory fallback stays fully permissive there.+const IS_PRODUCTION = env.NODE_ENV === 'production' || env.VERCEL_ENV === 'production';+const REDIS_CONFIGURED = Boolean(redis);++// Loud, one-time startup warning when Redis is unconfigured in production. Without+// Redis every limiter falls back to a PER-INSTANCE in-memory map, which is+// effectively unbounded across serverless fan-out — fine for dev, dangerous for+// the money/cost limiters in prod (see failClosedLimiter below).+if (IS_PRODUCTION && !REDIS_CONFIGURED) {+ console.error(+ '[rate-limit] FATAL CONFIG: UPSTASH_REDIS_REST_URL/TOKEN are unset in production. ' ++ 'Cost/money-moving limiters will FAIL CLOSED (deny) until Redis is configured; ' ++ 'cheap per-IP limiters fall back to a non-distributed in-memory map.',+ );+}+const limiters = new Map();const memoryBuckets = new Map();+// A limiter that always denies. Used in production for cost/money-moving buckets+// when Redis is absent: better to 503 a paid action than to silently allow+// unbounded spend across serverless instances.+function failClosedLimiter({ limit, window }) {+ const ms = parseWindowMs(window);+ return {+ async limit() {+ return {+ success: false,+ limit,+ remaining: 0,+ reset: Date.now() + ms,+ reason: 'rate_limiter_unavailable',+ };+ },+ };+}++/**+ * @param {string} name+ * @param {{ limit: number, window: string, critical?: boolean }} opts+ * `critical: true` marks a cost/money-moving bucket. When Redis is absent in+ * production these fail closed (deny) instead of using the unbounded in-memory+ * fallback. Non-critical buckets keep the permissive in-memory fallback so a+ * missing-Redis misconfig degrades read endpoints gracefully rather than+ * taking the whole site down.+ */function getLimiter(name, opts) {const key = `${name}:${opts.limit}:${opts.window}`;if (limiters.has(key)) return limiters.get(key);if (!redis) {- const lim = memoryLimiter(opts);+ const lim =+ opts.critical && IS_PRODUCTION ? failClosedLimiter(opts) : memoryLimiter(opts);limiters.set(key, lim);return lim;}@@ -70,21 +115,24 @@ export const limits = {getLimiter('oauth:register:ip', { limit: 10, window: '1 h' }).limit(ip),mcpUser: (userId) => getLimiter('mcp:user', { limit: 1200, window: '1 m' }).limit(userId),mcpIp: (ip) => getLimiter('mcp:ip', { limit: 600, window: '1 m' }).limit(ip),- mcpValidate: (key) => getLimiter('mcp:validate', { limit: 10, window: '1 m' }).limit(key),- mcpInspect: (key) => getLimiter('mcp:inspect', { limit: 30, window: '1 m' }).limit(key),- mcpOptimize: (key) => getLimiter('mcp:optimize', { limit: 10, window: '1 m' }).limit(key),+ // Paid MCP tools — each call runs real compute (glTF validation / inspection+ // / optimization on a fetched model). Marked critical so they fail closed in+ // prod without Redis rather than allowing unbounded paid work per instance.+ mcpValidate: (key) => getLimiter('mcp:validate', { limit: 10, window: '1 m', critical: true }).limit(key),+ mcpInspect: (key) => getLimiter('mcp:inspect', { limit: 30, window: '1 m', critical: true }).limit(key),+ mcpOptimize: (key) => getLimiter('mcp:optimize', { limit: 10, window: '1 m', critical: true }).limit(key),// 3D Studio MCP. Generation submits a real GPU job on Replicate (text→image// and/or image→3D reconstruction) that costs real money, so it gets a hard// hourly ceiling per principal. Status polling is cheap and frequent.- mcp3dGenerate: (key) => getLimiter('mcp3d:generate', { limit: 12, window: '1 h' }).limit(key),+ mcp3dGenerate: (key) => getLimiter('mcp3d:generate', { limit: 12, window: '1 h', critical: true }).limit(key),mcp3dStatus: (key) => getLimiter('mcp3d:status', { limit: 240, window: '1 m' }).limit(key),// x402 Bazaar MCP. Discovery calls fan out to external facilitators, so cap// per principal to keep that egress bounded without throttling normal use.- mcpBazaar: (key) => getLimiter('mcp:bazaar', { limit: 60, window: '1 m' }).limit(key),+ mcpBazaar: (key) => getLimiter('mcp:bazaar', { limit: 60, window: '1 m', critical: true }).limit(key),// threews-agent MCP. Read/discovery calls are cheap; pay_and_call moves real// money, so it gets a much tighter ceiling on top of the per-spend caps.- mcpAgent: (key) => getLimiter('mcp:agent', { limit: 60, window: '1 m' }).limit(key),- mcpAgentPay: (key) => getLimiter('mcp:agent:pay', { limit: 20, window: '1 m' }).limit(key),+ mcpAgent: (key) => getLimiter('mcp:agent', { limit: 60, window: '1 m', critical: true }).limit(key),+ mcpAgentPay: (key) => getLimiter('mcp:agent:pay', { limit: 20, window: '1 m', critical: true }).limit(key),oauthToken: (clientId) =>getLimiter('oauth:token', { limit: 120, window: '1 m' }).limit(clientId),upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),@@ -102,12 +150,26 @@ export const limits = {// balance as the global ceiling.x402PayIp: (ip) => getLimiter('x402:pay:ip', { limit: 6, window: '1 m' }).limit(ip),x402PayGlobal: () =>- getLimiter('x402:pay:global', { limit: 600, window: '1 h' }).limit('global'),+ getLimiter('x402:pay:global', { limit: 600, window: '1 h', critical: true }).limit('global'),checkName: (ip) => getLimiter('check-name:ip', { limit: 60, window: '1 m' }).limit(ip),ensResolve: (ip) => getLimiter('ens:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),snsResolve: (ip) => getLimiter('sns:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),// Generic public read endpoints (explore, showcase, public agent fetch). 60/min per IP.publicIp: (ip) => getLimiter('public:ip', { limit: 60, window: '1 m' }).limit(ip),+ // Browser Solana JSON-RPC proxy (api/solana-rpc). Forwards to the keyed+ // upstream (Helius), so cap per-IP burst to keep the studio launch panel+ // responsive while preventing anonymous quota drain, plus a global hourly+ // ceiling as a hard cost cap independent of any one client.+ solanaRpcIp: (ip) => getLimiter('solana-rpc:ip', { limit: 120, window: '1 m' }).limit(ip),+ solanaRpcGlobal: () =>+ getLimiter('solana-rpc:global', { limit: 12000, window: '1 h' }).limit('global'),+ // Agent-to-agent economy demo (api/agent-economy/transact). Each call can send+ // a tiny real SOL payment from the server wallet, so cap per-IP and add a+ // global daily ceiling as a hard spend cap independent of wallet balance.+ // The global bucket is only consumed when a payment actually fires.+ agentEconomyIp: (ip) => getLimiter('agent-economy:ip', { limit: 10, window: '1 h' }).limit(ip),+ agentEconomyGlobal: () =>+ getLimiter('agent-economy:global', { limit: 500, window: '1 d' }).limit('global'),// IBM watsonx.ai Granite embeddings (api/watsonx/embed). Each call bills real// watsonx inference against the server key, so keep the per-IP burst small and// add a global hourly ceiling as a hard cost cap independent of any one client.@@ -150,7 +212,8 @@ export const limits = {window: '1 m',}).limit(agentId),// Autonomous agent skill purchases: 10 per hour per buyer agent to prevent runaway spending.- agentBuy: (agentId) => getLimiter('agent:buy', { limit: 10, window: '1 h' }).limit(agentId),+ // Critical (moves real money) — fail closed in prod without Redis.+ agentBuy: (agentId) => getLimiter('agent:buy', { limit: 10, window: '1 h', critical: true }).limit(agentId),// Gas-spending endpoints: 10 redeems per 5 minutes per IPstrict: (key) =>getLimiter('permissions:redeem:strict', { limit: 10, window: '5 m' }).limit(key),@@ -177,7 +240,8 @@ export const limits = {getLimiter('resend-verify:user', { limit: 2, window: '10 m' }).limit(userId),newsletterIp: (ip) => getLimiter('newsletter:ip', { limit: 5, window: '1 h' }).limit(ip),// Voice cloning: expensive ElevenLabs API call — 3 per user per day.- voiceClone: (userId) => getLimiter('voice:clone', { limit: 3, window: '1 d' }).limit(userId),+ // Critical (real per-call cost) — fail closed in prod without Redis.+ voiceClone: (userId) => getLimiter('voice:clone', { limit: 3, window: '1 d', critical: true }).limit(userId),// Persona extraction: Claude API call — 5 per user per day.personaExtract: (userId) =>getLimiter('persona:extract', { limit: 5, window: '1 d' }).limit(userId),diff --git a/api/_lib/siwx-server.js b/api/_lib/siwx-server.jsindex f0c4dbdf8..9ef149adb 100644--- a/api/_lib/siwx-server.js+++ b/api/_lib/siwx-server.js@@ -130,10 +130,22 @@ export async function authenticateSiwx({ req, resourceUrl }) {};}- await siwxStorage.recordNonce(payload.nonce, {+ // Atomically claim the nonce. The earlier checkNonce read is only a fast+ // pre-filter; this INSERT is the authority. Two concurrent requests with+ // the same captured proof both clear validation, but only the winner of+ // the insert is granted — the loser is a replay and re-issues a 402.+ const claimed = await siwxStorage.recordNonce(payload.nonce, {resource: resourceUrl,address: normalizedAddress,});+ if (!claimed) {+ return {+ ok: false,+ status: 402,+ code: 'siwx_nonce_replayed',+ error: 'sign-in proof already used; sign a fresh challenge',+ };+ }return { ok: true, address: normalizedAddress, network: payload.chainId };}diff --git a/api/_lib/siwx-storage.js b/api/_lib/siwx-storage.jsindex 30e5595f5..f4c06c2dd 100644--- a/api/_lib/siwx-storage.js+++ b/api/_lib/siwx-storage.js@@ -96,13 +96,23 @@ async function hasUsedNonce(nonce) {return rows.length > 0;}+// Atomically claim a nonce. Returns true when this call inserted the row (the+// nonce was unused), false when it was already present (replay / lost race).+//+// The `RETURNING` on an `ON CONFLICT DO NOTHING` yields zero rows for the+// loser of a concurrent insert, so callers can gate access on the boolean and+// reject replays without a separate read — the SELECT-then-INSERT pattern has+// a race window (two requests both see "unused", both proceed) that this+// closes. `hasUsedNonce` stays as a cheap pre-check; this is the authority.async function recordNonce(nonce, ctx = {}) {- if (!nonce) return;- await sql`+ if (!nonce) return false;+ const rows = await sql`insert into siwx_nonces (nonce, resource, address, used_at)values (${nonce}, ${ctx.resource || ''}, ${ctx.address || ''}, now())on conflict (nonce) do nothing+ returning nonce`;+ return rows.length > 0;}// Cron helpers exported for api/cron/siwx-gc.js + tests. Both return thediff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex 46ba03cbe..389da4f03 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -28,7 +28,7 @@// helper. Missing keys fall back to env (so a single override doesn't// disable the other networks).-import { cors, error } from './http.js';+import { cors, error, respondError } from './http.js';import { env } from './env.js';import { clientIp } from './rate-limit.js';import { logPaymentEvent } from './x402/audit-log.js';@@ -52,6 +52,7 @@ import {checkCache,enforceRequired,extractIdFromHeader,+ hashPaymentProof,hashRequestPayload,paymentIdentifierExtension,storeResponse,@@ -146,7 +147,9 @@ function buildRequirements({ priceAtomics, networks, resourceUrl, payToOverrideconst solTo = payToOverride?.solana || env.X402_PAY_TO_SOLANA;const bscTo = payToOverride?.bsc || env.X402_PAY_TO_BSC;if (net === NETWORK_BASE_MAINNET && !baseTo) continue;- if (net === NETWORK_SOLANA_MAINNET && !solTo) continue;+ // Solana also needs a fee payer to be co-signable — skip the network+ // rather than advertise an accept the facilitator will reject.+ if (net === NETWORK_SOLANA_MAINNET && (!solTo || !env.X402_FEE_PAYER_SOLANA)) continue;if (net === NETWORK_BSC_MAINNET && !bscTo) continue;const accept = buildAccept(net, priceAtomics, resourceUrl, payToOverride);out.push(accept);@@ -476,11 +479,11 @@ export function paidEndpoint(spec) {if (err instanceof X402Error && err.status === 402) {return send402(res, { ...challenge, error: err.message });}- return error(+ return respondError(res,err.status || 500,err.code || 'internal_error',- err.message,+ err,);}if (res.writableEnded) return;@@ -549,11 +552,11 @@ export function paidEndpoint(spec) {if (err instanceof X402Error && err.status === 402) {return send402(res, { ...challenge, error: err.message });}- return error(+ return respondError(res,err.status || 500,err.code || 'internal_error',- err.message,+ err,);}if (res.writableEnded) return;@@ -602,11 +605,11 @@ export function paidEndpoint(spec) {if (err instanceof X402Error && err.status === 402) {return send402(res, { ...challenge, error: err.message });}- return error(+ return respondError(res,err.status || 500,err.code || 'internal_error',- err.message,+ err,);}if (res.writableEnded) return;@@ -660,8 +663,11 @@ export function paidEndpoint(spec) {url: req.url,body: null,});+ // Bind the idempotency cache to the signed payment proof so a stolen or+ // guessed payment-identifier can't redeem a prior paid response for free.+ const paymentHash = hashPaymentProof(paymentHeader);if (paymentId) {- const lookup = await checkCache({ route, paymentId, payloadHash });+ const lookup = await checkCache({ route, paymentId, payloadHash, paymentHash });if (lookup.kind === 'hit') {return writeCachedResponse(res, lookup.entry);}@@ -670,6 +676,7 @@ export function paidEndpoint(spec) {route,attemptedHash: lookup.attemptedHash,existingHash: lookup.existingHash,+ reason: lookup.reason,});}}@@ -679,7 +686,7 @@ export function paidEndpoint(spec) {verified = await verifyPayment({ paymentHeader, requirements, builderCode });} catch (err) {if (err.status === 402) return send402(res, { ...challenge, error: err.message });- return error(res, err.status || 502, err.code || 'verify_failed', err.message);+ return respondError(res, err.status || 502, err.code || 'verify_failed', err);}let result;@@ -694,7 +701,7 @@ export function paidEndpoint(spec) {if (err instanceof X402Error && err.status === 402) {return send402(res, { ...challenge, error: err.message });}- return error(res, err.status || 500, err.code || 'internal_error', err.message);+ return respondError(res, err.status || 500, err.code || 'internal_error', err);}// Handler may end the response itself (e.g. binary body); only settle +@@ -719,7 +726,7 @@ export function paidEndpoint(spec) {userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,metadata: { error: err.message, code: err.code },});- return error(res, err.status || 502, err.code || 'settle_failed', err.message);+ return respondError(res, err.status || 502, err.code || 'settle_failed', err);}// Record the SIWX grant so the wallet can re-access via signature next@@ -745,7 +752,7 @@ export function paidEndpoint(spec) {metadata: { ttlSeconds: siwx.ttlSeconds ?? null },});} catch (err) {- return error(res, 502, 'siwx_record_failed', err.message);+ return respondError(res, 502, 'siwx_record_failed', err);}}@@ -801,6 +808,7 @@ export function paidEndpoint(spec) {route,paymentId,payloadHash,+ paymentHash,status: 200,body,contentType,diff --git a/api/_lib/x402-solana-confirm.js b/api/_lib/x402-solana-confirm.jsnew file mode 100644index 000000000..8f23e1549--- /dev/null+++ b/api/_lib/x402-solana-confirm.js@@ -0,0 +1,182 @@+// Server-side defense-in-depth for Solana "exact" payments.+//+// The Solana x402 flow puts a fully-signed, base64-serialized transaction in+// `paymentPayload.payload.transaction`; the facilitator (PayAI) simulates it on+// /verify and co-signs + submits it on /settle. Unlike the EVM path — where the+// EIP-712 signature exposes the amount and recipient directly (decodeSignedAmount+// / decodeSignedRecipient in x402-spec.js) — the Solana amount lives inside that+// opaque transaction, so historically we trusted the facilitator entirely.+//+// This module closes that gap WITHOUT an RPC round-trip: it statically decodes+// the signed transaction and reads the SPL-Token TransferChecked instruction the+// buyer actually signed, then asserts it pays at least the required amount, in+// the required mint, to the ATA owned by our payTo. A compromised or buggy+// facilitator therefore cannot get us to deliver a resource for an underpaid or+// mis-routed Solana transfer.+//+// The check is conservative: it only returns a definitive `{ ok: false }` when+// it positively decodes a token transfer that pays us too little (or pays the+// wrong recipient/mint). Anything it can't decode (unexpected payload shape,+// non-standard instruction layout) returns `{ inconclusive: true }` and the+// caller falls back to facilitator trust — so we never reject a valid payment+// over a parsing quirk.++import { PublicKey, VersionedTransaction } from '@solana/web3.js';+import {+ ASSOCIATED_TOKEN_PROGRAM_ID,+ TOKEN_PROGRAM_ID,+ getAssociatedTokenAddressSync,+} from '@solana/spl-token';++// CAIP-2 ids for Solana, inlined (rather than imported from x402-spec.js) to+// keep this module free of a circular import — x402-spec.js imports us.+const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+const NETWORK_SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';++// SPL-Token instruction discriminators (first byte of instruction data).+const IX_TRANSFER = 3;+const IX_TRANSFER_CHECKED = 12;++export function isSolanaNetwork(network) {+ return (+ network === NETWORK_SOLANA_MAINNET ||+ network === NETWORK_SOLANA_DEVNET ||+ network === 'solana'+ );+}++// Normalize a VersionedTransaction's message into a flat list of+// { programId: PublicKey, accountKeys: PublicKey[], data: Uint8Array } so we can+// walk instructions without caring about v0-vs-legacy message internals. Returns+// null when the message can't be normalized.+function readInstructions(message) {+ const keys = message.staticAccountKeys || message.accountKeys;+ if (!Array.isArray(keys) || keys.length === 0) return null;+ const compiled = message.compiledInstructions || message.instructions;+ if (!Array.isArray(compiled)) return null;+ const out = [];+ for (const ix of compiled) {+ const programIdIndex = ix.programIdIndex;+ const accountIndexes = ix.accountKeyIndexes || ix.accounts;+ const data = ix.data;+ if (typeof programIdIndex !== 'number' || !accountIndexes) continue;+ const programId = keys[programIdIndex];+ if (!programId) continue;+ const accountKeys = [];+ for (const i of accountIndexes) {+ if (keys[i]) accountKeys.push(keys[i]);+ }+ // Legacy messages carry base58-encoded instruction data as a string; v0+ // compiled instructions carry a Uint8Array. Only the latter is parseable+ // here, and that's what our Solana builder emits.+ out.push({ programId, accountKeys, data: data instanceof Uint8Array ? data : null });+ }+ return out;+}++function readU64LE(data, offset) {+ return Buffer.from(data.buffer, data.byteOffset + offset, 8).readBigUInt64LE(0);+}++// Decode the SPL-Token transfers in a signed Solana payment transaction and sum+// the atomic amount routed to the receiver ATA owned by `payTo` for `asset`.+// Returns { ok, reason?, paidToPayTo, sawTokenTransfer }.+function decodeSolanaTransfer({ transactionBase64, asset, payTo }) {+ let tx;+ try {+ tx = VersionedTransaction.deserialize(Buffer.from(transactionBase64, 'base64'));+ } catch {+ return { inconclusive: true, reason: 'undeserializable_transaction' };+ }+ const instructions = readInstructions(tx.message);+ if (!instructions) return { inconclusive: true, reason: 'unreadable_message' };++ let mint;+ let receiverAta;+ try {+ mint = new PublicKey(asset);+ // allowOwnerOffCurve=true so a PDA payTo never throws here; for a normal+ // wallet this yields the same ATA the buyer-side builder derived.+ receiverAta = getAssociatedTokenAddressSync(+ mint,+ new PublicKey(payTo),+ true,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ } catch {+ return { inconclusive: true, reason: 'bad_asset_or_payto' };+ }+ const receiverAtaStr = receiverAta.toBase58();+ const mintStr = mint.toBase58();++ let paidToPayTo = 0n;+ let sawTokenTransfer = false;++ for (const ix of instructions) {+ if (!ix.programId.equals(TOKEN_PROGRAM_ID) || !ix.data || ix.data.length < 1) continue;+ const kind = ix.data[0];++ if (kind === IX_TRANSFER_CHECKED) {+ // accounts: [source, mint, destination, owner, ...signers]+ // data: [12, amount(u64 LE), decimals(u8)]+ if (ix.accountKeys.length < 3 || ix.data.length < 10) continue;+ sawTokenTransfer = true;+ const ixMint = ix.accountKeys[1].toBase58();+ const ixDest = ix.accountKeys[2].toBase58();+ if (ixDest === receiverAtaStr && ixMint === mintStr) {+ paidToPayTo += readU64LE(ix.data, 1);+ }+ } else if (kind === IX_TRANSFER) {+ // accounts: [source, destination, owner]; data: [3, amount(u64 LE)].+ // No mint in the instruction — a destination match implies our mint+ // because the receiver ATA is mint-specific.+ if (ix.accountKeys.length < 2 || ix.data.length < 9) continue;+ sawTokenTransfer = true;+ const ixDest = ix.accountKeys[1].toBase58();+ if (ixDest === receiverAtaStr) {+ paidToPayTo += readU64LE(ix.data, 1);+ }+ }+ }++ return { ok: true, paidToPayTo, sawTokenTransfer };+}++// Public entry point used by verifyPayment. Returns:+// { confirmed: true } — signed tx pays >= required to payTo.+// { confirmed: false, reason } — definitively underpaid / mis-routed.+// { inconclusive: true, reason } — couldn't decode; defer to facilitator.+export function confirmSolanaPayment({ paymentPayload, requirement }) {+ const transactionBase64 = paymentPayload?.payload?.transaction;+ if (typeof transactionBase64 !== 'string' || !transactionBase64) {+ return { inconclusive: true, reason: 'no_serialized_transaction' };+ }+ let required;+ try {+ required = BigInt(requirement.amount);+ } catch {+ return { inconclusive: true, reason: 'bad_requirement_amount' };+ }++ const decoded = decodeSolanaTransfer({+ transactionBase64,+ asset: requirement.asset,+ payTo: requirement.payTo,+ });+ if (decoded.inconclusive) return decoded;++ // We positively decoded the token transfers but none (or too little) reached+ // our payTo — only treat as a hard failure when we actually saw a transfer+ // to parse; an empty/odd instruction set stays inconclusive.+ if (decoded.paidToPayTo < required) {+ if (!decoded.sawTokenTransfer) {+ return { inconclusive: true, reason: 'no_token_transfer_found' };+ }+ return {+ confirmed: false,+ reason: `signed Solana transfer to payTo totals ${decoded.paidToPayTo.toString()} below required ${required.toString()}`,+ };+ }+ return { confirmed: true, paidToPayTo: decoded.paidToPayTo.toString() };+}diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex a727c6b67..8305bfa22 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -43,6 +43,7 @@ import {import { env } from './env.js';import { X402Error } from './x402-errors.js';+import { confirmSolanaPayment, isSolanaNetwork } from './x402-solana-confirm.js';import {PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC,settleDirectPayment,@@ -144,10 +145,15 @@ function pushEvmAccepts(out, accept) {//// In v2, `resource` / `description` / `mimeType` are top-level on the 402 body// (not per-accepts), and the price field is `amount` (not `maxAmountRequired`).-export function paymentRequirements(resourceUrl) {+// `amount` (optional) overrides the per-call price advertised in every accept+// entry. The MCP server passes the per-tool price derived from priceFor() so the+// 402 challenge advertises exactly what the settle path will charge for the+// called tool, instead of a single flat X402_MAX_AMOUNT_REQUIRED. Falls back to+// the flat env default when omitted (non-MCP paid endpoints, free-tool probes).+export function paymentRequirements(resourceUrl, { amount } = {}) {const common = {scheme: 'exact',- amount: env.X402_MAX_AMOUNT_REQUIRED,+ amount: amount != null ? String(amount) : env.X402_MAX_AMOUNT_REQUIRED,maxTimeoutSeconds: 60,...(resourceUrl ? { resource: resourceUrl } : {}),};@@ -595,6 +601,38 @@ function decodeSignedAmount(paymentPayload) {return null;}+// Extract the recipient the payer actually signed over, so we can confirm the+// funds are bound to OUR `requirement.payTo` and not an attacker address the+// facilitator might (if compromised/buggy) accept. Returns a lowercase hex+// string, or null when the recipient can't be located without trusting the+// facilitator (e.g. Solana SPL transfers).+//+// Defense-in-depth: the EIP-712 signature commits to `to`, so a payment whose+// signed recipient differs from the offered payTo is invalid regardless of+// what /verify returns.+function decodeSignedRecipient(paymentPayload) {+ const inner = paymentPayload?.payload;+ if (!inner || typeof inner !== 'object') return null;+ // EIP-3009 transferWithAuthorization — `authorization.to` is signed.+ if (inner.authorization && typeof inner.authorization === 'object') {+ const to = inner.authorization.to;+ if (typeof to === 'string' && to) return to.toLowerCase();+ }+ // Permit2 — the spend recipient travels in the witness/transfer details.+ // Clients shape this a few ways; check the known locations and bail out+ // (null = facilitator-trusted) rather than guess when none are present.+ if (inner.permit2Authorization && typeof inner.permit2Authorization === 'object') {+ const p2 = inner.permit2Authorization;+ const candidate =+ p2.transferDetails?.to ??+ p2.witness?.to ??+ p2.spender ??+ p2.to;+ if (typeof candidate === 'string' && candidate) return candidate.toLowerCase();+ }+ return null;+}+// Build a deterministic idempotency key per (verified-payment-payload, requirement).// Idempotent retries of /settle (timeouts, transient 5xx) will hash to the same// key and let the facilitator de-duplicate, preventing double-settlement. Hashing@@ -670,6 +708,20 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode });}}+ // Defense-in-depth recipient check. The EIP-712 signature commits to the+ // recipient, so confirm the payer signed funds to OUR payTo — a compromised+ // facilitator can't redirect a wrong-recipient authorization past us. Null+ // (Solana SPL / unknown shape) falls through to facilitator trust.+ const signedRecipient = decodeSignedRecipient(paymentPayload);+ if (signedRecipient !== null && requirement.payTo) {+ if (signedRecipient !== String(requirement.payTo).toLowerCase()) {+ throw new X402Error(+ 'invalid_payment',+ `signed payment recipient ${signedRecipient} does not match required payTo ${requirement.payTo}`,+ 402,+ );+ }+ }const config = facilitatorFor(requirement.network);if (config.direct) {const directVerified = await verifyDirectPayment({ paymentPayload, requirement });@@ -710,6 +762,19 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }502,);}+ // Solana defense-in-depth: the amount/recipient live inside the opaque+ // serialized transaction, so the facilitator was historically the only+ // guard. Statically decode the signed SPL transfer and reject if it pays+ // us less than required (or to the wrong ATA/mint) — symmetric with the+ // EVM signed-amount/recipient checks above. Undecodable payloads stay+ // facilitator-trusted (inconclusive) so a parsing quirk never blocks a+ // valid payment.+ if (isSolanaNetwork(requirement.network)) {+ const confirm = confirmSolanaPayment({ paymentPayload, requirement });+ if (confirm.confirmed === false) {+ throw new X402Error('invalid_payment', confirm.reason, 402);+ }+ }return { paymentPayload, requirement, payer: result.payer || null };}diff --git a/api/_lib/x402/a2a-server.js b/api/_lib/x402/a2a-server.jsindex e3ba18145..14c94a053 100644--- a/api/_lib/x402/a2a-server.js+++ b/api/_lib/x402/a2a-server.js@@ -43,6 +43,17 @@ import {} from '../x402-spec.js';import { declareBuilderCodeExtension } from '../x402-builder-code.js';import { PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC } from '../x402-bsc-direct.js';+import {+ get as idemGet,+ set as idemSet,+ hashPaymentProof,+} from './idempotency-cache.js';++// Idempotency TTL for the A2A leg, mirroring the HTTP payment-identifier cache.+function a2aIdempotencyTtl() {+ const n = Number.parseInt(env.X402_IDEMPOTENCY_TTL_SECONDS, 10);+ return Number.isFinite(n) && n > 0 ? n : 3600;+}export const A2A_X402_EXTENSION_URI = 'https://github.com/google-a2a/a2a-x402/v0.1';export const A2A_EXTENSIONS_HEADER = 'X-A2A-Extensions';@@ -113,7 +124,9 @@ function buildAccepts({ priceAtomics, networks, resourceUrl, payToOverride }) {const solTo = payToOverride?.solana || env.X402_PAY_TO_SOLANA;const bscTo = payToOverride?.bsc || env.X402_PAY_TO_BSC;if (net === NETWORK_BASE_MAINNET && !baseTo) continue;- if (net === NETWORK_SOLANA_MAINNET && !solTo) continue;+ // Solana also needs a fee payer to be co-signable — skip the network+ // rather than advertise an accept the facilitator will reject.+ if (net === NETWORK_SOLANA_MAINNET && (!solTo || !env.X402_FEE_PAYER_SOLANA)) continue;if (net === NETWORK_BSC_MAINNET && !bscTo) continue;const accept = buildAccept(net, priceAtomics, resourceUrl, payToOverride);out.push(accept);@@ -334,6 +347,22 @@ export async function handleA2ARequest({const builderCode = builderCodeForServices(services);const paymentHeader = encodePaymentHeaderFromPayload(payload);+ // Proof-bound idempotency. The A2A leg has no payment-identifier header, so+ // we key on a hash of the signed payment proof itself: a resubmission of the+ // SAME payment (network blip, client retry, or a deliberate replay) returns+ // the cached completed task instead of re-verifying, re-settling, and+ // re-running the handler. Only the original payer can reproduce the exact+ // proof, so this can't be abused to replay someone else's payment.+ const paymentHash = hashPaymentProof(paymentHeader);+ if (paymentHash) {+ try {+ const cached = await idemGet(resourceUrl, paymentHash);+ if (cached?.task) return jsonrpcResult(reqId, cached.task);+ } catch {+ /* cache read is best-effort — fall through to the live path */+ }+ }+// Reconstruct the same accepts list we advertised on the first leg so the// facilitator sees the resource/network/payTo trio it expects.let requirements;@@ -515,10 +544,24 @@ export async function handleA2ARequest({},});- return jsonrpcResult(- reqId,- task({ id: taskId, state: 'completed', message: completedMessage, artifacts }),- );+ const completedTask = task({+ id: taskId,+ state: 'completed',+ message: completedMessage,+ artifacts,+ });++ // Cache the completed task against the payment proof so a resubmission of+ // the same proof replays this result instead of double-charging / re-running.+ if (paymentHash) {+ try {+ await idemSet(resourceUrl, paymentHash, { task: completedTask }, a2aIdempotencyTtl());+ } catch {+ /* cache write is best-effort — the payment already settled on-chain */+ }+ }++ return jsonrpcResult(reqId, completedTask);}// Compose a Vercel-style HTTP handler around `handleA2ARequest`. POSTs arediff --git a/api/_lib/x402/access-control.js b/api/_lib/x402/access-control.jsindex b69f19ce8..2de76a0c6 100644--- a/api/_lib/x402/access-control.js+++ b/api/_lib/x402/access-control.js@@ -105,7 +105,11 @@ export function installAccessControl({ requiredScope, resolveCaller } = {}) {route,reason: 'Invalid API key',granted: false,- meta: { ...meta, key_prefix: apiKey.slice(0, 16) },+ // Log only the non-secret namespace prefix on a FAILED attempt+ // — a valid key's `x402_live_` prefix is fine, but logging 16+ // chars of an arbitrary probed key persists secret bytes. The+ // `x402_live_` / `x402_test_` namespace is 10 chars.+ meta: { ...meta, key_namespace: apiKey.slice(0, 10) },});return { abort: true, status: 403, reason: 'Invalid API key' };}diff --git a/api/_lib/x402/auth-hints.js b/api/_lib/x402/auth-hints.jsindex cb2819f22..a024adf41 100644--- a/api/_lib/x402/auth-hints.js+++ b/api/_lib/x402/auth-hints.js@@ -256,11 +256,18 @@ export async function verifyAuthHintsSiwx({ req, resourceUrl }) {const address = normalizeAddress(payload.chainId, verification.address);- // Burn the nonce so the proof can't be replayed against this endpoint.- await siwxStorage.recordNonce(payload.nonce, {+ // Atomically claim the nonce so the proof can't be replayed against this+ // endpoint. The claim is the authoritative gate, not the earlier+ // checkNonce read: under concurrency two requests bearing the same proof+ // both pass validation, but only one wins the INSERT — the loser is a+ // replay and must be rejected here rather than granted free access.+ const claimed = await siwxStorage.recordNonce(payload.nonce, {resource: resourceUrl,address,});+ if (!claimed) {+ return { ok: false, reason: 'siwx_nonce_replayed' };+ }return {ok: true,diff --git a/api/_lib/x402/idempotency-cache.js b/api/_lib/x402/idempotency-cache.jsindex 5688bd801..5537376d9 100644--- a/api/_lib/x402/idempotency-cache.js+++ b/api/_lib/x402/idempotency-cache.js@@ -83,6 +83,18 @@ export function hashRequestPayload({ method, url, body }) {return h.digest('hex');}+// Hash of the signed X-PAYMENT proof. The idempotency id is a client-chosen+// label and proves nothing on its own — binding the cache entry to this hash+// means a replay only serves the cached response to a caller presenting the+// SAME signed payment (which only the original payer can produce). A caller who+// merely learned or guessed the id, but holds a different/forged payment,+// hashes differently and is denied the cached body. Returns null when there's+// no header to hash.+export function hashPaymentProof(paymentHeader) {+ if (!paymentHeader) return null;+ return createHash('sha256').update(String(paymentHeader)).digest('hex');+}+// Read a cached response by route + paymentId. Returns null if the key is// missing or expired. The returned shape is whatever `set()` was given.export async function get(route, paymentId) {diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.jsindex e68261419..2254b0c9b 100644--- a/api/_lib/x402/payment-identifier-server.js+++ b/api/_lib/x402/payment-identifier-server.js@@ -90,12 +90,31 @@ export function enforceRequired({ paymentHeader, required }) {// { kind: 'hit', entry } — replay entry; skip settle.// { kind: 'conflict', existingHash, attemptedHash } — same id, different payload.//-// When `payloadHash` is omitted we treat a cache entry with a non-null-// stored hash as a conflict — pass the hash whenever you can compute it.-export async function checkCache({ route, paymentId, payloadHash }) {+// Security: a cache hit MUST be bound to the signed payment proof, not just the+// client-chosen id. We require `paymentHash` (sha256 of the X-PAYMENT header)+// to match the hash stored when the entry was written — only the original+// payer can reproduce that exact signed proof. A caller who knows the id but+// presents a different payment hashes differently and gets a `conflict`, never+// the cached body. `payloadHash` (request method+url) is an additional binding.+//+// When `payloadHash`/`paymentHash` is omitted we treat a cache entry with a+// non-null stored hash as a conflict — pass both whenever you can compute them.+export async function checkCache({ route, paymentId, payloadHash, paymentHash }) {if (!paymentId) return { kind: 'miss' };const entry = await cache.get(route, paymentId);if (!entry) return { kind: 'miss' };+ // Payment-proof binding: a stored entry written with a paymentHash only+ // replays to a caller presenting the same signed proof. A mismatch (or a+ // caller that omits the proof against a proof-bound entry) is a conflict —+ // this is the guard against a stolen/guessed id being redeemed for free.+ if (entry.paymentHash && entry.paymentHash !== (paymentHash || null)) {+ return {+ kind: 'conflict',+ existingHash: entry.payloadHash || null,+ attemptedHash: payloadHash || null,+ reason: 'payment_proof_mismatch',+ };+ }// Stored hash may be null on legacy/unknown-payload entries; treat// "no stored hash" as compatible with any incoming request so older// cached entries don't suddenly start 409ing.@@ -116,6 +135,7 @@ export async function storeResponse({route,paymentId,payloadHash,+ paymentHash,status,body,contentType,@@ -133,6 +153,9 @@ export async function storeResponse({contentType,paymentResponseHeader,payloadHash: payloadHash || null,+ // Bind the entry to the signed payment proof so only the original+ // payer (who can reproduce the exact X-PAYMENT) can replay it.+ paymentHash: paymentHash || null,storedAt: new Date().toISOString(),},ttl,@@ -154,18 +177,25 @@ export function writeCachedResponse(res, entry) {res.end(entry.body ?? '');}-// Write a 409 Conflict explaining the payload mismatch.-export function writeConflict(res, { route, attemptedHash, existingHash }) {+// Write a 409 Conflict explaining the mismatch. `reason` distinguishes a+// request-payload mismatch (same id reused for a different call) from a+// payment-proof mismatch (a stolen/guessed id presented with a different+// payment) — the latter is the security-relevant denial.+export function writeConflict(res, { route, attemptedHash, existingHash, reason }) {res.statusCode = 409;res.setHeader('content-type', 'application/json; charset=utf-8');res.setHeader('cache-control', 'no-store');res.setHeader('x-x402-idempotent', 'conflict');+ const description =+ reason === 'payment_proof_mismatch'+ ? 'this payment-identifier was already used by a different payment; ' ++ 'generate a fresh id and pay again'+ : 'a different request body was already processed under this payment-identifier; ' ++ 'either retry the original payload or generate a new id';res.end(JSON.stringify({error: 'payment_identifier_conflict',- error_description:- 'a different request body was already processed under this payment-identifier; ' +- 'either retry the original payload or generate a new id',+ error_description: description,route,attemptedPayloadHash: attemptedHash,existingPayloadHash: existingHash,@@ -173,5 +203,5 @@ export function writeConflict(res, { route, attemptedHash, existingHash }) {);}-export { hashRequestPayload } from './idempotency-cache.js';+export { hashRequestPayload, hashPaymentProof } from './idempotency-cache.js';export const ttlSeconds = envTtl;diff --git a/api/_mcp/auth.js b/api/_mcp/auth.jsindex 36bd679f1..a568f00f9 100644--- a/api/_mcp/auth.js+++ b/api/_mcp/auth.js@@ -54,7 +54,13 @@ export function sendJsonRpcError(res, id, code, message, data) {}// Returns { auth, x402Ctx } on success, or null if a response was already sent.-export async function authenticateRequest(req, res) {+//+// `opts.x402Amount` (atomic-unit string | null) is the per-tool price for the+// tools/call being made. When provided it overrides the flat env price in the+// 402 challenge AND in the requirements used to verify the X-PAYMENT, so the+// advertised price and the charged price agree. null = use the flat default+// (initialize / tools/list / free tools / mixed batches).+export async function authenticateRequest(req, res, { x402Amount } = {}) {const bearer = extractBearer(req);const paymentHeader = req.headers['x-payment'];@@ -68,7 +74,10 @@ export async function authenticateRequest(req, res) {}const resourceUrl = resolveResourceUrl(req, '/api/mcp');- const requirements = paymentRequirements(resourceUrl);+ const requirements = paymentRequirements(+ resourceUrl,+ x402Amount != null ? { amount: x402Amount } : {},+ );if (paymentHeader) {try {@@ -97,6 +106,11 @@ export async function authenticateRequest(req, res) {scope: '',source: 'x402',payer: x402Ctx.payer,+ // The HTTP layer verified this X-PAYMENT against the per-tool+ // price (paymentRequirements amount === x402AmountForTool). The+ // dispatcher reads this to avoid double-billing the caller with a+ // redundant pump-agent-payments subscription demand.+ x402Paid: true,},x402Ctx,};diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.jsindex a4697e544..ede8e16b9 100644--- a/api/_mcp/dispatch.js+++ b/api/_mcp/dispatch.js@@ -2,6 +2,7 @@ import { hasScope } from '../_lib/auth.js';import { recordEvent, logger } from '../_lib/usage.js';import { priceFor, findActiveSubscription, resolveBillingMint } from '../_lib/pump-pricing.js';import { declareMcpDiscovery } from '../_lib/x402/bazaar-helpers.js';+import { sanitizeToolError } from '../_lib/mcp-error-sanitize.js';import { TOOL_CATALOG, TOOLS } from './catalog.js';export const PROTOCOL_VERSION = '2025-06-18';@@ -130,12 +131,18 @@ async function onToolCall(params, auth, started) {throw rpcError(-32602, `invalid params for ${name}: ${detail}`);}- // Pump-agent-payments gate. Free tools and paid-bearer-authenticated users- // (existing subscription plans) bypass. x402 callers and anonymous payers- // must either supply X-PAYMENT (handled at the HTTP layer above) or have- // an active pump-agent-payments subscription window for this tool.+ // Payment gate for priced tools called by anonymous x402 principals.+ //+ // An x402 principal reaches here only after the HTTP layer verified an+ // X-PAYMENT against this tool's per-tool price (auth.x402Paid). That single+ // pay-per-call payment satisfies the charge — we do NOT additionally demand a+ // pump-agent-payments subscription, which would double-bill a caller who just+ // paid. The subscription path stays as an ALTERNATIVE for x402 principals who+ // did not pay per-call (auth.x402Paid falsy): if they hold an active+ // pump-agent-payments window for this tool we honor it, otherwise we 402 with+ // the subscription challenge. This keeps advertised price == charged price.const price = priceFor(name);- if (price && auth.source === 'x402') {+ if (price && auth.source === 'x402' && !auth.x402Paid) {const billingMint = resolveBillingMint();const payerWallet = args.payer_wallet || auth.payer || null;if (billingMint && payerWallet) {@@ -157,6 +164,16 @@ async function onToolCall(params, auth, started) {});}auth.subscription = sub;+ } else if (billingMint) {+ // A price is advertised and billing is configured, but the caller gave+ // no wallet to match a subscription against and did not pay per-call.+ throw rpcError(-32402, 'payment required for this tool', {+ scheme: 'pump-agent-payments',+ tool: name,+ amount_usdc: price.amount_usdc,+ recipient_mint: billingMint,+ prep_endpoint: '/api/pump/accept-payment-prep',+ });}}@@ -187,13 +204,12 @@ async function onToolCall(params, auth, started) {// postgres SQL states (e.g. '42P01') — sanitize those rather than leaking them.if (err.code && typeof err.code === 'number') throw err;// Framework convention: tool errors go in result.isError, not rpc error.- // Detect postgres driver errors by their severity field and suppress internals.- if (err.severity !== undefined || err.schema !== undefined) {- log.error('tool_db_error', { tool: name, pg_code: err.code });- return { content: [{ type: 'text', text: 'Error: internal error' }], isError: true };- }+ // Shared sanitizer suppresses pg/driver internals + internal hostnames,+ // logs full detail to stderr with a log id, and passes safe+ // handler-authored messages through unchanged.+ const { message } = sanitizeToolError(err, { tool: name, server: 'mcp', log });return {- content: [{ type: 'text', text: `Error: ${err.message || 'tool call failed'}` }],+ content: [{ type: 'text', text: `Error: ${message}` }],isError: true,};}diff --git a/api/admin/pump-cron-health.js b/api/admin/pump-cron-health.jsindex 69236223d..f1600e72a 100644--- a/api/admin/pump-cron-health.js+++ b/api/admin/pump-cron-health.js@@ -5,20 +5,22 @@// + admin plan, OR `Bearer $CRON_SECRET` for monitoring scrapers.import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { requireAdmin } from '../_lib/admin.js';+import { cors, json, method, wrap } from '../_lib/http.js';import { env } from '../_lib/env.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;+ // Monitoring scrapers authenticate with the cron secret; everyone else must+ // be a real admin. The previous `user.plan === 'admin'` check was dead — there+ // is no 'admin' plan (free|pro|team|enterprise) — so it rejected every admin.const auth = req.headers.authorization || '';const isCron = env.CRON_SECRET && auth === `Bearer ${env.CRON_SECRET}`;- const user = isCron ? null : await getSessionUser(req);if (!isCron) {- if (!user) return error(res, 401, 'unauthorized', 'sign in required');- if (user.plan !== 'admin') return error(res, 403, 'forbidden', 'admin only');+ const admin = await requireAdmin(req, res);+ if (!admin) return;}const [distribute, buyback, stats, trades] = await Promise.all([diff --git a/api/agent-economy/status.js b/api/agent-economy/status.jsindex b11986cf5..5b3a512c4 100644--- a/api/agent-economy/status.js+++ b/api/agent-economy/status.js@@ -17,12 +17,13 @@ import {isValidPubkey,explorerAccountUrl,} from '../_lib/avatar-wallet.js';-import { cors, wrap } from '../_lib/http.js';+import { cors, method, wrap } from '../_lib/http.js';const RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;const cfgA = avatarWalletConfig();const conn = getConnection(RPC_URL);diff --git a/api/agent-economy/transact.js b/api/agent-economy/transact.jsindex 3234b169d..061add90f 100644--- a/api/agent-economy/transact.js+++ b/api/agent-economy/transact.js@@ -79,7 +79,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const rl = await limits.authIp(clientIp(req));+ const rl = await limits.agentEconomyIp(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');const body = parse(bodySchema, await readJson(req));@@ -108,7 +108,13 @@ export default wrap(async (req, res) => {);const balance = await getSolBalance(connection, fromKeypair.publicKey);- if (balance >= lamports + FEE_BUFFER_LAMPORTS) {+ // Global daily spend ceiling — consumed only when we're about to+ // actually pay, so non-paying requests (unconfigured wallet, empty+ // balance, unknown service) can't exhaust the demo budget and DoS it.+ const spendRl = await limits.agentEconomyGlobal();+ if (!spendRl.success) {+ txResult = { error: 'rate_limited', message: 'daily demo transaction budget reached — try again tomorrow.' };+ } else if (balance >= lamports + FEE_BUFFER_LAMPORTS) {const memo = `three.ws agent-economy · ${svc.name}`;const signature = await sendSol({connection,diff --git a/api/api-keys.js b/api/api-keys.jsindex 0b1c4fcf6..968384c6b 100644--- a/api/api-keys.js+++ b/api/api-keys.js@@ -3,6 +3,7 @@ import { sql } from './_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from './_lib/auth.js';import { cors, json, error, wrap, method, readJson } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';+import { requireCsrf } from './_lib/csrf.js';import { parse } from './_lib/validate.js';import { z } from 'zod';@@ -42,7 +43,11 @@ export default wrap(async (req, res) => {return json(res, 200, { data: rows });}- // POST — create+ // POST — create. CSRF-guard the cookie-authenticated path so a logged-in+ // user can't be tricked into minting a key cross-site. requireCsrf is a+ // no-op for Bearer callers (the token itself is proof of intent).+ if (!(await requireCsrf(req, res, userId))) return;+const body = parse(createSchema, await readJson(req));// Validate requested scopes are all knowndiff --git a/api/auth/[action].js b/api/auth/[action].jsindex 7d7ea12b8..1e929e286 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -21,6 +21,11 @@ import { z } from 'zod';const APP_ORIGIN = process.env.APP_ORIGIN || 'https://three.ws';+// Fixed bcrypt hash (cost 11) of a throwaway string — NOT a real credential.+// Compared against when a login targets a non-existent account so the bcrypt+// cost is paid either way and login timing can't be used to enumerate users.+const DUMMY_PASSWORD_HASH = '$2a$11$lbeuSxk2uZlrn87LKkZBq.2zXLxDFb6PSJ525DddtFq7wVLzVCK0W';+// ── login ─────────────────────────────────────────────────────────────────────async function handleLogin(req, res) {@@ -35,7 +40,13 @@ async function handleLogin(req, res) {? await sql`select id, email, password_hash, display_name, plan, avatar_url, referral_code from users where email = ${body.email} and deleted_at is null limit 1`: await sql`select id, email, password_hash, display_name, plan, avatar_url, referral_code from users where display_name ilike ${body.email} and deleted_at is null limit 1`;const user = rows[0];- const ok = user && (await verifyPassword(body.password, user.password_hash));+ // Always run a bcrypt compare, even when the account doesn't exist, so the+ // response time doesn't reveal whether the email/username is registered.+ // The dummy hash is a fixed cost-11 hash of a throwaway string (never a+ // real credential); comparing against it for unknown users equalizes timing.+ const hashToCheck = user?.password_hash || DUMMY_PASSWORD_HASH;+ const passwordOk = await verifyPassword(body.password, hashToCheck);+ const ok = Boolean(user) && passwordOk;if (!ok) return error(res, 401, 'invalid_credentials', 'invalid username/email or password');await destroySession(req);const token = await createSession({ userId: user.id, userAgent: req.headers['user-agent'], ip });diff --git a/api/auth/wallet/[action].js b/api/auth/wallet/[action].jsdeleted file mode 100644index a1973e21c..000000000--- a/api/auth/wallet/[action].js+++ /dev/null@@ -1,117 +0,0 @@-// Consolidated wallet link/unlink endpoints.--import { verifyMessage, getAddress } from 'ethers';-import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { logAudit } from '../../_lib/audit.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { env } from '../../_lib/env.js';-import { parse } from '../../_lib/validate.js';-import { parseSiweMessage } from '../../_lib/siwe.js';--// ── link ──────────────────────────────────────────────────────────────────────--const linkSchema = z.object({ message: z.string().min(64).max(4000), signature: z.string().regex(/^0x[a-fA-F0-9]+$/) });--async function handleLink(req, res) {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.walletLink(String(user.id));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');-- const body = parse(linkSchema, await readJson(req));- const fields = parseSiweMessage(body.message);- if (!fields) return error(res, 400, 'invalid_message', 'malformed SIWE message');-- const appOrigin = env.APP_ORIGIN;- const appHost = new URL(appOrigin).host;- const vercelHost = process.env.VERCEL_URL || null;- const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));- if (!allowedHosts.has(fields.domain)) return error(res, 400, 'invalid_domain', `domain must be ${appHost}`);-- try {- const u = new URL(fields.uri);- const allowedOrigins = new Set([appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean));- if (!allowedOrigins.has(u.origin)) return error(res, 400, 'invalid_uri', 'uri origin mismatch');- } catch { return error(res, 400, 'invalid_uri', 'uri not a valid URL'); }-- const now = Date.now();- if (fields.expirationTime && Date.parse(fields.expirationTime) < now) return error(res, 400, 'expired', 'message expired');- if (fields.notBefore && Date.parse(fields.notBefore) > now) return error(res, 400, 'not_yet_valid', 'message not yet valid');-- const [nonceRow] = await sql`select nonce, expires_at, consumed_at from siwe_nonces where nonce = ${fields.nonce} limit 1`;- if (!nonceRow) return error(res, 400, 'invalid_nonce', 'unknown nonce');- if (nonceRow.consumed_at) return error(res, 400, 'nonce_reused', 'nonce already used');- if (new Date(nonceRow.expires_at) < new Date()) return error(res, 400, 'nonce_expired', 'nonce expired');-- let recovered;- try { recovered = verifyMessage(body.message, body.signature); } catch { return error(res, 401, 'invalid_signature', 'signature verification failed'); }- let claimed;- try { claimed = getAddress(fields.address); } catch { return error(res, 400, 'invalid_address', 'address not checksummed correctly'); }- if (recovered.toLowerCase() !== claimed.toLowerCase()) return error(res, 401, 'invalid_signature', 'signer does not match address');-- const burned = await sql`update siwe_nonces set consumed_at = now(), address = ${claimed.toLowerCase()} where nonce = ${fields.nonce} and consumed_at is null returning nonce`;- if (!burned[0]) return error(res, 400, 'nonce_reused', 'nonce already used');-- const addrLower = claimed.toLowerCase();- const [existing] = await sql`select user_id from user_wallets where address = ${addrLower} limit 1`;- if (existing) {- if (String(existing.user_id) !== String(user.id)) return error(res, 409, 'wallet_taken', 'wallet already linked to another account');- return json(res, 200, { ok: true, address: claimed, chainId: fields.chainId || null });- }-- await sql`insert into user_wallets (user_id, address, chain_id, is_primary) values (${user.id}, ${addrLower}, ${fields.chainId || null}, false)`;- return json(res, 200, { ok: true, address: claimed, chainId: fields.chainId || null });-}--// ── unlink ────────────────────────────────────────────────────────────────────--const unlinkSchema = z.object({ address: z.string().regex(/^0x[a-fA-F0-9]{40}$/) });--async function handleUnlink(req, res) {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');-- const body = parse(unlinkSchema, await readJson(req));- const addrLower = body.address.toLowerCase();-- const [walletRow] = await sql`select address, is_primary from user_wallets where user_id = ${user.id} and address = ${addrLower} limit 1`;- if (!walletRow) return error(res, 404, 'not_found', 'wallet not linked to your account');-- const [userRow] = await sql`select password_hash from users where id = ${user.id} limit 1`;- if (!userRow?.password_hash) {- const [{ count }] = await sql`select count(*)::int as count from user_wallets where user_id = ${user.id}`;- if (count <= 1) return error(res, 409, 'last_auth_method', 'cannot remove your only authentication method');- }-- if (walletRow.is_primary) {- await sql`update user_wallets set is_primary = true where user_id = ${user.id} and address != ${addrLower} and address = (select address from user_wallets where user_id = ${user.id} and address != ${addrLower} order by last_used_at desc nulls last limit 1)`;- }-- await sql`delete from user_wallets where user_id = ${user.id} and address = ${addrLower}`;- logAudit({ userId: user.id, action: 'unlink_wallet', resourceId: addrLower });- return json(res, 200, { ok: true });-}--// ── dispatcher ────────────────────────────────────────────────────────────────--const DISPATCH = { link: handleLink, unlink: handleUnlink };--export default wrap(async (req, res) => {- const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();- const fn = DISPATCH[action];- if (!fn) return error(res, 404, 'not_found', `unknown wallet action: ${action}`);- return fn(req, res);-});diff --git a/api/auth/wallets/[action].js b/api/auth/wallets/[action].jsindex 579785f07..e208d1196 100644--- a/api/auth/wallets/[action].js+++ b/api/auth/wallets/[action].js@@ -256,18 +256,27 @@ async function handleCheck(req, res) {// signature to the active session's user.async function handleNonce(req, res) {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;const session = await getSessionUser(req);if (!session) return error(res, 401, 'unauthorized', 'sign in required');- const { address, chainId } = parse(nonceBody, await readJson(req));-- const nonce = issueNonce(session.id);-const appOrigin = env.APP_ORIGIN;const domain = new URL(appOrigin).host;+ const nonce = issueNonce(session.id);++ // GET: bare per-user link nonce for the connect-button component, which+ // builds the SIWE message client-side. The security of linking rests on this+ // nonce being bound to the current session (handleLinkWallet validates it via+ // consumeNonce(nonce, session.id)) and living in a store separate from the+ // login nonce pool — so a captured *login* signature can't be replayed here.+ if (req.method === 'GET') {+ return json(res, 200, { nonce, domain, uri: appOrigin, ttl: NONCE_TTL_SEC });+ }++ const { address, chainId } = parse(nonceBody, await readJson(req));+const issuedAt = new Date().toISOString();const expirationTime = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();diff --git a/api/billing/withdrawals/index.js b/api/billing/withdrawals/index.jsindex f9d6d0ec6..1aa8907df 100644--- a/api/billing/withdrawals/index.js+++ b/api/billing/withdrawals/index.js@@ -93,35 +93,47 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 404, 'not_found', 'agent not found');}- // Check available balance (earned minus in-flight withdrawals)- const [balance] = await sql`- select- coalesce(sum(re.net_amount), 0)::bigint as earned,- (- select coalesce(sum(w2.amount), 0)::bigint- from agent_withdrawals w2- where w2.user_id = ${user.id}- and w2.status in ('pending', 'processing')- and w2.currency_mint = ${currency_mint}- ) as pending_amount- from agent_revenue_events re- join agent_identities ai on ai.id = re.agent_id- where ai.user_id = ${user.id}- and re.currency_mint = ${currency_mint}- `;-- const available = Number(balance.earned) - Number(balance.pending_amount);- if (amount > available) {+ // Reserve the withdrawal atomically. The available balance (earned minus+ // in-flight withdrawals) must be re-derived and compared *inside* the same+ // statement that inserts the new pending row — a read-then-insert pair is a+ // TOCTOU hole: N concurrent requests all read pending=0 and all insert,+ // over-withdrawing past the real balance (the per-user rate limit admits up+ // to 5 before any pending row exists, so it can't be relied on for integrity).+ //+ // pg_advisory_xact_lock serializes concurrent requests for the same+ // (user, mint) so the loser sees the winner's committed pending row in its+ // balance subquery; the conditional INSERT…SELECT then refuses to insert+ // when the amount exceeds what's actually available.+ const lockKey = `withdrawal:${user.id}:${currency_mint}`;+ const [, inserted] = await sql.transaction([+ sql`select pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`,+ sql`+ insert into agent_withdrawals+ (user_id, agent_id, amount, currency_mint, chain, to_address, status)+ select ${user.id}, ${agent_id}, ${amount}, ${currency_mint}, ${chain}, ${to_address}, 'pending'+ where ${amount} <= (+ (+ select coalesce(sum(re.net_amount), 0)::bigint+ from agent_revenue_events re+ join agent_identities ai on ai.id = re.agent_id+ where ai.user_id = ${user.id}+ and re.currency_mint = ${currency_mint}+ ) - (+ select coalesce(sum(w2.amount), 0)::bigint+ from agent_withdrawals w2+ where w2.user_id = ${user.id}+ and w2.status in ('pending', 'processing')+ and w2.currency_mint = ${currency_mint}+ )+ )+ returning id, agent_id, amount, currency_mint, chain, to_address, status, tx_signature, created_at, updated_at+ `,+ ]);++ const withdrawal = inserted?.[0];+ if (!withdrawal) {return error(res, 422, 'insufficient_balance', 'requested amount exceeds available balance');}- const [withdrawal] = await sql`- insert into agent_withdrawals- (user_id, agent_id, amount, currency_mint, chain, to_address, status)- values- (${user.id}, ${agent_id}, ${amount}, ${currency_mint}, ${chain}, ${to_address}, 'pending')- returning id, agent_id, amount, currency_mint, chain, to_address, status, tx_signature, created_at, updated_at- `;-return json(res, 201, { withdrawal });});diff --git a/api/cron/[name].js b/api/cron/[name].jsindex f551c00d9..e2ff3f4ff 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -2708,6 +2708,12 @@ async function handleAuditLogCleanup(req, res) {async function handleExpirePendingPurchases(req, res) {if (!method(req, res, ['GET'])) return;+ const auth = req.headers['authorization'] || '';+ const cronSecret = env.CRON_SECRET;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }const result = await sql`UPDATE skill_purchasesSET status = 'expired', updated_at = now()@@ -2723,6 +2729,12 @@ async function handleExpirePendingPurchases(req, res) {async function handleCleanupCsrfTokens(req, res) {if (!method(req, res, ['GET'])) return;+ const auth = req.headers['authorization'] || '';+ const cronSecret = env.CRON_SECRET;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }const result = await sql`DELETE FROM csrf_tokens WHERE expires_at < now() RETURNING token`;return json(res, 200, { deleted: result.length });}diff --git a/api/discover-detail.js b/api/discover-detail.jsindex f6ab6a397..78ecafaec 100644--- a/api/discover-detail.js+++ b/api/discover-detail.js@@ -13,7 +13,7 @@*/import { sql } from './_lib/db.js';-import { cors, wrap } from './_lib/http.js';+import { cors, method, wrap } from './_lib/http.js';import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';import { publicUrl } from './_lib/r2.js';import { DEMO_AVATARS } from './_lib/demo-avatars.js';@@ -21,6 +21,7 @@ import { env } from './_lib/env.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;const url = new URL(req.url, 'http://x');const kind = url.searchParams.get('kind');diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.jsindex a75647d37..e56a6b766 100644--- a/api/insights/revenue-vision.js+++ b/api/insights/revenue-vision.js@@ -30,6 +30,7 @@ import {PAYMENT_IDENTIFIER,checkCache,extractIdFromHeader,+ hashPaymentProof,hashRequestPayload,paymentIdentifierExtension,storeResponse,@@ -214,14 +215,16 @@ export default wrap(async (req, res) => {url: req.url,body: null,});+ const paymentHash = hashPaymentProof(paymentHeader);if (paymentId) {- const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash });+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);if (lookup.kind === 'conflict') {return writeConflict(res, {route: ROUTE,attemptedHash: lookup.attemptedHash,existingHash: lookup.existingHash,+ reason: lookup.reason,});}}@@ -276,6 +279,7 @@ export default wrap(async (req, res) => {route: ROUTE,paymentId,payloadHash,+ paymentHash,status: 200,body,contentType,diff --git a/api/mcp.js b/api/mcp.jsindex 3e8dfe131..ad74bcadc 100644--- a/api/mcp.js+++ b/api/mcp.js@@ -3,10 +3,25 @@import { cors, readJson, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js';+import { x402AmountForTool } from './_lib/pump-pricing.js';import { PROTOCOL_VERSION, dispatch } from './_mcp/dispatch.js';import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';import { sendX402Error } from './_mcp/payments.js';+// Peek the single called tool name from a (possibly batched) JSON-RPC body so+// the x402 challenge can advertise — and the settle path charge — exactly the+// per-tool price. We only special-case a request that calls ONE tool; mixed+// batches keep the flat default. Returns { toolName } | { toolName: null }.+function peekCalledTool(body) {+ const batch = Array.isArray(body) ? body : [body];+ const calls = batch.filter((m) => m && m.method === 'tools/call');+ if (calls.length === 1) {+ const name = calls[0]?.params?.name;+ return { toolName: typeof name === 'string' ? name : null };+ }+ return { toolName: null };+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;@@ -14,7 +29,18 @@ export default wrap(async (req, res) => {if (req.method === 'DELETE') return handleTerminate(req, res);if (req.method !== 'POST') return send401(res, 'method not supported');- const result = await authenticateRequest(req, res);+ // Read + parse the body BEFORE the x402 challenge so we can price the 402 by+ // the tool actually being called. Malformed JSON throws with status 400,+ // handled by wrap() — identical to the previous post-auth read.+ const body = await readJson(req, 2_000_000);++ // Derive the per-tool x402 price. The advertised 402 amount and the settled+ // charge are both keyed off this, so we never advertise a price the flow+ // won't honor. A free tool yields null → no per-call charge is required.+ const { toolName } = peekCalledTool(body);+ const x402Amount = toolName ? x402AmountForTool(toolName) : null;++ const result = await authenticateRequest(req, res, { x402Amount });if (!result) return;const { auth, x402Ctx } = result;@@ -29,7 +55,6 @@ export default wrap(async (req, res) => {retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),});- const body = await readJson(req, 2_000_000);const batch = Array.isArray(body) ? body : [body];// Per-request batch cap — each message can trigger DB queries, so an// unbounded batch multiplies rate-limited work by N against the user's budget.diff --git a/api/payments/evm/[action].js b/api/payments/evm/[action].jsindex a9b1d264c..b7255de11 100644--- a/api/payments/evm/[action].js+++ b/api/payments/evm/[action].js@@ -76,13 +76,50 @@ async function handleConfirm(req, res) {try { receipt = await client.getTransactionReceipt({ hash: tx_hash }); }catch { return error(res, 422, 'tx_not_found', 'transaction not found on chain — may need more confirmations'); }if (receipt.status !== 'success') return error(res, 422, 'tx_failed', 'transaction reverted');+ // Require a confirmation depth before granting the (irreversible, 30-day)+ // plan — a single-receipt check accepts a tx that a short reorg could revert.+ const MIN_CONFIRMATIONS = 12n;+ try {+ const head = await client.getBlockNumber();+ if (head - receipt.blockNumber < MIN_CONFIRMATIONS) {+ return error(res, 422, 'insufficient_confirmations', 'transaction needs more confirmations — retry shortly');+ }+ } catch {+ return error(res, 422, 'tx_not_found', 'unable to read chain head for confirmation depth');+ }const usdcAddress = EVM_USDC[chainId]?.toLowerCase();const logs = await client.getLogs({ address: usdcAddress, event: ERC20_ABI[0], fromBlock: receipt.blockNumber, toBlock: receipt.blockNumber });const expectedRecipient = intent.recipient.toLowerCase();const expectedAtomics = BigInt(Math.round(Number(intent.amount_usdc) * 1_000_000));const matchingLog = logs.find((log) => log.transactionHash?.toLowerCase() === tx_hash.toLowerCase() && log.args.to?.toLowerCase() === expectedRecipient && BigInt(log.args.value ?? 0) >= expectedAtomics);if (!matchingLog) return error(res, 422, 'transfer_not_found', `No USDC transfer of ${intent.amount_usdc} USDC to ${expectedRecipient} found in tx`);- await sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_hash}, confirmed_at=now() where id=${intent_id}`;++ // Bind the on-chain payment to this account. The treasury recipient is shared+ // across all users, so "a transfer of the right amount to the treasury exists"+ // is not proof THIS user paid — without binding, anyone could confirm any+ // public transfer against their own intent. EVM USDC transfers carry no memo+ // (unlike the Solana path's nonce memo), so we bind on the payer address: the+ // funds must originate from a wallet linked to this account.+ const payer = matchingLog.args.from?.toLowerCase();+ if (!payer) return error(res, 422, 'transfer_not_found', 'could not determine payer address from transaction');+ const [linked] = await sql`select 1 from user_wallets where user_id = ${user.id} and lower(address) = ${payer} limit 1`;+ if (!linked) {+ return error(res, 422, 'payer_not_linked', 'payment must be sent from a wallet linked to your account — link the paying wallet, then retry', { payer });+ }++ // Reject a tx_hash already consumed by another confirmed intent (replay).+ // The partial unique index payment_intents_tx_hash_unique is the hard backstop;+ // this pre-check turns the race-loser into a clean 409 instead of a 500.+ const [dupe] = await sql`select id from plan_payment_intents where chain_type = 'evm' and tx_hash = ${tx_hash} and status = 'confirmed' limit 1`;+ if (dupe) return error(res, 409, 'tx_already_used', 'this transaction has already been used to confirm a payment');++ try {+ await sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_hash}, confirmed_at=now() where id=${intent_id} and status != 'confirmed'`;+ } catch (e) {+ // Unique-index violation: a concurrent confirm claimed this tx first.+ if (e?.code === '23505') return error(res, 409, 'tx_already_used', 'this transaction has already been used to confirm a payment');+ throw e;+ }const planConfig = PLANS[intent.plan];const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);await sql`insert into subscriptions (user_id, plan, chain_type, chain_id, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'evm', ${chainId}, ${usdcAddress}, ${tx_hash}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, chain_id=excluded.chain_id, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`;diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].jsindex e4e891c14..71d8ec153 100644--- a/api/payments/solana/[action].js+++ b/api/payments/solana/[action].js@@ -72,10 +72,13 @@ async function handleConfirm(req, res) {return error(res, 410, 'intent_expired', 'payment session expired');}const rpcUrl = network === 'devnet' ? SOLANA_RPC_DEVNET : SOLANA_RPC_MAINNET;- const connection = new Connection(rpcUrl, 'confirmed');+ // A confirmed plan payment grants 30 days of paid plan — an irreversible,+ // latency-tolerant, one-time grant. Require 'finalized' so a short reorg+ // can't roll back the tx after we've already upgraded the account.+ const connection = new Connection(rpcUrl, 'finalized');const usdcMint = network === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : SOLANA_USDC_MINT;let tx;- try { tx = await connection.getParsedTransaction(tx_signature, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' }); }+ try { tx = await connection.getParsedTransaction(tx_signature, { maxSupportedTransactionVersion: 0, commitment: 'finalized' }); }catch { return error(res, 422, 'tx_not_found', 'transaction not found — may need more confirmations'); }if (!tx) return error(res, 422, 'tx_not_found', 'transaction not found');if (tx.meta?.err) return error(res, 422, 'tx_failed', 'transaction failed on-chain');diff --git a/api/permissions/[action].js b/api/permissions/[action].jsindex 1d7f1bf3d..fa12ebe0f 100644--- a/api/permissions/[action].js+++ b/api/permissions/[action].js@@ -1166,7 +1166,9 @@ async function handleVerify(req, res) {res.statusCode = 502;res.setHeader('content-type', 'application/json; charset=utf-8');res.setHeader('cache-control', 'no-store');- res.end(JSON.stringify({ ok: false, error: 'rpc_error', message: err.message }));+ // Don't leak the upstream error string to the client — log it (above) and+ // return a stable code. The internal message goes to server logs only.+ res.end(JSON.stringify({ ok: false, error: 'rpc_error', error_description: 'on-chain verification failed' }));return;}diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.jsindex 5f032435b..958940f08 100644--- a/api/pump-fun-mcp.js+++ b/api/pump-fun-mcp.js@@ -18,6 +18,8 @@import { cors, json, method, wrap, readJson, error } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';+import { extractBearer, authenticateBearer } from './_lib/auth.js';+import { verifyPayment, resolveResourceUrl, paymentRequirements } from './_lib/x402-spec.js';import { getPumpSdk, getConnection, solanaPubkey, getAmmPoolState } from './_lib/pump.js';import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';import { getRadarSignals } from '../src/kol/radar.js';@@ -261,17 +263,34 @@ async function rawBotCall(tool, args) {}}-async function handleVanityMint({ suffix = '', prefix = '', caseSensitive = false, maxAttempts = 5_000_000 }) {+// Hard ceiling on the single-threaded vanity grind. Each iteration is a full+// ed25519 keygen; an unbounded budget lets one authenticated caller pin a CPU+// for the whole serverless window. 1.5M ≈ comfortably inside the 58s abort.+const VANITY_MAX_ATTEMPTS_CEILING = 1_500_000;+// Suffix/prefix length cap — the match space is base58^len, so >4 chars makes a+// hit astronomically unlikely within the budget and just burns CPU.+const VANITY_MAX_PATTERN_LEN = 4;++async function handleVanityMint({ suffix = '', prefix = '', caseSensitive = false, maxAttempts = 1_500_000 }) {if (!suffix && !prefix) throw rpcError(-32602, 'at least one of suffix or prefix is required');+ if (String(suffix).length > VANITY_MAX_PATTERN_LEN || String(prefix).length > VANITY_MAX_PATTERN_LEN)+ throw rpcError(-32602, `suffix/prefix must each be ≤ ${VANITY_MAX_PATTERN_LEN} characters`);+ const budget = Math.min(+ VANITY_MAX_ATTEMPTS_CEILING,+ Math.max(1, Number(maxAttempts) || VANITY_MAX_ATTEMPTS_CEILING),+ );const ac = new AbortController();const timer = setTimeout(() => ac.abort(), 58_000);let result;try {- result = await generateVanityKey({ suffix, prefix, caseSensitive, maxAttempts, signal: ac.signal });+ result = await generateVanityKey({ suffix, prefix, caseSensitive, maxAttempts: budget, signal: ac.signal });} finally {clearTimeout(timer);}- if (!result) throw rpcError(-32003, `no match found in ${maxAttempts} attempts`);+ if (!result) throw rpcError(-32003, `no match found in ${budget} attempts`);+ // SECURITY: the secretKey is returned to the (authenticated) caller but must+ // never be logged or recorded server-side. Keep it out of any usage/event+ // metadata — the caller is the sole custodian of this key.return {publicKey: result.publicKey,secretKey: bs58.encode(result.secretKey),@@ -556,6 +575,52 @@ const HANDLERS = {// ── HTTP entrypoint ────────────────────────────────────────────────────────+// Tools that are expensive (CPU grind or long-lived RPC subscriptions) or that+// return sensitive material (a secret key). These require authentication — a+// valid bearer (OAuth access token or sk_live_/sk_test_ API key) OR a verified+// x402 micropayment. The free read-only snapshot/quote tools stay open.+const AUTH_REQUIRED_TOOLS = new Set([+ 'pumpfun_vanity_mint',+ 'pumpfun_watch_whales',+ 'pumpfun_watch_claims',+]);++// Verify the request is authenticated for a gated tool. Returns true on success;+// on failure it writes the JSON-RPC error envelope and returns false. Accepts a+// bearer (API key / OAuth JWT) or a verified X-PAYMENT header.+async function authorizeGatedTool(req, res, id) {+ const bearer = extractBearer(req);+ if (bearer) {+ const auth = await authenticateBearer(bearer).catch(() => null);+ if (auth) return true;+ json(res, 401, rpcEnvelope(id, null, {+ code: -32001,+ message: 'authentication required: invalid or expired bearer token',+ }));+ return false;+ }+ const paymentHeader = req.headers['x-payment'];+ if (paymentHeader) {+ const resourceUrl = resolveResourceUrl(req, '/api/pump-fun-mcp');+ const requirements = paymentRequirements(resourceUrl);+ try {+ await verifyPayment({ paymentHeader, requirements });+ return true;+ } catch (err) {+ json(res, 402, rpcEnvelope(id, null, {+ code: -32402,+ message: `payment verification failed: ${err?.message || 'invalid payment'}`,+ }));+ return false;+ }+ }+ json(res, 401, rpcEnvelope(id, null, {+ code: -32001,+ message: 'authentication required for this tool (provide a Bearer token or X-PAYMENT)',+ }));+ return false;+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;if (!method(req, res, ['POST'])) return;@@ -577,7 +642,7 @@ export default wrap(async (req, res) => {res,200,rpcEnvelope(id, {- protocolVersion: '2024-11-05',+ protocolVersion: '2025-06-18',capabilities: { tools: {} },serverInfo: { name: 'three.ws-pumpfun-mcp', version: '0.1.0' },}),@@ -599,6 +664,13 @@ export default wrap(async (req, res) => {rpcEnvelope(id, null, { code: -32601, message: `unknown tool: ${name}` }),);}+ // Auth gate: expensive (vanity grind, long-lived RPC watch) and sensitive+ // (returns a secret key) tools require a bearer or verified x402 payment.+ // authorizeGatedTool writes the 401/402 envelope and returns false on deny.+ if (AUTH_REQUIRED_TOOLS.has(name)) {+ const okAuth = await authorizeGatedTool(req, res, id);+ if (!okAuth) return;+ }try {const data = await handler(args);// Mirror MCP content shape so existing skill clients can unwrap text.diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 0d82273ad..69235caf1 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -1495,6 +1495,15 @@ async function handleAcceptPaymentConfirm(req, res) {if (payment.status === 'confirmed')return error(res, 409, 'already_confirmed', 'payment already confirmed');+ // One signature confirms one invoice. Reject a signature already consumed by+ // another payment before doing any on-chain work (the partial unique index+ // pump_agent_payments_tx_signature_unique is the hard backstop).+ const [sigDupe] = await sql`+ select id from pump_agent_payments+ where tx_signature=${body.tx_signature} and status='confirmed' and id != ${payment.id} limit 1+ `;+ if (sigDupe) return error(res, 409, 'tx_already_used', 'this transaction already confirmed another payment');+let tx;try {tx = await verifySignature({ network: payment.network, signature: body.tx_signature });@@ -1510,11 +1519,48 @@ async function handleAcceptPaymentConfirm(req, res) {return error(res, 422, 'mint_not_in_tx', 'agent mint not in tx accounts');}- await sql`- update pump_agent_payments- set status='confirmed', tx_signature=${body.tx_signature}, confirmed_at=now()- where id=${payment.id}- `;+ // The declared payer must have signed the tx — a signature that didn't+ // involve this payer can't satisfy this invoice.+ const signed = tx.transaction.message.accountKeys.some(+ (k) => (k.pubkey || k).toString() === payment.payer_wallet && k.signer === true,+ );+ if (!signed) return error(res, 422, 'payer_not_signer', 'declared payer did not sign the transaction');++ // Verify the agent's payment vault was actually credited the invoiced amount+ // of the invoiced currency. Without this, "the mint pubkey appears in the tx"+ // is not proof of payment — any cheap unrelated tx referencing the mint would+ // pass. The vault is the ATA owned by the TokenAgentPayments PDA for this mint.+ const { agentPda } = await getPumpAgentOffline({ network: payment.network, mint: payment.mint });+ if (!agentPda) {+ return error(res, 503, 'verification_unavailable', 'unable to derive agent payment vault for verification');+ }+ const vaultOwner = agentPda.toString();+ const expectedAtomics = BigInt(payment.amount_atomics);+ const post = tx.meta?.postTokenBalances || [];+ const pre = tx.meta?.preTokenBalances || [];+ let credited = 0n;+ for (const p of post) {+ if (p.mint !== payment.currency_mint) continue;+ if (p.owner !== vaultOwner) continue;+ const before = pre.find((b) => b.accountIndex === p.accountIndex);+ const delta = BigInt(p.uiTokenAmount?.amount ?? '0') - BigInt(before?.uiTokenAmount?.amount ?? '0');+ if (delta > credited) credited = delta;+ }+ if (credited < expectedAtomics) {+ await sql`update pump_agent_payments set status='failed' where id=${payment.id}`;+ return error(res, 422, 'amount_not_credited', 'transaction did not credit the invoiced amount to the agent payment vault');+ }++ try {+ await sql`+ update pump_agent_payments+ set status='confirmed', tx_signature=${body.tx_signature}, confirmed_at=now()+ where id=${payment.id} and status != 'confirmed'+ `;+ } catch (e) {+ if (e?.code === '23505') return error(res, 409, 'tx_already_used', 'this transaction already confirmed another payment');+ throw e;+ }return json(res, 200, {ok: true,diff --git a/api/render/avatar-clip.js b/api/render/avatar-clip.jsindex 72bcbeb19..14d32c56b 100644--- a/api/render/avatar-clip.js+++ b/api/render/avatar-clip.js@@ -14,6 +14,8 @@import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';import { renderClip } from '../_lib/render-clip.js';import { PRESETS } from '../../src/pose-presets.js';+import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';+import { clientIp } from '../_lib/rate-limit.js';export const maxDuration = 30;@@ -37,20 +39,6 @@ function rateCheck(ip) {return true;}-function isPublicHttpUrl(u) {- try {- const url = new URL(u);- if (url.protocol !== 'https:' && url.protocol !== 'http:') return false;- const host = url.hostname;- if (host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0') return false;- if (host.startsWith('169.254.') || host.startsWith('10.') || host.startsWith('192.168.')) return false;- if (host.endsWith('.internal') || host.endsWith('.local')) return false;- return true;- } catch {- return false;- }-}-async function preflightSize(url) {try {const r = await fetch(url, { method: 'HEAD' });@@ -81,7 +69,7 @@ export default wrap(async function handler(req, res) {if (!method(req, res, ['POST'])) return;- const ip = (req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket?.remoteAddress;+ const ip = clientIp(req);if (!rateCheck(ip)) {return error(res, 429, 'rate_limited', `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);}@@ -95,8 +83,13 @@ export default wrap(async function handler(req, res) {const glbUrl = typeof body.glbUrl === 'string' ? body.glbUrl.trim() : '';if (!glbUrl) return error(res, 400, 'bad_request', 'glbUrl is required');- if (!isPublicHttpUrl(glbUrl)) {- return error(res, 400, 'bad_request', 'glbUrl must be a public http(s) URL');+ // DNS-resolving SSRF guard (see render/glb.js) — headless chromium loads this+ // URL inside the function, so a prefix denylist was bypassable.+ try {+ await assertSafePublicUrl(glbUrl, { allowHttp: true });+ } catch (e) {+ if (e instanceof SsrfBlockedError) return error(res, 400, 'bad_request', 'glbUrl must be a public http(s) URL');+ throw e;}const width = Math.max(MIN_DIM, Math.min(MAX_DIM, Number(body.width) || 1024));diff --git a/api/render/glb.js b/api/render/glb.jsindex 4e961875a..5a3223a9b 100644--- a/api/render/glb.js+++ b/api/render/glb.js@@ -20,6 +20,8 @@import { cors, error, method, readJson, wrap } from '../_lib/http.js';import { renderGlbToPng } from '../_lib/render-glb.js';+import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';+import { clientIp } from '../_lib/rate-limit.js';export const maxDuration = 30;@@ -43,22 +45,6 @@ function rateCheck(ip) {return true;}-function isPublicHttpUrl(u) {- try {- const url = new URL(u);- if (url.protocol !== 'https:' && url.protocol !== 'http:') return false;- const host = url.hostname;- // Block localhost and link-local — chromium running on Vercel could- // otherwise be coerced into hitting internal services.- if (host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0') return false;- if (host.startsWith('169.254.') || host.startsWith('10.') || host.startsWith('192.168.')) return false;- if (host.endsWith('.internal') || host.endsWith('.local')) return false;- return true;- } catch {- return false;- }-}-async function preflightSize(url) {try {const r = await fetch(url, { method: 'HEAD' });@@ -80,7 +66,7 @@ export default wrap(async function handler(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;- const ip = (req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket?.remoteAddress;+ const ip = clientIp(req);if (!rateCheck(ip)) {return error(res, 429, 'rate_limited', `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);}@@ -94,8 +80,15 @@ export default wrap(async function handler(req, res) {const glbUrl = typeof body.glbUrl === 'string' ? body.glbUrl.trim() : '';if (!glbUrl) return error(res, 400, 'bad_request', 'glbUrl is required');- if (!isPublicHttpUrl(glbUrl)) {- return error(res, 400, 'bad_request', 'glbUrl must be a public http(s) URL');+ // DNS-resolving SSRF guard: rejects any host that resolves to a private,+ // loopback, link-local, or cloud-metadata range. The headless chromium that+ // loads this URL runs inside the function, so a naive prefix denylist (the+ // previous check) was bypassable via DNS rebinding, 172.16/12, IPv6, etc.+ try {+ await assertSafePublicUrl(glbUrl, { allowHttp: true });+ } catch (e) {+ if (e instanceof SsrfBlockedError) return error(res, 400, 'bad_request', 'glbUrl must be a public http(s) URL');+ throw e;}const width = Math.max(MIN_DIM, Math.min(MAX_DIM, Number(body.width) || 1024));diff --git a/api/solana-rpc.js b/api/solana-rpc.jsindex 9a69a11a5..e13277364 100644--- a/api/solana-rpc.js+++ b/api/solana-rpc.js@@ -9,12 +9,52 @@// Usage from browser:// new Connection('/api/solana-rpc') -> mainnet// new Connection('/api/solana-rpc?net=devnet') -> devnet+//+// Hardening: this proxy fronts a keyed (paid) upstream, so it is rate-limited+// per-IP with a global hourly ceiling and only forwards an allowlist of the+// read/send methods the launch panel needs — never the expensive scan methods+// (getProgramAccounts, getBlock*) that would let an anonymous caller drain the+// upstream quota.-import { cors, method, json, error } from './_lib/http.js';+import { cors, method, wrap, readJson, error } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';const PUBLIC_DEVNET = 'https://api.devnet.solana.com';+// Methods a browser Connection needs to read balances/accounts, build, simulate,+// send, and confirm transactions. Deliberately excludes getProgramAccounts and+// the getBlock* family — heavy scans that have no place in the launch panel and+// are the prime vector for upstream quota abuse.+const ALLOWED_METHODS = new Set([+ 'getBalance',+ 'getAccountInfo',+ 'getMultipleAccounts',+ 'getLatestBlockhash',+ 'getRecentBlockhash',+ 'isBlockhashValid',+ 'getFeeForMessage',+ 'getMinimumBalanceForRentExemption',+ 'getSignatureStatuses',+ 'getSignaturesForAddress',+ 'getTransaction',+ 'sendTransaction',+ 'simulateTransaction',+ 'getTokenAccountBalance',+ 'getTokenAccountsByOwner',+ 'getTokenSupply',+ 'getEpochInfo',+ 'getSlot',+ 'getBlockHeight',+ 'getGenesisHash',+ 'getHealth',+ 'getVersion',+]);++// Cap batch requests so a single POST can't fan out into hundreds of upstream+// calls and sidestep the per-request rate limit.+const MAX_BATCH = 10;+function upstreamUrl(network) {if (network === 'devnet') {return process.env.SOLANA_RPC_URL_DEVNET || PUBLIC_DEVNET;@@ -22,35 +62,65 @@ function upstreamUrl(network) {return process.env.SOLANA_RPC_URL || PUBLIC_MAINNET;}-export default async function handler(req, res) {+// Validate one or a batch of JSON-RPC payloads. Returns an error code string,+// or null when every entry is a well-formed call to an allowlisted method.+function rejectReason(body) {+ const entries = Array.isArray(body) ? body : [body];+ if (entries.length === 0) return 'empty_request';+ if (entries.length > MAX_BATCH) return 'batch_too_large';+ for (const e of entries) {+ if (!e || typeof e !== 'object') return 'malformed_request';+ if (typeof e.method !== 'string') return 'malformed_request';+ if (!ALLOWED_METHODS.has(e.method)) return 'method_not_allowed';+ }+ return null;+}++export default wrap(async function handler(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;if (!method(req, res, ['POST'])) return;+ const ip = clientIp(req);+ const [ipRl, globalRl] = await Promise.all([limits.solanaRpcIp(ip), limits.solanaRpcGlobal()]);+ if (!ipRl.success || !globalRl.success) {+ return error(res, 429, 'rate_limited', 'too many RPC requests');+ }+const url = new URL(req.url, 'http://x');const network = url.searchParams.get('net') === 'devnet' ? 'devnet' : 'mainnet';- let bodyText;+ let body;try {- const chunks = [];- for await (const c of req) chunks.push(c);- bodyText = Buffer.concat(chunks).toString('utf8');+ body = await readJson(req, 200_000);} catch (e) {- return error(res, 400, 'bad_body', 'failed to read body');+ return error(res, e.status || 400, 'bad_body', 'failed to read JSON body');+ }++ const reason = rejectReason(body);+ if (reason) {+ const msg =+ reason === 'method_not_allowed'+ ? 'this RPC method is not permitted through the proxy'+ : reason === 'batch_too_large'+ ? `batch exceeds ${MAX_BATCH} requests`+ : 'malformed JSON-RPC request';+ return error(res, reason === 'method_not_allowed' ? 403 : 400, reason, msg);}- if (!bodyText) return error(res, 400, 'empty_body', 'empty body');+ let upstream;try {- const r = await fetch(upstreamUrl(network), {+ upstream = await fetch(upstreamUrl(network), {method: 'POST',headers: { 'content-type': 'application/json' },- body: bodyText,+ body: JSON.stringify(body),});- const text = await r.text();- res.statusCode = r.status;- res.setHeader('content-type', 'application/json; charset=utf-8');- res.setHeader('cache-control', 'no-store');- res.end(text);} catch (e) {- return error(res, 502, 'upstream_error', e.message || 'rpc upstream failed');+ return error(res, 502, 'upstream_error', 'rpc upstream failed');}-}++ const text = await upstream.text();+ res.statusCode = upstream.status;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('cache-control', 'no-store');+ res.end(text);+});diff --git a/api/users/me/agent-skills/[agentId].js b/api/users/me/agent-skills/[agentId].jsdeleted file mode 100644index e624ce22d..000000000--- a/api/users/me/agent-skills/[agentId].js+++ /dev/null@@ -1,13 +0,0 @@-export default (req, res) => {- // In a real application, you would fetch this from a database- // based on the authenticated user's ID.- const purchasedSkills = {- "1": ["generate-poem"],- "2": ["refactor-code"],- };-- const { agentId } = req.query;- const skills = purchasedSkills[agentId] || [];-- res.status(200).json({ skills });-}diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.jsindex 427eaf418..5b781824e 100644--- a/api/x402/mint-to-mesh.js+++ b/api/x402/mint-to-mesh.js@@ -36,6 +36,7 @@ import {PAYMENT_IDENTIFIER,checkCache,extractIdFromHeader,+ hashPaymentProof,hashRequestPayload,paymentIdentifierExtension,storeResponse,@@ -298,14 +299,16 @@ export default wrap(async (req, res) => {url: req.url,body: null,});+ const paymentHash = hashPaymentProof(paymentHeader);if (paymentId) {- const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash });+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);if (lookup.kind === 'conflict') {return writeConflict(res, {route: ROUTE,attemptedHash: lookup.attemptedHash,existingHash: lookup.existingHash,+ reason: lookup.reason,});}}@@ -351,6 +354,7 @@ export default wrap(async (req, res) => {route: ROUTE,paymentId,payloadHash,+ paymentHash,status: 200,body,contentType,diff --git a/api/x402/model-check.js b/api/x402/model-check.jsindex 93f3329b1..64e2265fb 100644--- a/api/x402/model-check.js+++ b/api/x402/model-check.js@@ -33,6 +33,7 @@ import {PAYMENT_IDENTIFIER,checkCache,extractIdFromHeader,+ hashPaymentProof,hashRequestPayload,paymentIdentifierExtension,storeResponse,@@ -337,14 +338,16 @@ export default wrap(async (req, res) => {url: req.url,body: null,});+ const paymentHash = hashPaymentProof(paymentHeader);if (paymentId) {- const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash });+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);if (lookup.kind === 'conflict') {return writeConflict(res, {route: ROUTE,attemptedHash: lookup.attemptedHash,existingHash: lookup.existingHash,+ reason: lookup.reason,});}}@@ -388,6 +391,7 @@ export default wrap(async (req, res) => {route: ROUTE,paymentId,payloadHash,+ paymentHash,status: 200,body,contentType,diff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex f5c90822d..c0e1e4f20 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -40,6 +40,7 @@ import {PAYMENT_IDENTIFIER,checkCache,extractIdFromHeader,+ hashPaymentProof,hashRequestPayload,paymentIdentifierExtension,storeResponse,@@ -339,14 +340,16 @@ export default wrap(async (req, res) => {// instead of grinding a fresh one and double-charging.const paymentId = extractIdFromHeader(paymentHeader);const payloadHash = hashRequestPayload({ method: req.method, url: req.url, body: null });+ const paymentHash = hashPaymentProof(paymentHeader);if (paymentId) {- const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash });+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);if (lookup.kind === 'conflict') {return writeConflict(res, {route: ROUTE,attemptedHash: lookup.attemptedHash,existingHash: lookup.existingHash,+ reason: lookup.reason,});}}@@ -389,6 +392,7 @@ export default wrap(async (req, res) => {route: ROUTE,paymentId,payloadHash,+ paymentHash,status: 200,body,contentType,diff --git a/contracts/agent-invocation/src/lib.rs b/contracts/agent-invocation/src/lib.rsindex c46ceffb6..0bd8cf21d 100644--- a/contracts/agent-invocation/src/lib.rs+++ b/contracts/agent-invocation/src/lib.rs@@ -2,34 +2,128 @@ use anchor_lang::prelude::*;declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");+/// Max accepted length (bytes) for `skill_name`, bounding the size of the+/// emitted event and the compute spent formatting it.+const MAX_SKILL_NAME_LEN: usize = 64;+/// Max accepted length (bytes) for the `parameters` blob.+const MAX_PARAMETERS_LEN: usize = 512;++/// PDA seed prefix that ties an agent identity account to this program. An+/// agent PDA is derived as [`AGENT_SEED`, authority] so it is impossible to+/// pass an arbitrary, attacker-chosen account in its place.+const AGENT_SEED: &[u8] = b"agent";+#[program]pub mod agent_invocation {use super::*;- pub fn invoke_skill(ctx: Context<InvokeSkill>, skill_name: String, parameters: String) -> Result<()> {- msg!("Agent {} invoked skill '{}' on agent {} with parameters: {}",- ctx.accounts.invoker_agent.key(),- skill_name,- ctx.accounts.target_agent.key(),- parameters);-- // In a full implementation, this would:- // 1. Verify the invoker has the right to call the skill (e.g., holds a specific NFT).- // 2. Look up the skill price from on-chain data.- // 3. Transfer the required payment from the invoker's wallet to the target's wallet.- // 4. Emit an event with the invocation details for off-chain services to process.++ /// Record a skill invocation from one agent to another.+ ///+ /// This instruction is intentionally non-trust-bearing: it does NOT move+ /// funds or grant any capability. Its only effect is to validate the caller+ /// and emit a verifiable [`SkillInvoked`] event that off-chain services can+ /// consume. All trust-bearing checks are enforced by Anchor constraints on+ /// [`InvokeSkill`] before this body runs:+ ///+ /// * `invoker_authority` must be a transaction signer (`Signer`).+ /// * `invoker_agent` must be the program-derived address for that authority+ /// (`seeds = [AGENT_SEED, invoker_authority]`, `bump`), so the caller can+ /// only ever act as their own agent identity.+ /// * `target_agent` must be a valid agent PDA owned by this program+ /// (`seeds = [AGENT_SEED, target_authority]`, `bump`).+ ///+ /// Because both agent accounts are constrained PDAs rather than raw+ /// `AccountInfo`, no future caller can substitute an unchecked account and+ /// have downstream logic trust it.+ pub fn invoke_skill(+ ctx: Context<InvokeSkill>,+ skill_name: String,+ parameters: String,+ ) -> Result<()> {+ require!(!skill_name.is_empty(), InvocationError::EmptySkillName);+ require!(+ skill_name.len() <= MAX_SKILL_NAME_LEN,+ InvocationError::SkillNameTooLong+ );+ require!(+ parameters.len() <= MAX_PARAMETERS_LEN,+ InvocationError::ParametersTooLong+ );++ let invoker_agent = ctx.accounts.invoker_agent.key();+ let target_agent = ctx.accounts.target_agent.key();++ msg!(+ "agent {} invoked skill '{}' on agent {}",+ invoker_agent,+ skill_name,+ target_agent+ );++ emit!(SkillInvoked {+ invoker_agent,+ target_agent,+ invoker_authority: ctx.accounts.invoker_authority.key(),+ skill_name,+ parameters,+ timestamp: Clock::get()?.unix_timestamp,+ });Ok(())}}#[derive(Accounts)]+#[instruction(skill_name: String, parameters: String)]pub struct InvokeSkill<'info> {- /// CHECK: This is the agent performing the invocation- pub invoker_agent: AccountInfo<'info>,- /// CHECK: This is the agent whose skill is being invoked- pub target_agent: AccountInfo<'info>,- /// CHECK: The user or authority wallet for the invoker- #[account(signer)]- pub invoker_authority: AccountInfo<'info>,+ /// The invoking agent's program-derived identity. Constrained to the PDA+ /// for `invoker_authority`, binding the on-chain agent to the signer.+ /// CHECK: validated by the `seeds`/`bump` PDA constraint against this+ /// program; never read or written, only its key is recorded.+ #[account(+ seeds = [AGENT_SEED, invoker_authority.key().as_ref()],+ bump,+ )]+ pub invoker_agent: UncheckedAccount<'info>,++ /// The authority controlling `invoker_agent`. Must sign the transaction, so+ /// the caller can only invoke as the agent identity they own.+ pub invoker_authority: Signer<'info>,++ /// The authority that owns the target agent. Supplied so the target agent+ /// PDA can be re-derived and verified; it does not need to sign.+ /// CHECK: only its public key is used to derive `target_agent`'s PDA.+ pub target_authority: UncheckedAccount<'info>,++ /// The target agent's program-derived identity. Constrained to the PDA for+ /// `target_authority`, so an arbitrary account cannot be passed as a target.+ /// CHECK: validated by the `seeds`/`bump` PDA constraint against this+ /// program; never read or written, only its key is recorded.+ #[account(+ seeds = [AGENT_SEED, target_authority.key().as_ref()],+ bump,+ )]+ pub target_agent: UncheckedAccount<'info>,+pub system_program: Program<'info, System>,}++#[event]+pub struct SkillInvoked {+ pub invoker_agent: Pubkey,+ pub target_agent: Pubkey,+ pub invoker_authority: Pubkey,+ pub skill_name: String,+ pub parameters: String,+ pub timestamp: i64,+}++#[error_code]+pub enum InvocationError {+ #[msg("skill_name must not be empty")]+ EmptySkillName,+ #[msg("skill_name exceeds the maximum allowed length")]+ SkillNameTooLong,+ #[msg("parameters exceed the maximum allowed length")]+ ParametersTooLong,+}diff --git a/contracts/src/IdentityRegistry.sol b/contracts/src/IdentityRegistry.solindex 2c8c96aa4..f48e6471d 100644--- a/contracts/src/IdentityRegistry.sol+++ b/contracts/src/IdentityRegistry.sol@@ -36,6 +36,11 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {// Max spend per on-chain agent ID per authorized spender (set by agent NFT owner)mapping(uint256 => mapping(address => uint256)) public spendAllowance;+ // Per-agent deposited ETH balance held by this contract. The sum of all+ // agentBalance entries equals the contract's spendable ETH; spend() may only+ // draw against the calling agent's own balance, never a shared pool.+ mapping(uint256 => uint256) public agentBalance;+// EIP-712 typehash for delegated wallet binding.bytes32 private constant _SET_WALLET_TYPEHASH = keccak256("SetAgentWallet(uint256 agentId,address newWallet,uint256 nonce,uint256 deadline)"@@ -50,6 +55,8 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {event WalletSet(uint256 indexed agentId, address indexed wallet);event WalletUnset(uint256 indexed agentId);event SpendAllowanceSet(uint256 indexed agentId, address indexed spender, uint256 maxWei);+ event AgentDeposit(uint256 indexed agentId, address indexed from, uint256 amountWei);+ event AgentWithdrawal(uint256 indexed agentId, address indexed to, uint256 amountWei);event AgentPayment(uint256 indexed agentId,address indexed spender,@@ -72,6 +79,9 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {error SignatureExpired();error InvalidSignature();error UnknownAgent();+ error ZeroDeposit();+ error InsufficientAgentBalance();+ error DirectTransferRejected();// ---------------------------------------------------------------------// Constructor@@ -201,7 +211,41 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {// Agent spend delegation// ---------------------------------------------------------------------- receive() external payable {}+ /// @notice Reject bare ETH transfers. ETH must always be attributed to a+ /// specific agent via deposit(agentId); a blanket receive() would+ /// pool funds with no per-agent ownership, letting one agent's+ /// spender drain another agent's ETH.+ receive() external payable {+ revert DirectTransferRejected();+ }++ fallback() external payable {+ revert DirectTransferRejected();+ }++ /// @notice Deposit ETH credited to a specific agent's balance. Anyone may+ /// fund an agent (e.g. the agent's operator topping up its budget),+ /// but the funds become spendable only against that agent's own+ /// balance, never a shared pool.+ function deposit(uint256 agentId) external payable {+ if (_ownerOf(agentId) == address(0)) revert UnknownAgent();+ if (msg.value == 0) revert ZeroDeposit();+ agentBalance[agentId] += msg.value;+ emit AgentDeposit(agentId, msg.sender, msg.value);+ }++ /// @notice Withdraw ETH from an agent's balance back to its NFT owner.+ /// Only the agent owner can reclaim its unspent deposits.+ function withdraw(uint256 agentId, address payable recipient, uint256 amountWei)+ external+ nonReentrant+ {+ if (ownerOf(agentId) != msg.sender) revert NotAgentOwner();+ if (agentBalance[agentId] < amountWei) revert InsufficientAgentBalance();+ agentBalance[agentId] -= amountWei;+ recipient.transfer(amountWei);+ emit AgentWithdrawal(agentId, recipient, amountWei);+ }/// @notice Agent NFT owner authorizes a spender (e.g. delegated server key) to/// spend up to maxWei from this contract on behalf of the agent.@@ -214,7 +258,9 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {}/// @notice Spend ETH held by this contract on behalf of an agent.- /// Caller must have been granted allowance via setSpendAllowance.+ /// Caller must have been granted allowance via setSpendAllowance,+ /// AND the spend is capped by the agent's own deposited balance so+ /// funds belonging to other agents can never be drained.function spend(uint256 agentId,address payable recipient,@@ -222,8 +268,9 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {string calldata memo) external nonReentrant {require(spendAllowance[agentId][msg.sender] >= amountWei, "allowance exceeded");- require(address(this).balance >= amountWei, "contract balance insufficient");+ if (agentBalance[agentId] < amountWei) revert InsufficientAgentBalance();spendAllowance[agentId][msg.sender] -= amountWei;+ agentBalance[agentId] -= amountWei;recipient.transfer(amountWei);emit AgentPayment(agentId, msg.sender, recipient, amountWei, memo);}diff --git a/contracts/src/ReputationRegistry.sol b/contracts/src/ReputationRegistry.solindex 9d6fa368b..3ede0c613 100644--- a/contracts/src/ReputationRegistry.sol+++ b/contracts/src/ReputationRegistry.sol@@ -1,6 +1,8 @@// SPDX-License-Identifier: MITpragma solidity ^0.8.24;+import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";+interface IIdentityRegistry {function isAgent(uint256 agentId) external view returns (bool);function ownerOf(uint256 agentId) external view returns (address);@@ -10,7 +12,7 @@ interface IIdentityRegistry {/// @notice Stores signed-by-tx-sender reputation feedback about registered/// agents. Scores are clamped to [-100, 100]. Aggregates are updated/// in-place so reads are O(1).-contract ReputationRegistry {+contract ReputationRegistry is ReentrancyGuard {// ---------------------------------------------------------------------// Storage// ---------------------------------------------------------------------@@ -33,7 +35,12 @@ contract ReputationRegistry {mapping(uint256 => Aggregate) private _aggregate;// agentId => reviewer => hasSubmitted (one review per address per agent)mapping(uint256 => mapping(address => bool)) public hasReviewed;+ // agentId => aggregate ETH currently staked across all stakersmapping(uint256 => uint256) private _totalStake;+ // agentId => staker => their refundable staked ETH. Attributing stake per+ // staker is what makes withdrawStake() access-correct: each staker can only+ // ever reclaim what they personally locked, never another staker's ETH.+ mapping(uint256 => mapping(address => uint256)) public stakeOf;// ---------------------------------------------------------------------// Events@@ -53,6 +60,12 @@ contract ReputationRegistry {uint256 value);+ event StakeWithdrawn(+ uint256 indexed agentId,+ address indexed staker,+ uint256 value+ );+// ---------------------------------------------------------------------// Errors// ---------------------------------------------------------------------@@ -61,6 +74,8 @@ contract ReputationRegistry {error AlreadyReviewed();error ScoreOutOfRange();error SelfReviewForbidden();+ error NoStakeToWithdraw();+ error RefundFailed();// ---------------------------------------------------------------------// Constructor@@ -165,12 +180,35 @@ contract ReputationRegistry {}_totalStake[agentId] += msg.value;+ stakeOf[agentId][msg.sender] += msg.value;emit FeedbackSubmitted(agentId, msg.sender, int8(uint8(score)), comment);emit ReputationStaked(agentId, msg.sender, score, msg.value);}+ /// @notice Reclaim the ETH you personally staked on an agent. The review you+ /// submitted (score + comment) remains on-chain; only your escrowed+ /// stake is refunded. A staker may withdraw at any time and can only+ /// ever recover their own deposit.+ function withdrawStake(uint256 agentId) external nonReentrant {+ uint256 amount = stakeOf[agentId][msg.sender];+ if (amount == 0) revert NoStakeToWithdraw();++ stakeOf[agentId][msg.sender] = 0;+ _totalStake[agentId] -= amount;++ (bool ok, ) = payable(msg.sender).call{value: amount}("");+ if (!ok) revert RefundFailed();++ emit StakeWithdrawn(agentId, msg.sender, amount);+ }+function getTotalStake(uint256 agentId) external view returns (uint256) {return _totalStake[agentId];}++ /// @notice The refundable stake a specific staker holds on an agent.+ function getStake(uint256 agentId, address staker) external view returns (uint256) {+ return stakeOf[agentId][staker];+ }}diff --git a/docs/internal/api-inventory.md b/docs/internal/api-inventory.mdindex ba59dfbf4..f5993e73f 100644--- a/docs/internal/api-inventory.md+++ b/docs/internal/api-inventory.md@@ -64,9 +64,8 @@ Generated reference of every HTTP endpoint under `/api/`. Paths reflect the exte| `/api/auth/siwe/nonce` | GET | public (rate-limited) | EIP-4361 nonce + CSRF cookie | — | `{nonce}` || `/api/auth/siwe/verify` | POST | CSRF + signature | Verify SIWE; create/link user + session | `{message,signature}` | `{user}` + Set-Cookie || `/api/auth/privy/verify` | POST | public (rate-limited) | Exchange Privy idToken for session | `{idToken}` | `{user,wallet}` + Set-Cookie |-| `/api/auth/wallet/link` | POST | session | Link wallet via SIWE to logged-in account | `{message,signature}` | `{wallet}` |-| `/api/auth/wallet/unlink` | POST | session | Unlink one wallet | `{address}` | `{ok}` |-| `/api/auth/wallets` | GET, POST | session | List linked wallets / link new (nonce-based) | POST: `{address,message,signature,nonce}` | `{wallets[]}` / `{wallet}` |+| `/api/auth/wallets/nonce` | GET, POST | session | Per-user link nonce (separate from login pool) | GET: — / POST: `{address,chainId}` | `{nonce,domain,uri}` / `{message}`|+| `/api/auth/wallets` | GET, POST | session | List linked wallets / link new (link-nonce-based) | POST: `{message,signature}` | `{wallets[]}` / `{wallet}` || `/api/auth/wallets/:address` | DELETE | session | Unlink by address (blocks last wallet if no password) | — | `{ok}` || `/api/auth/wallets/nonce` | POST | session | Issue SIWE-like nonce for wallet link | — | `{nonce,message}` |diff --git a/mcp-bridge/src/bazaar-discover.js b/mcp-bridge/src/bazaar-discover.jsindex 10d1639dd..e0359b17d 100644--- a/mcp-bridge/src/bazaar-discover.js+++ b/mcp-bridge/src/bazaar-discover.js@@ -21,6 +21,8 @@import axios from 'axios';+import { assertPayableUrl, maxPriceAtomic } from './url-guard.js';+const DEFAULT_LIMIT = 20;const DEFAULT_BAZAAR_URL = 'https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources';@@ -39,12 +41,6 @@ function discoverLimit() {return Math.floor(v);}-function maxPriceAtomic() {- const raw = process.env.MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC;- if (!raw) return null;- return BigInt(raw);-}-// Derive a stable MCP tool name from a Bazaar item.//// MCP tool names must be unique and conventionally are snake_case identifiers.@@ -106,7 +102,7 @@ function summarizeAccepts(accepts) {}function affordable(accepts) {- const cap = maxPriceAtomic();+ const cap = maxPriceAtomic({ strict: false });if (cap === null) return true;return accepts.some((a) => {try {@@ -119,10 +115,15 @@ function affordable(accepts) {export async function fetchBazaarResources({ url = bazaarUrl(), limit = discoverLimit() } = {}) {if (limit === 0) return [];- const res = await axios.get(url, {+ // The bazaar response drives payable-tool registration, so a malicious+ // MCP_BRIDGE_BAZAAR_URL override is an SSRF + supply-chain vector. Validate+ // scheme + host before fetching, same as any payable URL.+ const safeUrl = await assertPayableUrl(url);+ const res = await axios.get(safeUrl, {params: { limit },timeout: 15_000,validateStatus: (s) => s >= 200 && s < 300,+ maxRedirects: 0,});const items = Array.isArray(res.data?.items) ? res.data.items : [];return items;diff --git a/mcp-bridge/src/index.js b/mcp-bridge/src/index.jsindex d7fb8557e..aaf24001f 100755--- a/mcp-bridge/src/index.js+++ b/mcp-bridge/src/index.js@@ -21,6 +21,7 @@ import { z } from 'zod';import { buildBuyerAxios, extractReceipt } from './x402-axios-client.js';import { discoverBazaarTools } from './bazaar-discover.js';+import { assertPayableUrl } from './url-guard.js';const BRIDGE_NAME = '3d-agent-x402-bridge';const BRIDGE_VERSION = '1.0.0';@@ -56,10 +57,13 @@ function decodePaymentResponseFromHeaders(headers) {async function callPaidEndpoint({ api, httpClient }, args) {const { url, method = 'GET', body, params, headers } = args;+ // SSRF chokepoint: validate scheme + resolve host before any payment-wrapped+ // request leaves the process. Throws on private/blocked targets.+ const safeUrl = await assertPayableUrl(url);const normalizedMethod = String(method).toUpperCase();const hasBody = body !== undefined && body !== null;const res = await api.request({- url,+ url: safeUrl,method: normalizedMethod,data: hasBody ? body : undefined,params,diff --git a/mcp-bridge/src/url-guard.js b/mcp-bridge/src/url-guard.jsnew file mode 100644index 000000000..804bf9d06--- /dev/null+++ b/mcp-bridge/src/url-guard.js@@ -0,0 +1,253 @@+// SSRF guard + shared spend-limit parsing for the x402 MCP bridge.+//+// THREAT MODEL: this bridge holds live EVM + SVM signers and an auto-pay+// interceptor. A URL supplied by the LLM (call_paid_endpoint) or by an+// untrusted Bazaar listing (dynamic tools) flows into a payment-wrapped axios+// request. Without validation, an attacker can point that request at internal+// infrastructure — cloud metadata (169.254.169.254), localhost admin panels,+// RFC-1918 hosts — and, worse, get the bridge to SIGN a payment to do it.+//+// `assertPayableUrl` is the single chokepoint that every outbound payable+// request must pass through. It enforces:+// - scheme allowlist (https only; http behind an explicit dev opt-in)+// - DNS resolution of the hostname and rejection if ANY resolved address is+// private/loopback/link-local/unspecified/ULA/CGNAT (defeats DNS rebinding+// at request-build time and literal-IP SSRF)+// - optional strict host allowlist via MCP_BRIDGE_ALLOWED_HOSTS+//+// No external dependency: the CIDR checks parse octets / IPv6 hextets directly.++import { promises as dns } from 'node:dns';+import net from 'node:net';++const DEFAULT_MAX_PRICE_ATOMIC = 100_000n; // $0.10 USDC++// ---------------------------------------------------------------------------+// Shared spend-limit parsing (de-duplicated from x402-axios-client.js and+// bazaar-discover.js, which previously defined this with differing semantics).+//+// `strict: true` → throw on a negative value, return the default when unset+// (used by the spending-cap hook, which needs a real number).+// `strict: false` → return null when unset (used by bazaar discovery, which+// treats "no cap configured" as "show every tool").+// ---------------------------------------------------------------------------+export function maxPriceAtomic({ strict = true } = {}) {+ const raw = process.env.MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC;+ if (!raw) return strict ? DEFAULT_MAX_PRICE_ATOMIC : null;+ let v;+ try {+ v = BigInt(raw);+ } catch {+ throw new Error('MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC must be an integer (atomic units)');+ }+ if (v < 0n) throw new Error('MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC must be non-negative');+ return v;+}++export { DEFAULT_MAX_PRICE_ATOMIC };++// ---------------------------------------------------------------------------+// IP range classification+// ---------------------------------------------------------------------------++function ipv4ToInt(ip) {+ const parts = ip.split('.');+ if (parts.length !== 4) return null;+ let n = 0;+ for (const part of parts) {+ if (!/^\d{1,3}$/.test(part)) return null;+ const octet = Number(part);+ if (octet > 255) return null;+ n = n * 256 + octet;+ }+ return n >>> 0;+}++function inV4Cidr(intIp, baseStr, prefix) {+ const baseInt = ipv4ToInt(baseStr);+ if (baseInt === null) return false;+ const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;+ return (intIp & mask) === (baseInt & mask);+}++// Private / non-routable / sensitive IPv4 ranges that must never be paid-fetched.+function isPrivateIPv4(ip) {+ const n = ipv4ToInt(ip);+ if (n === null) return true; // unparseable → treat as unsafe+ return (+ inV4Cidr(n, '0.0.0.0', 8) || // "this" network / unspecified+ inV4Cidr(n, '10.0.0.0', 8) || // RFC1918+ inV4Cidr(n, '127.0.0.0', 8) || // loopback+ inV4Cidr(n, '169.254.0.0', 16) || // link-local incl. 169.254.169.254 metadata+ inV4Cidr(n, '172.16.0.0', 12) || // RFC1918+ inV4Cidr(n, '192.168.0.0', 16) || // RFC1918+ inV4Cidr(n, '100.64.0.0', 10) // CGNAT (RFC6598)+ );+}++// Expand an IPv6 address (possibly with `::` or an embedded IPv4 tail) to its+// 8 16-bit hextet integers. Returns null if it cannot be parsed.+function expandIPv6(addr) {+ let s = addr.trim();+ // Strip zone id (fe80::1%eth0).+ const pct = s.indexOf('%');+ if (pct !== -1) s = s.slice(0, pct);++ const halves = s.split('::');+ if (halves.length > 2) return null;++ const toHextets = (segment) => {+ if (segment === '') return [];+ const out = [];+ for (const part of segment.split(':')) {+ if (part.includes('.')) {+ // Embedded IPv4 tail (e.g. ::ffff:10.0.0.1) → two hextets.+ const v4 = ipv4ToInt(part);+ if (v4 === null) return null;+ out.push((v4 >>> 16) & 0xffff, v4 & 0xffff);+ } else {+ if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return null;+ out.push(parseInt(part, 16));+ }+ }+ return out;+ };++ const head = toHextets(halves[0]);+ if (head === null) return null;+ let tail = [];+ if (halves.length === 2) {+ tail = toHextets(halves[1]);+ if (tail === null) return null;+ } else if (head.length !== 8) {+ return null; // no `::`, so it must be fully specified+ }++ const fill = 8 - head.length - tail.length;+ if (fill < 0) return null;+ return [...head, ...new Array(fill).fill(0), ...tail];+}++function isPrivateIPv6(addr) {+ const h = expandIPv6(addr);+ if (h === null) return true; // unparseable → unsafe++ // :: (unspecified)+ if (h.every((x) => x === 0)) return true;+ // ::1 (loopback)+ if (h.slice(0, 7).every((x) => x === 0) && h[7] === 1) return true;+ // fc00::/7 (ULA)+ if ((h[0] & 0xfe00) === 0xfc00) return true;+ // fe80::/10 (link-local)+ if ((h[0] & 0xffc0) === 0xfe80) return true;++ // IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible — re-check the v4 tail.+ const isV4Mapped = h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff;+ const isV4Compat = h.slice(0, 6).every((x) => x === 0) && (h[6] !== 0 || h[7] > 1);+ if (isV4Mapped || isV4Compat) {+ const v4 = `${h[6] >>> 8}.${h[6] & 0xff}.${h[7] >>> 8}.${h[7] & 0xff}`;+ return isPrivateIPv4(v4);+ }++ return false;+}++// True if `ip` (a literal address string) is in a blocked range.+export function isBlockedAddress(ip) {+ const kind = net.isIP(ip);+ if (kind === 4) return isPrivateIPv4(ip);+ if (kind === 6) return isPrivateIPv6(ip);+ // Not a literal IP — caller must resolve via DNS first.+ return true;+}++// ---------------------------------------------------------------------------+// Allowlists / scheme policy+// ---------------------------------------------------------------------------++function allowedHosts() {+ const raw = process.env.MCP_BRIDGE_ALLOWED_HOSTS;+ if (!raw || !raw.trim()) return null;+ return new Set(+ raw+ .split(',')+ .map((h) => h.trim().toLowerCase())+ .filter(Boolean),+ );+}++function httpAllowed() {+ return process.env.MCP_BRIDGE_ALLOW_HTTP === '1';+}++// ---------------------------------------------------------------------------+// The guard+// ---------------------------------------------------------------------------++/**+ * Validate that `rawUrl` is safe to issue a payment-wrapped request against.+ * Throws a clear Error on any violation. Returns the (string) validated URL.+ */+export async function assertPayableUrl(rawUrl) {+ let parsed;+ try {+ parsed = new URL(rawUrl);+ } catch {+ throw new Error(`refused: not a parseable URL: ${String(rawUrl)}`);+ }++ // Scheme policy: https only, http behind explicit dev opt-in. Everything+ // else (file:, ftp:, data:, gopher:, etc.) is rejected outright.+ if (parsed.protocol === 'http:') {+ if (!httpAllowed()) {+ throw new Error(+ 'refused: http:// is disabled (set MCP_BRIDGE_ALLOW_HTTP=1 for local dev only)',+ );+ }+ } else if (parsed.protocol !== 'https:') {+ throw new Error(`refused: unsupported URL scheme "${parsed.protocol}" (only https is allowed)`);+ }++ const host = parsed.hostname.toLowerCase();+ if (!host) throw new Error('refused: URL has no host');++ // Strict host allowlist mode.+ const allow = allowedHosts();+ if (allow && !allow.has(host)) {+ throw new Error(`refused: host "${host}" is not in MCP_BRIDGE_ALLOWED_HOSTS allowlist`);+ }++ // Literal-IP host → check directly, no DNS.+ const literalKind = net.isIP(host) || net.isIP(stripBrackets(host));+ if (literalKind) {+ const ip = stripBrackets(host);+ if (isBlockedAddress(ip)) {+ throw new Error(`refused: host resolves to a private/blocked address (${ip})`);+ }+ return parsed.toString();+ }++ // Hostname → resolve ALL addresses and reject if ANY is internal. Checking+ // every result (not just the first) closes the multi-A-record / partial+ // rebinding gap.+ let records;+ try {+ records = await dns.lookup(host, { all: true });+ } catch (err) {+ throw new Error(`refused: DNS lookup failed for "${host}": ${err?.code || err?.message || 'error'}`);+ }+ if (!records || records.length === 0) {+ throw new Error(`refused: "${host}" did not resolve to any address`);+ }+ for (const { address } of records) {+ if (isBlockedAddress(address)) {+ throw new Error(`refused: "${host}" resolves to a private/blocked address (${address})`);+ }+ }++ return parsed.toString();+}++function stripBrackets(host) {+ return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;+}diff --git a/mcp-bridge/src/x402-axios-client.js b/mcp-bridge/src/x402-axios-client.jsindex 5955d5c7a..c769e0535 100644--- a/mcp-bridge/src/x402-axios-client.js+++ b/mcp-bridge/src/x402-axios-client.js@@ -11,10 +11,14 @@// against the same wildcard is correct: the scheme whose name matches the// server's selected accept wins.//-// Spending cap: `onBeforePaymentCreation` aborts payload creation when the-// selected accept's `amount` (atomic units) exceeds-// `MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC`. The default cap is 100_000 atomic-// units of USDC = $0.10. Set the env explicitly for higher-cost endpoints.+// Spend controls: `onBeforePaymentCreation` aborts payload creation when any+// of these is violated:+// - per-call: selected accept's `amount` exceeds+// MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC (default 100_000 = $0.10)+// - session: cumulative atomic spent this process would exceed+// MCP_BRIDGE_MAX_TOTAL_ATOMIC (default 1_000_000 = $1.00)+// - payee: selected `payTo` not in MCP_BRIDGE_ALLOWED_PAYTO (when set)+// The session accumulator only increments when a payment is actually created.//// Channel storage: `FileClientChannelStorage` persists voucher + cumulative// amount per channel under `~/.x402-mcp-bridge/channels/client/`. Restart-safe.@@ -31,19 +35,36 @@ import { ExactSvmScheme } from '@x402/svm/exact/client';import { getEvmSigner, getSvmSigner } from './signers.js';import { getChannelsDirectory } from './storage.js';+import { maxPriceAtomic } from './url-guard.js';-const DEFAULT_MAX_PRICE_ATOMIC = 100_000n; // $0.10 USDCconst DEFAULT_DEPOSIT_MULTIPLIER = 5;const DEFAULT_MAX_DEPOSIT_ATOMIC = 5_000_000n; // $5.00 USDC cap on a single deposit+const DEFAULT_MAX_TOTAL_ATOMIC = 1_000_000n; // $1.00 USDC cumulative session ceiling-function maxPriceAtomic() {- const raw = process.env.MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC;- if (!raw) return DEFAULT_MAX_PRICE_ATOMIC;+function maxTotalAtomic() {+ const raw = process.env.MCP_BRIDGE_MAX_TOTAL_ATOMIC;+ if (!raw) return DEFAULT_MAX_TOTAL_ATOMIC;const v = BigInt(raw);- if (v < 0n) throw new Error('MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC must be non-negative');+ if (v < 0n) throw new Error('MCP_BRIDGE_MAX_TOTAL_ATOMIC must be non-negative');return v;}+function allowedPayTo() {+ const raw = process.env.MCP_BRIDGE_ALLOWED_PAYTO;+ if (!raw || !raw.trim()) return null;+ return new Set(+ raw+ .split(',')+ .map((a) => a.trim().toLowerCase())+ .filter(Boolean),+ );+}++// Cumulative atomic spend across all payments created in this process. Reset+// only on restart. The session ceiling guards against a compromised/looping+// LLM draining the signer one sub-cap call at a time.+let sessionSpentAtomic = 0n;+function maxDepositAtomic() {const raw = process.env.MCP_BRIDGE_MAX_DEPOSIT_ATOMIC;if (!raw) return DEFAULT_MAX_DEPOSIT_ATOMIC;@@ -61,15 +82,43 @@ function depositMultiplier() {}function buildSpendingCapHook() {- const cap = maxPriceAtomic();+ const perCallCap = maxPriceAtomic();+ const totalCap = maxTotalAtomic();+ const payToAllow = allowedPayTo();return async ({ selectedRequirements }) => {const amount = BigInt(selectedRequirements?.amount ?? '0');- if (amount > cap) {+ const network = selectedRequirements?.network;+ const asset = selectedRequirements?.asset;+ const payTo = selectedRequirements?.payTo;++ // 1. Per-call amount cap.+ if (amount > perCallCap) {+ return {+ abort: true,+ reason: `payment refused: selected accept amount ${amount} exceeds per-call cap ${perCallCap} (set MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC to override) — network=${network}, asset=${asset}`,+ };+ }++ // 2. Payee allowlist — reject any payTo not explicitly trusted.+ if (payToAllow) {+ const normalized = String(payTo ?? '').toLowerCase();+ if (!normalized || !payToAllow.has(normalized)) {+ return {+ abort: true,+ reason: `payment refused: payee "${payTo}" is not in MCP_BRIDGE_ALLOWED_PAYTO allowlist — network=${network}`,+ };+ }+ }++ // 3. Cumulative session ceiling. Reserve atomically so concurrent calls+ // can't both pass the check and jointly overshoot the cap.+ if (sessionSpentAtomic + amount > totalCap) {return {abort: true,- reason: `selected accept amount ${amount} exceeds spending cap ${cap} (set MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC to override) — network=${selectedRequirements?.network}, asset=${selectedRequirements?.asset}`,+ reason: `payment refused: would exceed session spend cap (${sessionSpentAtomic + amount} > ${totalCap}; already spent ${sessionSpentAtomic}). Set MCP_BRIDGE_MAX_TOTAL_ATOMIC to raise it.`,};}+ sessionSpentAtomic += amount;return undefined;};}@@ -123,6 +172,11 @@ export async function buildBuyerAxios() {// Surface 4xx/5xx as rejections so the bridge returns errors to the LLM// instead of silently producing a "success" tool result with an error body.validateStatus: (s) => s >= 200 && s < 300,+ // SSRF: never follow redirects. assertPayableUrl validates the request+ // URL, but a public host can 3xx-redirect to an internal target+ // (169.254.169.254, localhost, RFC1918) that bypasses that check. With+ // maxRedirects:0 a 3xx surfaces as an error instead of being chased.+ maxRedirects: 0,}),client,);diff --git a/mcp-bridge/tests/url-guard.test.mjs b/mcp-bridge/tests/url-guard.test.mjsnew file mode 100644index 000000000..316998ae5--- /dev/null+++ b/mcp-bridge/tests/url-guard.test.mjs@@ -0,0 +1,136 @@+// Hermetic tests for src/url-guard.js — no network/DNS required.+//+// We test literal-IP URLs (which skip DNS) and scheme/allowlist policy so the+// suite is deterministic and offline. Run: node tests/url-guard.test.mjs+// Exits non-zero on the first failure.++import { assertPayableUrl, isBlockedAddress, maxPriceAtomic } from '../src/url-guard.js';++let passed = 0;+function pass(msg) {+ passed++;+ console.log('PASS:', msg);+}+function fail(msg) {+ console.error('FAIL:', msg);+ process.exit(1);+}++async function expectReject(url, label) {+ try {+ await assertPayableUrl(url);+ fail(`${label} — expected rejection but it was allowed: ${url}`);+ } catch {+ pass(`${label} (${url})`);+ }+}++async function expectAllow(url, label) {+ try {+ const out = await assertPayableUrl(url);+ if (typeof out !== 'string' || !out) fail(`${label} — returned non-string: ${out}`);+ pass(`${label} (${url})`);+ } catch (err) {+ fail(`${label} — expected allow but rejected: ${url} :: ${err?.message}`);+ }+}++function withEnv(overrides, fn) {+ const saved = {};+ for (const k of Object.keys(overrides)) {+ saved[k] = process.env[k];+ if (overrides[k] === undefined) delete process.env[k];+ else process.env[k] = overrides[k];+ }+ return Promise.resolve()+ .then(fn)+ .finally(() => {+ for (const k of Object.keys(overrides)) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ });+}++async function main() {+ // --- scheme policy ---+ await expectReject('file:///etc/passwd', 'file:// rejected');+ await expectReject('ftp://example.com/x', 'ftp:// rejected');+ await expectReject('data:text/plain,hi', 'data: rejected');+ await expectReject('gopher://8.8.8.8/x', 'gopher:// rejected');+ await expectReject('not a url', 'unparseable URL rejected');++ // http rejected by default, allowed only behind the dev opt-in.+ await withEnv({ MCP_BRIDGE_ALLOW_HTTP: undefined }, () =>+ expectReject('http://8.8.8.8/x', 'http:// rejected without MCP_BRIDGE_ALLOW_HTTP'),+ );+ await withEnv({ MCP_BRIDGE_ALLOW_HTTP: '1' }, () =>+ expectAllow('http://8.8.8.8/x', 'http:// allowed with MCP_BRIDGE_ALLOW_HTTP=1 (public IP)'),+ );++ // --- SSRF: private / metadata / loopback literal IPs (https, no DNS) ---+ await expectReject('https://169.254.169.254/latest/meta-data/', 'cloud metadata IP rejected');+ await expectReject('https://10.0.0.1/x', '10.0.0.0/8 rejected');+ await expectReject('https://172.16.5.4/x', '172.16.0.0/12 rejected');+ await expectReject('https://192.168.1.1/x', '192.168.0.0/16 rejected');+ await expectReject('https://127.0.0.1/x', 'loopback 127.0.0.1 rejected');+ await expectReject('https://0.0.0.0/x', 'unspecified 0.0.0.0 rejected');+ await expectReject('https://100.64.1.1/x', 'CGNAT 100.64.0.0/10 rejected');+ await expectReject('https://[::1]/x', 'IPv6 loopback ::1 rejected');+ await expectReject('https://[fd00::1]/x', 'IPv6 ULA fc00::/7 rejected');+ await expectReject('https://[fe80::1]/x', 'IPv6 link-local fe80::/10 rejected');+ await expectReject('https://[::ffff:10.0.0.1]/x', 'IPv4-mapped private rejected');++ // http://localhost & http://10.0.0.1 explicitly (require the http opt-in to+ // reach the IP check; without it the scheme rejection fires first — both+ // must reject). localhost resolves via DNS to a loopback address.+ await withEnv({ MCP_BRIDGE_ALLOW_HTTP: '1' }, async () => {+ await expectReject('http://10.0.0.1/x', 'http://10.0.0.1 rejected (private)');+ await expectReject('http://localhost/x', 'http://localhost rejected (resolves loopback)');+ });++ // --- public literal IPs allowed (https) ---+ await expectAllow('https://8.8.8.8/x', 'public 8.8.8.8 allowed');+ await expectAllow('https://93.184.216.34/x', 'public 93.184.216.34 allowed');++ // --- host allowlist mode ---+ await withEnv({ MCP_BRIDGE_ALLOWED_HOSTS: '8.8.8.8' }, async () => {+ await expectAllow('https://8.8.8.8/x', 'allowlisted host allowed');+ await expectReject('https://93.184.216.34/x', 'non-allowlisted host rejected');+ });++ // --- isBlockedAddress unit checks ---+ if (!isBlockedAddress('127.0.0.1')) fail('isBlockedAddress(127.0.0.1) should be true');+ if (isBlockedAddress('8.8.8.8')) fail('isBlockedAddress(8.8.8.8) should be false');+ if (!isBlockedAddress('::1')) fail('isBlockedAddress(::1) should be true');+ if (!isBlockedAddress('not-an-ip')) fail('isBlockedAddress(non-IP) should be true');+ pass('isBlockedAddress literal-IP classification');++ // --- maxPriceAtomic shared helper ---+ await withEnv({ MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: undefined }, () => {+ if (maxPriceAtomic({ strict: true }) !== 100_000n)+ fail('maxPriceAtomic strict default should be 100_000n');+ if (maxPriceAtomic({ strict: false }) !== null)+ fail('maxPriceAtomic non-strict unset should be null');+ });+ await withEnv({ MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: '250000' }, () => {+ if (maxPriceAtomic({ strict: false }) !== 250_000n)+ fail('maxPriceAtomic should parse env value');+ });+ await withEnv({ MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: '-5' }, () => {+ try {+ maxPriceAtomic({ strict: true });+ fail('maxPriceAtomic should reject negative');+ } catch {+ /* expected */+ }+ });+ pass('maxPriceAtomic strict/non-strict semantics');++ console.log(`\nAll ${passed} url-guard checks passed.`);+}++main().catch((err) => {+ console.error('FATAL:', err?.stack || err);+ process.exit(1);+});diff --git a/mcp-server/package.json b/mcp-server/package.jsonindex 3d7c1bcee..00db6f7d6 100644--- a/mcp-server/package.json+++ b/mcp-server/package.json@@ -57,7 +57,7 @@"@ethereum-attestation-service/eas-sdk": "0.29.1","@metaplex-foundation/js": "^0.20.1","@modelcontextprotocol/sdk": "^1.29.0",- "@solana/web3.js": "latest",+ "@solana/web3.js": "^1.98.4","@tetsuo-ai/protocol": "^0.2.0","@tetsuo-ai/sdk": "^1.4.0","@x402/core": "^2.13.0",diff --git a/mcp-server/src/index.js b/mcp-server/src/index.jsindex 7371ebca5..bb0bf51ae 100755--- a/mcp-server/src/index.js+++ b/mcp-server/src/index.js@@ -21,9 +21,6 @@ import { buildPumpSnapshotTool } from './tools/pump-snapshot.js';import { buildAgentReputationTool } from './tools/agent-reputation.js';import { buildVanityGrinderTool } from './tools/vanity-grinder.js';import { buildTextToAvatarTool } from './tools/text-to-avatar.js';-import { buildRenderAvatarClipTool } from './tools/render-avatar-clip.js';-import { buildTtsSpeakTool } from './tools/tts-speak.js';-import { buildOptimizeGlbTool } from './tools/optimize-glb.js';import { buildSentimentPulseTool } from './tools/sentiment-pulse.js';import { buildEnsSnsResolveTool } from './tools/ens-sns-resolve.js';import { buildAgentDelegateActionTool } from './tools/agent-delegate-action.js';@@ -55,9 +52,8 @@ async function main() {instructions:'Paid x402 MCP tools from three.ws. Each tool quotes its USDC price in its description. ' +'Tool calls without an x402 payment payload in _meta return a PaymentRequired structuredContent ' +- '(v2 MCP transport spec). Tools cover: 3D avatar generation (text_to_avatar), server-side ' +- 'avatar rendering with pose + camera (render_avatar_clip), GLB transcoding/draco/texture ' +- 'compression (optimize_glb), text-to-speech (tts_speak), ENS + SNS name resolution ' ++ '(v2 MCP transport spec). Tools cover: 3D avatar generation (text_to_avatar), ' ++ 'ENS + SNS name resolution ' +'(ens_sns_resolve), agent-to-agent delegation (agent_delegate_action), token sentiment pulse ' +'(sentiment_pulse), pose generation (get_pose_seed), Solana token snapshots (pump_snapshot), ' +'ERC-8004 agent reputation (agent_reputation), Solana vanity address mining ' +@@ -68,9 +64,6 @@ async function main() {const tools = await Promise.all([buildTextToAvatarTool(),- buildRenderAvatarClipTool(),- buildOptimizeGlbTool(),- buildTtsSpeakTool(),buildEnsSnsResolveTool(),buildAgentDelegateActionTool(),buildSentimentPulseTool(),diff --git a/mcp-server/src/tools/vanity-grinder.js b/mcp-server/src/tools/vanity-grinder.jsindex 358d13a35..9d8807da8 100644--- a/mcp-server/src/tools/vanity-grinder.js+++ b/mcp-server/src/tools/vanity-grinder.js@@ -27,22 +27,42 @@ const TOOL_NAME = 'vanity_grinder';// Flat price charged per successful grind, in USDC on Solana.const PRICE_USD = process.env.MCP_VANITY_PRICE_USD?.trim() || '$0.05';+// Hard upper bound on grinder iterations. Each iteration is a synchronous+// ed25519 keypair generation; the loop yields periodically but still pins the+// single-threaded event loop while running. Cap it so a single paid call+// cannot monopolize the process. 1.5M attempts is enough to reliably find a+// 4-char prefix (~58^4 ≈ 11.3M expected, but most 1-3 char requests land far+// sooner); anything longer is rejected up front by the difficulty guard below.+const MAX_ITERATIONS_CAP = 1_500_000;+const DEFAULT_MAX_ITERATIONS = 1_500_000;++// Reject requests whose expected attempts dwarf the iteration cap rather than+// grinding to the cap and timing out. We allow a generous multiple of the cap+// (vanity grinding is probabilistic, so a request with expected ~= cap can+// still succeed), but a prefix that is, say, 10x harder than the cap will+// almost always time out and waste the caller's time and payment.+const DIFFICULTY_REJECT_MULTIPLE = 4;+const TOOL_DESCRIPTION =- `Generate a Solana keypair whose base58 address starts with a chosen prefix (and optionally ends with a chosen suffix). Returns the full 64-byte secret key — handle as a secret. Billed via x402 \`exact\` (flat ${PRICE_USD} USDC on Solana).`;+ `Generate a Solana keypair whose base58 address starts with a chosen prefix (and optionally ends with a chosen suffix). ` ++ `SECURITY: the returned \`privateKey64\` is a REAL, fully-funded-capable private key. It transits the MCP channel in plaintext, ` ++ `so the MCP host (Claude Desktop, Cursor, any proxy) MAY LOG the entire response. Treat the whole tool result as a secret, ` ++ `import it into a wallet immediately, and never reuse a key that may have been logged. ` ++ `Billed via x402 \`exact\` (flat ${PRICE_USD} USDC on Solana).`;const inputJsonSchema = {type: 'object',properties: {prefix: {type: 'string',- description: `Base58 prefix the address must start with. Allowed chars: ${BASE58_ALPHABET}. Max 6 chars.`,- minLength: 0,+ description: `Base58 prefix the address must start with. Allowed chars: ${BASE58_ALPHABET}. 1-6 chars (longer prefixes are exponentially harder and are rejected).`,+ minLength: 1,maxLength: 6,},suffix: {type: 'string',- description: 'Optional base58 suffix the address must end with. Max 6 chars.',- minLength: 0,+ description: 'Optional base58 suffix the address must end with. 1-6 chars.',+ minLength: 1,maxLength: 6,},ignoreCase: {@@ -51,9 +71,9 @@ const inputJsonSchema = {},maxIterations: {type: 'integer',- description: 'Hard cap on grinder iterations. Default 2_000_000.',+ description: `Hard cap on grinder iterations. Default ${DEFAULT_MAX_ITERATIONS}, clamped to ${MAX_ITERATIONS_CAP}.`,minimum: 1,- maximum: 5_000_000,+ maximum: MAX_ITERATIONS_CAP,},},required: ['prefix'],@@ -62,11 +82,34 @@ const inputJsonSchema = {const inputZodShape = {prefix: z.string().min(1).max(6),- suffix: z.string().max(6).optional(),+ suffix: z.string().min(1).max(6).optional(),ignoreCase: z.boolean().optional(),- maxIterations: z.number().int().min(1).max(5_000_000).optional(),+ maxIterations: z.number().int().min(1).max(MAX_ITERATIONS_CAP).optional(),};+// Up-front difficulty guard. Returns null if the request is feasible within the+// iteration cap, or a helpful Error (status 400) if the requested prefix/suffix+// is so hard it would grind to the cap and time out. Exported for tests.+export function assertGrindFeasible({ prefix, suffix, ignoreCase = false, maxIterations = DEFAULT_MAX_ITERATIONS } = {}) {+ const cap = Math.min(Math.max(1, Math.floor(maxIterations)), MAX_ITERATIONS_CAP);+ const expected = estimateAttempts({ prefix, suffix, ignoreCase });+ if (expected > cap * DIFFICULTY_REJECT_MULTIPLE) {+ const pattern = [prefix ? `prefix '${prefix}'` : null, suffix ? `suffix '${suffix}'` : null]+ .filter(Boolean)+ .join(' + ');+ return Object.assign(+ new Error(+ `Pattern too hard: ${pattern} needs ~${Math.round(expected).toLocaleString()} expected attempts, ` ++ `but the grinder caps at ${cap.toLocaleString()} iterations. ` ++ `Use a shorter prefix/suffix (each extra base58 char is ~${ignoreCase ? 33 : 58}x harder)` ++ `${ignoreCase ? '' : ', or enable ignoreCase to roughly halve the difficulty per char'}.`,+ ),+ { status: 400, code: 'vanity_too_hard' },+ );+ }+ return null;+}+export async function buildVanityGrinderTool() {const handler = await paid({@@ -83,18 +126,30 @@ export async function buildVanityGrinderTool() {priceUsd: PRICE_USD,},},- async ({ prefix, suffix, ignoreCase = false, maxIterations = 2_000_000 }) => {+ async ({ prefix, suffix, ignoreCase = false, maxIterations = DEFAULT_MAX_ITERATIONS }) => {+ // Clamp the caller-supplied cap into the safe range so a single paid+ // call can never schedule millions of synchronous keypair generations.+ const cap = Math.min(Math.max(1, Math.floor(maxIterations)), MAX_ITERATIONS_CAP);++ // Reject impossible-to-satisfy patterns up front instead of grinding+ // to the cap and timing out (event-loop DoS / wasted payment).+ const infeasible = assertGrindFeasible({ prefix, suffix, ignoreCase, maxIterations: cap });+ if (infeasible) throw infeasible;+const expected = estimateAttempts({ prefix, suffix, ignoreCase });const grind = await grindMintKeypair({prefix,suffix,ignoreCase,- maxIterations,+ maxIterations: cap,});const address = grind.keypair.publicKey.toBase58();// @solana/web3.js Keypair.secretKey is the full 64-byte ed25519 secret// (32-byte seed || 32-byte pubkey). Wallets like Phantom import this// directly as base58. The client is responsible for storing it.+ //+ // NOTE: privateKey64 is intentionally NEVER passed to console.log/error+ // anywhere in this path — the only sink is the structured tool result.const privateKey64 = bs58.encode(Buffer.from(grind.keypair.secretKey));return {address,@@ -107,7 +162,9 @@ export async function buildVanityGrinderTool() {ignoreCase,priceUsd: PRICE_USD,_secretWarning:- 'privateKey64 is a real private key. Treat the entire MCP response as a secret and store securely.',+ 'privateKey64 is a REAL Solana private key. It just transited the MCP channel in plaintext, ' ++ 'so the MCP host (Claude Desktop / Cursor / any proxy) MAY have logged this entire response. ' ++ 'Import it into a wallet now, treat the whole result as a secret, and do not reuse a key you suspect was logged.',};},);diff --git a/packages/avatar-agent-mcp/package.json b/packages/avatar-agent-mcp/package.jsonindex dddd12478..ae140a9af 100644--- a/packages/avatar-agent-mcp/package.json+++ b/packages/avatar-agent-mcp/package.json@@ -54,6 +54,7 @@},"scripts": {"start": "node src/index.js",+ "test": "node --test \"test/**/*.test.mjs\"","inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"},"dependencies": {diff --git a/packages/avatar-agent-mcp/server.json b/packages/avatar-agent-mcp/server.jsonindex 29756dbbc..4a684d168 100644--- a/packages/avatar-agent-mcp/server.json+++ b/packages/avatar-agent-mcp/server.json@@ -4,7 +4,8 @@"description": "3D AI Agent Avatar — render any GLB, give it a Solana wallet, a voice, and pump.fun powers.","repository": {"url": "https://github.com/nirholas/three.ws",- "source": "github"+ "source": "github",+ "subfolder": "packages/avatar-agent-mcp"},"version": "1.0.3","packages": [diff --git a/packages/avatar-agent-mcp/src/config.js b/packages/avatar-agent-mcp/src/config.jsindex dc5c3a454..3d818297c 100644--- a/packages/avatar-agent-mcp/src/config.js+++ b/packages/avatar-agent-mcp/src/config.js@@ -7,7 +7,32 @@ export function env(key, fallback) {return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;}-export const SOLANA_RPC_URL = env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');+// Validate the Solana RPC endpoint at load time. We sign and broadcast real+// mainnet transactions over this URL, so a plaintext-http endpoint (outside of+// localhost) is a credential/MITM risk — reject it. http://localhost and+// http://127.0.0.1 are allowed for local validators in dev.+function validateRpcUrl(raw) {+ let u;+ try {+ u = new URL(raw);+ } catch {+ throw Object.assign(new Error(`SOLANA_RPC_URL is not a valid URL: "${raw}"`), { code: 'bad_rpc_url' });+ }+ if (u.protocol === 'https:') return raw;+ const isLocal = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(u.hostname);+ if (u.protocol === 'http:' && isLocal) return raw;+ throw Object.assign(+ new Error(+ `SOLANA_RPC_URL must be https (got "${u.protocol}//${u.hostname}"). ` ++ 'Only http://localhost is allowed for local dev validators.',+ ),+ { code: 'insecure_rpc_url' },+ );+}++export const SOLANA_RPC_URL = validateRpcUrl(+ env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com'),+);export const ETH_RPC_URL = env('ETH_RPC_URL') || env('MAINNET_RPC_URL') || null;export const HELIUS_API_KEY = env('HELIUS_API_KEY', '');export const OPENAI_API_KEY = env('OPENAI_API_KEY', '');@@ -18,13 +43,13 @@ export const REPLICATE_TEXT_TO_AVATAR_MODEL = env('REPLICATE_TEXT_TO_AVATAR_MODE// argument that overrides this on a per-call basis.export const SOLANA_DEFAULT_SECRET = env('SOLANA_SECRET_KEY') || env('FUNDER_SECRET') || '';-// $three is the official three.ws token on pump.fun. Used as the canonical-// example mint in tool examples and README demos.+// $three is the official three.ws token on pump.fun and the ONLY coin this+// server references by name. The `target:"three"` shortcut in pump_buy resolves+// to this CA. Operators may override THREE_MINT only to track an updated+// canonical $three contract — never to point the alias at a different coin.export const THREE_MINT = env('THREE_MINT',- // Placeholder until the user pins their real $three CA. Override via- // the THREE_MINT env var when running the MCP.- '',+ 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',);export const VIEWER_BASE = env('VIEWER_BASE', 'https://three.ws/viewer');diff --git a/packages/avatar-agent-mcp/src/index.js b/packages/avatar-agent-mcp/src/index.jsindex b7635fe5e..b559a72f2 100755--- a/packages/avatar-agent-mcp/src/index.js+++ b/packages/avatar-agent-mcp/src/index.js@@ -102,6 +102,8 @@ async function main() {ok: false,error: err?.code || 'unhandled',message: err?.message || String(err),+ ...(err?.status ? { status: err.status } : {}),+ ...(err?.signature ? { signature: err.signature } : {}),};return {content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],diff --git a/packages/avatar-agent-mcp/src/lib/atomic-collect.js b/packages/avatar-agent-mcp/src/lib/atomic-collect.jsindex 0a6f38682..9b6cd40e6 100644--- a/packages/avatar-agent-mcp/src/lib/atomic-collect.js+++ b/packages/avatar-agent-mcp/src/lib/atomic-collect.js@@ -21,10 +21,13 @@ import {import { bs58encode, getConnection, keypairFromSecret } from './solana.js';import { randomTipAccount, submitBundle, waitForSignatures } from './jito.js';--// Rent-exempt minimum for a bare system account. Leaving exactly this in-// the creator keeps the account alive without locking up unnecessary SOL.-const RENT_EXEMPT_LAMPORTS = 890_880;+import {+ assertLamportsWithinCap,+ clampJitoTipSol,+ clampPriorityMicroLamports,+ enforceMinBuffer,+ RENT_EXEMPT_LAMPORTS,+} from './spend-policy.js';export async function atomicCollect({funderSecret,@@ -36,6 +39,11 @@ export async function atomicCollect({minVaultSol = 0.001,}) {if (!destination) throw new Error('atomicCollect: destination is required');+ // Clamp the tip + priority to policy ceilings and floor the buffer to the+ // rent-exempt minimum so a typo can't burn SOL on a tip or close the creator.+ jitoTipSol = clampJitoTipSol(jitoTipSol);+ priorityMicroLamports = clampPriorityMicroLamports(priorityMicroLamports);+ bufferLamports = enforceMinBuffer(bufferLamports);const destinationPk = new PublicKey(destination);const funder = keypairFromSecret(funderSecret);const creator = keypairFromSecret(creatorSecret);@@ -69,6 +77,8 @@ export async function atomicCollect({creatorPreBalSol: creatorPreBal / LAMPORTS_PER_SOL,};}+ // Spend cap — the drain moves real SOL to the destination; bound it.+ assertLamportsWithinCap(transferAmount, 'pump_collect_fees drain');const funderBal = await conn.getBalance(funder.publicKey, 'confirmed');const needed = (jitoTipSol + 0.002) * LAMPORTS_PER_SOL;@@ -123,8 +133,13 @@ export async function atomicCollect({const sig = bs58encode(tx.signatures[0]);const wait = await waitForSignatures(conn, [sig], { timeoutMs: 60_000, intervalMs: 2_000 });+ const status = wait.err === 'timeout' ? 'pending' : wait.ok ? 'confirmed' : 'failed';return {ok: wait.ok,+ status,+ ...(status === 'pending'+ ? { note: `Collect bundle ${bundleId} did not confirm within the timeout. The drain MAY still land — do NOT resubmit without checking ${sig} on Solscan first (risk of double-collect).` }+ : {}),bundleId,bundleExplorer: explorer,signature: sig,diff --git a/packages/avatar-agent-mcp/src/lib/atomic-launch.js b/packages/avatar-agent-mcp/src/lib/atomic-launch.jsindex 5edb4209c..e47ea7c7e 100644--- a/packages/avatar-agent-mcp/src/lib/atomic-launch.js+++ b/packages/avatar-agent-mcp/src/lib/atomic-launch.js@@ -26,6 +26,11 @@ import FormData from 'form-data';import { bs58encode, bs58decode, getConnection, keypairFromSecret } from './solana.js';import { JITO_TIP_ACCOUNTS, randomTipAccount, submitBundle, waitForSignatures } from './jito.js';+import {+ assertSolWithinCap,+ clampJitoTipSol,+ clampPriorityMicroLamports,+} from './spend-policy.js';const PUMP_IPFS_URL = 'https://pump.fun/api/ipfs';@@ -96,6 +101,13 @@ export async function atomicLaunch({if (!symbol) throw new Error('atomicLaunch: symbol is required');if (!uri) throw new Error('atomicLaunch: uri is required (call uploadPumpMetadata first or pass an existing one)');+ // Spend cap + tip/priority clamps. The funder's outlay is rent + tip; bound+ // each so an injected arg can't drain the funder.+ jitoTipSol = clampJitoTipSol(jitoTipSol);+ priorityMicroLamports = clampPriorityMicroLamports(priorityMicroLamports);+ assertSolWithinCap(rentSol, 'pump_launch (creator rent transfer)');+ assertSolWithinCap(rentSol + jitoTipSol, 'pump_launch (funder total outlay)');+const funder = keypairFromSecret(funderSecret);const creator = keypairFromSecret(creatorSecret);const mint = mintSecret@@ -165,8 +177,13 @@ export async function atomicLaunch({const sig2 = bs58encode(tx2.signatures[0]);const wait = await waitForSignatures(conn, [sig1, sig2], { timeoutMs: 60_000, intervalMs: 2_000 });+ const status = wait.err === 'timeout' ? 'pending' : wait.ok ? 'confirmed' : 'failed';return {ok: wait.ok,+ status,+ ...(status === 'pending'+ ? { note: `Launch bundle ${bundleId} did not confirm within the timeout. The mint MAY still have been created — do NOT relaunch without checking ${mint.publicKey.toBase58()} on Solscan/pump.fun first.` }+ : {}),bundleId,bundleExplorer: explorer,mint: mint.publicKey.toBase58(),diff --git a/packages/avatar-agent-mcp/src/lib/jupiter-buy.js b/packages/avatar-agent-mcp/src/lib/jupiter-buy.jsindex 7f5d745f9..dfd224668 100644--- a/packages/avatar-agent-mcp/src/lib/jupiter-buy.js+++ b/packages/avatar-agent-mcp/src/lib/jupiter-buy.js@@ -18,6 +18,20 @@ import {import { bs58encode, getConnection, keypairFromSecret } from './solana.js';import { randomTipAccount, submitBundle, waitForSignatures } from './jito.js';+import {+ assertSolWithinCap,+ clampJitoTipSol,+ clampPriorityMicroLamports,+} from './spend-policy.js';++// Map a waitForSignatures result onto an unambiguous status. A timeout is+// 'pending' (tx MAY have landed — caller must NOT blindly retry); a confirmed+// error is 'failed'; otherwise 'confirmed'.+function settleStatus(wait) {+ if (wait.err === 'timeout') return 'pending';+ if (!wait.ok) return 'failed';+ return 'confirmed';+}const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -50,6 +64,8 @@ async function fetchJupiterSwapTx({ quoteResponse, userPublicKey, priorityMicroL}export async function jupiterBuyDirect({ buyerSecret, targetMint, buySol = 0.01, slippageBps = 500, priorityMicroLamports = 2_000_000 }) {+ assertSolWithinCap(buySol, 'pump_buy');+ const microLamports = clampPriorityMicroLamports(priorityMicroLamports);const buyer = keypairFromSecret(buyerSecret);const conn = getConnection();@@ -58,7 +74,7 @@ export async function jupiterBuyDirect({ buyerSecret, targetMint, buySol = 0.01,const { swapTransaction } = await fetchJupiterSwapTx({quoteResponse: quote,userPublicKey: buyer.publicKey.toBase58(),- priorityMicroLamports,+ priorityMicroLamports: microLamports,});const swapTx = VersionedTransaction.deserialize(Buffer.from(swapTransaction, 'base64'));swapTx.sign([buyer]);@@ -66,8 +82,13 @@ export async function jupiterBuyDirect({ buyerSecret, targetMint, buySol = 0.01,const sig = await conn.sendTransaction(swapTx, { maxRetries: 5 });const wait = await waitForSignatures(conn, [sig], { timeoutMs: 60_000, intervalMs: 2_000 });+ const status = settleStatus(wait);return {ok: wait.ok,+ status,+ ...(status === 'pending'+ ? { note: `Swap ${sig} did not confirm within the timeout. It MAY still land — do NOT resend without checking Solscan first.` }+ : {}),signature: sig,buyer: buyer.publicKey.toBase58(),target: targetMint,@@ -90,6 +111,9 @@ export async function jupiterBuyBundled({jitoTipSol = 0.005,priorityMicroLamports = 2_000_000,}) {+ assertSolWithinCap(buySol, 'pump_buy (bundled)');+ jitoTipSol = clampJitoTipSol(jitoTipSol);+ const microLamports = clampPriorityMicroLamports(priorityMicroLamports);const funder = keypairFromSecret(funderSecret);const buyer = keypairFromSecret(buyerSecret);const conn = getConnection();@@ -109,7 +133,7 @@ export async function jupiterBuyBundled({const { swapTransaction } = await fetchJupiterSwapTx({quoteResponse: quote,userPublicKey: buyer.publicKey.toBase58(),- priorityMicroLamports,+ priorityMicroLamports: microLamports,});const swapTx = VersionedTransaction.deserialize(Buffer.from(swapTransaction, 'base64'));swapTx.sign([buyer]);@@ -122,7 +146,7 @@ export async function jupiterBuyBundled({payerKey: funder.publicKey,recentBlockhash: blockhash,instructions: [- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityMicroLamports }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports }),ComputeBudgetProgram.setComputeUnitLimit({ units: 1000 }),SystemProgram.transfer({ fromPubkey: funder.publicKey, toPubkey: buyer.publicKey, lamports: transferToBuyer }),SystemProgram.transfer({ fromPubkey: funder.publicKey, toPubkey: tipAccount, lamports: Math.floor(jitoTipSol * LAMPORTS_PER_SOL) }),@@ -137,8 +161,13 @@ export async function jupiterBuyBundled({const sig2 = bs58encode(swapTx.signatures[0]);const wait = await waitForSignatures(conn, [sig1, sig2], { timeoutMs: 60_000, intervalMs: 2_000 });+ const status = settleStatus(wait);return {ok: wait.ok,+ status,+ ...(status === 'pending'+ ? { note: `Bundle ${bundleId} did not confirm within the timeout. The swap MAY still land — do NOT resubmit without checking the signatures on Solscan first.` }+ : {}),bundleId,bundleExplorer: explorer,fundTxSignature: sig1,diff --git a/packages/avatar-agent-mcp/src/lib/solana.js b/packages/avatar-agent-mcp/src/lib/solana.jsindex a48987bba..7c16d2d0b 100644--- a/packages/avatar-agent-mcp/src/lib/solana.js+++ b/packages/avatar-agent-mcp/src/lib/solana.js@@ -17,6 +17,7 @@ import {import bs58 from 'bs58';import { SOLANA_RPC_URL, SOLANA_DEFAULT_SECRET } from '../config.js';+import { assertSolWithinCap, clampPriorityMicroLamports } from './spend-policy.js';const bs58encode = bs58.default ? bs58.default.encode : bs58.encode;const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;@@ -103,6 +104,9 @@ export async function sendSol({ secret, to, sol, priorityMicroLamports = 100000err.code = 'invalid_destination';throw err;}+ // Spend cap — enforced here in the signing lib so EVERY caller is covered,+ // not just the wallet_send schema.+ assertSolWithinCap(sol, 'wallet_send');const signer = loadSigner(secret);const conn = getConnection();const lamports = Math.floor(Number(sol) * LAMPORTS_PER_SOL);@@ -111,12 +115,13 @@ export async function sendSol({ secret, to, sol, priorityMicroLamports = 100000err.code = 'invalid_amount';throw err;}+ const microLamports = clampPriorityMicroLamports(priorityMicroLamports);const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');const msg = new TransactionMessage({payerKey: signer.publicKey,recentBlockhash: blockhash,instructions: [- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityMicroLamports }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports }),ComputeBudgetProgram.setComputeUnitLimit({ units: 1000 }),SystemProgram.transfer({fromPubkey: signer.publicKey,@@ -128,17 +133,35 @@ export async function sendSol({ secret, to, sol, priorityMicroLamports = 100000const tx = new VersionedTransaction(msg);tx.sign([signer]);const sig = await conn.sendTransaction(tx, { maxRetries: 5 });- const conf = await conn.confirmTransaction(- { signature: sig, blockhash, lastValidBlockHeight },- 'confirmed',- );++ // Confirmation can throw (e.g. block-height-exceeded timeout) even though+ // the tx may still land. Distinguish "confirmed failure" from "unknown" so+ // the caller does NOT blindly retry and risk a double-spend.+ let conf;+ try {+ conf = await conn.confirmTransaction(+ { signature: sig, blockhash, lastValidBlockHeight },+ 'confirmed',+ );+ } catch (waitErr) {+ const err = new Error(+ `Transaction ${sig} was submitted but confirmation timed out (${waitErr?.message || waitErr}). ` ++ 'It MAY still land. Do NOT resend — check the signature on Solscan first to avoid a double-spend.',+ );+ err.code = 'tx_unconfirmed';+ err.status = 'pending';+ err.signature = sig;+ throw err;+ }if (conf?.value?.err) {const err = new Error(`Transaction failed: ${JSON.stringify(conf.value.err)}`);err.code = 'tx_failed';+ err.status = 'failed';err.signature = sig;throw err;}return {+ status: 'confirmed',signature: sig,from: signer.publicKey.toBase58(),to,diff --git a/packages/avatar-agent-mcp/src/lib/spend-policy.js b/packages/avatar-agent-mcp/src/lib/spend-policy.jsnew file mode 100644index 000000000..3e683b7bb--- /dev/null+++ b/packages/avatar-agent-mcp/src/lib/spend-policy.js@@ -0,0 +1,194 @@+// Spend policy: hard guardrails around every value-moving operation.+//+// This is the single source of truth for the operator-configurable limits+// that wrap the wallet/pump tools. The caps are read once from the env at+// module load and enforced in two places:+//+// • The SIGNING libs (solana.js, jupiter-buy.js, atomic-collect.js,+// atomic-launch.js) call assertSolWithinCap() right before they build a+// transaction, so EVERY path — direct, bundled, atomic — is covered even+// if a future tool forgets to check.+// • The tool HANDLERS enforce the recipient allowlist and the explicit+// `confirm:true` requirement for irreversible actions.+//+// Limits are intentionally conservative by default. An operator who wants+// larger spends sets the env var explicitly and thereby accepts the risk.++import { LAMPORTS_PER_SOL } from '@solana/web3.js';++function envRaw(key) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : undefined;+}++function envNumber(key, fallback) {+ const raw = envRaw(key);+ if (raw === undefined) return fallback;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) {+ throw Object.assign(new Error(`${key} must be a non-negative number (got "${raw}")`), {+ code: 'bad_policy_config',+ });+ }+ return n;+}++function envBool(key, fallback) {+ const raw = envRaw(key);+ if (raw === undefined) return fallback;+ return !['0', 'false', 'no', 'off'].includes(raw.toLowerCase());+}++// Max SOL that any single transaction may move (send / buy / launch funding /+// fee drain). Default 0.5 SOL — generous for testing, low enough to bound a+// leaked-key or prompt-injection blast radius.+export const MAX_SOL_PER_TX = envNumber('MAX_SOL_PER_TX', 0.5);++// Optional recipient allowlist. Comma-separated base58 pubkeys. When set, SOL+// destinations (wallet_send, pump_collect drain target) must be in the list.+export const RECIPIENT_ALLOWLIST = (() => {+ const raw = envRaw('RECIPIENT_ALLOWLIST');+ if (!raw) return null; // null = no allowlist configured (allow any valid pubkey)+ const set = new Set(+ raw+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean),+ );+ return set.size ? set : null;+})();++// Irreversible tools require an explicit confirm:true unless the operator+// opts out by setting REQUIRE_CONFIRM=0.+export const REQUIRE_CONFIRM = envBool('REQUIRE_CONFIRM', true);++// Hard ceiling on the Jito tip so a typo / injected arg can't burn SOL on a+// tip. Bundled launches/collects clamp to this.+export const MAX_JITO_TIP_SOL = envNumber('MAX_JITO_TIP_SOL', 0.02);++// Sane ceiling on the compute-unit price (micro-lamports). 50,000,000 µLamports+// at the small unit limits these txs use stays well under 0.01 SOL of priority.+export const MAX_PRIORITY_MICRO_LAMPORTS = envNumber('MAX_PRIORITY_MICRO_LAMPORTS', 50_000_000);++// Rent-exempt minimum for a bare system account. The collect drain must leave+// at least this so the creator account isn't closed out from under pump.fun.+export const RENT_EXEMPT_LAMPORTS = 890_880;++/**+ * Assert a SOL amount is within MAX_SOL_PER_TX. Throws `over_spend_cap` with a+ * clear message otherwise. Call this inside the signing libs.+ * @param {number} sol+ * @param {string} [label] — what the spend is for (logged in the error text)+ */+export function assertSolWithinCap(sol, label = 'transaction') {+ const n = Number(sol);+ if (!Number.isFinite(n) || n < 0) {+ throw Object.assign(new Error(`${label}: amount must be a non-negative number (got ${sol})`), {+ code: 'invalid_amount',+ });+ }+ if (n > MAX_SOL_PER_TX) {+ throw Object.assign(+ new Error(+ `${label}: ${n} SOL exceeds the per-tx spend cap of ${MAX_SOL_PER_TX} SOL. ` ++ 'Raise MAX_SOL_PER_TX in the MCP server environment to allow larger spends.',+ ),+ { code: 'over_spend_cap' },+ );+ }+ return n;+}++/**+ * Assert a lamports amount is within MAX_SOL_PER_TX. Used by the collect drain,+ * which computes the transfer in lamports (BigInt-safe — no float round-trip).+ * @param {bigint|number} lamports+ * @param {string} [label]+ */+export function assertLamportsWithinCap(lamports, label = 'transaction') {+ const cap = BigInt(Math.round(MAX_SOL_PER_TX * LAMPORTS_PER_SOL));+ const value = typeof lamports === 'bigint' ? lamports : BigInt(Math.floor(Number(lamports)));+ if (value < 0n) {+ throw Object.assign(new Error(`${label}: lamports must be non-negative`), { code: 'invalid_amount' });+ }+ if (value > cap) {+ throw Object.assign(+ new Error(+ `${label}: ${(Number(value) / LAMPORTS_PER_SOL).toFixed(6)} SOL exceeds the per-tx spend cap of ` ++ `${MAX_SOL_PER_TX} SOL. Raise MAX_SOL_PER_TX to allow larger spends.`,+ ),+ { code: 'over_spend_cap' },+ );+ }+ return value;+}++/**+ * Enforce the recipient allowlist (if configured). Throws `recipient_not_allowed`.+ * @param {string} pubkey — destination base58+ * @param {string} [label]+ */+export function assertRecipientAllowed(pubkey, label = 'destination') {+ if (!RECIPIENT_ALLOWLIST) return; // no allowlist → any valid pubkey is fine+ if (!RECIPIENT_ALLOWLIST.has(String(pubkey))) {+ throw Object.assign(+ new Error(+ `${label} ${pubkey} is not in RECIPIENT_ALLOWLIST. ` ++ 'Add it to the allowlist env var to permit sends to this address.',+ ),+ { code: 'recipient_not_allowed' },+ );+ }+}++/**+ * Gate an irreversible tool on an explicit confirm flag. Returns a refusal+ * object (for the handler to return directly) when confirmation is required+ * but absent; returns null when the action may proceed.+ * @param {boolean|undefined} confirm — the tool's `confirm` arg+ * @param {string} action — human-readable name of the irreversible action+ */+export function confirmationGate(confirm, action) {+ if (!REQUIRE_CONFIRM) return null;+ if (confirm === true) return null;+ return {+ ok: false,+ error: 'confirmation_required',+ message:+ `${action} is IRREVERSIBLE and moves real funds on Solana mainnet. ` ++ 'Re-issue the call with `confirm: true` to proceed. ' ++ '(Set REQUIRE_CONFIRM=0 on the MCP server to disable this prompt.)',+ };+}++/**+ * Clamp a Jito tip (SOL) to MAX_JITO_TIP_SOL. Returns the clamped value.+ * @param {number} tipSol+ */+export function clampJitoTipSol(tipSol) {+ const n = Number(tipSol);+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.min(n, MAX_JITO_TIP_SOL);+}++/**+ * Clamp a compute-unit price to MAX_PRIORITY_MICRO_LAMPORTS.+ * @param {number} micros+ */+export function clampPriorityMicroLamports(micros) {+ const n = Math.floor(Number(micros));+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.min(n, MAX_PRIORITY_MICRO_LAMPORTS);+}++/**+ * Enforce a floor on the collect drain buffer so the creator account stays+ * rent-exempt. Returns the larger of the requested buffer and the rent-exempt+ * minimum.+ * @param {number|bigint} bufferLamports+ */+export function enforceMinBuffer(bufferLamports) {+ const n = typeof bufferLamports === 'bigint' ? Number(bufferLamports) : Math.floor(Number(bufferLamports));+ if (!Number.isFinite(n) || n < RENT_EXEMPT_LAMPORTS) return RENT_EXEMPT_LAMPORTS;+ return n;+}diff --git a/packages/avatar-agent-mcp/src/tools/pump-buy.js b/packages/avatar-agent-mcp/src/tools/pump-buy.jsindex e0995c57c..d8a1c9a72 100644--- a/packages/avatar-agent-mcp/src/tools/pump-buy.js+++ b/packages/avatar-agent-mcp/src/tools/pump-buy.js@@ -13,6 +13,7 @@ import { z } from 'zod';import { isValidPubkey } from '../lib/solana.js';import { jupiterBuyBundled, jupiterBuyDirect } from '../lib/jupiter-buy.js';+import { confirmationGate } from '../lib/spend-policy.js';import { THREE_MINT } from '../config.js';export const def = {@@ -30,8 +31,11 @@ export const def = {jitoTipSol: z.number().min(0).optional().describe('Jito tip in SOL (default 0.005). Only used when jitoBundle=true.'),priorityMicroLamports: z.number().int().min(0).max(20_000_000).optional().describe('Compute-unit price (default 2_000_000).'),+ confirm: z.boolean().optional().describe('Must be true to execute this irreversible swap (when REQUIRE_CONFIRM is on).'),},async handler(args) {+ const gate = confirmationGate(args.confirm, 'pump_buy (token swap)');+ if (gate) return gate;let target = args.target;if (target === 'three' || target === '$three') {if (!THREE_MINT) return { ok: false, error: 'three_mint_not_configured' };diff --git a/packages/avatar-agent-mcp/src/tools/pump-collect.js b/packages/avatar-agent-mcp/src/tools/pump-collect.jsindex a122d2f2b..e75cf2289 100644--- a/packages/avatar-agent-mcp/src/tools/pump-collect.js+++ b/packages/avatar-agent-mcp/src/tools/pump-collect.js@@ -12,6 +12,7 @@import { z } from 'zod';import { atomicCollect } from '../lib/atomic-collect.js';+import { assertRecipientAllowed, confirmationGate } from '../lib/spend-policy.js';export const def = {name: 'pump_collect_fees',@@ -29,9 +30,13 @@ export const def = {.describe('Lamports to leave in the creator wallet (default 890880, rent-exempt minimum).'),minVaultSol: z.number().min(0).optional().describe('Abort if the vault holds less than this (default 0.001).'),+ confirm: z.boolean().optional().describe('Must be true to execute this irreversible collect+drain (when REQUIRE_CONFIRM is on).'),},async handler(args) {+ const gate = confirmationGate(args.confirm, 'pump_collect_fees (vault drain)');+ if (gate) return gate;try {+ assertRecipientAllowed(args.destination, 'pump_collect_fees destination');return await atomicCollect({funderSecret: args.funderSecret,creatorSecret: args.creatorSecret,diff --git a/packages/avatar-agent-mcp/src/tools/pump-launch.js b/packages/avatar-agent-mcp/src/tools/pump-launch.jsindex 023f65bd0..0fb5df14f 100644--- a/packages/avatar-agent-mcp/src/tools/pump-launch.js+++ b/packages/avatar-agent-mcp/src/tools/pump-launch.js@@ -16,6 +16,7 @@import { z } from 'zod';import { atomicLaunch, uploadPumpMetadata } from '../lib/atomic-launch.js';+import { confirmationGate } from '../lib/spend-policy.js';export const def = {name: 'pump_launch',@@ -38,8 +39,11 @@ export const def = {jitoTipSol: z.number().min(0).optional().describe('Jito tip in SOL (default 0.005).'),priorityMicroLamports: z.number().int().min(0).max(20_000_000).optional().describe('Compute-unit priority price (default 2_000_000).'),+ confirm: z.boolean().optional().describe('Must be true to execute this irreversible mint launch (when REQUIRE_CONFIRM is on).'),},async handler(args) {+ const gate = confirmationGate(args.confirm, 'pump_launch (token mint)');+ if (gate) return gate;try {let uri = args.uri;let uploadedMeta = null;diff --git a/packages/avatar-agent-mcp/src/tools/wallet-send.js b/packages/avatar-agent-mcp/src/tools/wallet-send.jsindex 05e7328d7..e6756bbb9 100644--- a/packages/avatar-agent-mcp/src/tools/wallet-send.js+++ b/packages/avatar-agent-mcp/src/tools/wallet-send.js@@ -6,21 +6,26 @@import { z } from 'zod';import { sendSol } from '../lib/solana.js';+import { assertRecipientAllowed, confirmationGate } from '../lib/spend-policy.js';export const def = {name: 'wallet_send',title: 'Send SOL on Solana mainnet',description:- 'Send SOL from the configured signer to a destination pubkey. The signer is supplied via the `secret` arg (base58) or via SOLANA_SECRET_KEY env on the MCP server. Returns the confirmed signature and a Solscan link. EXECUTION ACTION — funds move on mainnet.',+ 'Send SOL from the configured signer to a destination pubkey. The signer is supplied via the `secret` arg (base58) or via SOLANA_SECRET_KEY env on the MCP server. Returns the confirmed signature and a Solscan link. EXECUTION ACTION — funds move on mainnet, irreversible: pass confirm:true. Capped by MAX_SOL_PER_TX; destination must be in RECIPIENT_ALLOWLIST if one is configured.',inputSchema: {to: z.string().min(32).max(64).describe('Destination Solana pubkey.'),sol: z.number().positive().describe('Amount of SOL to send.'),secret: z.string().optional().describe('Base58 secret of the sender. Falls back to SOLANA_SECRET_KEY env.'),priorityMicroLamports: z.number().int().min(0).max(10_000_000).optional().describe('Compute-unit price (default 100000).'),+ confirm: z.boolean().optional().describe('Must be true to execute this irreversible send (when REQUIRE_CONFIRM is on).'),},async handler(args) {+ const gate = confirmationGate(args.confirm, 'wallet_send (SOL transfer)');+ if (gate) return gate;try {+ assertRecipientAllowed(args.to, 'wallet_send destination');const out = await sendSol({secret: args.secret,to: args.to,@@ -29,7 +34,13 @@ export const def = {});return { ok: true, ...out };} catch (err) {- return { ok: false, error: err.code || 'send_failed', message: err.message, signature: err.signature || null };+ return {+ ok: false,+ error: err.code || 'send_failed',+ message: err.message,+ signature: err.signature || null,+ ...(err.status ? { status: err.status } : {}),+ };}},};diff --git a/packages/avatar-agent-mcp/test/spend-policy.test.mjs b/packages/avatar-agent-mcp/test/spend-policy.test.mjsnew file mode 100644index 000000000..6d81369f5--- /dev/null+++ b/packages/avatar-agent-mcp/test/spend-policy.test.mjs@@ -0,0 +1,78 @@+// C4 / H5: spend caps, allowlist, confirmation gate, and tip/buffer bounds.+// Pure logic — no network, no signing.+//+// Run: node --test packages/avatar-agent-mcp/test/spend-policy.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import {+ MAX_SOL_PER_TX,+ assertSolWithinCap,+ assertLamportsWithinCap,+ assertRecipientAllowed,+ confirmationGate,+ clampJitoTipSol,+ clampPriorityMicroLamports,+ enforceMinBuffer,+ RENT_EXEMPT_LAMPORTS,+ MAX_JITO_TIP_SOL,+ MAX_PRIORITY_MICRO_LAMPORTS,+} from '../src/lib/spend-policy.js';++test('default per-tx cap is 0.5 SOL', () => {+ assert.equal(MAX_SOL_PER_TX, 0.5);+});++test('assertSolWithinCap allows an amount at/under the cap', () => {+ assert.doesNotThrow(() => assertSolWithinCap(0.5, 'test'));+ assert.equal(assertSolWithinCap(0.1, 'test'), 0.1);+});++test('assertSolWithinCap throws over_spend_cap above the cap', () => {+ assert.throws(+ () => assertSolWithinCap(1, 'wallet_send'),+ (err) => err.code === 'over_spend_cap' && /spend cap/.test(err.message),+ );+});++test('assertSolWithinCap rejects NaN/negative as invalid_amount', () => {+ assert.throws(() => assertSolWithinCap(-1, 't'), (e) => e.code === 'invalid_amount');+ assert.throws(() => assertSolWithinCap(NaN, 't'), (e) => e.code === 'invalid_amount');+});++test('assertLamportsWithinCap is BigInt-safe and respects the cap', () => {+ const cap = BigInt(Math.round(MAX_SOL_PER_TX * 1e9));+ assert.doesNotThrow(() => assertLamportsWithinCap(cap, 'drain'));+ assert.throws(() => assertLamportsWithinCap(cap + 1n, 'drain'), (e) => e.code === 'over_spend_cap');+});++test('confirmationGate refuses without confirm and passes with confirm:true', () => {+ const refusal = confirmationGate(undefined, 'wallet_send');+ assert.equal(refusal.ok, false);+ assert.equal(refusal.error, 'confirmation_required');+ assert.match(refusal.message, /confirm: true/);+ assert.equal(confirmationGate(true, 'wallet_send'), null);+ assert.notEqual(confirmationGate(false, 'wallet_send'), null);+});++test('assertRecipientAllowed is a no-op when no allowlist is configured', () => {+ // No RECIPIENT_ALLOWLIST set in this process → any pubkey allowed.+ assert.doesNotThrow(() => assertRecipientAllowed('AnyAddr1111111111111111111111111111111111', 'dest'));+});++test('clampJitoTipSol caps the tip at MAX_JITO_TIP_SOL', () => {+ assert.equal(clampJitoTipSol(MAX_JITO_TIP_SOL + 5), MAX_JITO_TIP_SOL);+ assert.equal(clampJitoTipSol(0.001), 0.001);+ assert.equal(clampJitoTipSol(-1), 0);+});++test('clampPriorityMicroLamports caps the priority price', () => {+ assert.equal(clampPriorityMicroLamports(MAX_PRIORITY_MICRO_LAMPORTS * 10), MAX_PRIORITY_MICRO_LAMPORTS);+ assert.equal(clampPriorityMicroLamports(123), 123);+});++test('enforceMinBuffer floors the buffer at the rent-exempt minimum', () => {+ assert.equal(enforceMinBuffer(0), RENT_EXEMPT_LAMPORTS);+ assert.equal(enforceMinBuffer(RENT_EXEMPT_LAMPORTS + 100), RENT_EXEMPT_LAMPORTS + 100);+});diff --git a/packages/pumpfun-mcp/server.json b/packages/pumpfun-mcp/server.jsonindex 3065e53c1..a1bdb7257 100644--- a/packages/pumpfun-mcp/server.json+++ b/packages/pumpfun-mcp/server.json@@ -4,7 +4,8 @@"description": "Free, read-only pump.fun + Solana MCP server: token discovery, on-chain bonding-curve & holder analysis, creator fee-claim tracking, SNS name resolution, KOL radar/leaderboard signals, read-only swap quotes, and live 3D token snapshots (coin medallion + holder galaxy + graduation ring via three.ws/coin3d). No API keys required.","repository": {"url": "https://github.com/nirholas/three.ws",- "source": "github"+ "source": "github",+ "subfolder": "packages/pumpfun-mcp"},"version": "0.1.0","packages": [diff --git a/packages/pumpfun-mcp/src/native.js b/packages/pumpfun-mcp/src/native.jsindex 55d9b2e69..192696797 100644--- a/packages/pumpfun-mcp/src/native.js+++ b/packages/pumpfun-mcp/src/native.js@@ -86,7 +86,7 @@ async function token3dHandler(args, { call, siteBase }) {}const name = d.name || d.metadata?.name || null;- const symbol = d.symbol || d.metadata?.symbol || '' || null;+ const symbol = d.symbol || d.metadata?.symbol || null;const image = await resolveImage(d);const q = new URLSearchParams({ mint });diff --git a/packages/three-token-mcp/package.json b/packages/three-token-mcp/package.jsonindex 7e8b1e30d..d07eafbe3 100644--- a/packages/three-token-mcp/package.json+++ b/packages/three-token-mcp/package.json@@ -49,6 +49,7 @@},"scripts": {"start": "node src/index.js",+ "test": "node --test \"test/**/*.test.mjs\"","inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"},"dependencies": {diff --git a/packages/three-token-mcp/src/config.js b/packages/three-token-mcp/src/config.jsindex c4933bca9..9443896b7 100644--- a/packages/three-token-mcp/src/config.js+++ b/packages/three-token-mcp/src/config.js@@ -12,11 +12,65 @@ export function env(key, fallback) {return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;}+// The ONLY coin this server may ever burn. The HTTP token config is fetched at+// runtime, but it is UNTRUSTED for the mint: token.js asserts the resolved mint+// equals this canonical $THREE CA before signing any burn. Hardcoding it here is+// the security control — a compromised/misconfigured endpoint cannot redirect a+// burn to a different token.+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// The canonical Solana incinerator (unspendable). The burn leg must route here.+// An operator who runs a non-default burn sink pins it via THREE_BURN_ADDRESS,+// mirroring api/_lib/env.js. Absent that, only the incinerator is accepted.+export const INCINERATOR_ADDRESS = '1nc1nerator11111111111111111111111111111111';+export const EXPECTED_BURN_ADDRESS = env('THREE_BURN_ADDRESS', INCINERATOR_ADDRESS);+// Base URL of the three.ws API that serves /api/token/config and /api/token/price.export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws');+// Validate the Solana RPC endpoint at load time. Burns are signed and broadcast+// over this URL, so a plaintext-http endpoint (outside of localhost) is a+// MITM/credential risk — reject it. http://localhost is allowed for dev.+function validateRpcUrl(raw) {+ let u;+ try {+ u = new URL(raw);+ } catch {+ throw Object.assign(new Error(`SOLANA_RPC_URL is not a valid URL: "${raw}"`), { code: 'bad_rpc_url' });+ }+ if (u.protocol === 'https:') return raw;+ const isLocal = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(u.hostname);+ if (u.protocol === 'http:' && isLocal) return raw;+ throw Object.assign(+ new Error(+ `SOLANA_RPC_URL must be https (got "${u.protocol}//${u.hostname}"). ` ++ 'Only http://localhost is allowed for local dev validators.',+ ),+ { code: 'insecure_rpc_url' },+ );+}+// Solana RPC. Bring your own (Helius / QuickNode / Triton) for production.-export const SOLANA_RPC_URL = env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');+export const SOLANA_RPC_URL = validateRpcUrl(env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com'));++// Max USD value of $THREE a single burn may destroy. Default 100 — bounds a+// runaway/injected burn. Raise MAX_BURN_USD to allow larger burns.+export const MAX_BURN_USD = (() => {+ const raw = env('MAX_BURN_USD');+ if (raw === undefined) return 100;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) {+ throw Object.assign(new Error(`MAX_BURN_USD must be a positive number (got "${raw}")`), { code: 'bad_policy_config' });+ }+ return n;+})();++// Irreversible burn requires an explicit confirm:true unless opted out.+export const REQUIRE_CONFIRM = (() => {+ const raw = env('REQUIRE_CONFIRM');+ if (raw === undefined) return true;+ return !['0', 'false', 'no', 'off'].includes(String(raw).toLowerCase());+})();// Optional default signer (base58 secret key). Tools that burn accept a// per-call `secret` argument that overrides this.diff --git a/packages/three-token-mcp/src/index.js b/packages/three-token-mcp/src/index.jsindex f3e4ec411..ed15a8611 100644--- a/packages/three-token-mcp/src/index.js+++ b/packages/three-token-mcp/src/index.js@@ -59,6 +59,7 @@ async function main() {ok: false,error: err?.code || 'unhandled',message: err?.message || String(err),+ ...(err?.status ? { status: err.status } : {}),...(err?.signature ? { signature: err.signature } : {}),};return {diff --git a/packages/three-token-mcp/src/lib/token.js b/packages/three-token-mcp/src/lib/token.jsindex ae4ffe243..33a3cb620 100644--- a/packages/three-token-mcp/src/lib/token.js+++ b/packages/three-token-mcp/src/lib/token.js@@ -18,7 +18,13 @@ import {getAssociatedTokenAddressSync,} from '@solana/spl-token';-import { THREE_WS_BASE, MEMO_PROGRAM_ID } from '../config.js';+import {+ THREE_WS_BASE,+ MEMO_PROGRAM_ID,+ THREE_MINT,+ EXPECTED_BURN_ADDRESS,+ MAX_BURN_USD,+} from '../config.js';import {PublicKey,getConnection,@@ -54,6 +60,35 @@ export function fetchTokenPrice(usd) {const fmt = (atomics, decimals) => Number(BigInt(atomics)) / 10 ** decimals;+/**+ * Assert the HTTP-resolved token config actually describes canonical $THREE and+ * routes the burn to the expected incinerator. The config endpoint is UNTRUSTED:+ * a compromised or misconfigured server must not be able to redirect a burn to a+ * different token or sink. This is the H1 invariant — call it before signing.+ * @param {object} config — output of fetchTokenConfig()+ */+export function assertCanonicalThree(config) {+ if (!config || config.mint !== THREE_MINT) {+ throw Object.assign(+ new Error(+ `refusing to burn: resolved mint does not match canonical $THREE. ` ++ `expected ${THREE_MINT}, got ${config?.mint ?? '(none)'}.`,+ ),+ { code: 'mint_mismatch' },+ );+ }+ if (!config.burn_address || config.burn_address !== EXPECTED_BURN_ADDRESS) {+ throw Object.assign(+ new Error(+ `refusing to burn: burn_address does not match the expected incinerator. ` ++ `expected ${EXPECTED_BURN_ADDRESS}, got ${config?.burn_address ?? '(none)'}. ` ++ 'Set THREE_BURN_ADDRESS only if you intentionally run a non-default burn sink.',+ ),+ { code: 'burn_address_mismatch' },+ );+ }+}+/*** Resolve just the $THREE mint (+ symbol/decimals if available). Prefers the* full config, but falls back to the price endpoint's `mint` so read-only tools@@ -111,6 +146,15 @@ export async function burnThree({ usd, burnBps = 5000, secret, memo }) {if (!(Number(usd) > 0)) {throw Object.assign(new Error('usd must be a positive number'), { code: 'bad_amount' });}+ if (Number(usd) > MAX_BURN_USD) {+ throw Object.assign(+ new Error(+ `burn of $${usd} exceeds the per-burn cap of $${MAX_BURN_USD}. ` ++ 'Raise MAX_BURN_USD in the MCP server environment to allow larger burns.',+ ),+ { code: 'over_burn_cap' },+ );+ }const signer = loadSigner(secret);const payer = signer.publicKey;@@ -119,6 +163,8 @@ export async function burnThree({ usd, burnBps = 5000, secret, memo }) {if (!config.mint || !config.burn_address) {throw Object.assign(new Error('token config missing mint/burn_address'), { code: 'config_incomplete' });}+ // H1 invariant: never trust the HTTP config blindly for the mint or sink.+ assertCanonicalThree(config);if (!price.quote?.atomics) {throw Object.assign(new Error('price endpoint returned no quote for the requested usd'), { code: 'no_quote' });}@@ -166,16 +212,32 @@ export async function burnThree({ usd, burnBps = 5000, secret, memo }) {tx.sign(signer);const signature = await conn.sendRawTransaction(tx.serialize(), { maxRetries: 5 });- const conf = await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');++ // Confirmation can throw on timeout even though the burn may still land.+ // Surface 'pending' so the caller does NOT blindly re-burn (double-burn).+ let conf;+ try {+ conf = await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');+ } catch (waitErr) {+ throw Object.assign(+ new Error(+ `burn ${signature} was submitted but confirmation timed out (${waitErr?.message || waitErr}). ` ++ 'It MAY still land — do NOT re-burn; check the signature on Solscan first to avoid a double-burn.',+ ),+ { code: 'tx_unconfirmed', status: 'pending', signature },+ );+ }if (conf.value?.err) {throw Object.assign(new Error(`transaction failed to confirm: ${JSON.stringify(conf.value.err)}`), {code: 'tx_failed',+ status: 'failed',signature,});}return {ok: true,+ status: 'confirmed',signature,explorer: `https://solscan.io/tx/${signature}`,mint: config.mint,diff --git a/packages/three-token-mcp/src/tools/three-burn.js b/packages/three-token-mcp/src/tools/three-burn.jsindex f6a00c2a3..65c4dc127 100644--- a/packages/three-token-mcp/src/tools/three-burn.js+++ b/packages/three-token-mcp/src/tools/three-burn.js@@ -5,12 +5,13 @@import { z } from 'zod';import { burnThree } from '../lib/token.js';+import { REQUIRE_CONFIRM } from '../config.js';export const def = {name: 'three_burn',title: 'Burn $THREE on-chain (incinerator + treasury split)',description:- 'Burn a USD-denominated amount of the $THREE your wallet holds. Quotes USD→$THREE via Jupiter, then sends ONE Solana transaction that splits it between the incinerator (burn) and the three.ws treasury, per the live public token config. EXECUTION ACTION — signs and broadcasts on Solana mainnet, irreversible. Requires a signer (SOLANA_SECRET_KEY env or the `secret` arg) holding enough $THREE. Returns the tx signature, the burned/treasury breakdown, and a Solscan link.',+ 'Burn a USD-denominated amount of the $THREE your wallet holds. Quotes USD→$THREE via Jupiter, then sends ONE Solana transaction that splits it between the incinerator (burn) and the three.ws treasury, per the live public token config. EXECUTION ACTION — signs and broadcasts on Solana mainnet, IRREVERSIBLE: pass confirm:true. Capped by MAX_BURN_USD. The resolved mint is asserted to be canonical $THREE before signing. Requires a signer (SOLANA_SECRET_KEY env or the `secret` arg) holding enough $THREE. Returns the tx signature, the burned/treasury breakdown, and a Solscan link.',inputSchema: {usd: z.number().positive().describe('USD value of $THREE to burn (priced live via Jupiter).'),burnBps: z@@ -26,9 +27,23 @@ export const def = {.string().optional().describe('Base58 signer override. Defaults to SOLANA_SECRET_KEY. Treat like cash.'),+ confirm: z+ .boolean()+ .optional()+ .describe('Must be true to execute this irreversible burn (when REQUIRE_CONFIRM is on).'),},async handler(args) {- const { usd, burnBps, memo, secret } = args || {};+ const { usd, burnBps, memo, secret, confirm } = args || {};+ if (REQUIRE_CONFIRM && confirm !== true) {+ return {+ ok: false,+ error: 'confirmation_required',+ message:+ 'three_burn is IRREVERSIBLE — it destroys $THREE on Solana mainnet. ' ++ 'Re-issue the call with `confirm: true` to proceed. ' ++ '(Set REQUIRE_CONFIRM=0 on the MCP server to disable this prompt.)',+ };+ }return burnThree({ usd, burnBps, memo, secret });},};diff --git a/packages/three-token-mcp/test/mint-guard.test.mjs b/packages/three-token-mcp/test/mint-guard.test.mjsnew file mode 100644index 000000000..dcf0485ec--- /dev/null+++ b/packages/three-token-mcp/test/mint-guard.test.mjs@@ -0,0 +1,52 @@+// H1 invariant: the burn engine must refuse any mint that is not canonical+// $THREE, and must refuse a burn_address that is not the expected incinerator.+// These guards never touch the network — they validate the (untrusted) HTTP+// config object before a transaction is ever built.+//+// Run: node --test packages/three-token-mcp/test/mint-guard.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { assertCanonicalThree } from '../src/lib/token.js';+import { THREE_MINT, EXPECTED_BURN_ADDRESS } from '../src/config.js';++const CANONICAL = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++test('THREE_MINT is the canonical $THREE CA', () => {+ assert.equal(THREE_MINT, CANONICAL);+});++test('accepts a config that matches canonical $THREE + incinerator', () => {+ assert.doesNotThrow(() =>+ assertCanonicalThree({ mint: THREE_MINT, burn_address: EXPECTED_BURN_ADDRESS }),+ );+});++test('refuses a non-$THREE mint', () => {+ assert.throws(+ () => assertCanonicalThree({ mint: 'So11111111111111111111111111111111111111112', burn_address: EXPECTED_BURN_ADDRESS }),+ (err) => err.code === 'mint_mismatch' && /canonical \$THREE/.test(err.message),+ );+});++test('refuses a missing mint', () => {+ assert.throws(+ () => assertCanonicalThree({ burn_address: EXPECTED_BURN_ADDRESS }),+ (err) => err.code === 'mint_mismatch',+ );+});++test('refuses a tampered burn_address even when the mint is correct', () => {+ assert.throws(+ () => assertCanonicalThree({ mint: THREE_MINT, burn_address: 'AttackerAddr1111111111111111111111111111111' }),+ (err) => err.code === 'burn_address_mismatch',+ );+});++test('refuses a missing burn_address', () => {+ assert.throws(+ () => assertCanonicalThree({ mint: THREE_MINT }),+ (err) => err.code === 'burn_address_mismatch',+ );+});diff --git a/packages/threews-avatar-mcp/app/avatar-app.js b/packages/threews-avatar-mcp/app/avatar-app.jsindex dff3edb22..0f65e8127 100644--- a/packages/threews-avatar-mcp/app/avatar-app.js+++ b/packages/threews-avatar-mcp/app/avatar-app.js@@ -15,11 +15,36 @@ const viewer = document.getElementById('viewer');const nameEl = document.getElementById('name');const statusEl = document.getElementById('status');+// Defense in depth: only point model-viewer at an https GLB/GLTF URL (http+// allowed solely for localhost dev). Blocks javascript:/data:/blob:/file:+// schemes from ever reaching the src attribute even if a malicious tool+// result slips through the server-side validation.+function isSafeModelUrl(url) {+ if (typeof url !== 'string' || url.trim() === '') return false;+ let parsed;+ try {+ parsed = new URL(url);+ } catch {+ return false;+ }+ if (parsed.protocol === 'https:') return true;+ if (parsed.protocol === 'http:') {+ const host = parsed.hostname;+ return host === 'localhost' || host === '127.0.0.1' || host === '[::1]';+ }+ return false;+}+function applyResult(result) {const sc = (result && result.structuredContent) || {};- if (sc.model_url) {+ if (sc.model_url && isSafeModelUrl(sc.model_url)) {viewer.setAttribute('src', sc.model_url);statusEl.hidden = true;+ } else if (sc.model_url) {+ viewer.removeAttribute('src');+ statusEl.hidden = false;+ statusEl.textContent = 'Blocked an unsafe model URL.';+ console.warn('[avatar-app] ignored unsafe model_url:', sc.model_url);}if (sc.name) {nameEl.textContent = sc.name;diff --git a/packages/threews-avatar-mcp/package.json b/packages/threews-avatar-mcp/package.jsonindex 9cf128b1f..4b9455917 100644--- a/packages/threews-avatar-mcp/package.json+++ b/packages/threews-avatar-mcp/package.json@@ -37,9 +37,9 @@"LICENSE"],"bin": {- "avatar-mcp": "src/index.js"+ "avatar-mcp": "./src/index.js"},- "main": "src/index.js",+ "main": "./src/index.js","exports": {".": "./src/index.js"},diff --git a/packages/threews-avatar-mcp/src/avatar-app.html b/packages/threews-avatar-mcp/src/avatar-app.htmlindex 6be721f51..c509a1f83 100644--- a/packages/threews-avatar-mcp/src/avatar-app.html+++ b/packages/threews-avatar-mcp/src/avatar-app.html@@ -29,10 +29,10 @@<div id="name"></div><div id="status">Loading avatar…</div></div>-<script>"use strict";(()=>{var Oc=Object.defineProperty;var od=(t,r,n)=>r in t?Oc(t,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[r]=n;var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(r,n)=>(typeof require<"u"?require:r)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,r)=>()=>(t&&(r=t(t=0)),r);var $e=(t,r)=>{for(var n in r)Oc(t,n,{get:r[n],enumerable:!0})};var A=(t,r,n)=>od(t,typeof r!="symbol"?r+"":r,n);function u(t,r,n){function i(c,d){var h;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(h=c._zod).traits??(h.traits=new Set),c._zod.traits.add(t),r(c,d);for(let g in a.prototype)g in c||Object.defineProperty(c,g,{value:a.prototype[g].bind(c)});c._zod.constr=a,c._zod.def=d}let e=n?.Parent??Object;class o extends e{}Object.defineProperty(o,"name",{value:t});function a(c){var d;let h=n?.Parent?new o:this;i(h,c),(d=h._zod).deferred??(d.deferred=[]);for(let g of h._zod.deferred)g();return h}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}function B(t){return t&&Object.assign(zt,t),zt}var br,_r,de,zt,Le=k(()=>{br=Object.freeze({status:"aborted"});_r=Symbol("zod_brand"),de=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},zt={}});var y={};$e(y,{BIGINT_FORMAT_RANGES:()=>jo,Class:()=>yo,NUMBER_FORMAT_RANGES:()=>Io,aborted:()=>Oe,allowsEval:()=>ko,assert:()=>ud,assertEqual:()=>id,assertIs:()=>sd,assertNever:()=>cd,assertNotEqual:()=>ad,assignProp:()=>zo,cached:()=>wt,captureStackTrace:()=>yr,cleanEnum:()=>xd,cleanRegex:()=>It,clone:()=>ne,createTransparentProxy:()=>gd,defineLazy:()=>D,esc:()=>Te,escapeRegex:()=>be,extend:()=>bd,finalizeIssue:()=>ae,floatSafeRemainder:()=>xo,getElementAtPath:()=>ld,getEnumValues:()=>St,getLengthableOrigin:()=>Tt,getParsedType:()=>fd,getSizableOrigin:()=>Pt,isObject:()=>qe,isPlainObject:()=>Ve,issue:()=>Po,joinValues:()=>f,jsonStringifyReplacer:()=>$o,merge:()=>_d,normalizeParams:()=>v,nullish:()=>xe,numKeys:()=>pd,omit:()=>vd,optionalKeys:()=>wo,partial:()=>yd,pick:()=>hd,prefixIssues:()=>oe,primitiveTypes:()=>So,promiseAllObject:()=>md,propertyKeyTypes:()=>jt,randomString:()=>dd,required:()=>$d,stringifyPrimitive:()=>_,unwrapMessage:()=>kt});function id(t){return t}function ad(t){return t}function sd(t){}function cd(t){throw new Error}function ud(t){}function St(t){let r=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,e])=>r.indexOf(+i)===-1).map(([i,e])=>e)}function f(t,r="|"){return t.map(n=>_(n)).join(r)}function $o(t,r){return typeof r=="bigint"?r.toString():r}function wt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function xe(t){return t==null}function It(t){let r=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(r,n)}function xo(t,r){let n=(t.toString().split(".")[1]||"").length,i=(r.toString().split(".")[1]||"").length,e=n>i?n:i,o=Number.parseInt(t.toFixed(e).replace(".","")),a=Number.parseInt(r.toFixed(e).replace(".",""));return o%a/10**e}function D(t,r,n){Object.defineProperty(t,r,{get(){{let e=n();return t[r]=e,e}throw new Error("cached value already set")},set(e){Object.defineProperty(t,r,{value:e})},configurable:!0})}function zo(t,r,n){Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ld(t,r){return r?r.reduce((n,i)=>n?.[i],t):t}function md(t){let r=Object.keys(t),n=r.map(i=>t[i]);return Promise.all(n).then(i=>{let e={};for(let o=0;o<r.length;o++)e[r[o]]=i[o];return e})}function dd(t=10){let r="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<t;i++)n+=r[Math.floor(Math.random()*r.length)];return n}function Te(t){return JSON.stringify(t)}function qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ve(t){if(qe(t)===!1)return!1;let r=t.constructor;if(r===void 0)return!0;let n=r.prototype;return!(qe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function pd(t){let r=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&r++;return r}function be(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ne(t,r,n){let i=new t._zod.constr(r??t._zod.def);return(!r||n?.parent)&&(i._zod.parent=t),i}function v(t){let r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function gd(t){let r;return new Proxy({},{get(n,i,e){return r??(r=t()),Reflect.get(r,i,e)},set(n,i,e,o){return r??(r=t()),Reflect.set(r,i,e,o)},has(n,i){return r??(r=t()),Reflect.has(r,i)},deleteProperty(n,i){return r??(r=t()),Reflect.deleteProperty(r,i)},ownKeys(n){return r??(r=t()),Reflect.ownKeys(r)},getOwnPropertyDescriptor(n,i){return r??(r=t()),Reflect.getOwnPropertyDescriptor(r,i)},defineProperty(n,i,e){return r??(r=t()),Reflect.defineProperty(r,i,e)}})}function _(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wo(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}function hd(t,r){let n={},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(n[e]=i.shape[e])}return ne(t,{...t._zod.def,shape:n,checks:[]})}function vd(t,r){let n={...t._zod.def.shape},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&delete n[e]}return ne(t,{...t._zod.def,shape:n,checks:[]})}function bd(t,r){if(!Ve(r))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let i={...t._zod.def.shape,...r};return zo(this,"shape",i),i},checks:[]};return ne(t,n)}function _d(t,r){return ne(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...r._zod.def.shape};return zo(this,"shape",n),n},catchall:r._zod.def.catchall,checks:[]})}function yd(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=t?new t({type:"optional",innerType:i[o]}):i[o])}else for(let o in i)e[o]=t?new t({type:"optional",innerType:i[o]}):i[o];return ne(r,{...r._zod.def,shape:e,checks:[]})}function $d(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in e))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)e[o]=new t({type:"nonoptional",innerType:i[o]});return ne(r,{...r._zod.def,shape:e,checks:[]})}function Oe(t,r=0){for(let n=r;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function oe(t,r){return r.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(t),n})}function kt(t){return typeof t=="string"?t:t?.message}function ae(t,r,n){let i={...t,path:t.path??[]};if(!t.message){let e=kt(t.inst?._zod.def?.error?.(t))??kt(r?.error?.(t))??kt(n.customError?.(t))??kt(n.localeError?.(t))??"Invalid input";i.message=e}return delete i.inst,delete i.continue,r?.reportInput||delete i.input,i}function Pt(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Tt(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Po(...t){let[r,n,i]=t;return typeof r=="string"?{message:r,code:"custom",input:n,inst:i}:{...r}}function xd(t){return Object.entries(t).filter(([r,n])=>Number.isNaN(Number.parseInt(r,10))).map(r=>r[1])}var yr,ko,fd,jt,So,Io,jo,yo,P=k(()=>{yr=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};ko=wt(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});fd=t=>{let r=typeof t;switch(r){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${r}`)}},jt=new Set(["string","number","symbol"]),So=new Set(["string","number","bigint","boolean","symbol","undefined"]);Io={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},jo={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};yo=class{constructor(...r){}}});function He(t,r=n=>n.message){let n={},i=[];for(let e of t.issues)e.path.length>0?(n[e.path[0]]=n[e.path[0]]||[],n[e.path[0]].push(r(e))):i.push(r(e));return{formErrors:i,fieldErrors:n}}function Je(t,r){let n=r||function(o){return o.message},i={_errors:[]},e=o=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>e({issues:c}));else if(a.code==="invalid_key")e({issues:a.issues});else if(a.code==="invalid_element")e({issues:a.issues});else if(a.path.length===0)i._errors.push(n(a));else{let c=i,d=0;for(;d<a.path.length;){let h=a.path[d];d===a.path.length-1?(c[h]=c[h]||{_errors:[]},c[h]._errors.push(n(a))):c[h]=c[h]||{_errors:[]},c=c[h],d++}}};return e(t),i}function $r(t,r){let n=r||function(o){return o.message},i={errors:[]},e=(o,a=[])=>{var c,d;for(let h of o.issues)if(h.code==="invalid_union"&&h.errors.length)h.errors.map(g=>e({issues:g},h.path));else if(h.code==="invalid_key")e({issues:h.issues},h.path);else if(h.code==="invalid_element")e({issues:h.issues},h.path);else{let g=[...a,...h.path];if(g.length===0){i.errors.push(n(h));continue}let l=i,$=0;for(;$<g.length;){let b=g[$],p=$===g.length-1;typeof b=="string"?(l.properties??(l.properties={}),(c=l.properties)[b]??(c[b]={errors:[]}),l=l.properties[b]):(l.items??(l.items=[]),(d=l.items)[b]??(d[b]={errors:[]}),l=l.items[b]),p&&l.errors.push(n(h)),$++}}};return e(t),i}function Uc(t){let r=[];for(let n of t)typeof n=="number"?r.push(`[${n}]`):typeof n=="symbol"?r.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?r.push(`[${JSON.stringify(n)}]`):(r.length&&r.push("."),r.push(n));return r.join("")}function xr(t){let r=[],n=[...t.issues].sort((i,e)=>i.path.length-e.path.length);for(let i of n)r.push(`\u2716 ${i.message}`),i.path?.length&&r.push(` \u2192 at ${Uc(i.path)}`);return r.join(`-`)}var Nc,Ot,Fe,To=k(()=>{Le();P();Nc=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(r,$o,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ot=u("$ZodError",Nc),Fe=u("$ZodError",Nc,{Parent:Error})});var zr,Nt,kr,Ut,Sr,Be,wr,Et,Ir=k(()=>{Le();To();P();zr=t=>(r,n,i,e)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new de;if(a.issues.length){let c=new(e?.Err??t)(a.issues.map(d=>ae(d,o,B())));throw yr(c,e?.callee),c}return a.value},Nt=zr(Fe),kr=t=>async(r,n,i,e)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(e?.Err??t)(a.issues.map(d=>ae(d,o,B())));throw yr(c,e?.callee),c}return a.value},Ut=kr(Fe),Sr=t=>(r,n,i)=>{let e=i?{...i,async:!1}:{async:!1},o=r._zod.run({value:n,issues:[]},e);if(o instanceof Promise)throw new de;return o.issues.length?{success:!1,error:new(t??Ot)(o.issues.map(a=>ae(a,e,B())))}:{success:!0,data:o.value}},Be=Sr(Fe),wr=t=>async(r,n,i)=>{let e=i?Object.assign(i,{async:!0}):{async:!0},o=r._zod.run({value:n,issues:[]},e);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>ae(a,e,B())))}:{success:!0,data:o.value}},Et=wr(Fe)});var ze={};$e(ze,{_emoji:()=>Ec,base64:()=>Ho,base64url:()=>jr,bigint:()=>Yo,boolean:()=>ti,browserEmail:()=>Od,cidrv4:()=>Vo,cidrv6:()=>Fo,cuid:()=>Oo,cuid2:()=>No,date:()=>Wo,datetime:()=>Go,domain:()=>Nd,duration:()=>Ro,e164:()=>Bo,email:()=>Co,emoji:()=>Mo,extendedDuration:()=>kd,guid:()=>Ao,hostname:()=>Jo,html5Email:()=>jd,integer:()=>Xo,ipv4:()=>Lo,ipv6:()=>qo,ksuid:()=>Zo,lowercase:()=>oi,nanoid:()=>Do,null:()=>ri,number:()=>ei,rfc5322Email:()=>Pd,string:()=>Qo,time:()=>Ko,ulid:()=>Uo,undefined:()=>ni,unicodeEmail:()=>Td,uppercase:()=>ii,uuid:()=>Ne,uuid4:()=>Sd,uuid6:()=>wd,uuid7:()=>Id,xid:()=>Eo});function Mo(){return new RegExp(Ec,"u")}function Dc(t){let r="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${r}`:t.precision===0?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ko(t){return new RegExp(`^${Dc(t)}$`)}function Go(t){let r=Dc({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let i=`${r}(?:${n.join("|")})`;return new RegExp(`^${Zc}T(?:${i})$`)}var Oo,No,Uo,Eo,Zo,Do,Ro,kd,Ao,Ne,Sd,wd,Id,Co,jd,Pd,Td,Od,Ec,Lo,qo,Vo,Fo,Ho,jr,Jo,Nd,Bo,Zc,Wo,Qo,Yo,Xo,ei,ti,ri,ni,oi,ii,Pr=k(()=>{Oo=/^[cC][^\s-]{8,}$/,No=/^[0-9a-z]+$/,Uo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Eo=/^[0-9a-vA-V]{20}$/,Zo=/^[A-Za-z0-9]{27}$/,Do=/^[a-zA-Z0-9_-]{21}$/,Ro=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,kd=/^[-+]?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)?)??$/,Ao=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ne=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Sd=Ne(4),wd=Ne(6),Id=Ne(7),Co=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,jd=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Pd=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Td=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Od=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Ec="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Lo=/^(?:(?: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])$/,qo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Vo=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Fo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ho=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,jr=/^[A-Za-z0-9_-]*$/,Jo=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Nd=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Bo=/^\+(?:[0-9]){6,14}[0-9]$/,Zc="(?:(?:\\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])))",Wo=new RegExp(`^${Zc}$`);Qo=t=>{let r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},Yo=/^\d+n?$/,Xo=/^\d+$/,ei=/^-?\d+(?:\.\d+)?/i,ti=/true|false/i,ri=/null/i,ni=/undefined/i,oi=/^[^A-Z]*$/,ii=/^[^a-z]*$/});function Rc(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues))}var J,Ac,Tr,Or,ai,si,ci,ui,li,mi,di,pi,fi,We,gi,hi,vi,bi,_i,yi,$i,xi,zi,Nr=k(()=>{Le();Pr();P();J=u("$ZodCheck",(t,r)=>{var n;t._zod??(t._zod={}),t._zod.def=r,(n=t._zod).onattach??(n.onattach=[])}),Ac={number:"number",bigint:"bigint",object:"date"},Tr=u("$ZodCheckLessThan",(t,r)=>{J.init(t,r);let n=Ac[typeof r.value];t._zod.onattach.push(i=>{let e=i._zod.bag,o=(r.inclusive?e.maximum:e.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<o&&(r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value)}),t._zod.check=i=>{(r.inclusive?i.value<=r.value:i.value<r.value)||i.issues.push({origin:n,code:"too_big",maximum:r.value,input:i.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),Or=u("$ZodCheckGreaterThan",(t,r)=>{J.init(t,r);let n=Ac[typeof r.value];t._zod.onattach.push(i=>{let e=i._zod.bag,o=(r.inclusive?e.minimum:e.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>o&&(r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value)}),t._zod.check=i=>{(r.inclusive?i.value>=r.value:i.value>r.value)||i.issues.push({origin:n,code:"too_small",minimum:r.value,input:i.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),ai=u("$ZodCheckMultipleOf",(t,r)=>{J.init(t,r),t._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=r.value)}),t._zod.check=n=>{if(typeof n.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%r.value===BigInt(0):xo(n.value,r.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:r.value,input:n.value,inst:t,continue:!r.abort})}}),si=u("$ZodCheckNumberFormat",(t,r)=>{J.init(t,r),r.format=r.format||"float64";let n=r.format?.includes("int"),i=n?"int":"number",[e,o]=Io[r.format];t._zod.onattach.push(a=>{let c=a._zod.bag;c.format=r.format,c.minimum=e,c.maximum=o,n&&(c.pattern=Xo)}),t._zod.check=a=>{let c=a.value;if(n){if(!Number.isInteger(c)){a.issues.push({expected:i,format:r.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!r.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!r.abort});return}}c<e&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:e,inclusive:!0,inst:t,continue:!r.abort}),c>o&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:o,inst:t})}}),ci=u("$ZodCheckBigIntFormat",(t,r)=>{J.init(t,r);let[n,i]=jo[r.format];t._zod.onattach.push(e=>{let o=e._zod.bag;o.format=r.format,o.minimum=n,o.maximum=i}),t._zod.check=e=>{let o=e.value;o<n&&e.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!r.abort}),o>i&&e.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inst:t})}}),ui=u("$ZodCheckMaxSize",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<e&&(i._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let e=i.value;e.size<=r.maximum||i.issues.push({origin:Pt(e),code:"too_big",maximum:r.maximum,input:e,inst:t,continue:!r.abort})}}),li=u("$ZodCheckMinSize",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>e&&(i._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let e=i.value;e.size>=r.minimum||i.issues.push({origin:Pt(e),code:"too_small",minimum:r.minimum,input:e,inst:t,continue:!r.abort})}}),mi=u("$ZodCheckSizeEquals",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag;e.minimum=r.size,e.maximum=r.size,e.size=r.size}),t._zod.check=i=>{let e=i.value,o=e.size;if(o===r.size)return;let a=o>r.size;i.issues.push({origin:Pt(e),...a?{code:"too_big",maximum:r.size}:{code:"too_small",minimum:r.size},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),di=u("$ZodCheckMaxLength",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<e&&(i._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let e=i.value;if(e.length<=r.maximum)return;let a=Tt(e);i.issues.push({origin:a,code:"too_big",maximum:r.maximum,inclusive:!0,input:e,inst:t,continue:!r.abort})}}),pi=u("$ZodCheckMinLength",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>e&&(i._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let e=i.value;if(e.length>=r.minimum)return;let a=Tt(e);i.issues.push({origin:a,code:"too_small",minimum:r.minimum,inclusive:!0,input:e,inst:t,continue:!r.abort})}}),fi=u("$ZodCheckLengthEquals",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag;e.minimum=r.length,e.maximum=r.length,e.length=r.length}),t._zod.check=i=>{let e=i.value,o=e.length;if(o===r.length)return;let a=Tt(e),c=o>r.length;i.issues.push({origin:a,...c?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),We=u("$ZodCheckStringFormat",(t,r)=>{var n,i;J.init(t,r),t._zod.onattach.push(e=>{let o=e._zod.bag;o.format=r.format,r.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(r.pattern))}),r.pattern?(n=t._zod).check??(n.check=e=>{r.pattern.lastIndex=0,!r.pattern.test(e.value)&&e.issues.push({origin:"string",code:"invalid_format",format:r.format,input:e.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(i=t._zod).check??(i.check=()=>{})}),gi=u("$ZodCheckRegex",(t,r)=>{We.init(t,r),t._zod.check=n=>{r.pattern.lastIndex=0,!r.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),hi=u("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=oi),We.init(t,r)}),vi=u("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=ii),We.init(t,r)}),bi=u("$ZodCheckIncludes",(t,r)=>{J.init(t,r);let n=be(r.includes),i=new RegExp(typeof r.position=="number"?`^.{${r.position}}${n}`:n);r.pattern=i,t._zod.onattach.push(e=>{let o=e._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),t._zod.check=e=>{e.value.includes(r.includes,r.position)||e.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:e.value,inst:t,continue:!r.abort})}}),_i=u("$ZodCheckStartsWith",(t,r)=>{J.init(t,r);let n=new RegExp(`^${be(r.prefix)}.*`);r.pattern??(r.pattern=n),t._zod.onattach.push(i=>{let e=i._zod.bag;e.patterns??(e.patterns=new Set),e.patterns.add(n)}),t._zod.check=i=>{i.value.startsWith(r.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:i.value,inst:t,continue:!r.abort})}}),yi=u("$ZodCheckEndsWith",(t,r)=>{J.init(t,r);let n=new RegExp(`.*${be(r.suffix)}$`);r.pattern??(r.pattern=n),t._zod.onattach.push(i=>{let e=i._zod.bag;e.patterns??(e.patterns=new Set),e.patterns.add(n)}),t._zod.check=i=>{i.value.endsWith(r.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:i.value,inst:t,continue:!r.abort})}});$i=u("$ZodCheckProperty",(t,r)=>{J.init(t,r),t._zod.check=n=>{let i=r.schema._zod.run({value:n.value[r.property],issues:[]},{});if(i instanceof Promise)return i.then(e=>Rc(e,n,r.property));Rc(i,n,r.property)}}),xi=u("$ZodCheckMimeType",(t,r)=>{J.init(t,r);let n=new Set(r.mime);t._zod.onattach.push(i=>{i._zod.bag.mime=r.mime}),t._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:r.mime,input:i.value.type,inst:t})}}),zi=u("$ZodCheckOverwrite",(t,r)=>{J.init(t,r),t._zod.check=n=>{n.value=r.tx(n.value)}})});var Zt,ki=k(()=>{Zt=class{constructor(r=[]){this.content=[],this.indent=0,this&&(this.args=r)}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r=="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}let i=r.split(`+<script>"use strict";(()=>{var Uc=Object.defineProperty;var od=(t,r,n)=>r in t?Uc(t,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[r]=n;var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(r,n)=>(typeof require<"u"?require:r)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,r)=>()=>(t&&(r=t(t=0)),r);var $e=(t,r)=>{for(var n in r)Uc(t,n,{get:r[n],enumerable:!0})};var A=(t,r,n)=>od(t,typeof r!="symbol"?r+"":r,n);function u(t,r,n){function i(c,d){var h;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(h=c._zod).traits??(h.traits=new Set),c._zod.traits.add(t),r(c,d);for(let g in a.prototype)g in c||Object.defineProperty(c,g,{value:a.prototype[g].bind(c)});c._zod.constr=a,c._zod.def=d}let e=n?.Parent??Object;class o extends e{}Object.defineProperty(o,"name",{value:t});function a(c){var d;let h=n?.Parent?new o:this;i(h,c),(d=h._zod).deferred??(d.deferred=[]);for(let g of h._zod.deferred)g();return h}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}function B(t){return t&&Object.assign(zt,t),zt}var br,_r,de,zt,Le=k(()=>{br=Object.freeze({status:"aborted"});_r=Symbol("zod_brand"),de=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},zt={}});var y={};$e(y,{BIGINT_FORMAT_RANGES:()=>Po,Class:()=>$o,NUMBER_FORMAT_RANGES:()=>jo,aborted:()=>Oe,allowsEval:()=>So,assert:()=>ud,assertEqual:()=>id,assertIs:()=>sd,assertNever:()=>cd,assertNotEqual:()=>ad,assignProp:()=>ko,cached:()=>wt,captureStackTrace:()=>yr,cleanEnum:()=>xd,cleanRegex:()=>It,clone:()=>ne,createTransparentProxy:()=>gd,defineLazy:()=>D,esc:()=>Te,escapeRegex:()=>be,extend:()=>bd,finalizeIssue:()=>ae,floatSafeRemainder:()=>zo,getElementAtPath:()=>ld,getEnumValues:()=>St,getLengthableOrigin:()=>Tt,getParsedType:()=>fd,getSizableOrigin:()=>Pt,isObject:()=>qe,isPlainObject:()=>Ve,issue:()=>To,joinValues:()=>f,jsonStringifyReplacer:()=>xo,merge:()=>_d,normalizeParams:()=>v,nullish:()=>xe,numKeys:()=>pd,omit:()=>vd,optionalKeys:()=>Io,partial:()=>yd,pick:()=>hd,prefixIssues:()=>oe,primitiveTypes:()=>wo,promiseAllObject:()=>md,propertyKeyTypes:()=>jt,randomString:()=>dd,required:()=>$d,stringifyPrimitive:()=>_,unwrapMessage:()=>kt});function id(t){return t}function ad(t){return t}function sd(t){}function cd(t){throw new Error}function ud(t){}function St(t){let r=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,e])=>r.indexOf(+i)===-1).map(([i,e])=>e)}function f(t,r="|"){return t.map(n=>_(n)).join(r)}function xo(t,r){return typeof r=="bigint"?r.toString():r}function wt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function xe(t){return t==null}function It(t){let r=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(r,n)}function zo(t,r){let n=(t.toString().split(".")[1]||"").length,i=(r.toString().split(".")[1]||"").length,e=n>i?n:i,o=Number.parseInt(t.toFixed(e).replace(".","")),a=Number.parseInt(r.toFixed(e).replace(".",""));return o%a/10**e}function D(t,r,n){Object.defineProperty(t,r,{get(){{let e=n();return t[r]=e,e}throw new Error("cached value already set")},set(e){Object.defineProperty(t,r,{value:e})},configurable:!0})}function ko(t,r,n){Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ld(t,r){return r?r.reduce((n,i)=>n?.[i],t):t}function md(t){let r=Object.keys(t),n=r.map(i=>t[i]);return Promise.all(n).then(i=>{let e={};for(let o=0;o<r.length;o++)e[r[o]]=i[o];return e})}function dd(t=10){let r="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<t;i++)n+=r[Math.floor(Math.random()*r.length)];return n}function Te(t){return JSON.stringify(t)}function qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ve(t){if(qe(t)===!1)return!1;let r=t.constructor;if(r===void 0)return!0;let n=r.prototype;return!(qe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function pd(t){let r=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&r++;return r}function be(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ne(t,r,n){let i=new t._zod.constr(r??t._zod.def);return(!r||n?.parent)&&(i._zod.parent=t),i}function v(t){let r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function gd(t){let r;return new Proxy({},{get(n,i,e){return r??(r=t()),Reflect.get(r,i,e)},set(n,i,e,o){return r??(r=t()),Reflect.set(r,i,e,o)},has(n,i){return r??(r=t()),Reflect.has(r,i)},deleteProperty(n,i){return r??(r=t()),Reflect.deleteProperty(r,i)},ownKeys(n){return r??(r=t()),Reflect.ownKeys(r)},getOwnPropertyDescriptor(n,i){return r??(r=t()),Reflect.getOwnPropertyDescriptor(r,i)},defineProperty(n,i,e){return r??(r=t()),Reflect.defineProperty(r,i,e)}})}function _(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Io(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}function hd(t,r){let n={},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(n[e]=i.shape[e])}return ne(t,{...t._zod.def,shape:n,checks:[]})}function vd(t,r){let n={...t._zod.def.shape},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&delete n[e]}return ne(t,{...t._zod.def,shape:n,checks:[]})}function bd(t,r){if(!Ve(r))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let i={...t._zod.def.shape,...r};return ko(this,"shape",i),i},checks:[]};return ne(t,n)}function _d(t,r){return ne(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...r._zod.def.shape};return ko(this,"shape",n),n},catchall:r._zod.def.catchall,checks:[]})}function yd(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=t?new t({type:"optional",innerType:i[o]}):i[o])}else for(let o in i)e[o]=t?new t({type:"optional",innerType:i[o]}):i[o];return ne(r,{...r._zod.def,shape:e,checks:[]})}function $d(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in e))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)e[o]=new t({type:"nonoptional",innerType:i[o]});return ne(r,{...r._zod.def,shape:e,checks:[]})}function Oe(t,r=0){for(let n=r;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function oe(t,r){return r.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(t),n})}function kt(t){return typeof t=="string"?t:t?.message}function ae(t,r,n){let i={...t,path:t.path??[]};if(!t.message){let e=kt(t.inst?._zod.def?.error?.(t))??kt(r?.error?.(t))??kt(n.customError?.(t))??kt(n.localeError?.(t))??"Invalid input";i.message=e}return delete i.inst,delete i.continue,r?.reportInput||delete i.input,i}function Pt(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Tt(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function To(...t){let[r,n,i]=t;return typeof r=="string"?{message:r,code:"custom",input:n,inst:i}:{...r}}function xd(t){return Object.entries(t).filter(([r,n])=>Number.isNaN(Number.parseInt(r,10))).map(r=>r[1])}var yr,So,fd,jt,wo,jo,Po,$o,P=k(()=>{yr=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};So=wt(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});fd=t=>{let r=typeof t;switch(r){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${r}`)}},jt=new Set(["string","number","symbol"]),wo=new Set(["string","number","bigint","boolean","symbol","undefined"]);jo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Po={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};$o=class{constructor(...r){}}});function He(t,r=n=>n.message){let n={},i=[];for(let e of t.issues)e.path.length>0?(n[e.path[0]]=n[e.path[0]]||[],n[e.path[0]].push(r(e))):i.push(r(e));return{formErrors:i,fieldErrors:n}}function Je(t,r){let n=r||function(o){return o.message},i={_errors:[]},e=o=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>e({issues:c}));else if(a.code==="invalid_key")e({issues:a.issues});else if(a.code==="invalid_element")e({issues:a.issues});else if(a.path.length===0)i._errors.push(n(a));else{let c=i,d=0;for(;d<a.path.length;){let h=a.path[d];d===a.path.length-1?(c[h]=c[h]||{_errors:[]},c[h]._errors.push(n(a))):c[h]=c[h]||{_errors:[]},c=c[h],d++}}};return e(t),i}function $r(t,r){let n=r||function(o){return o.message},i={errors:[]},e=(o,a=[])=>{var c,d;for(let h of o.issues)if(h.code==="invalid_union"&&h.errors.length)h.errors.map(g=>e({issues:g},h.path));else if(h.code==="invalid_key")e({issues:h.issues},h.path);else if(h.code==="invalid_element")e({issues:h.issues},h.path);else{let g=[...a,...h.path];if(g.length===0){i.errors.push(n(h));continue}let l=i,$=0;for(;$<g.length;){let b=g[$],p=$===g.length-1;typeof b=="string"?(l.properties??(l.properties={}),(c=l.properties)[b]??(c[b]={errors:[]}),l=l.properties[b]):(l.items??(l.items=[]),(d=l.items)[b]??(d[b]={errors:[]}),l=l.items[b]),p&&l.errors.push(n(h)),$++}}};return e(t),i}function Zc(t){let r=[];for(let n of t)typeof n=="number"?r.push(`[${n}]`):typeof n=="symbol"?r.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?r.push(`[${JSON.stringify(n)}]`):(r.length&&r.push("."),r.push(n));return r.join("")}function xr(t){let r=[],n=[...t.issues].sort((i,e)=>i.path.length-e.path.length);for(let i of n)r.push(`\u2716 ${i.message}`),i.path?.length&&r.push(` \u2192 at ${Zc(i.path)}`);return r.join(`+`)}var Ec,Ot,Fe,Oo=k(()=>{Le();P();Ec=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(r,xo,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ot=u("$ZodError",Ec),Fe=u("$ZodError",Ec,{Parent:Error})});var zr,Nt,kr,Ut,Sr,Be,wr,Et,Ir=k(()=>{Le();Oo();P();zr=t=>(r,n,i,e)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new de;if(a.issues.length){let c=new(e?.Err??t)(a.issues.map(d=>ae(d,o,B())));throw yr(c,e?.callee),c}return a.value},Nt=zr(Fe),kr=t=>async(r,n,i,e)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(e?.Err??t)(a.issues.map(d=>ae(d,o,B())));throw yr(c,e?.callee),c}return a.value},Ut=kr(Fe),Sr=t=>(r,n,i)=>{let e=i?{...i,async:!1}:{async:!1},o=r._zod.run({value:n,issues:[]},e);if(o instanceof Promise)throw new de;return o.issues.length?{success:!1,error:new(t??Ot)(o.issues.map(a=>ae(a,e,B())))}:{success:!0,data:o.value}},Be=Sr(Fe),wr=t=>async(r,n,i)=>{let e=i?Object.assign(i,{async:!0}):{async:!0},o=r._zod.run({value:n,issues:[]},e);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>ae(a,e,B())))}:{success:!0,data:o.value}},Et=wr(Fe)});var ze={};$e(ze,{_emoji:()=>Dc,base64:()=>Jo,base64url:()=>jr,bigint:()=>Xo,boolean:()=>ri,browserEmail:()=>Od,cidrv4:()=>Fo,cidrv6:()=>Ho,cuid:()=>No,cuid2:()=>Uo,date:()=>Ko,datetime:()=>Qo,domain:()=>Nd,duration:()=>Ao,e164:()=>Wo,email:()=>Mo,emoji:()=>Lo,extendedDuration:()=>kd,guid:()=>Co,hostname:()=>Bo,html5Email:()=>jd,integer:()=>ei,ipv4:()=>qo,ipv6:()=>Vo,ksuid:()=>Do,lowercase:()=>ii,nanoid:()=>Ro,null:()=>ni,number:()=>ti,rfc5322Email:()=>Pd,string:()=>Yo,time:()=>Go,ulid:()=>Eo,undefined:()=>oi,unicodeEmail:()=>Td,uppercase:()=>ai,uuid:()=>Ne,uuid4:()=>Sd,uuid6:()=>wd,uuid7:()=>Id,xid:()=>Zo});function Lo(){return new RegExp(Dc,"u")}function Ac(t){let r="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${r}`:t.precision===0?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Go(t){return new RegExp(`^${Ac(t)}$`)}function Qo(t){let r=Ac({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let i=`${r}(?:${n.join("|")})`;return new RegExp(`^${Rc}T(?:${i})$`)}var No,Uo,Eo,Zo,Do,Ro,Ao,kd,Co,Ne,Sd,wd,Id,Mo,jd,Pd,Td,Od,Dc,qo,Vo,Fo,Ho,Jo,jr,Bo,Nd,Wo,Rc,Ko,Yo,Xo,ei,ti,ri,ni,oi,ii,ai,Pr=k(()=>{No=/^[cC][^\s-]{8,}$/,Uo=/^[0-9a-z]+$/,Eo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zo=/^[0-9a-vA-V]{20}$/,Do=/^[A-Za-z0-9]{27}$/,Ro=/^[a-zA-Z0-9_-]{21}$/,Ao=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,kd=/^[-+]?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)?)??$/,Co=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ne=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Sd=Ne(4),wd=Ne(6),Id=Ne(7),Mo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,jd=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Pd=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Td=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Od=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Dc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";qo=/^(?:(?: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])$/,Vo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Fo=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ho=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Jo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,jr=/^[A-Za-z0-9_-]*$/,Bo=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Nd=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Wo=/^\+(?:[0-9]){6,14}[0-9]$/,Rc="(?:(?:\\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])))",Ko=new RegExp(`^${Rc}$`);Yo=t=>{let r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},Xo=/^\d+n?$/,ei=/^\d+$/,ti=/^-?\d+(?:\.\d+)?/i,ri=/true|false/i,ni=/null/i,oi=/undefined/i,ii=/^[^A-Z]*$/,ai=/^[^a-z]*$/});function Cc(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues))}var J,Mc,Tr,Or,si,ci,ui,li,mi,di,pi,fi,gi,We,hi,vi,bi,_i,yi,$i,xi,zi,ki,Nr=k(()=>{Le();Pr();P();J=u("$ZodCheck",(t,r)=>{var n;t._zod??(t._zod={}),t._zod.def=r,(n=t._zod).onattach??(n.onattach=[])}),Mc={number:"number",bigint:"bigint",object:"date"},Tr=u("$ZodCheckLessThan",(t,r)=>{J.init(t,r);let n=Mc[typeof r.value];t._zod.onattach.push(i=>{let e=i._zod.bag,o=(r.inclusive?e.maximum:e.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<o&&(r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value)}),t._zod.check=i=>{(r.inclusive?i.value<=r.value:i.value<r.value)||i.issues.push({origin:n,code:"too_big",maximum:r.value,input:i.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),Or=u("$ZodCheckGreaterThan",(t,r)=>{J.init(t,r);let n=Mc[typeof r.value];t._zod.onattach.push(i=>{let e=i._zod.bag,o=(r.inclusive?e.minimum:e.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>o&&(r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value)}),t._zod.check=i=>{(r.inclusive?i.value>=r.value:i.value>r.value)||i.issues.push({origin:n,code:"too_small",minimum:r.value,input:i.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),si=u("$ZodCheckMultipleOf",(t,r)=>{J.init(t,r),t._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=r.value)}),t._zod.check=n=>{if(typeof n.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%r.value===BigInt(0):zo(n.value,r.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:r.value,input:n.value,inst:t,continue:!r.abort})}}),ci=u("$ZodCheckNumberFormat",(t,r)=>{J.init(t,r),r.format=r.format||"float64";let n=r.format?.includes("int"),i=n?"int":"number",[e,o]=jo[r.format];t._zod.onattach.push(a=>{let c=a._zod.bag;c.format=r.format,c.minimum=e,c.maximum=o,n&&(c.pattern=ei)}),t._zod.check=a=>{let c=a.value;if(n){if(!Number.isInteger(c)){a.issues.push({expected:i,format:r.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!r.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!r.abort});return}}c<e&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:e,inclusive:!0,inst:t,continue:!r.abort}),c>o&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:o,inst:t})}}),ui=u("$ZodCheckBigIntFormat",(t,r)=>{J.init(t,r);let[n,i]=Po[r.format];t._zod.onattach.push(e=>{let o=e._zod.bag;o.format=r.format,o.minimum=n,o.maximum=i}),t._zod.check=e=>{let o=e.value;o<n&&e.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!r.abort}),o>i&&e.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inst:t})}}),li=u("$ZodCheckMaxSize",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<e&&(i._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let e=i.value;e.size<=r.maximum||i.issues.push({origin:Pt(e),code:"too_big",maximum:r.maximum,input:e,inst:t,continue:!r.abort})}}),mi=u("$ZodCheckMinSize",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>e&&(i._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let e=i.value;e.size>=r.minimum||i.issues.push({origin:Pt(e),code:"too_small",minimum:r.minimum,input:e,inst:t,continue:!r.abort})}}),di=u("$ZodCheckSizeEquals",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag;e.minimum=r.size,e.maximum=r.size,e.size=r.size}),t._zod.check=i=>{let e=i.value,o=e.size;if(o===r.size)return;let a=o>r.size;i.issues.push({origin:Pt(e),...a?{code:"too_big",maximum:r.size}:{code:"too_small",minimum:r.size},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),pi=u("$ZodCheckMaxLength",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<e&&(i._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let e=i.value;if(e.length<=r.maximum)return;let a=Tt(e);i.issues.push({origin:a,code:"too_big",maximum:r.maximum,inclusive:!0,input:e,inst:t,continue:!r.abort})}}),fi=u("$ZodCheckMinLength",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>e&&(i._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let e=i.value;if(e.length>=r.minimum)return;let a=Tt(e);i.issues.push({origin:a,code:"too_small",minimum:r.minimum,inclusive:!0,input:e,inst:t,continue:!r.abort})}}),gi=u("$ZodCheckLengthEquals",(t,r)=>{var n;J.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!xe(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag;e.minimum=r.length,e.maximum=r.length,e.length=r.length}),t._zod.check=i=>{let e=i.value,o=e.length;if(o===r.length)return;let a=Tt(e),c=o>r.length;i.issues.push({origin:a,...c?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),We=u("$ZodCheckStringFormat",(t,r)=>{var n,i;J.init(t,r),t._zod.onattach.push(e=>{let o=e._zod.bag;o.format=r.format,r.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(r.pattern))}),r.pattern?(n=t._zod).check??(n.check=e=>{r.pattern.lastIndex=0,!r.pattern.test(e.value)&&e.issues.push({origin:"string",code:"invalid_format",format:r.format,input:e.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(i=t._zod).check??(i.check=()=>{})}),hi=u("$ZodCheckRegex",(t,r)=>{We.init(t,r),t._zod.check=n=>{r.pattern.lastIndex=0,!r.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),vi=u("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=ii),We.init(t,r)}),bi=u("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=ai),We.init(t,r)}),_i=u("$ZodCheckIncludes",(t,r)=>{J.init(t,r);let n=be(r.includes),i=new RegExp(typeof r.position=="number"?`^.{${r.position}}${n}`:n);r.pattern=i,t._zod.onattach.push(e=>{let o=e._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),t._zod.check=e=>{e.value.includes(r.includes,r.position)||e.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:e.value,inst:t,continue:!r.abort})}}),yi=u("$ZodCheckStartsWith",(t,r)=>{J.init(t,r);let n=new RegExp(`^${be(r.prefix)}.*`);r.pattern??(r.pattern=n),t._zod.onattach.push(i=>{let e=i._zod.bag;e.patterns??(e.patterns=new Set),e.patterns.add(n)}),t._zod.check=i=>{i.value.startsWith(r.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:i.value,inst:t,continue:!r.abort})}}),$i=u("$ZodCheckEndsWith",(t,r)=>{J.init(t,r);let n=new RegExp(`.*${be(r.suffix)}$`);r.pattern??(r.pattern=n),t._zod.onattach.push(i=>{let e=i._zod.bag;e.patterns??(e.patterns=new Set),e.patterns.add(n)}),t._zod.check=i=>{i.value.endsWith(r.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:i.value,inst:t,continue:!r.abort})}});xi=u("$ZodCheckProperty",(t,r)=>{J.init(t,r),t._zod.check=n=>{let i=r.schema._zod.run({value:n.value[r.property],issues:[]},{});if(i instanceof Promise)return i.then(e=>Cc(e,n,r.property));Cc(i,n,r.property)}}),zi=u("$ZodCheckMimeType",(t,r)=>{J.init(t,r);let n=new Set(r.mime);t._zod.onattach.push(i=>{i._zod.bag.mime=r.mime}),t._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:r.mime,input:i.value.type,inst:t})}}),ki=u("$ZodCheckOverwrite",(t,r)=>{J.init(t,r),t._zod.check=n=>{n.value=r.tx(n.value)}})});var Zt,Si=k(()=>{Zt=class{constructor(r=[]){this.content=[],this.indent=0,this&&(this.args=r)}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r=="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}let i=r.split(``).filter(a=>a),e=Math.min(...i.map(a=>a.length-a.trimStart().length)),o=i.map(a=>a.slice(e)).map(a=>" ".repeat(this.indent*2)+a);for(let a of o)this.content.push(a)}compile(){let r=Function,n=this?.args,e=[...(this?.content??[""]).map(o=>` ${o}`)];return new r(...n,e.join(`-`))}}});var Si,wi=k(()=>{Si={major:4,minor:0,patch:0}});function Bi(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Qc(t){if(!jr.test(t))return!1;let r=t.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=r.padEnd(Math.ceil(r.length/4)*4,"=");return Bi(n)}function Yc(t,r=null){try{let n=t.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let e=JSON.parse(atob(i));return!("typ"in e&&e?.typ!=="JWT"||!e.alg||r&&(!("alg"in e)||e.alg!==r))}catch{return!1}}function Mc(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues)),r.value[n]=t.value}function Ur(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues)),r.value[n]=t.value}function Lc(t,r,n,i){t.issues.length?i[n]===void 0?n in i?r.value[n]=void 0:r.value[n]=t.value:r.issues.push(...oe(n,t.issues)):t.value===void 0?n in i&&(r.value[n]=void 0):r.value[n]=t.value}function qc(t,r,n,i){for(let e of t)if(e.issues.length===0)return r.value=e.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:n,errors:t.map(e=>e.issues.map(o=>ae(o,i,B())))}),r}function Ii(t,r){if(t===r)return{valid:!0,data:t};if(t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(Ve(t)&&Ve(r)){let n=Object.keys(r),i=Object.keys(t).filter(o=>n.indexOf(o)!==-1),e={...t,...r};for(let o of i){let a=Ii(t[o],r[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};e[o]=a.data}return{valid:!0,data:e}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<t.length;i++){let e=t[i],o=r[i],a=Ii(e,o);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vc(t,r,n){if(r.issues.length&&t.issues.push(...r.issues),n.issues.length&&t.issues.push(...n.issues),Oe(t))return t;let i=Ii(r.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}function Er(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues)),r.value[n]=t.value}function Fc(t,r,n,i,e,o,a){t.issues.length&&(jt.has(typeof i)?n.issues.push(...oe(i,t.issues)):n.issues.push({origin:"map",code:"invalid_key",input:e,inst:o,issues:t.issues.map(c=>ae(c,a,B()))})),r.issues.length&&(jt.has(typeof i)?n.issues.push(...oe(i,r.issues)):n.issues.push({origin:"map",code:"invalid_element",input:e,inst:o,key:i,issues:r.issues.map(c=>ae(c,a,B()))})),n.value.set(t.value,r.value)}function Hc(t,r){t.issues.length&&r.issues.push(...t.issues),r.value.add(t.value)}function Jc(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}function Bc(t,r){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}function Wc(t,r,n){return Oe(t)?t:r.out._zod.run({value:t.value,issues:t.issues},n)}function Kc(t){return t.value=Object.freeze(t.value),t}function Gc(t,r,n,i){if(!t){let e={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(e.params=i._zod.def.params),r.issues.push(Po(e))}}var T,Ue,q,ji,Pi,Ti,Oi,Ni,Ui,Ei,Zi,Di,Ri,Ai,Ci,Mi,Li,qi,Vi,Fi,Hi,Ji,Wi,Ki,Gi,Qi,Yi,Zr,Xi,Dt,Dr,ea,ta,ra,na,oa,Ke,ia,aa,sa,Rt,ca,Rr,ua,la,Ee,ma,da,pa,fa,ga,ha,At,va,ba,_a,ya,$a,xa,za,ka,Ct,Sa,wa,Ia,ja,Pa,Mt=k(()=>{Nr();Le();ki();Ir();Pr();P();wi();P();T=u("$ZodType",(t,r)=>{var n;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=Si;let i=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&i.unshift(t);for(let e of i)for(let o of e._zod.onattach)o(t);if(i.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let e=(o,a,c)=>{let d=Oe(o),h;for(let g of a){if(g._zod.def.when){if(!g._zod.def.when(o))continue}else if(d)continue;let l=o.issues.length,$=g._zod.check(o);if($ instanceof Promise&&c?.async===!1)throw new de;if(h||$ instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await $,o.issues.length!==l&&(d||(d=Oe(o,l)))});else{if(o.issues.length===l)continue;d||(d=Oe(o,l))}}return h?h.then(()=>o):o};t._zod.run=(o,a)=>{let c=t._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new de;return c.then(d=>e(d,i,a))}return e(c,i,a)}}t["~standard"]={validate:e=>{try{let o=Be(t,e);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Et(t,e).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Ue=u("$ZodString",(t,r)=>{T.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Qo(t._zod.bag),t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),q=u("$ZodStringFormat",(t,r)=>{We.init(t,r),Ue.init(t,r)}),ji=u("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=Ao),q.init(t,r)}),Pi=u("$ZodUUID",(t,r)=>{if(r.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(i===void 0)throw new Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=Ne(i))}else r.pattern??(r.pattern=Ne());q.init(t,r)}),Ti=u("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=Co),q.init(t,r)}),Oi=u("$ZodURL",(t,r)=>{q.init(t,r),t._zod.check=n=>{try{let i=n.value,e=new URL(i),o=e.href;r.hostname&&(r.hostname.lastIndex=0,r.hostname.test(e.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Jo.source,input:n.value,inst:t,continue:!r.abort})),r.protocol&&(r.protocol.lastIndex=0,r.protocol.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:n.value,inst:t,continue:!r.abort})),!i.endsWith("/")&&o.endsWith("/")?n.value=o.slice(0,-1):n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!r.abort})}}}),Ni=u("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=Mo()),q.init(t,r)}),Ui=u("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=Do),q.init(t,r)}),Ei=u("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=Oo),q.init(t,r)}),Zi=u("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=No),q.init(t,r)}),Di=u("$ZodULID",(t,r)=>{r.pattern??(r.pattern=Uo),q.init(t,r)}),Ri=u("$ZodXID",(t,r)=>{r.pattern??(r.pattern=Eo),q.init(t,r)}),Ai=u("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=Zo),q.init(t,r)}),Ci=u("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=Go(r)),q.init(t,r)}),Mi=u("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=Wo),q.init(t,r)}),Li=u("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=Ko(r)),q.init(t,r)}),qi=u("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=Ro),q.init(t,r)}),Vi=u("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=Lo),q.init(t,r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv4"})}),Fi=u("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=qo),q.init(t,r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!r.abort})}}}),Hi=u("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=Vo),q.init(t,r)}),Ji=u("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=Fo),q.init(t,r),t._zod.check=n=>{let[i,e]=n.value.split("/");try{if(!e)throw new Error;let o=Number(e);if(`${o}`!==e)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!r.abort})}}});Wi=u("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=Ho),q.init(t,r),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Bi(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!r.abort})}});Ki=u("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=jr),q.init(t,r),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Qc(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!r.abort})}}),Gi=u("$ZodE164",(t,r)=>{r.pattern??(r.pattern=Bo),q.init(t,r)});Qi=u("$ZodJWT",(t,r)=>{q.init(t,r),t._zod.check=n=>{Yc(n.value,r.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!r.abort})}}),Yi=u("$ZodCustomStringFormat",(t,r)=>{q.init(t,r),t._zod.check=n=>{r.fn(n.value)||n.issues.push({code:"invalid_format",format:r.format,input:n.value,inst:t,continue:!r.abort})}}),Zr=u("$ZodNumber",(t,r)=>{T.init(t,r),t._zod.pattern=t._zod.bag.pattern??ei,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=Number(n.value)}catch{}let e=n.value;if(typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e))return n;let o=typeof e=="number"?Number.isNaN(e)?"NaN":Number.isFinite(e)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:e,inst:t,...o?{received:o}:{}}),n}}),Xi=u("$ZodNumber",(t,r)=>{si.init(t,r),Zr.init(t,r)}),Dt=u("$ZodBoolean",(t,r)=>{T.init(t,r),t._zod.pattern=ti,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=!!n.value}catch{}let e=n.value;return typeof e=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:e,inst:t}),n}}),Dr=u("$ZodBigInt",(t,r)=>{T.init(t,r),t._zod.pattern=Yo,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),ea=u("$ZodBigInt",(t,r)=>{ci.init(t,r),Dr.init(t,r)}),ta=u("$ZodSymbol",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return typeof e=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:e,inst:t}),n}}),ra=u("$ZodUndefined",(t,r)=>{T.init(t,r),t._zod.pattern=ni,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(n,i)=>{let e=n.value;return typeof e>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:e,inst:t}),n}}),na=u("$ZodNull",(t,r)=>{T.init(t,r),t._zod.pattern=ri,t._zod.values=new Set([null]),t._zod.parse=(n,i)=>{let e=n.value;return e===null||n.issues.push({expected:"null",code:"invalid_type",input:e,inst:t}),n}}),oa=u("$ZodAny",(t,r)=>{T.init(t,r),t._zod.parse=n=>n}),Ke=u("$ZodUnknown",(t,r)=>{T.init(t,r),t._zod.parse=n=>n}),ia=u("$ZodNever",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),aa=u("$ZodVoid",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return typeof e>"u"||n.issues.push({expected:"void",code:"invalid_type",input:e,inst:t}),n}}),sa=u("$ZodDate",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=new Date(n.value)}catch{}let e=n.value,o=e instanceof Date;return o&&!Number.isNaN(e.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:e,...o?{received:"Invalid Date"}:{},inst:t}),n}});Rt=u("$ZodArray",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!Array.isArray(e))return n.issues.push({expected:"array",code:"invalid_type",input:e,inst:t}),n;n.value=Array(e.length);let o=[];for(let a=0;a<e.length;a++){let c=e[a],d=r.element._zod.run({value:c,issues:[]},i);d instanceof Promise?o.push(d.then(h=>Mc(h,n,a))):Mc(d,n,a)}return o.length?Promise.all(o).then(()=>n):n}});ca=u("$ZodObject",(t,r)=>{T.init(t,r);let n=wt(()=>{let l=Object.keys(r.shape);for(let b of l)if(!(r.shape[b]instanceof T))throw new Error(`Invalid element at key "${b}": expected a Zod schema`);let $=wo(r.shape);return{shape:r.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set($)}});D(t._zod,"propValues",()=>{let l=r.shape,$={};for(let b in l){let p=l[b]._zod;if(p.values){$[b]??($[b]=new Set);for(let x of p.values)$[b].add(x)}}return $});let i=l=>{let $=new Zt(["shape","payload","ctx"]),b=n.value,p=w=>{let j=Te(w);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};$.write("const input = payload.value;");let x=Object.create(null),S=0;for(let w of b.keys)x[w]=`key_${S++}`;$.write("const newResult = {}");for(let w of b.keys)if(b.optionalKeys.has(w)){let j=x[w];$.write(`const ${j} = ${p(w)};`);let U=Te(w);$.write(`+`))}}});var wi,Ii=k(()=>{wi={major:4,minor:0,patch:0}});function Wi(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Xc(t){if(!jr.test(t))return!1;let r=t.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=r.padEnd(Math.ceil(r.length/4)*4,"=");return Wi(n)}function eu(t,r=null){try{let n=t.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let e=JSON.parse(atob(i));return!("typ"in e&&e?.typ!=="JWT"||!e.alg||r&&(!("alg"in e)||e.alg!==r))}catch{return!1}}function qc(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues)),r.value[n]=t.value}function Ur(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues)),r.value[n]=t.value}function Vc(t,r,n,i){t.issues.length?i[n]===void 0?n in i?r.value[n]=void 0:r.value[n]=t.value:r.issues.push(...oe(n,t.issues)):t.value===void 0?n in i&&(r.value[n]=void 0):r.value[n]=t.value}function Fc(t,r,n,i){for(let e of t)if(e.issues.length===0)return r.value=e.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:n,errors:t.map(e=>e.issues.map(o=>ae(o,i,B())))}),r}function ji(t,r){if(t===r)return{valid:!0,data:t};if(t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(Ve(t)&&Ve(r)){let n=Object.keys(r),i=Object.keys(t).filter(o=>n.indexOf(o)!==-1),e={...t,...r};for(let o of i){let a=ji(t[o],r[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};e[o]=a.data}return{valid:!0,data:e}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<t.length;i++){let e=t[i],o=r[i],a=ji(e,o);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Hc(t,r,n){if(r.issues.length&&t.issues.push(...r.issues),n.issues.length&&t.issues.push(...n.issues),Oe(t))return t;let i=ji(r.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}function Er(t,r,n){t.issues.length&&r.issues.push(...oe(n,t.issues)),r.value[n]=t.value}function Jc(t,r,n,i,e,o,a){t.issues.length&&(jt.has(typeof i)?n.issues.push(...oe(i,t.issues)):n.issues.push({origin:"map",code:"invalid_key",input:e,inst:o,issues:t.issues.map(c=>ae(c,a,B()))})),r.issues.length&&(jt.has(typeof i)?n.issues.push(...oe(i,r.issues)):n.issues.push({origin:"map",code:"invalid_element",input:e,inst:o,key:i,issues:r.issues.map(c=>ae(c,a,B()))})),n.value.set(t.value,r.value)}function Bc(t,r){t.issues.length&&r.issues.push(...t.issues),r.value.add(t.value)}function Wc(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}function Kc(t,r){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}function Gc(t,r,n){return Oe(t)?t:r.out._zod.run({value:t.value,issues:t.issues},n)}function Qc(t){return t.value=Object.freeze(t.value),t}function Yc(t,r,n,i){if(!t){let e={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(e.params=i._zod.def.params),r.issues.push(To(e))}}var T,Ue,q,Pi,Ti,Oi,Ni,Ui,Ei,Zi,Di,Ri,Ai,Ci,Mi,Li,qi,Vi,Fi,Hi,Ji,Bi,Ki,Gi,Qi,Yi,Xi,Zr,ea,Dt,Dr,ta,ra,na,oa,ia,Ke,aa,sa,ca,Rt,ua,Rr,la,ma,Ee,da,pa,fa,ga,ha,va,At,ba,_a,ya,$a,xa,za,ka,Sa,Ct,wa,Ia,ja,Pa,Ta,Mt=k(()=>{Nr();Le();Si();Ir();Pr();P();Ii();P();T=u("$ZodType",(t,r)=>{var n;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=wi;let i=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&i.unshift(t);for(let e of i)for(let o of e._zod.onattach)o(t);if(i.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let e=(o,a,c)=>{let d=Oe(o),h;for(let g of a){if(g._zod.def.when){if(!g._zod.def.when(o))continue}else if(d)continue;let l=o.issues.length,$=g._zod.check(o);if($ instanceof Promise&&c?.async===!1)throw new de;if(h||$ instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await $,o.issues.length!==l&&(d||(d=Oe(o,l)))});else{if(o.issues.length===l)continue;d||(d=Oe(o,l))}}return h?h.then(()=>o):o};t._zod.run=(o,a)=>{let c=t._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new de;return c.then(d=>e(d,i,a))}return e(c,i,a)}}t["~standard"]={validate:e=>{try{let o=Be(t,e);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Et(t,e).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Ue=u("$ZodString",(t,r)=>{T.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Yo(t._zod.bag),t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),q=u("$ZodStringFormat",(t,r)=>{We.init(t,r),Ue.init(t,r)}),Pi=u("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=Co),q.init(t,r)}),Ti=u("$ZodUUID",(t,r)=>{if(r.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(i===void 0)throw new Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=Ne(i))}else r.pattern??(r.pattern=Ne());q.init(t,r)}),Oi=u("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=Mo),q.init(t,r)}),Ni=u("$ZodURL",(t,r)=>{q.init(t,r),t._zod.check=n=>{try{let i=n.value,e=new URL(i),o=e.href;r.hostname&&(r.hostname.lastIndex=0,r.hostname.test(e.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Bo.source,input:n.value,inst:t,continue:!r.abort})),r.protocol&&(r.protocol.lastIndex=0,r.protocol.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:n.value,inst:t,continue:!r.abort})),!i.endsWith("/")&&o.endsWith("/")?n.value=o.slice(0,-1):n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!r.abort})}}}),Ui=u("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=Lo()),q.init(t,r)}),Ei=u("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=Ro),q.init(t,r)}),Zi=u("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=No),q.init(t,r)}),Di=u("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=Uo),q.init(t,r)}),Ri=u("$ZodULID",(t,r)=>{r.pattern??(r.pattern=Eo),q.init(t,r)}),Ai=u("$ZodXID",(t,r)=>{r.pattern??(r.pattern=Zo),q.init(t,r)}),Ci=u("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=Do),q.init(t,r)}),Mi=u("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=Qo(r)),q.init(t,r)}),Li=u("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=Ko),q.init(t,r)}),qi=u("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=Go(r)),q.init(t,r)}),Vi=u("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=Ao),q.init(t,r)}),Fi=u("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=qo),q.init(t,r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv4"})}),Hi=u("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=Vo),q.init(t,r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!r.abort})}}}),Ji=u("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=Fo),q.init(t,r)}),Bi=u("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=Ho),q.init(t,r),t._zod.check=n=>{let[i,e]=n.value.split("/");try{if(!e)throw new Error;let o=Number(e);if(`${o}`!==e)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!r.abort})}}});Ki=u("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=Jo),q.init(t,r),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Wi(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!r.abort})}});Gi=u("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=jr),q.init(t,r),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Xc(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!r.abort})}}),Qi=u("$ZodE164",(t,r)=>{r.pattern??(r.pattern=Wo),q.init(t,r)});Yi=u("$ZodJWT",(t,r)=>{q.init(t,r),t._zod.check=n=>{eu(n.value,r.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!r.abort})}}),Xi=u("$ZodCustomStringFormat",(t,r)=>{q.init(t,r),t._zod.check=n=>{r.fn(n.value)||n.issues.push({code:"invalid_format",format:r.format,input:n.value,inst:t,continue:!r.abort})}}),Zr=u("$ZodNumber",(t,r)=>{T.init(t,r),t._zod.pattern=t._zod.bag.pattern??ti,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=Number(n.value)}catch{}let e=n.value;if(typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e))return n;let o=typeof e=="number"?Number.isNaN(e)?"NaN":Number.isFinite(e)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:e,inst:t,...o?{received:o}:{}}),n}}),ea=u("$ZodNumber",(t,r)=>{ci.init(t,r),Zr.init(t,r)}),Dt=u("$ZodBoolean",(t,r)=>{T.init(t,r),t._zod.pattern=ri,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=!!n.value}catch{}let e=n.value;return typeof e=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:e,inst:t}),n}}),Dr=u("$ZodBigInt",(t,r)=>{T.init(t,r),t._zod.pattern=Xo,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),ta=u("$ZodBigInt",(t,r)=>{ui.init(t,r),Dr.init(t,r)}),ra=u("$ZodSymbol",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return typeof e=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:e,inst:t}),n}}),na=u("$ZodUndefined",(t,r)=>{T.init(t,r),t._zod.pattern=oi,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(n,i)=>{let e=n.value;return typeof e>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:e,inst:t}),n}}),oa=u("$ZodNull",(t,r)=>{T.init(t,r),t._zod.pattern=ni,t._zod.values=new Set([null]),t._zod.parse=(n,i)=>{let e=n.value;return e===null||n.issues.push({expected:"null",code:"invalid_type",input:e,inst:t}),n}}),ia=u("$ZodAny",(t,r)=>{T.init(t,r),t._zod.parse=n=>n}),Ke=u("$ZodUnknown",(t,r)=>{T.init(t,r),t._zod.parse=n=>n}),aa=u("$ZodNever",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),sa=u("$ZodVoid",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return typeof e>"u"||n.issues.push({expected:"void",code:"invalid_type",input:e,inst:t}),n}}),ca=u("$ZodDate",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=new Date(n.value)}catch{}let e=n.value,o=e instanceof Date;return o&&!Number.isNaN(e.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:e,...o?{received:"Invalid Date"}:{},inst:t}),n}});Rt=u("$ZodArray",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!Array.isArray(e))return n.issues.push({expected:"array",code:"invalid_type",input:e,inst:t}),n;n.value=Array(e.length);let o=[];for(let a=0;a<e.length;a++){let c=e[a],d=r.element._zod.run({value:c,issues:[]},i);d instanceof Promise?o.push(d.then(h=>qc(h,n,a))):qc(d,n,a)}return o.length?Promise.all(o).then(()=>n):n}});ua=u("$ZodObject",(t,r)=>{T.init(t,r);let n=wt(()=>{let l=Object.keys(r.shape);for(let b of l)if(!(r.shape[b]instanceof T))throw new Error(`Invalid element at key "${b}": expected a Zod schema`);let $=Io(r.shape);return{shape:r.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set($)}});D(t._zod,"propValues",()=>{let l=r.shape,$={};for(let b in l){let p=l[b]._zod;if(p.values){$[b]??($[b]=new Set);for(let x of p.values)$[b].add(x)}}return $});let i=l=>{let $=new Zt(["shape","payload","ctx"]),b=n.value,p=w=>{let j=Te(w);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};$.write("const input = payload.value;");let x=Object.create(null),S=0;for(let w of b.keys)x[w]=`key_${S++}`;$.write("const newResult = {}");for(let w of b.keys)if(b.optionalKeys.has(w)){let j=x[w];$.write(`const ${j} = ${p(w)};`);let U=Te(w);$.write(`if (${j}.issues.length) {if (input[${U}] === undefined) {if (${U} in input) {@@ -55,9 +55,9 @@if (${j}.issues.length) payload.issues = payload.issues.concat(${j}.issues.map(iss => ({...iss,path: iss.path ? [${Te(w)}, ...iss.path] : [${Te(w)}]- })));`),$.write(`newResult[${Te(w)}] = ${j}.value`)}$.write("payload.value = newResult;"),$.write("return payload;");let R=$.compile();return(w,j)=>R(l,w,j)},e,o=qe,a=!zt.jitless,d=a&&ko.value,h=r.catchall,g;t._zod.parse=(l,$)=>{g??(g=n.value);let b=l.value;if(!o(b))return l.issues.push({expected:"object",code:"invalid_type",input:b,inst:t}),l;let p=[];if(a&&d&&$?.async===!1&&$.jitless!==!0)e||(e=i(r.shape)),l=e(l,$);else{l.value={};let j=g.shape;for(let U of g.keys){let je=j[U],vr=je._zod.run({value:b[U],issues:[]},$),Pc=je._zod.optin==="optional"&&je._zod.optout==="optional";vr instanceof Promise?p.push(vr.then(Tc=>Pc?Lc(Tc,l,U,b):Ur(Tc,l,U))):Pc?Lc(vr,l,U,b):Ur(vr,l,U)}}if(!h)return p.length?Promise.all(p).then(()=>l):l;let x=[],S=g.keySet,R=h._zod,w=R.def.type;for(let j of Object.keys(b)){if(S.has(j))continue;if(w==="never"){x.push(j);continue}let U=R.run({value:b[j],issues:[]},$);U instanceof Promise?p.push(U.then(je=>Ur(je,l,j))):Ur(U,l,j)}return x.length&&l.issues.push({code:"unrecognized_keys",keys:x,input:b,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Rr=u("$ZodUnion",(t,r)=>{T.init(t,r),D(t._zod,"optin",()=>r.options.some(n=>n._zod.optin==="optional")?"optional":void 0),D(t._zod,"optout",()=>r.options.some(n=>n._zod.optout==="optional")?"optional":void 0),D(t._zod,"values",()=>{if(r.options.every(n=>n._zod.values))return new Set(r.options.flatMap(n=>Array.from(n._zod.values)))}),D(t._zod,"pattern",()=>{if(r.options.every(n=>n._zod.pattern)){let n=r.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>It(i.source)).join("|")})$`)}}),t._zod.parse=(n,i)=>{let e=!1,o=[];for(let a of r.options){let c=a._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)o.push(c),e=!0;else{if(c.issues.length===0)return c;o.push(c)}}return e?Promise.all(o).then(a=>qc(a,n,t,i)):qc(o,n,t,i)}}),ua=u("$ZodDiscriminatedUnion",(t,r)=>{Rr.init(t,r);let n=t._zod.parse;D(t._zod,"propValues",()=>{let e={};for(let o of r.options){let a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(o)}"`);for(let[c,d]of Object.entries(a)){e[c]||(e[c]=new Set);for(let h of d)e[c].add(h)}}return e});let i=wt(()=>{let e=r.options,o=new Map;for(let a of e){let c=a._zod.propValues[r.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(a)}"`);for(let d of c){if(o.has(d))throw new Error(`Duplicate discriminator value "${String(d)}"`);o.set(d,a)}}return o});t._zod.parse=(e,o)=>{let a=e.value;if(!qe(a))return e.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),e;let c=i.value.get(a?.[r.discriminator]);return c?c._zod.run(e,o):r.unionFallback?n(e,o):(e.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[r.discriminator],inst:t}),e)}}),la=u("$ZodIntersection",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value,o=r.left._zod.run({value:e,issues:[]},i),a=r.right._zod.run({value:e,issues:[]},i);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([d,h])=>Vc(n,d,h)):Vc(n,o,a)}});Ee=u("$ZodTuple",(t,r)=>{T.init(t,r);let n=r.items,i=n.length-[...n].reverse().findIndex(e=>e._zod.optin!=="optional");t._zod.parse=(e,o)=>{let a=e.value;if(!Array.isArray(a))return e.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),e;e.value=[];let c=[];if(!r.rest){let h=a.length>n.length,g=a.length<i-1;if(h||g)return e.issues.push({input:a,inst:t,origin:"array",...h?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),e}let d=-1;for(let h of n){if(d++,d>=a.length&&d>=i)continue;let g=h._zod.run({value:a[d],issues:[]},o);g instanceof Promise?c.push(g.then(l=>Er(l,e,d))):Er(g,e,d)}if(r.rest){let h=a.slice(n.length);for(let g of h){d++;let l=r.rest._zod.run({value:g,issues:[]},o);l instanceof Promise?c.push(l.then($=>Er($,e,d))):Er(l,e,d)}}return c.length?Promise.all(c).then(()=>e):e}});ma=u("$ZodRecord",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!Ve(e))return n.issues.push({expected:"record",code:"invalid_type",input:e,inst:t}),n;let o=[];if(r.keyType._zod.values){let a=r.keyType._zod.values;n.value={};for(let d of a)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){let h=r.valueType._zod.run({value:e[d],issues:[]},i);h instanceof Promise?o.push(h.then(g=>{g.issues.length&&n.issues.push(...oe(d,g.issues)),n.value[d]=g.value})):(h.issues.length&&n.issues.push(...oe(d,h.issues)),n.value[d]=h.value)}let c;for(let d in e)a.has(d)||(c=c??[],c.push(d));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:e,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(e)){if(a==="__proto__")continue;let c=r.keyType._zod.run({value:a,issues:[]},i);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(h=>ae(h,i,B())),input:a,path:[a],inst:t}),n.value[c.value]=c.value;continue}let d=r.valueType._zod.run({value:e[a],issues:[]},i);d instanceof Promise?o.push(d.then(h=>{h.issues.length&&n.issues.push(...oe(a,h.issues)),n.value[c.value]=h.value})):(d.issues.length&&n.issues.push(...oe(a,d.issues)),n.value[c.value]=d.value)}}return o.length?Promise.all(o).then(()=>n):n}}),da=u("$ZodMap",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!(e instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:e,inst:t}),n;let o=[];n.value=new Map;for(let[a,c]of e){let d=r.keyType._zod.run({value:a,issues:[]},i),h=r.valueType._zod.run({value:c,issues:[]},i);d instanceof Promise||h instanceof Promise?o.push(Promise.all([d,h]).then(([g,l])=>{Fc(g,l,n,a,e,t,i)})):Fc(d,h,n,a,e,t,i)}return o.length?Promise.all(o).then(()=>n):n}});pa=u("$ZodSet",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!(e instanceof Set))return n.issues.push({input:e,inst:t,expected:"set",code:"invalid_type"}),n;let o=[];n.value=new Set;for(let a of e){let c=r.valueType._zod.run({value:a,issues:[]},i);c instanceof Promise?o.push(c.then(d=>Hc(d,n))):Hc(c,n)}return o.length?Promise.all(o).then(()=>n):n}});fa=u("$ZodEnum",(t,r)=>{T.init(t,r);let n=St(r.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(i=>jt.has(typeof i)).map(i=>typeof i=="string"?be(i):i.toString()).join("|")})$`),t._zod.parse=(i,e)=>{let o=i.value;return t._zod.values.has(o)||i.issues.push({code:"invalid_value",values:n,input:o,inst:t}),i}}),ga=u("$ZodLiteral",(t,r)=>{T.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(n=>typeof n=="string"?be(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let e=n.value;return t._zod.values.has(e)||n.issues.push({code:"invalid_value",values:r.values,input:e,inst:t}),n}}),ha=u("$ZodFile",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return e instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:e,inst:t}),n}}),At=u("$ZodTransform",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=r.transform(n.value,n);if(i.async)return(e instanceof Promise?e:Promise.resolve(e)).then(a=>(n.value=a,n));if(e instanceof Promise)throw new de;return n.value=e,n}}),va=u("$ZodOptional",(t,r)=>{T.init(t,r),t._zod.optin="optional",t._zod.optout="optional",D(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),D(t._zod,"pattern",()=>{let n=r.innerType._zod.pattern;return n?new RegExp(`^(${It(n.source)})?$`):void 0}),t._zod.parse=(n,i)=>r.innerType._zod.optin==="optional"?r.innerType._zod.run(n,i):n.value===void 0?n:r.innerType._zod.run(n,i)}),ba=u("$ZodNullable",(t,r)=>{T.init(t,r),D(t._zod,"optin",()=>r.innerType._zod.optin),D(t._zod,"optout",()=>r.innerType._zod.optout),D(t._zod,"pattern",()=>{let n=r.innerType._zod.pattern;return n?new RegExp(`^(${It(n.source)}|null)$`):void 0}),D(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(n,i)=>n.value===null?n:r.innerType._zod.run(n,i)}),_a=u("$ZodDefault",(t,r)=>{T.init(t,r),t._zod.optin="optional",D(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(n,i)=>{if(n.value===void 0)return n.value=r.defaultValue,n;let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>Jc(o,r)):Jc(e,r)}});ya=u("$ZodPrefault",(t,r)=>{T.init(t,r),t._zod.optin="optional",D(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(n,i)=>(n.value===void 0&&(n.value=r.defaultValue),r.innerType._zod.run(n,i))}),$a=u("$ZodNonOptional",(t,r)=>{T.init(t,r),D(t._zod,"values",()=>{let n=r.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>Bc(o,t)):Bc(e,t)}});xa=u("$ZodSuccess",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>(n.value=o.issues.length===0,n)):(n.value=e.issues.length===0,n)}}),za=u("$ZodCatch",(t,r)=>{T.init(t,r),t._zod.optin="optional",D(t._zod,"optout",()=>r.innerType._zod.optout),D(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>(n.value=o.value,o.issues.length&&(n.value=r.catchValue({...n,error:{issues:o.issues.map(a=>ae(a,i,B()))},input:n.value}),n.issues=[]),n)):(n.value=e.value,e.issues.length&&(n.value=r.catchValue({...n,error:{issues:e.issues.map(o=>ae(o,i,B()))},input:n.value}),n.issues=[]),n)}}),ka=u("$ZodNaN",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:t,expected:"nan",code:"invalid_type"}),n)}),Ct=u("$ZodPipe",(t,r)=>{T.init(t,r),D(t._zod,"values",()=>r.in._zod.values),D(t._zod,"optin",()=>r.in._zod.optin),D(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(n,i)=>{let e=r.in._zod.run(n,i);return e instanceof Promise?e.then(o=>Wc(o,r,i)):Wc(e,r,i)}});Sa=u("$ZodReadonly",(t,r)=>{T.init(t,r),D(t._zod,"propValues",()=>r.innerType._zod.propValues),D(t._zod,"values",()=>r.innerType._zod.values),D(t._zod,"optin",()=>r.innerType._zod.optin),D(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(Kc):Kc(e)}});wa=u("$ZodTemplateLiteral",(t,r)=>{T.init(t,r);let n=[];for(let i of r.parts)if(i instanceof T){if(!i._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);let e=i._zod.pattern instanceof RegExp?i._zod.pattern.source:i._zod.pattern;if(!e)throw new Error(`Invalid template literal part: ${i._zod.traits}`);let o=e.startsWith("^")?1:0,a=e.endsWith("$")?e.length-1:e.length;n.push(e.slice(o,a))}else if(i===null||So.has(typeof i))n.push(be(`${i}`));else throw new Error(`Invalid template literal part: ${i}`);t._zod.pattern=new RegExp(`^${n.join("")}$`),t._zod.parse=(i,e)=>typeof i.value!="string"?(i.issues.push({input:i.value,inst:t,expected:"template_literal",code:"invalid_type"}),i):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(i.value)||i.issues.push({input:i.value,inst:t,code:"invalid_format",format:"template_literal",pattern:t._zod.pattern.source}),i)}),Ia=u("$ZodPromise",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>Promise.resolve(n.value).then(e=>r.innerType._zod.run({value:e,issues:[]},i))}),ja=u("$ZodLazy",(t,r)=>{T.init(t,r),D(t._zod,"innerType",()=>r.getter()),D(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),D(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),D(t._zod,"optin",()=>t._zod.innerType._zod.optin),D(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(n,i)=>t._zod.innerType._zod.run(n,i)}),Pa=u("$ZodCustom",(t,r)=>{J.init(t,r),T.init(t,r),t._zod.parse=(n,i)=>n,t._zod.check=n=>{let i=n.value,e=r.fn(i);if(e instanceof Promise)return e.then(o=>Gc(o,n,i,t));Gc(e,n,i,t)}})});function eu(){return{localeError:Ud()}}var Ud,tu=k(()=>{P();Ud=()=>{let t={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};return e=>{switch(e.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${e.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${_(e.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${e.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${e.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${e.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${e.minimum.toString()} ${a.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${e.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${e.prefix}"`:o.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${o.suffix}"`:o.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${o.includes}"`:o.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${o.pattern}`:`${i[o.format]??e.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${e.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${e.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${e.keys.length>1?"\u0629":""}: ${f(e.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${e.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${e.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}}});function ru(){return{localeError:Ed()}}var Ed,nu=k(()=>{P();Ed=()=>{let t={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${e.expected}, daxil olan ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${_(e.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${e.origin??"d\u0259y\u0259r"} ${o}${e.maximum.toString()} ${a.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${e.origin??"d\u0259y\u0259r"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${e.origin} ${o}${e.minimum.toString()} ${a.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${o.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:o.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${o.suffix}" il\u0259 bitm\u0259lidir`:o.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${o.includes}" daxil olmal\u0131d\u0131r`:o.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${o.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${i[o.format]??e.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${e.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${e.keys.length>1?"lar":""}: ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${e.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}}});function ou(t,r,n,i){let e=Math.abs(t),o=e%10,a=e%100;return a>=11&&a<=19?i:o===1?r:o>=2&&o<=4?n:i}function iu(){return{localeError:Zd()}}var Zd,au=k(()=>{P();Zd=()=>{let t={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(e))return"\u043C\u0430\u0441\u0456\u045E";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};return e=>{switch(e.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${e.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${_(e.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);if(a){let c=Number(e.maximum),d=ou(c,a.unit.one,a.unit.few,a.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${a.verb} ${o}${e.maximum.toString()} ${d}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);if(a){let c=Number(e.minimum),d=ou(c,a.unit.one,a.unit.few,a.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${a.verb} ${o}${e.minimum.toString()} ${d}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${i[o.format]??e.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${e.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${e.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${e.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${e.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}}});function su(){return{localeError:Dd()}}var Dd,cu=k(()=>{P();Dd=()=>{let t={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${e.expected}, s'ha rebut ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Valor inv\xE0lid: s'esperava ${_(e.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${f(e.values," o ")}`;case"too_big":{let o=e.inclusive?"com a m\xE0xim":"menys de",a=r(e.origin);return a?`Massa gran: s'esperava que ${e.origin??"el valor"} contingu\xE9s ${o} ${e.maximum.toString()} ${a.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?"com a m\xEDnim":"m\xE9s de",a=r(e.origin);return a?`Massa petit: s'esperava que ${e.origin} contingu\xE9s ${o} ${e.minimum.toString()} ${a.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${o.prefix}"`:o.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${o.suffix}"`:o.format==="includes"?`Format inv\xE0lid: ha d'incloure "${o.includes}"`:o.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${o.pattern}`:`Format inv\xE0lid per a ${i[o.format]??e.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${e.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${e.origin}`;default:return"Entrada inv\xE0lida"}}}});function uu(){return{localeError:Rd()}}var Rd,lu=k(()=>{P();Rd=()=>{let t={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(e))return"pole";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${e.expected}, obdr\u017Eeno ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${_(e.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${e.origin??"hodnota"} mus\xED m\xEDt ${o}${e.maximum.toString()} ${a.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${e.origin??"hodnota"} mus\xED b\xFDt ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${e.origin??"hodnota"} mus\xED m\xEDt ${o}${e.minimum.toString()} ${a.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${e.origin??"hodnota"} mus\xED b\xFDt ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${o.prefix}"`:o.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${o.suffix}"`:o.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${o.includes}"`:o.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${o.pattern}`:`Neplatn\xFD form\xE1t ${i[o.format]??e.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${e.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${f(e.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${e.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${e.origin}`;default:return"Neplatn\xFD vstup"}}}});function mu(){return{localeError:Ad()}}var Ad,du=k(()=>{P();Ad=()=>{let t={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":{if(Array.isArray(e))return"Array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${e.expected}, erhalten ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ung\xFCltige Eingabe: erwartet ${_(e.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Zu gro\xDF: erwartet, dass ${e.origin??"Wert"} ${o}${e.maximum.toString()} ${a.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${e.origin??"Wert"} ${o}${e.maximum.toString()} ist`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Zu klein: erwartet, dass ${e.origin} ${o}${e.minimum.toString()} ${a.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${o}${e.minimum.toString()} ist`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ung\xFCltiger String: muss mit "${o.prefix}" beginnen`:o.format==="ends_with"?`Ung\xFCltiger String: muss mit "${o.suffix}" enden`:o.format==="includes"?`Ung\xFCltiger String: muss "${o.includes}" enthalten`:o.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${o.pattern} entsprechen`:`Ung\xFCltig: ${i[o.format]??e.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${f(e.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${e.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${e.origin}`;default:return"Ung\xFCltige Eingabe"}}}});function Ar(){return{localeError:Md()}}var Cd,Md,Ta=k(()=>{P();Cd=t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return r},Md=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function r(i){return t[i]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Invalid input: expected ${i.expected}, received ${Cd(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${_(i.values[0])}`:`Invalid option: expected one of ${f(i.values,"|")}`;case"too_big":{let e=i.inclusive?"<=":"<",o=r(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${e}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${e}${i.maximum.toString()}`}case"too_small":{let e=i.inclusive?">=":">",o=r(i.origin);return o?`Too small: expected ${i.origin} to have ${e}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${e}${i.minimum.toString()}`}case"invalid_format":{let e=i;return e.format==="starts_with"?`Invalid string: must start with "${e.prefix}"`:e.format==="ends_with"?`Invalid string: must end with "${e.suffix}"`:e.format==="includes"?`Invalid string: must include "${e.includes}"`:e.format==="regex"?`Invalid string: must match pattern ${e.pattern}`:`Invalid ${n[e.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${f(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}}});function pu(){return{localeError:qd()}}var Ld,qd,fu=k(()=>{P();Ld=t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"nombro";case"object":{if(Array.isArray(t))return"tabelo";if(t===null)return"senvalora";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return r},qd=()=>{let t={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function r(i){return t[i]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return i=>{switch(i.code){case"invalid_type":return`Nevalida enigo: atendi\u011Dis ${i.expected}, ricevi\u011Dis ${Ld(i.input)}`;case"invalid_value":return i.values.length===1?`Nevalida enigo: atendi\u011Dis ${_(i.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${f(i.values,"|")}`;case"too_big":{let e=i.inclusive?"<=":"<",o=r(i.origin);return o?`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${e}${i.maximum.toString()} ${o.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${e}${i.maximum.toString()}`}case"too_small":{let e=i.inclusive?">=":">",o=r(i.origin);return o?`Tro malgranda: atendi\u011Dis ke ${i.origin} havu ${e}${i.minimum.toString()} ${o.unit}`:`Tro malgranda: atendi\u011Dis ke ${i.origin} estu ${e}${i.minimum.toString()}`}case"invalid_format":{let e=i;return e.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${e.prefix}"`:e.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${e.suffix}"`:e.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${e.includes}"`:e.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${e.pattern}`:`Nevalida ${n[e.format]??i.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${i.divisor}`;case"unrecognized_keys":return`Nekonata${i.keys.length>1?"j":""} \u015Dlosilo${i.keys.length>1?"j":""}: ${f(i.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${i.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${i.origin}`;default:return"Nevalida enigo"}}}});function gu(){return{localeError:Vd()}}var Vd,hu=k(()=>{P();Vd=()=>{let t={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(e))return"arreglo";if(e===null)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}}return o},i={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${e.expected}, recibido ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Entrada inv\xE1lida: se esperaba ${_(e.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${o}${e.maximum.toString()} ${a.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Demasiado peque\xF1o: se esperaba que ${e.origin} tuviera ${o}${e.minimum.toString()} ${a.unit}`:`Demasiado peque\xF1o: se esperaba que ${e.origin} fuera ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${o.prefix}"`:o.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${o.suffix}"`:o.format==="includes"?`Cadena inv\xE1lida: debe incluir "${o.includes}"`:o.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${o.pattern}`:`Inv\xE1lido ${i[o.format]??e.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${e.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${e.origin}`;default:return"Entrada inv\xE1lida"}}}});function vu(){return{localeError:Fd()}}var Fd,bu=k(()=>{P();Fd=()=>{let t={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(e))return"\u0622\u0631\u0627\u06CC\u0647";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};return e=>{switch(e.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${e.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${n(e.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return e.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${_(e.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${f(e.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${e.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${e.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} ${a.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:o.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:o.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${o.includes}" \u0628\u0627\u0634\u062F`:o.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${o.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${i[o.format]??e.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${e.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${e.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${f(e.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${e.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${e.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}}});function _u(){return{localeError:Hd()}}var Hd,yu=k(()=>{P();Hd=()=>{let t={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${_(e.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Liian suuri: ${a.subject} t\xE4ytyy olla ${o}${e.maximum.toString()} ${a.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Liian pieni: ${a.subject} t\xE4ytyy olla ${o}${e.minimum.toString()} ${a.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${o.prefix}"`:o.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${o.suffix}"`:o.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${o.includes}"`:o.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${o.pattern}`:`Virheellinen ${i[o.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${f(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}}});function $u(){return{localeError:Jd()}}var Jd,xu=k(()=>{P();Jd=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":{if(Array.isArray(e))return"tableau";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return e=>{switch(e.code){case"invalid_type":return`Entr\xE9e invalide : ${e.expected} attendu, ${n(e.input)} re\xE7u`;case"invalid_value":return e.values.length===1?`Entr\xE9e invalide : ${_(e.values[0])} attendu`:`Option invalide : une valeur parmi ${f(e.values,"|")} attendue`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Trop grand : ${e.origin??"valeur"} doit ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${e.origin??"valeur"} doit \xEAtre ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Trop petit : ${e.origin} doit ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`Trop petit : ${e.origin} doit \xEAtre ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${o.pattern}`:`${i[o.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${e.divisor}`;case"unrecognized_keys":return`Cl\xE9${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${f(e.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${e.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`;default:return"Entr\xE9e invalide"}}}});function zu(){return{localeError:Bd()}}var Bd,ku=k(()=>{P();Bd=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return e=>{switch(e.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${e.expected}, re\xE7u ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Entr\xE9e invalide : attendu ${_(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"\u2264":"<",a=r(e.origin);return a?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${o}${e.maximum.toString()} ${a.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?"\u2265":">",a=r(e.origin);return a?`Trop petit : attendu que ${e.origin} ait ${o}${e.minimum.toString()} ${a.unit}`:`Trop petit : attendu que ${e.origin} soit ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${o.pattern}`:`${i[o.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${e.divisor}`;case"unrecognized_keys":return`Cl\xE9${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${f(e.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${e.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`;default:return"Entr\xE9e invalide"}}}});function Su(){return{localeError:Wd()}}var Wd,wu=k(()=>{P();Wd=()=>{let t={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"};return e=>{switch(e.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${e.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${_(e.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${e.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.maximum.toString()} ${a.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${e.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${e.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.minimum.toString()} ${a.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${e.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${o.prefix}"`:o.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${o.suffix}"`:o.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${o.includes}"`:o.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${o.pattern}`:`${i[o.format]??e.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${e.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${e.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${e.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${e.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${e.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}}});function Iu(){return{localeError:Kd()}}var Kd,ju=k(()=>{P();Kd=()=>{let t={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(e))return"t\xF6mb";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${e.expected}, a kapott \xE9rt\xE9k ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${_(e.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`T\xFAl nagy: ${e.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${o}${e.maximum.toString()} ${a.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${e.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${e.origin} m\xE9rete t\xFAl kicsi ${o}${e.minimum.toString()} ${a.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${e.origin} t\xFAl kicsi ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\xC9rv\xE9nytelen string: "${o.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:o.format==="ends_with"?`\xC9rv\xE9nytelen string: "${o.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:o.format==="includes"?`\xC9rv\xE9nytelen string: "${o.includes}" \xE9rt\xE9ket kell tartalmaznia`:o.format==="regex"?`\xC9rv\xE9nytelen string: ${o.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${i[o.format]??e.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${e.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${e.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${e.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}}});function Pu(){return{localeError:Gd()}}var Gd,Tu=k(()=>{P();Gd=()=>{let t={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Input tidak valid: diharapkan ${_(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${o}${e.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Terlalu kecil: diharapkan ${e.origin} memiliki ${o}${e.minimum.toString()} ${a.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`String tidak valid: harus dimulai dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak valid: harus berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak valid: harus menyertakan "${o.includes}"`:o.format==="regex"?`String tidak valid: harus sesuai pola ${o.pattern}`:`${i[o.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`;default:return"Input tidak valid"}}}});function Ou(){return{localeError:Qd()}}var Qd,Nu=k(()=>{P();Qd=()=>{let t={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":{if(Array.isArray(e))return"vettore";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Input non valido: atteso ${_(e.values[0])}`:`Opzione non valida: atteso uno tra ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Troppo grande: ${e.origin??"valore"} deve avere ${o}${e.maximum.toString()} ${a.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Troppo piccolo: ${e.origin} deve avere ${o}${e.minimum.toString()} ${a.unit}`:`Troppo piccolo: ${e.origin} deve essere ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Stringa non valida: deve iniziare con "${o.prefix}"`:o.format==="ends_with"?`Stringa non valida: deve terminare con "${o.suffix}"`:o.format==="includes"?`Stringa non valida: deve includere "${o.includes}"`:o.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${o.pattern}`:`Invalid ${i[o.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${f(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`;default:return"Input non valido"}}}});function Uu(){return{localeError:Yd()}}var Yd,Eu=k(()=>{P();Yd=()=>{let t={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(e))return"\u914D\u5217";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};return e=>{switch(e.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${e.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${n(e.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return e.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${_(e.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${f(e.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let o=e.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",a=r(e.origin);return a?`\u5927\u304D\u3059\u304E\u308B\u5024: ${e.origin??"\u5024"}\u306F${e.maximum.toString()}${a.unit??"\u8981\u7D20"}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${e.origin??"\u5024"}\u306F${e.maximum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let o=e.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",a=r(e.origin);return a?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${e.origin}\u306F${e.minimum.toString()}${a.unit}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${e.origin}\u306F${e.minimum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${o.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${i[o.format]??e.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${e.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${e.keys.length>1?"\u7FA4":""}: ${f(e.keys,"\u3001")}`;case"invalid_key":return`${e.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${e.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}}});function Zu(){return{localeError:Xd()}}var Xd,Du=k(()=>{P();Xd=()=>{let t={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)":"\u179B\u17C1\u1781";case"object":{if(Array.isArray(e))return"\u17A2\u17B6\u179A\u17C1 (Array)";if(e===null)return"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};return e=>{switch(e.code){case"invalid_type":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${_(e.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${e.maximum.toString()} ${a.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin} ${o} ${e.minimum.toString()} ${a.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin} ${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${o.prefix}"`:o.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${o.suffix}"`:o.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${o.includes}"`:o.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${o.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${e.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${f(e.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${e.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${e.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}}});function Ru(){return{localeError:ep()}}var ep,Au=k(()=>{P();ep=()=>{let t={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};return e=>{switch(e.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${e.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${n(e.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return e.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${_(e.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${f(e.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let o=e.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",a=o==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",c=r(e.origin),d=c?.unit??"\uC694\uC18C";return c?`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${e.maximum.toString()}${d} ${o}${a}`:`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${e.maximum.toString()} ${o}${a}`}case"too_small":{let o=e.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",a=o==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",c=r(e.origin),d=c?.unit??"\uC694\uC18C";return c?`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${e.minimum.toString()}${d} ${o}${a}`:`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${e.minimum.toString()} ${o}${a}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:o.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${o.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${i[o.format]??e.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${e.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${f(e.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${e.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${e.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}}});function Cu(){return{localeError:tp()}}var tp,Mu=k(()=>{P();tp=()=>{let t={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(e))return"\u043D\u0438\u0437\u0430";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};return e=>{switch(e.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Invalid input: expected ${_(e.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${o}${e.maximum.toString()} ${a.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin} \u0434\u0430 \u0438\u043C\u0430 ${o}${e.minimum.toString()} ${a.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${o.pattern}`:`Invalid ${i[o.format]??e.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${e.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${e.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}}});function Lu(){return{localeError:rp()}}var rp,qu=k(()=>{P();rp=()=>{let t={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Input tidak sah: dijangka ${_(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Terlalu besar: dijangka ${e.origin??"nilai"} ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Terlalu kecil: dijangka ${e.origin} ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`String tidak sah: mesti bermula dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak sah: mesti mengandungi "${o.includes}"`:o.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${o.pattern}`:`${i[o.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${f(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`;default:return"Input tidak sah"}}}});function Vu(){return{localeError:np()}}var np,Fu=k(()=>{P();np=()=>{let t={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ongeldige invoer: verwacht ${_(e.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Te lang: verwacht dat ${e.origin??"waarde"} ${o}${e.maximum.toString()} ${a.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${o}${e.maximum.toString()} is`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Te kort: verwacht dat ${e.origin} ${o}${e.minimum.toString()} ${a.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${o}${e.minimum.toString()} is`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ongeldige tekst: moet met "${o.prefix}" beginnen`:o.format==="ends_with"?`Ongeldige tekst: moet op "${o.suffix}" eindigen`:o.format==="includes"?`Ongeldige tekst: moet "${o.includes}" bevatten`:o.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${o.pattern}`:`Ongeldig: ${i[o.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`;default:return"Ongeldige invoer"}}}});function Hu(){return{localeError:op()}}var op,Ju=k(()=>{P();op=()=>{let t={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":{if(Array.isArray(e))return"liste";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ugyldig verdi: forventet ${_(e.values[0])}`:`Ugyldig valg: forventet en av ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`For stor(t): forventet ${e.origin??"value"} til \xE5 ha ${o}${e.maximum.toString()} ${a.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til \xE5 ha ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`For lite(n): forventet ${e.origin} til \xE5 ha ${o}${e.minimum.toString()} ${a.unit}`:`For lite(n): forventet ${e.origin} til \xE5 ha ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${o.pattern}`:`Ugyldig ${i[o.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${f(e.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${e.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`;default:return"Ugyldig input"}}}});function Bu(){return{localeError:ip()}}var ip,Wu=k(()=>{P();ip=()=>{let t={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":{if(Array.isArray(e))return"saf";if(e===null)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`F\xE2sit giren: umulan ${e.expected}, al\u0131nan ${n(e.input)}`;case"invalid_value":return e.values.length===1?`F\xE2sit giren: umulan ${_(e.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Fazla b\xFCy\xFCk: ${e.origin??"value"}, ${o}${e.maximum.toString()} ${a.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${e.origin??"value"}, ${o}${e.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Fazla k\xFC\xE7\xFCk: ${e.origin}, ${o}${e.minimum.toString()} ${a.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${e.origin}, ${o}${e.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let o=e;return o.format==="starts_with"?`F\xE2sit metin: "${o.prefix}" ile ba\u015Flamal\u0131.`:o.format==="ends_with"?`F\xE2sit metin: "${o.suffix}" ile bitmeli.`:o.format==="includes"?`F\xE2sit metin: "${o.includes}" ihtiv\xE2 etmeli.`:o.format==="regex"?`F\xE2sit metin: ${o.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${i[o.format]??e.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${e.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${e.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}}});function Ku(){return{localeError:ap()}}var ap,Gu=k(()=>{P();ap=()=>{let t={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(e))return"\u0627\u0631\u06D0";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};return e=>{switch(e.code){case"invalid_type":return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${e.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${n(e.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;case"invalid_value":return e.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${_(e.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${f(e.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${e.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${e.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} \u0648\u064A`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} ${a.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} \u0648\u064A`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:o.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:o.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${o.includes}" \u0648\u0644\u0631\u064A`:o.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${o.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${i[o.format]??e.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${e.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${e.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${e.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${e.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}}});function Qu(){return{localeError:sp()}}var sp,Yu=k(()=>{P();sp=()=>{let t={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":{if(Array.isArray(e))return"tablica";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};return e=>{switch(e.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${e.expected}, otrzymano ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${_(e.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${e.maximum.toString()} ${a.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${e.minimum.toString()} ${a.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${o.prefix}"`:o.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${o.suffix}"`:o.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${o.includes}"`:o.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${o.pattern}`:`Nieprawid\u0142ow(y/a/e) ${i[o.format]??e.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${e.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${e.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}}});function Xu(){return{localeError:cp()}}var cp,el=k(()=>{P();cp=()=>{let t={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(e))return"array";if(e===null)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${e.expected}, recebido ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Entrada inv\xE1lida: esperado ${_(e.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${o}${e.maximum.toString()} ${a.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Muito pequeno: esperado que ${e.origin} tivesse ${o}${e.minimum.toString()} ${a.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${o.prefix}"`:o.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${o.suffix}"`:o.format==="includes"?`Texto inv\xE1lido: deve incluir "${o.includes}"`:o.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${o.pattern}`:`${i[o.format]??e.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${e.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${e.origin}`;default:return"Campo inv\xE1lido"}}}});function tl(t,r,n,i){let e=Math.abs(t),o=e%10,a=e%100;return a>=11&&a<=19?i:o===1?r:o>=2&&o<=4?n:i}function rl(){return{localeError:up()}}var up,nl=k(()=>{P();up=()=>{let t={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(e))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};return e=>{switch(e.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${e.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${_(e.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);if(a){let c=Number(e.maximum),d=tl(c,a.unit.one,a.unit.few,a.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${e.maximum.toString()} ${d}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);if(a){let c=Number(e.minimum),d=tl(c,a.unit.one,a.unit.few,a.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${e.minimum.toString()} ${d}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin} \u0431\u0443\u0434\u0435\u0442 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${e.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${e.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${e.keys.length>1?"\u0438":""}: ${f(e.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${e.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${e.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}}});function ol(){return{localeError:lp()}}var lp,il=k(()=>{P();lp=()=>{let t={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(e))return"tabela";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${e.expected}, prejeto ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${_(e.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Preveliko: pri\u010Dakovano, da bo ${e.origin??"vrednost"} imelo ${o}${e.maximum.toString()} ${a.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${e.origin??"vrednost"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Premajhno: pri\u010Dakovano, da bo ${e.origin} imelo ${o}${e.minimum.toString()} ${a.unit}`:`Premajhno: pri\u010Dakovano, da bo ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${o.prefix}"`:o.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${o.suffix}"`:o.format==="includes"?`Neveljaven niz: mora vsebovati "${o.includes}"`:o.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${o.pattern}`:`Neveljaven ${i[o.format]??e.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${f(e.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${e.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`;default:return"Neveljaven vnos"}}}});function al(){return{localeError:mp()}}var mp,sl=k(()=>{P();mp=()=>{let t={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":{if(Array.isArray(e))return"lista";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: f\xF6rv\xE4ntat ${e.expected}, fick ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${_(e.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`F\xF6r stor(t): f\xF6rv\xE4ntade ${e.origin??"v\xE4rdet"} att ha ${o}${e.maximum.toString()} ${a.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${e.origin??"v\xE4rdet"} att ha ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`F\xF6r lite(t): f\xF6rv\xE4ntade ${e.origin??"v\xE4rdet"} att ha ${o}${e.minimum.toString()} ${a.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${e.origin??"v\xE4rdet"} att ha ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${o.prefix}"`:o.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${o.suffix}"`:o.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${o.includes}"`:o.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${o.pattern}"`:`Ogiltig(t) ${i[o.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${f(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${e.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}}});function cl(){return{localeError:dp()}}var dp,ul=k(()=>{P();dp=()=>{let t={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(e))return"\u0B85\u0BA3\u0BBF";if(e===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${_(e.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${f(e.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${e.maximum.toString()} ${a.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${e.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin} ${o}${e.minimum.toString()} ${a.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin} ${o}${e.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${o.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${e.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${e.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${e.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}}});function ll(){return{localeError:pp()}}var pp,ml=k(()=>{P();pp=()=>{let t={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(e))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(e===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};return e=>{switch(e.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${e.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${_(e.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",a=r(e.origin);return a?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.maximum.toString()} ${a.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",a=r(e.origin);return a?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.minimum.toString()} ${a.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${o.prefix}"`:o.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${o.suffix}"`:o.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${o.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:o.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${o.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${i[o.format]??e.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${e.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${f(e.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${e.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${e.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}}});function dl(){return{localeError:gp()}}var fp,gp,pl=k(()=>{P();fp=t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return r},gp=()=>{let t={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function r(i){return t[i]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};return i=>{switch(i.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${i.expected}, al\u0131nan ${fp(i.input)}`;case"invalid_value":return i.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${_(i.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${f(i.values,"|")}`;case"too_big":{let e=i.inclusive?"<=":"<",o=r(i.origin);return o?`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${e}${i.maximum.toString()} ${o.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${e}${i.maximum.toString()}`}case"too_small":{let e=i.inclusive?">=":">",o=r(i.origin);return o?`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${e}${i.minimum.toString()} ${o.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${e}${i.minimum.toString()}`}case"invalid_format":{let e=i;return e.format==="starts_with"?`Ge\xE7ersiz metin: "${e.prefix}" ile ba\u015Flamal\u0131`:e.format==="ends_with"?`Ge\xE7ersiz metin: "${e.suffix}" ile bitmeli`:e.format==="includes"?`Ge\xE7ersiz metin: "${e.includes}" i\xE7ermeli`:e.format==="regex"?`Ge\xE7ersiz metin: ${e.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[e.format]??i.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${i.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${i.keys.length>1?"lar":""}: ${f(i.keys,", ")}`;case"invalid_key":return`${i.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${i.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}}});function fl(){return{localeError:hp()}}var hp,gl=k(()=>{P();hp=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(e))return"\u043C\u0430\u0441\u0438\u0432";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};return e=>{switch(e.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${e.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${_(e.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin} ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin} \u0431\u0443\u0434\u0435 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${e.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${e.keys.length>1?"\u0456":""}: ${f(e.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${e.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${e.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}}});function hl(){return{localeError:vp()}}var vp,vl=k(()=>{P();vp=()=>{let t={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(e))return"\u0622\u0631\u06D2";if(e===null)return"\u0646\u0644";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};return e=>{switch(e.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${e.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${n(e.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return e.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${_(e.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${f(e.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${e.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${o}${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${e.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${o}${e.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${e.origin} \u06A9\u06D2 ${o}${e.minimum.toString()} ${a.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${e.origin} \u06A9\u0627 ${o}${e.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${o.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${e.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${e.keys.length>1?"\u0632":""}: ${f(e.keys,"\u060C ")}`;case"invalid_key":return`${e.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${e.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}}});function bl(){return{localeError:bp()}}var bp,_l=k(()=>{P();bp=()=>{let t={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(e))return"m\u1EA3ng";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};return e=>{switch(e.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${e.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${_(e.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${e.origin??"gi\xE1 tr\u1ECB"} ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${e.origin??"gi\xE1 tr\u1ECB"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${e.origin} ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${o.prefix}"`:o.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${o.suffix}"`:o.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${o.includes}"`:o.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${o.pattern}`:`${i[o.format]??e.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${e.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${f(e.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${e.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${e.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}}});function yl(){return{localeError:_p()}}var _p,$l=k(()=>{P();_p=()=>{let t={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(e))return"\u6570\u7EC4";if(e===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};return e=>{switch(e.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${e.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${_(e.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${e.origin??"\u503C"} ${o}${e.maximum.toString()} ${a.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${e.origin??"\u503C"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${e.origin} ${o}${e.minimum.toString()} ${a.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.prefix}" \u5F00\u5934`:o.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.suffix}" \u7ED3\u5C3E`:o.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${o.pattern}`:`\u65E0\u6548${i[o.format]??e.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${e.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${e.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}}});function xl(){return{localeError:yp()}}var yp,zl=k(()=>{P();yp=()=>{let t={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};return e=>{switch(e.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${e.expected}\uFF0C\u4F46\u6536\u5230 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${_(e.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${e.origin??"\u503C"} \u61C9\u70BA ${o}${e.maximum.toString()} ${a.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${e.origin??"\u503C"} \u61C9\u70BA ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${e.origin} \u61C9\u70BA ${o}${e.minimum.toString()} ${a.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${e.origin} \u61C9\u70BA ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.prefix}" \u958B\u982D`:o.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.suffix}" \u7D50\u5C3E`:o.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${o.pattern}`:`\u7121\u6548\u7684 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${e.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${e.keys.length>1?"\u5011":""}\uFF1A${f(e.keys,"\u3001")}`;case"invalid_key":return`${e.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${e.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}}});var Ge={};$e(Ge,{ar:()=>eu,az:()=>ru,be:()=>iu,ca:()=>su,cs:()=>uu,de:()=>mu,en:()=>Ar,eo:()=>pu,es:()=>gu,fa:()=>vu,fi:()=>_u,fr:()=>$u,frCA:()=>zu,he:()=>Su,hu:()=>Iu,id:()=>Pu,it:()=>Ou,ja:()=>Uu,kh:()=>Zu,ko:()=>Ru,mk:()=>Cu,ms:()=>Lu,nl:()=>Vu,no:()=>Hu,ota:()=>Bu,pl:()=>Qu,ps:()=>Ku,pt:()=>Xu,ru:()=>rl,sl:()=>ol,sv:()=>al,ta:()=>cl,th:()=>ll,tr:()=>dl,ua:()=>fl,ur:()=>hl,vi:()=>bl,zhCN:()=>yl,zhTW:()=>xl});var Oa=k(()=>{tu();nu();au();cu();lu();du();Ta();fu();hu();bu();yu();xu();ku();wu();ju();Tu();Nu();Eu();Du();Au();Mu();qu();Fu();Ju();Wu();Gu();Yu();el();nl();il();sl();ul();ml();pl();gl();vl();_l();$l();zl()});function Lt(){return new Qe}var Cr,Mr,Qe,me,Na=k(()=>{Cr=Symbol("ZodOutput"),Mr=Symbol("ZodInput"),Qe=class{constructor(){this._map=new Map,this._idmap=new Map}add(r,...n){let i=n[0];if(this._map.set(r,i),i&&typeof i=="object"&&"id"in i){if(this._idmap.has(i.id))throw new Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,r)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(r){let n=this._map.get(r);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(r),this}get(r){let n=r._zod.parent;if(n){let i={...this.get(n)??{}};return delete i.id,{...i,...this._map.get(r)}}return this._map.get(r)}has(r){return this._map.has(r)}};me=Lt()});function Ua(t,r){return new t({type:"string",...v(r)})}function Ea(t,r){return new t({type:"string",coerce:!0,...v(r)})}function Lr(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...v(r)})}function qt(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...v(r)})}function qr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...v(r)})}function Vr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(r)})}function Fr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(r)})}function Hr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(r)})}function Jr(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...v(r)})}function Br(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...v(r)})}function Wr(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(r)})}function Kr(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...v(r)})}function Gr(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(r)})}function Qr(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...v(r)})}function Yr(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...v(r)})}function Xr(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(r)})}function en(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(r)})}function tn(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(r)})}function rn(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(r)})}function nn(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(r)})}function on(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...v(r)})}function an(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...v(r)})}function sn(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...v(r)})}function cn(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...v(r)})}function Za(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(r)})}function Da(t,r){return new t({type:"string",format:"date",check:"string_format",...v(r)})}function Ra(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...v(r)})}function Aa(t,r){return new t({type:"string",format:"duration",check:"string_format",...v(r)})}function Ca(t,r){return new t({type:"number",checks:[],...v(r)})}function Ma(t,r){return new t({type:"number",coerce:!0,checks:[],...v(r)})}function La(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...v(r)})}function qa(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...v(r)})}function Va(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...v(r)})}function Fa(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...v(r)})}function Ha(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...v(r)})}function Ja(t,r){return new t({type:"boolean",...v(r)})}function Ba(t,r){return new t({type:"boolean",coerce:!0,...v(r)})}function Wa(t,r){return new t({type:"bigint",...v(r)})}function Ka(t,r){return new t({type:"bigint",coerce:!0,...v(r)})}function Ga(t,r){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...v(r)})}function Qa(t,r){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...v(r)})}function Ya(t,r){return new t({type:"symbol",...v(r)})}function Xa(t,r){return new t({type:"undefined",...v(r)})}function es(t,r){return new t({type:"null",...v(r)})}function ts(t){return new t({type:"any"})}function Ye(t){return new t({type:"unknown"})}function rs(t,r){return new t({type:"never",...v(r)})}function ns(t,r){return new t({type:"void",...v(r)})}function os(t,r){return new t({type:"date",...v(r)})}function is(t,r){return new t({type:"date",coerce:!0,...v(r)})}function as(t,r){return new t({type:"nan",...v(r)})}function pe(t,r){return new Tr({check:"less_than",...v(r),value:t,inclusive:!1})}function se(t,r){return new Tr({check:"less_than",...v(r),value:t,inclusive:!0})}function fe(t,r){return new Or({check:"greater_than",...v(r),value:t,inclusive:!1})}function re(t,r){return new Or({check:"greater_than",...v(r),value:t,inclusive:!0})}function ln(t){return fe(0,t)}function mn(t){return pe(0,t)}function dn(t){return se(0,t)}function pn(t){return re(0,t)}function ke(t,r){return new ai({check:"multiple_of",...v(r),value:t})}function Ze(t,r){return new ui({check:"max_size",...v(r),maximum:t})}function Se(t,r){return new li({check:"min_size",...v(r),minimum:t})}function Xe(t,r){return new mi({check:"size_equals",...v(r),size:t})}function De(t,r){return new di({check:"max_length",...v(r),maximum:t})}function _e(t,r){return new pi({check:"min_length",...v(r),minimum:t})}function Re(t,r){return new fi({check:"length_equals",...v(r),length:t})}function et(t,r){return new gi({check:"string_format",format:"regex",...v(r),pattern:t})}function tt(t){return new hi({check:"string_format",format:"lowercase",...v(t)})}function rt(t){return new vi({check:"string_format",format:"uppercase",...v(t)})}function nt(t,r){return new bi({check:"string_format",format:"includes",...v(r),includes:t})}function ot(t,r){return new _i({check:"string_format",format:"starts_with",...v(r),prefix:t})}function it(t,r){return new yi({check:"string_format",format:"ends_with",...v(r),suffix:t})}function fn(t,r,n){return new $i({check:"property",property:t,schema:r,...v(n)})}function at(t,r){return new xi({check:"mime_type",mime:t,...v(r)})}function ge(t){return new zi({check:"overwrite",tx:t})}function st(t){return ge(r=>r.normalize(t))}function ct(){return ge(t=>t.trim())}function ut(){return ge(t=>t.toLowerCase())}function lt(){return ge(t=>t.toUpperCase())}function Vt(t,r,n){return new t({type:"array",element:r,...v(n)})}function $p(t,r,n){return new t({type:"union",options:r,...v(n)})}function xp(t,r,n,i){return new t({type:"union",options:n,discriminator:r,...v(i)})}function zp(t,r,n){return new t({type:"intersection",left:r,right:n})}function ss(t,r,n,i){let e=n instanceof T,o=e?i:n,a=e?n:null;return new t({type:"tuple",items:r,rest:a,...v(o)})}function kp(t,r,n,i){return new t({type:"record",keyType:r,valueType:n,...v(i)})}function Sp(t,r,n,i){return new t({type:"map",keyType:r,valueType:n,...v(i)})}function wp(t,r,n){return new t({type:"set",valueType:r,...v(n)})}function Ip(t,r,n){let i=Array.isArray(r)?Object.fromEntries(r.map(e=>[e,e])):r;return new t({type:"enum",entries:i,...v(n)})}function jp(t,r,n){return new t({type:"enum",entries:r,...v(n)})}function Pp(t,r,n){return new t({type:"literal",values:Array.isArray(r)?r:[r],...v(n)})}function cs(t,r){return new t({type:"file",...v(r)})}function Tp(t,r){return new t({type:"transform",transform:r})}function Op(t,r){return new t({type:"optional",innerType:r})}function Np(t,r){return new t({type:"nullable",innerType:r})}function Up(t,r,n){return new t({type:"default",innerType:r,get defaultValue(){return typeof n=="function"?n():n}})}function Ep(t,r,n){return new t({type:"nonoptional",innerType:r,...v(n)})}function Zp(t,r){return new t({type:"success",innerType:r})}function Dp(t,r,n){return new t({type:"catch",innerType:r,catchValue:typeof n=="function"?n:()=>n})}function Rp(t,r,n){return new t({type:"pipe",in:r,out:n})}function Ap(t,r){return new t({type:"readonly",innerType:r})}function Cp(t,r,n){return new t({type:"template_literal",parts:r,...v(n)})}function Mp(t,r){return new t({type:"lazy",getter:r})}function Lp(t,r){return new t({type:"promise",innerType:r})}function us(t,r,n){let i=v(n);return i.abort??(i.abort=!0),new t({type:"custom",check:"custom",fn:r,...i})}function ls(t,r,n){return new t({type:"custom",check:"custom",fn:r,...v(n)})}function ms(t,r){let n=v(r),i=n.truthy??["true","1","yes","on","y","enabled"],e=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(i=i.map(p=>typeof p=="string"?p.toLowerCase():p),e=e.map(p=>typeof p=="string"?p.toLowerCase():p));let o=new Set(i),a=new Set(e),c=t.Pipe??Ct,d=t.Boolean??Dt,h=t.String??Ue,g=t.Transform??At,l=new g({type:"transform",transform:(p,x)=>{let S=p;return n.case!=="sensitive"&&(S=S.toLowerCase()),o.has(S)?!0:a.has(S)?!1:(x.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...a],input:x.value,inst:l}),{})},error:n.error}),$=new c({type:"pipe",in:new h({type:"string",error:n.error}),out:l,error:n.error});return new c({type:"pipe",in:$,out:new d({type:"boolean",error:n.error}),error:n.error})}function ds(t,r,n,i={}){let e=v(i),o={...v(i),check:"string_format",type:"string",format:r,fn:typeof n=="function"?n:c=>n.test(c),...e};return n instanceof RegExp&&(o.pattern=n),new t(o)}var un,ps=k(()=>{Nr();Mt();P();un={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function hn(t){return new gn({type:"function",input:Array.isArray(t?.input)?ss(Ee,t?.input):t?.input??Vt(Rt,Ye(Ke)),output:t?.output??Ye(Ke)})}var gn,kl=k(()=>{ps();Ir();Mt();Mt();gn=class{constructor(r){this._def=r,this.def=r}implement(r){if(typeof r!="function")throw new Error("implement() must be called with a function");let n=((...i)=>{let e=this._def.input?Nt(this._def.input,i,void 0,{callee:n}):i;if(!Array.isArray(e))throw new Error("Invalid arguments schema: not an array or tuple schema.");let o=r(...e);return this._def.output?Nt(this._def.output,o,void 0,{callee:n}):o});return n}implementAsync(r){if(typeof r!="function")throw new Error("implement() must be called with a function");let n=(async(...i)=>{let e=this._def.input?await Ut(this._def.input,i,void 0,{callee:n}):i;if(!Array.isArray(e))throw new Error("Invalid arguments schema: not an array or tuple schema.");let o=await r(...e);return this._def.output?Ut(this._def.output,o,void 0,{callee:n}):o});return n}input(...r){let n=this.constructor;return Array.isArray(r[0])?new n({type:"function",input:new Ee({type:"tuple",items:r[0],rest:r[1]}),output:this._def.output}):new n({type:"function",input:r[0],output:this._def.output})}output(r){let n=this.constructor;return new n({type:"function",input:this._def.input,output:r})}}});function vn(t,r){if(t instanceof Qe){let i=new Ft(r),e={};for(let c of t._idmap.entries()){let[d,h]=c;i.process(h)}let o={},a={registry:t,uri:r?.uri,defs:e};for(let c of t._idmap.entries()){let[d,h]=c;o[d]=i.emit(h,{...r,external:a})}if(Object.keys(e).length>0){let c=i.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[c]:e}}return{schemas:o}}let n=new Ft(r);return n.process(t),n.emit(t,r)}function K(t,r){let n=r??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let e=t._zod.def;switch(e.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return K(e.element,n);case"object":{for(let o in e.shape)if(K(e.shape[o],n))return!0;return!1}case"union":{for(let o of e.options)if(K(o,n))return!0;return!1}case"intersection":return K(e.left,n)||K(e.right,n);case"tuple":{for(let o of e.items)if(K(o,n))return!0;return!!(e.rest&&K(e.rest,n))}case"record":return K(e.keyType,n)||K(e.valueType,n);case"map":return K(e.keyType,n)||K(e.valueType,n);case"set":return K(e.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return K(e.innerType,n);case"lazy":return K(e.getter(),n);case"default":return K(e.innerType,n);case"prefault":return K(e.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return K(e.in,n)||K(e.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${e.type}`)}var Ft,Sl=k(()=>{Na();P();Ft=class{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??me,this.target=r?.target??"draft-2020-12",this.unrepresentable=r?.unrepresentable??"throw",this.override=r?.override??(()=>{}),this.io=r?.io??"output",this.seen=new Map}process(r,n={path:[],schemaPath:[]}){var i;let e=r._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(r);if(a)return a.count++,n.schemaPath.includes(r)&&(a.cycle=n.path),a.schema;let c={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(r,c);let d=r._zod.toJSONSchema?.();if(d)c.schema=d;else{let l={...n,schemaPath:[...n.schemaPath,r],path:n.path},$=r._zod.parent;if($)c.ref=$,this.process($,l),this.seen.get($).isParent=!0;else{let b=c.schema;switch(e.type){case"string":{let p=b;p.type="string";let{minimum:x,maximum:S,format:R,patterns:w,contentEncoding:j}=r._zod.bag;if(typeof x=="number"&&(p.minLength=x),typeof S=="number"&&(p.maxLength=S),R&&(p.format=o[R]??R,p.format===""&&delete p.format),j&&(p.contentEncoding=j),w&&w.size>0){let U=[...w];U.length===1?p.pattern=U[0].source:U.length>1&&(c.schema.allOf=[...U.map(je=>({...this.target==="draft-7"?{type:"string"}:{},pattern:je.source}))])}break}case"number":{let p=b,{minimum:x,maximum:S,format:R,multipleOf:w,exclusiveMaximum:j,exclusiveMinimum:U}=r._zod.bag;typeof R=="string"&&R.includes("int")?p.type="integer":p.type="number",typeof U=="number"&&(p.exclusiveMinimum=U),typeof x=="number"&&(p.minimum=x,typeof U=="number"&&(U>=x?delete p.minimum:delete p.exclusiveMinimum)),typeof j=="number"&&(p.exclusiveMaximum=j),typeof S=="number"&&(p.maximum=S,typeof j=="number"&&(j<=S?delete p.maximum:delete p.exclusiveMaximum)),typeof w=="number"&&(p.multipleOf=w);break}case"boolean":{let p=b;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{b.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{b.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=b,{minimum:x,maximum:S}=r._zod.bag;typeof x=="number"&&(p.minItems=x),typeof S=="number"&&(p.maxItems=S),p.type="array",p.items=this.process(e.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=b;p.type="object",p.properties={};let x=e.shape;for(let w in x)p.properties[w]=this.process(x[w],{...l,path:[...l.path,"properties",w]});let S=new Set(Object.keys(x)),R=new Set([...S].filter(w=>{let j=e.shape[w]._zod;return this.io==="input"?j.optin===void 0:j.optout===void 0}));R.size>0&&(p.required=Array.from(R)),e.catchall?._zod.def.type==="never"?p.additionalProperties=!1:e.catchall?e.catchall&&(p.additionalProperties=this.process(e.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=b;p.anyOf=e.options.map((x,S)=>this.process(x,{...l,path:[...l.path,"anyOf",S]}));break}case"intersection":{let p=b,x=this.process(e.left,{...l,path:[...l.path,"allOf",0]}),S=this.process(e.right,{...l,path:[...l.path,"allOf",1]}),R=j=>"allOf"in j&&Object.keys(j).length===1,w=[...R(x)?x.allOf:[x],...R(S)?S.allOf:[S]];p.allOf=w;break}case"tuple":{let p=b;p.type="array";let x=e.items.map((w,j)=>this.process(w,{...l,path:[...l.path,"prefixItems",j]}));if(this.target==="draft-2020-12"?p.prefixItems=x:p.items=x,e.rest){let w=this.process(e.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=w:p.additionalItems=w}e.rest&&(p.items=this.process(e.rest,{...l,path:[...l.path,"items"]}));let{minimum:S,maximum:R}=r._zod.bag;typeof S=="number"&&(p.minItems=S),typeof R=="number"&&(p.maxItems=R);break}case"record":{let p=b;p.type="object",p.propertyNames=this.process(e.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(e.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=b,x=St(e.entries);x.every(S=>typeof S=="number")&&(p.type="number"),x.every(S=>typeof S=="string")&&(p.type="string"),p.enum=x;break}case"literal":{let p=b,x=[];for(let S of e.values)if(S===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof S=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");x.push(Number(S))}else x.push(S);if(x.length!==0)if(x.length===1){let S=x[0];p.type=S===null?"null":typeof S,p.const=S}else x.every(S=>typeof S=="number")&&(p.type="number"),x.every(S=>typeof S=="string")&&(p.type="string"),x.every(S=>typeof S=="boolean")&&(p.type="string"),x.every(S=>S===null)&&(p.type="null"),p.enum=x;break}case"file":{let p=b,x={type:"string",format:"binary",contentEncoding:"binary"},{minimum:S,maximum:R,mime:w}=r._zod.bag;S!==void 0&&(x.minLength=S),R!==void 0&&(x.maxLength=R),w?w.length===1?(x.contentMediaType=w[0],Object.assign(p,x)):p.anyOf=w.map(j=>({...x,contentMediaType:j})):Object.assign(p,x);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(e.innerType,l);b.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(e.innerType,l),c.ref=e.innerType;break}case"success":{let p=b;p.type="boolean";break}case"default":{this.process(e.innerType,l),c.ref=e.innerType,b.default=JSON.parse(JSON.stringify(e.defaultValue));break}case"prefault":{this.process(e.innerType,l),c.ref=e.innerType,this.io==="input"&&(b._prefault=JSON.parse(JSON.stringify(e.defaultValue)));break}case"catch":{this.process(e.innerType,l),c.ref=e.innerType;let p;try{p=e.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}b.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=b,x=r._zod.pattern;if(!x)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=x.source;break}case"pipe":{let p=this.io==="input"?e.in._zod.def.type==="transform"?e.out:e.in:e.out;this.process(p,l),c.ref=p;break}case"readonly":{this.process(e.innerType,l),c.ref=e.innerType,b.readOnly=!0;break}case"promise":{this.process(e.innerType,l),c.ref=e.innerType;break}case"optional":{this.process(e.innerType,l),c.ref=e.innerType;break}case"lazy":{let p=r._zod.innerType;this.process(p,l),c.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let h=this.metadataRegistry.get(r);return h&&Object.assign(c.schema,h),this.io==="input"&&K(r)&&(delete c.schema.examples,delete c.schema.default),this.io==="input"&&c.schema._prefault&&((i=c.schema).default??(i.default=c.schema._prefault)),delete c.schema._prefault,this.seen.get(r).schema}emit(r,n){let i={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},e=this.seen.get(r);if(!e)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=g=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(i.external){let x=i.external.registry.get(g[0])?.id,S=i.external.uri??(w=>w);if(x)return{ref:S(x)};let R=g[1].defId??g[1].schema.id??`schema${this.counter++}`;return g[1].defId=R,{defId:R,ref:`${S("__shared")}#/${l}/${R}`}}if(g[1]===e)return{ref:"#"};let b=`#/${l}/`,p=g[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:b+p}},a=g=>{if(g[1].schema.$ref)return;let l=g[1],{ref:$,defId:b}=o(g);l.def={...l.schema},b&&(l.defId=b);let p=l.schema;for(let x in p)delete p[x];p.$ref=$};if(i.cycles==="throw")for(let g of this.seen.entries()){let l=g[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>+ })));`),$.write(`newResult[${Te(w)}] = ${j}.value`)}$.write("payload.value = newResult;"),$.write("return payload;");let R=$.compile();return(w,j)=>R(l,w,j)},e,o=qe,a=!zt.jitless,d=a&&So.value,h=r.catchall,g;t._zod.parse=(l,$)=>{g??(g=n.value);let b=l.value;if(!o(b))return l.issues.push({expected:"object",code:"invalid_type",input:b,inst:t}),l;let p=[];if(a&&d&&$?.async===!1&&$.jitless!==!0)e||(e=i(r.shape)),l=e(l,$);else{l.value={};let j=g.shape;for(let U of g.keys){let je=j[U],vr=je._zod.run({value:b[U],issues:[]},$),Oc=je._zod.optin==="optional"&&je._zod.optout==="optional";vr instanceof Promise?p.push(vr.then(Nc=>Oc?Vc(Nc,l,U,b):Ur(Nc,l,U))):Oc?Vc(vr,l,U,b):Ur(vr,l,U)}}if(!h)return p.length?Promise.all(p).then(()=>l):l;let x=[],S=g.keySet,R=h._zod,w=R.def.type;for(let j of Object.keys(b)){if(S.has(j))continue;if(w==="never"){x.push(j);continue}let U=R.run({value:b[j],issues:[]},$);U instanceof Promise?p.push(U.then(je=>Ur(je,l,j))):Ur(U,l,j)}return x.length&&l.issues.push({code:"unrecognized_keys",keys:x,input:b,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Rr=u("$ZodUnion",(t,r)=>{T.init(t,r),D(t._zod,"optin",()=>r.options.some(n=>n._zod.optin==="optional")?"optional":void 0),D(t._zod,"optout",()=>r.options.some(n=>n._zod.optout==="optional")?"optional":void 0),D(t._zod,"values",()=>{if(r.options.every(n=>n._zod.values))return new Set(r.options.flatMap(n=>Array.from(n._zod.values)))}),D(t._zod,"pattern",()=>{if(r.options.every(n=>n._zod.pattern)){let n=r.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>It(i.source)).join("|")})$`)}}),t._zod.parse=(n,i)=>{let e=!1,o=[];for(let a of r.options){let c=a._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)o.push(c),e=!0;else{if(c.issues.length===0)return c;o.push(c)}}return e?Promise.all(o).then(a=>Fc(a,n,t,i)):Fc(o,n,t,i)}}),la=u("$ZodDiscriminatedUnion",(t,r)=>{Rr.init(t,r);let n=t._zod.parse;D(t._zod,"propValues",()=>{let e={};for(let o of r.options){let a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(o)}"`);for(let[c,d]of Object.entries(a)){e[c]||(e[c]=new Set);for(let h of d)e[c].add(h)}}return e});let i=wt(()=>{let e=r.options,o=new Map;for(let a of e){let c=a._zod.propValues[r.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(a)}"`);for(let d of c){if(o.has(d))throw new Error(`Duplicate discriminator value "${String(d)}"`);o.set(d,a)}}return o});t._zod.parse=(e,o)=>{let a=e.value;if(!qe(a))return e.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),e;let c=i.value.get(a?.[r.discriminator]);return c?c._zod.run(e,o):r.unionFallback?n(e,o):(e.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[r.discriminator],inst:t}),e)}}),ma=u("$ZodIntersection",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value,o=r.left._zod.run({value:e,issues:[]},i),a=r.right._zod.run({value:e,issues:[]},i);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([d,h])=>Hc(n,d,h)):Hc(n,o,a)}});Ee=u("$ZodTuple",(t,r)=>{T.init(t,r);let n=r.items,i=n.length-[...n].reverse().findIndex(e=>e._zod.optin!=="optional");t._zod.parse=(e,o)=>{let a=e.value;if(!Array.isArray(a))return e.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),e;e.value=[];let c=[];if(!r.rest){let h=a.length>n.length,g=a.length<i-1;if(h||g)return e.issues.push({input:a,inst:t,origin:"array",...h?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),e}let d=-1;for(let h of n){if(d++,d>=a.length&&d>=i)continue;let g=h._zod.run({value:a[d],issues:[]},o);g instanceof Promise?c.push(g.then(l=>Er(l,e,d))):Er(g,e,d)}if(r.rest){let h=a.slice(n.length);for(let g of h){d++;let l=r.rest._zod.run({value:g,issues:[]},o);l instanceof Promise?c.push(l.then($=>Er($,e,d))):Er(l,e,d)}}return c.length?Promise.all(c).then(()=>e):e}});da=u("$ZodRecord",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!Ve(e))return n.issues.push({expected:"record",code:"invalid_type",input:e,inst:t}),n;let o=[];if(r.keyType._zod.values){let a=r.keyType._zod.values;n.value={};for(let d of a)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){let h=r.valueType._zod.run({value:e[d],issues:[]},i);h instanceof Promise?o.push(h.then(g=>{g.issues.length&&n.issues.push(...oe(d,g.issues)),n.value[d]=g.value})):(h.issues.length&&n.issues.push(...oe(d,h.issues)),n.value[d]=h.value)}let c;for(let d in e)a.has(d)||(c=c??[],c.push(d));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:e,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(e)){if(a==="__proto__")continue;let c=r.keyType._zod.run({value:a,issues:[]},i);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(h=>ae(h,i,B())),input:a,path:[a],inst:t}),n.value[c.value]=c.value;continue}let d=r.valueType._zod.run({value:e[a],issues:[]},i);d instanceof Promise?o.push(d.then(h=>{h.issues.length&&n.issues.push(...oe(a,h.issues)),n.value[c.value]=h.value})):(d.issues.length&&n.issues.push(...oe(a,d.issues)),n.value[c.value]=d.value)}}return o.length?Promise.all(o).then(()=>n):n}}),pa=u("$ZodMap",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!(e instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:e,inst:t}),n;let o=[];n.value=new Map;for(let[a,c]of e){let d=r.keyType._zod.run({value:a,issues:[]},i),h=r.valueType._zod.run({value:c,issues:[]},i);d instanceof Promise||h instanceof Promise?o.push(Promise.all([d,h]).then(([g,l])=>{Jc(g,l,n,a,e,t,i)})):Jc(d,h,n,a,e,t,i)}return o.length?Promise.all(o).then(()=>n):n}});fa=u("$ZodSet",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!(e instanceof Set))return n.issues.push({input:e,inst:t,expected:"set",code:"invalid_type"}),n;let o=[];n.value=new Set;for(let a of e){let c=r.valueType._zod.run({value:a,issues:[]},i);c instanceof Promise?o.push(c.then(d=>Bc(d,n))):Bc(c,n)}return o.length?Promise.all(o).then(()=>n):n}});ga=u("$ZodEnum",(t,r)=>{T.init(t,r);let n=St(r.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(i=>jt.has(typeof i)).map(i=>typeof i=="string"?be(i):i.toString()).join("|")})$`),t._zod.parse=(i,e)=>{let o=i.value;return t._zod.values.has(o)||i.issues.push({code:"invalid_value",values:n,input:o,inst:t}),i}}),ha=u("$ZodLiteral",(t,r)=>{T.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(n=>typeof n=="string"?be(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let e=n.value;return t._zod.values.has(e)||n.issues.push({code:"invalid_value",values:r.values,input:e,inst:t}),n}}),va=u("$ZodFile",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return e instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:e,inst:t}),n}}),At=u("$ZodTransform",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=r.transform(n.value,n);if(i.async)return(e instanceof Promise?e:Promise.resolve(e)).then(a=>(n.value=a,n));if(e instanceof Promise)throw new de;return n.value=e,n}}),ba=u("$ZodOptional",(t,r)=>{T.init(t,r),t._zod.optin="optional",t._zod.optout="optional",D(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),D(t._zod,"pattern",()=>{let n=r.innerType._zod.pattern;return n?new RegExp(`^(${It(n.source)})?$`):void 0}),t._zod.parse=(n,i)=>r.innerType._zod.optin==="optional"?r.innerType._zod.run(n,i):n.value===void 0?n:r.innerType._zod.run(n,i)}),_a=u("$ZodNullable",(t,r)=>{T.init(t,r),D(t._zod,"optin",()=>r.innerType._zod.optin),D(t._zod,"optout",()=>r.innerType._zod.optout),D(t._zod,"pattern",()=>{let n=r.innerType._zod.pattern;return n?new RegExp(`^(${It(n.source)}|null)$`):void 0}),D(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(n,i)=>n.value===null?n:r.innerType._zod.run(n,i)}),ya=u("$ZodDefault",(t,r)=>{T.init(t,r),t._zod.optin="optional",D(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(n,i)=>{if(n.value===void 0)return n.value=r.defaultValue,n;let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>Wc(o,r)):Wc(e,r)}});$a=u("$ZodPrefault",(t,r)=>{T.init(t,r),t._zod.optin="optional",D(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(n,i)=>(n.value===void 0&&(n.value=r.defaultValue),r.innerType._zod.run(n,i))}),xa=u("$ZodNonOptional",(t,r)=>{T.init(t,r),D(t._zod,"values",()=>{let n=r.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>Kc(o,t)):Kc(e,t)}});za=u("$ZodSuccess",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>(n.value=o.issues.length===0,n)):(n.value=e.issues.length===0,n)}}),ka=u("$ZodCatch",(t,r)=>{T.init(t,r),t._zod.optin="optional",D(t._zod,"optout",()=>r.innerType._zod.optout),D(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(o=>(n.value=o.value,o.issues.length&&(n.value=r.catchValue({...n,error:{issues:o.issues.map(a=>ae(a,i,B()))},input:n.value}),n.issues=[]),n)):(n.value=e.value,e.issues.length&&(n.value=r.catchValue({...n,error:{issues:e.issues.map(o=>ae(o,i,B()))},input:n.value}),n.issues=[]),n)}}),Sa=u("$ZodNaN",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:t,expected:"nan",code:"invalid_type"}),n)}),Ct=u("$ZodPipe",(t,r)=>{T.init(t,r),D(t._zod,"values",()=>r.in._zod.values),D(t._zod,"optin",()=>r.in._zod.optin),D(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(n,i)=>{let e=r.in._zod.run(n,i);return e instanceof Promise?e.then(o=>Gc(o,r,i)):Gc(e,r,i)}});wa=u("$ZodReadonly",(t,r)=>{T.init(t,r),D(t._zod,"propValues",()=>r.innerType._zod.propValues),D(t._zod,"values",()=>r.innerType._zod.values),D(t._zod,"optin",()=>r.innerType._zod.optin),D(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(n,i)=>{let e=r.innerType._zod.run(n,i);return e instanceof Promise?e.then(Qc):Qc(e)}});Ia=u("$ZodTemplateLiteral",(t,r)=>{T.init(t,r);let n=[];for(let i of r.parts)if(i instanceof T){if(!i._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);let e=i._zod.pattern instanceof RegExp?i._zod.pattern.source:i._zod.pattern;if(!e)throw new Error(`Invalid template literal part: ${i._zod.traits}`);let o=e.startsWith("^")?1:0,a=e.endsWith("$")?e.length-1:e.length;n.push(e.slice(o,a))}else if(i===null||wo.has(typeof i))n.push(be(`${i}`));else throw new Error(`Invalid template literal part: ${i}`);t._zod.pattern=new RegExp(`^${n.join("")}$`),t._zod.parse=(i,e)=>typeof i.value!="string"?(i.issues.push({input:i.value,inst:t,expected:"template_literal",code:"invalid_type"}),i):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(i.value)||i.issues.push({input:i.value,inst:t,code:"invalid_format",format:"template_literal",pattern:t._zod.pattern.source}),i)}),ja=u("$ZodPromise",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>Promise.resolve(n.value).then(e=>r.innerType._zod.run({value:e,issues:[]},i))}),Pa=u("$ZodLazy",(t,r)=>{T.init(t,r),D(t._zod,"innerType",()=>r.getter()),D(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),D(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),D(t._zod,"optin",()=>t._zod.innerType._zod.optin),D(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(n,i)=>t._zod.innerType._zod.run(n,i)}),Ta=u("$ZodCustom",(t,r)=>{J.init(t,r),T.init(t,r),t._zod.parse=(n,i)=>n,t._zod.check=n=>{let i=n.value,e=r.fn(i);if(e instanceof Promise)return e.then(o=>Yc(o,n,i,t));Yc(e,n,i,t)}})});function ru(){return{localeError:Ud()}}var Ud,nu=k(()=>{P();Ud=()=>{let t={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};return e=>{switch(e.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${e.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${_(e.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${e.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${e.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${e.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${e.minimum.toString()} ${a.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${e.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${e.prefix}"`:o.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${o.suffix}"`:o.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${o.includes}"`:o.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${o.pattern}`:`${i[o.format]??e.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${e.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${e.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${e.keys.length>1?"\u0629":""}: ${f(e.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${e.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${e.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}}});function ou(){return{localeError:Ed()}}var Ed,iu=k(()=>{P();Ed=()=>{let t={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${e.expected}, daxil olan ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${_(e.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${e.origin??"d\u0259y\u0259r"} ${o}${e.maximum.toString()} ${a.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${e.origin??"d\u0259y\u0259r"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${e.origin} ${o}${e.minimum.toString()} ${a.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${o.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:o.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${o.suffix}" il\u0259 bitm\u0259lidir`:o.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${o.includes}" daxil olmal\u0131d\u0131r`:o.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${o.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${i[o.format]??e.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${e.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${e.keys.length>1?"lar":""}: ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${e.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}}});function au(t,r,n,i){let e=Math.abs(t),o=e%10,a=e%100;return a>=11&&a<=19?i:o===1?r:o>=2&&o<=4?n:i}function su(){return{localeError:Zd()}}var Zd,cu=k(()=>{P();Zd=()=>{let t={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(e))return"\u043C\u0430\u0441\u0456\u045E";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};return e=>{switch(e.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${e.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${_(e.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);if(a){let c=Number(e.maximum),d=au(c,a.unit.one,a.unit.few,a.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${a.verb} ${o}${e.maximum.toString()} ${d}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);if(a){let c=Number(e.minimum),d=au(c,a.unit.one,a.unit.few,a.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${a.verb} ${o}${e.minimum.toString()} ${d}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${e.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${i[o.format]??e.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${e.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${e.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${e.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${e.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}}});function uu(){return{localeError:Dd()}}var Dd,lu=k(()=>{P();Dd=()=>{let t={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${e.expected}, s'ha rebut ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Valor inv\xE0lid: s'esperava ${_(e.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${f(e.values," o ")}`;case"too_big":{let o=e.inclusive?"com a m\xE0xim":"menys de",a=r(e.origin);return a?`Massa gran: s'esperava que ${e.origin??"el valor"} contingu\xE9s ${o} ${e.maximum.toString()} ${a.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?"com a m\xEDnim":"m\xE9s de",a=r(e.origin);return a?`Massa petit: s'esperava que ${e.origin} contingu\xE9s ${o} ${e.minimum.toString()} ${a.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${o.prefix}"`:o.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${o.suffix}"`:o.format==="includes"?`Format inv\xE0lid: ha d'incloure "${o.includes}"`:o.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${o.pattern}`:`Format inv\xE0lid per a ${i[o.format]??e.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${e.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${e.origin}`;default:return"Entrada inv\xE0lida"}}}});function mu(){return{localeError:Rd()}}var Rd,du=k(()=>{P();Rd=()=>{let t={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(e))return"pole";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${e.expected}, obdr\u017Eeno ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${_(e.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${e.origin??"hodnota"} mus\xED m\xEDt ${o}${e.maximum.toString()} ${a.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${e.origin??"hodnota"} mus\xED b\xFDt ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${e.origin??"hodnota"} mus\xED m\xEDt ${o}${e.minimum.toString()} ${a.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${e.origin??"hodnota"} mus\xED b\xFDt ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${o.prefix}"`:o.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${o.suffix}"`:o.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${o.includes}"`:o.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${o.pattern}`:`Neplatn\xFD form\xE1t ${i[o.format]??e.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${e.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${f(e.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${e.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${e.origin}`;default:return"Neplatn\xFD vstup"}}}});function pu(){return{localeError:Ad()}}var Ad,fu=k(()=>{P();Ad=()=>{let t={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":{if(Array.isArray(e))return"Array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${e.expected}, erhalten ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ung\xFCltige Eingabe: erwartet ${_(e.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Zu gro\xDF: erwartet, dass ${e.origin??"Wert"} ${o}${e.maximum.toString()} ${a.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${e.origin??"Wert"} ${o}${e.maximum.toString()} ist`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Zu klein: erwartet, dass ${e.origin} ${o}${e.minimum.toString()} ${a.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${o}${e.minimum.toString()} ist`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ung\xFCltiger String: muss mit "${o.prefix}" beginnen`:o.format==="ends_with"?`Ung\xFCltiger String: muss mit "${o.suffix}" enden`:o.format==="includes"?`Ung\xFCltiger String: muss "${o.includes}" enthalten`:o.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${o.pattern} entsprechen`:`Ung\xFCltig: ${i[o.format]??e.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${f(e.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${e.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${e.origin}`;default:return"Ung\xFCltige Eingabe"}}}});function Ar(){return{localeError:Md()}}var Cd,Md,Oa=k(()=>{P();Cd=t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return r},Md=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function r(i){return t[i]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Invalid input: expected ${i.expected}, received ${Cd(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${_(i.values[0])}`:`Invalid option: expected one of ${f(i.values,"|")}`;case"too_big":{let e=i.inclusive?"<=":"<",o=r(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${e}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${e}${i.maximum.toString()}`}case"too_small":{let e=i.inclusive?">=":">",o=r(i.origin);return o?`Too small: expected ${i.origin} to have ${e}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${e}${i.minimum.toString()}`}case"invalid_format":{let e=i;return e.format==="starts_with"?`Invalid string: must start with "${e.prefix}"`:e.format==="ends_with"?`Invalid string: must end with "${e.suffix}"`:e.format==="includes"?`Invalid string: must include "${e.includes}"`:e.format==="regex"?`Invalid string: must match pattern ${e.pattern}`:`Invalid ${n[e.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${f(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}}});function gu(){return{localeError:qd()}}var Ld,qd,hu=k(()=>{P();Ld=t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"nombro";case"object":{if(Array.isArray(t))return"tabelo";if(t===null)return"senvalora";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return r},qd=()=>{let t={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function r(i){return t[i]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return i=>{switch(i.code){case"invalid_type":return`Nevalida enigo: atendi\u011Dis ${i.expected}, ricevi\u011Dis ${Ld(i.input)}`;case"invalid_value":return i.values.length===1?`Nevalida enigo: atendi\u011Dis ${_(i.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${f(i.values,"|")}`;case"too_big":{let e=i.inclusive?"<=":"<",o=r(i.origin);return o?`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${e}${i.maximum.toString()} ${o.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${e}${i.maximum.toString()}`}case"too_small":{let e=i.inclusive?">=":">",o=r(i.origin);return o?`Tro malgranda: atendi\u011Dis ke ${i.origin} havu ${e}${i.minimum.toString()} ${o.unit}`:`Tro malgranda: atendi\u011Dis ke ${i.origin} estu ${e}${i.minimum.toString()}`}case"invalid_format":{let e=i;return e.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${e.prefix}"`:e.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${e.suffix}"`:e.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${e.includes}"`:e.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${e.pattern}`:`Nevalida ${n[e.format]??i.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${i.divisor}`;case"unrecognized_keys":return`Nekonata${i.keys.length>1?"j":""} \u015Dlosilo${i.keys.length>1?"j":""}: ${f(i.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${i.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${i.origin}`;default:return"Nevalida enigo"}}}});function vu(){return{localeError:Vd()}}var Vd,bu=k(()=>{P();Vd=()=>{let t={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(e))return"arreglo";if(e===null)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}}return o},i={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${e.expected}, recibido ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Entrada inv\xE1lida: se esperaba ${_(e.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${o}${e.maximum.toString()} ${a.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Demasiado peque\xF1o: se esperaba que ${e.origin} tuviera ${o}${e.minimum.toString()} ${a.unit}`:`Demasiado peque\xF1o: se esperaba que ${e.origin} fuera ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${o.prefix}"`:o.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${o.suffix}"`:o.format==="includes"?`Cadena inv\xE1lida: debe incluir "${o.includes}"`:o.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${o.pattern}`:`Inv\xE1lido ${i[o.format]??e.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${e.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${e.origin}`;default:return"Entrada inv\xE1lida"}}}});function _u(){return{localeError:Fd()}}var Fd,yu=k(()=>{P();Fd=()=>{let t={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(e))return"\u0622\u0631\u0627\u06CC\u0647";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};return e=>{switch(e.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${e.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${n(e.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return e.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${_(e.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${f(e.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${e.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${e.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} ${a.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:o.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:o.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${o.includes}" \u0628\u0627\u0634\u062F`:o.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${o.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${i[o.format]??e.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${e.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${e.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${f(e.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${e.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${e.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}}});function $u(){return{localeError:Hd()}}var Hd,xu=k(()=>{P();Hd=()=>{let t={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${_(e.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Liian suuri: ${a.subject} t\xE4ytyy olla ${o}${e.maximum.toString()} ${a.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Liian pieni: ${a.subject} t\xE4ytyy olla ${o}${e.minimum.toString()} ${a.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${o.prefix}"`:o.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${o.suffix}"`:o.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${o.includes}"`:o.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${o.pattern}`:`Virheellinen ${i[o.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${f(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}}});function zu(){return{localeError:Jd()}}var Jd,ku=k(()=>{P();Jd=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":{if(Array.isArray(e))return"tableau";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return e=>{switch(e.code){case"invalid_type":return`Entr\xE9e invalide : ${e.expected} attendu, ${n(e.input)} re\xE7u`;case"invalid_value":return e.values.length===1?`Entr\xE9e invalide : ${_(e.values[0])} attendu`:`Option invalide : une valeur parmi ${f(e.values,"|")} attendue`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Trop grand : ${e.origin??"valeur"} doit ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${e.origin??"valeur"} doit \xEAtre ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Trop petit : ${e.origin} doit ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`Trop petit : ${e.origin} doit \xEAtre ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${o.pattern}`:`${i[o.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${e.divisor}`;case"unrecognized_keys":return`Cl\xE9${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${f(e.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${e.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`;default:return"Entr\xE9e invalide"}}}});function Su(){return{localeError:Bd()}}var Bd,wu=k(()=>{P();Bd=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return e=>{switch(e.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${e.expected}, re\xE7u ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Entr\xE9e invalide : attendu ${_(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"\u2264":"<",a=r(e.origin);return a?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${o}${e.maximum.toString()} ${a.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?"\u2265":">",a=r(e.origin);return a?`Trop petit : attendu que ${e.origin} ait ${o}${e.minimum.toString()} ${a.unit}`:`Trop petit : attendu que ${e.origin} soit ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${o.pattern}`:`${i[o.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${e.divisor}`;case"unrecognized_keys":return`Cl\xE9${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${f(e.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${e.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`;default:return"Entr\xE9e invalide"}}}});function Iu(){return{localeError:Wd()}}var Wd,ju=k(()=>{P();Wd=()=>{let t={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"};return e=>{switch(e.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${e.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${_(e.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${e.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.maximum.toString()} ${a.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${e.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${e.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.minimum.toString()} ${a.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${e.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${o.prefix}"`:o.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${o.suffix}"`:o.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${o.includes}"`:o.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${o.pattern}`:`${i[o.format]??e.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${e.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${e.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${e.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${e.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${e.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}}});function Pu(){return{localeError:Kd()}}var Kd,Tu=k(()=>{P();Kd=()=>{let t={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(e))return"t\xF6mb";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${e.expected}, a kapott \xE9rt\xE9k ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${_(e.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`T\xFAl nagy: ${e.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${o}${e.maximum.toString()} ${a.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${e.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${e.origin} m\xE9rete t\xFAl kicsi ${o}${e.minimum.toString()} ${a.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${e.origin} t\xFAl kicsi ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\xC9rv\xE9nytelen string: "${o.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:o.format==="ends_with"?`\xC9rv\xE9nytelen string: "${o.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:o.format==="includes"?`\xC9rv\xE9nytelen string: "${o.includes}" \xE9rt\xE9ket kell tartalmaznia`:o.format==="regex"?`\xC9rv\xE9nytelen string: ${o.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${i[o.format]??e.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${e.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${e.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${e.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}}});function Ou(){return{localeError:Gd()}}var Gd,Nu=k(()=>{P();Gd=()=>{let t={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Input tidak valid: diharapkan ${_(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${o}${e.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Terlalu kecil: diharapkan ${e.origin} memiliki ${o}${e.minimum.toString()} ${a.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`String tidak valid: harus dimulai dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak valid: harus berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak valid: harus menyertakan "${o.includes}"`:o.format==="regex"?`String tidak valid: harus sesuai pola ${o.pattern}`:`${i[o.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`;default:return"Input tidak valid"}}}});function Uu(){return{localeError:Qd()}}var Qd,Eu=k(()=>{P();Qd=()=>{let t={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":{if(Array.isArray(e))return"vettore";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Input non valido: atteso ${_(e.values[0])}`:`Opzione non valida: atteso uno tra ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Troppo grande: ${e.origin??"valore"} deve avere ${o}${e.maximum.toString()} ${a.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Troppo piccolo: ${e.origin} deve avere ${o}${e.minimum.toString()} ${a.unit}`:`Troppo piccolo: ${e.origin} deve essere ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Stringa non valida: deve iniziare con "${o.prefix}"`:o.format==="ends_with"?`Stringa non valida: deve terminare con "${o.suffix}"`:o.format==="includes"?`Stringa non valida: deve includere "${o.includes}"`:o.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${o.pattern}`:`Invalid ${i[o.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${f(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`;default:return"Input non valido"}}}});function Zu(){return{localeError:Yd()}}var Yd,Du=k(()=>{P();Yd=()=>{let t={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(e))return"\u914D\u5217";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};return e=>{switch(e.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${e.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${n(e.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return e.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${_(e.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${f(e.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let o=e.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",a=r(e.origin);return a?`\u5927\u304D\u3059\u304E\u308B\u5024: ${e.origin??"\u5024"}\u306F${e.maximum.toString()}${a.unit??"\u8981\u7D20"}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${e.origin??"\u5024"}\u306F${e.maximum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let o=e.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",a=r(e.origin);return a?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${e.origin}\u306F${e.minimum.toString()}${a.unit}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${e.origin}\u306F${e.minimum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${o.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${i[o.format]??e.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${e.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${e.keys.length>1?"\u7FA4":""}: ${f(e.keys,"\u3001")}`;case"invalid_key":return`${e.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${e.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}}});function Ru(){return{localeError:Xd()}}var Xd,Au=k(()=>{P();Xd=()=>{let t={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)":"\u179B\u17C1\u1781";case"object":{if(Array.isArray(e))return"\u17A2\u17B6\u179A\u17C1 (Array)";if(e===null)return"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};return e=>{switch(e.code){case"invalid_type":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${_(e.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${e.maximum.toString()} ${a.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin} ${o} ${e.minimum.toString()} ${a.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${e.origin} ${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${o.prefix}"`:o.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${o.suffix}"`:o.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${o.includes}"`:o.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${o.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${e.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${f(e.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${e.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${e.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}}});function Cu(){return{localeError:ep()}}var ep,Mu=k(()=>{P();ep=()=>{let t={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};return e=>{switch(e.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${e.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${n(e.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return e.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${_(e.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${f(e.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let o=e.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",a=o==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",c=r(e.origin),d=c?.unit??"\uC694\uC18C";return c?`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${e.maximum.toString()}${d} ${o}${a}`:`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${e.maximum.toString()} ${o}${a}`}case"too_small":{let o=e.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",a=o==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",c=r(e.origin),d=c?.unit??"\uC694\uC18C";return c?`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${e.minimum.toString()}${d} ${o}${a}`:`${e.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${e.minimum.toString()} ${o}${a}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:o.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${o.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${i[o.format]??e.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${e.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${f(e.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${e.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${e.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}}});function Lu(){return{localeError:tp()}}var tp,qu=k(()=>{P();tp=()=>{let t={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(e))return"\u043D\u0438\u0437\u0430";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};return e=>{switch(e.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Invalid input: expected ${_(e.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${o}${e.maximum.toString()} ${a.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin} \u0434\u0430 \u0438\u043C\u0430 ${o}${e.minimum.toString()} ${a.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${e.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${o.pattern}`:`Invalid ${i[o.format]??e.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${e.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${e.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}}});function Vu(){return{localeError:rp()}}var rp,Fu=k(()=>{P();rp=()=>{let t={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Input tidak sah: dijangka ${_(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Terlalu besar: dijangka ${e.origin??"nilai"} ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Terlalu kecil: dijangka ${e.origin} ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`String tidak sah: mesti bermula dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak sah: mesti mengandungi "${o.includes}"`:o.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${o.pattern}`:`${i[o.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${f(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`;default:return"Input tidak sah"}}}});function Hu(){return{localeError:np()}}var np,Ju=k(()=>{P();np=()=>{let t={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ongeldige invoer: verwacht ${_(e.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Te lang: verwacht dat ${e.origin??"waarde"} ${o}${e.maximum.toString()} ${a.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${o}${e.maximum.toString()} is`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Te kort: verwacht dat ${e.origin} ${o}${e.minimum.toString()} ${a.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${o}${e.minimum.toString()} is`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ongeldige tekst: moet met "${o.prefix}" beginnen`:o.format==="ends_with"?`Ongeldige tekst: moet op "${o.suffix}" eindigen`:o.format==="includes"?`Ongeldige tekst: moet "${o.includes}" bevatten`:o.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${o.pattern}`:`Ongeldig: ${i[o.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`;default:return"Ongeldige invoer"}}}});function Bu(){return{localeError:op()}}var op,Wu=k(()=>{P();op=()=>{let t={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":{if(Array.isArray(e))return"liste";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ugyldig verdi: forventet ${_(e.values[0])}`:`Ugyldig valg: forventet en av ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`For stor(t): forventet ${e.origin??"value"} til \xE5 ha ${o}${e.maximum.toString()} ${a.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til \xE5 ha ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`For lite(n): forventet ${e.origin} til \xE5 ha ${o}${e.minimum.toString()} ${a.unit}`:`For lite(n): forventet ${e.origin} til \xE5 ha ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${o.pattern}`:`Ugyldig ${i[o.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${f(e.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${e.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`;default:return"Ugyldig input"}}}});function Ku(){return{localeError:ip()}}var ip,Gu=k(()=>{P();ip=()=>{let t={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":{if(Array.isArray(e))return"saf";if(e===null)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`F\xE2sit giren: umulan ${e.expected}, al\u0131nan ${n(e.input)}`;case"invalid_value":return e.values.length===1?`F\xE2sit giren: umulan ${_(e.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Fazla b\xFCy\xFCk: ${e.origin??"value"}, ${o}${e.maximum.toString()} ${a.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${e.origin??"value"}, ${o}${e.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Fazla k\xFC\xE7\xFCk: ${e.origin}, ${o}${e.minimum.toString()} ${a.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${e.origin}, ${o}${e.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let o=e;return o.format==="starts_with"?`F\xE2sit metin: "${o.prefix}" ile ba\u015Flamal\u0131.`:o.format==="ends_with"?`F\xE2sit metin: "${o.suffix}" ile bitmeli.`:o.format==="includes"?`F\xE2sit metin: "${o.includes}" ihtiv\xE2 etmeli.`:o.format==="regex"?`F\xE2sit metin: ${o.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${i[o.format]??e.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${e.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${e.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}}});function Qu(){return{localeError:ap()}}var ap,Yu=k(()=>{P();ap=()=>{let t={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(e))return"\u0627\u0631\u06D0";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};return e=>{switch(e.code){case"invalid_type":return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${e.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${n(e.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;case"invalid_value":return e.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${_(e.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${f(e.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${e.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${e.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${e.maximum.toString()} \u0648\u064A`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} ${a.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${e.origin} \u0628\u0627\u06CC\u062F ${o}${e.minimum.toString()} \u0648\u064A`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:o.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:o.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${o.includes}" \u0648\u0644\u0631\u064A`:o.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${o.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${i[o.format]??e.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${e.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${e.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${f(e.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${e.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${e.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}}});function Xu(){return{localeError:sp()}}var sp,el=k(()=>{P();sp=()=>{let t={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":{if(Array.isArray(e))return"tablica";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};return e=>{switch(e.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${e.expected}, otrzymano ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${_(e.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${e.maximum.toString()} ${a.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${e.minimum.toString()} ${a.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${e.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${o.prefix}"`:o.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${o.suffix}"`:o.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${o.includes}"`:o.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${o.pattern}`:`Nieprawid\u0142ow(y/a/e) ${i[o.format]??e.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${e.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${e.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}}});function tl(){return{localeError:cp()}}var cp,rl=k(()=>{P();cp=()=>{let t={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(e))return"array";if(e===null)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${e.expected}, recebido ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Entrada inv\xE1lida: esperado ${_(e.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${o}${e.maximum.toString()} ${a.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Muito pequeno: esperado que ${e.origin} tivesse ${o}${e.minimum.toString()} ${a.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${o.prefix}"`:o.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${o.suffix}"`:o.format==="includes"?`Texto inv\xE1lido: deve incluir "${o.includes}"`:o.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${o.pattern}`:`${i[o.format]??e.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${f(e.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${e.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${e.origin}`;default:return"Campo inv\xE1lido"}}}});function nl(t,r,n,i){let e=Math.abs(t),o=e%10,a=e%100;return a>=11&&a<=19?i:o===1?r:o>=2&&o<=4?n:i}function ol(){return{localeError:up()}}var up,il=k(()=>{P();up=()=>{let t={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(e))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};return e=>{switch(e.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${e.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${_(e.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);if(a){let c=Number(e.maximum),d=nl(c,a.unit.one,a.unit.few,a.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${e.maximum.toString()} ${d}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);if(a){let c=Number(e.minimum),d=nl(c,a.unit.one,a.unit.few,a.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${e.minimum.toString()} ${d}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${e.origin} \u0431\u0443\u0434\u0435\u0442 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${e.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${e.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${e.keys.length>1?"\u0438":""}: ${f(e.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${e.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${e.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}}});function al(){return{localeError:lp()}}var lp,sl=k(()=>{P();lp=()=>{let t={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(e))return"tabela";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${e.expected}, prejeto ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${_(e.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Preveliko: pri\u010Dakovano, da bo ${e.origin??"vrednost"} imelo ${o}${e.maximum.toString()} ${a.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${e.origin??"vrednost"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Premajhno: pri\u010Dakovano, da bo ${e.origin} imelo ${o}${e.minimum.toString()} ${a.unit}`:`Premajhno: pri\u010Dakovano, da bo ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${o.prefix}"`:o.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${o.suffix}"`:o.format==="includes"?`Neveljaven niz: mora vsebovati "${o.includes}"`:o.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${o.pattern}`:`Neveljaven ${i[o.format]??e.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${f(e.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${e.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`;default:return"Neveljaven vnos"}}}});function cl(){return{localeError:mp()}}var mp,ul=k(()=>{P();mp=()=>{let t={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":{if(Array.isArray(e))return"lista";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: f\xF6rv\xE4ntat ${e.expected}, fick ${n(e.input)}`;case"invalid_value":return e.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${_(e.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`F\xF6r stor(t): f\xF6rv\xE4ntade ${e.origin??"v\xE4rdet"} att ha ${o}${e.maximum.toString()} ${a.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${e.origin??"v\xE4rdet"} att ha ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`F\xF6r lite(t): f\xF6rv\xE4ntade ${e.origin??"v\xE4rdet"} att ha ${o}${e.minimum.toString()} ${a.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${e.origin??"v\xE4rdet"} att ha ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${o.prefix}"`:o.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${o.suffix}"`:o.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${o.includes}"`:o.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${o.pattern}"`:`Ogiltig(t) ${i[o.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${f(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${e.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}}});function ll(){return{localeError:dp()}}var dp,ml=k(()=>{P();dp=()=>{let t={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(e))return"\u0B85\u0BA3\u0BBF";if(e===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${_(e.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${f(e.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${e.maximum.toString()} ${a.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${e.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin} ${o}${e.minimum.toString()} ${a.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${e.origin} ${o}${e.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${o.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${e.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${e.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${e.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}}});function dl(){return{localeError:pp()}}var pp,pl=k(()=>{P();pp=()=>{let t={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(e))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(e===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};return e=>{switch(e.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${e.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${_(e.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",a=r(e.origin);return a?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.maximum.toString()} ${a.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",a=r(e.origin);return a?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.minimum.toString()} ${a.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${e.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${o.prefix}"`:o.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${o.suffix}"`:o.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${o.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:o.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${o.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${i[o.format]??e.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${e.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${f(e.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${e.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${e.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}}});function fl(){return{localeError:gp()}}var fp,gp,gl=k(()=>{P();fp=t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return r},gp=()=>{let t={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function r(i){return t[i]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};return i=>{switch(i.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${i.expected}, al\u0131nan ${fp(i.input)}`;case"invalid_value":return i.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${_(i.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${f(i.values,"|")}`;case"too_big":{let e=i.inclusive?"<=":"<",o=r(i.origin);return o?`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${e}${i.maximum.toString()} ${o.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${e}${i.maximum.toString()}`}case"too_small":{let e=i.inclusive?">=":">",o=r(i.origin);return o?`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${e}${i.minimum.toString()} ${o.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${e}${i.minimum.toString()}`}case"invalid_format":{let e=i;return e.format==="starts_with"?`Ge\xE7ersiz metin: "${e.prefix}" ile ba\u015Flamal\u0131`:e.format==="ends_with"?`Ge\xE7ersiz metin: "${e.suffix}" ile bitmeli`:e.format==="includes"?`Ge\xE7ersiz metin: "${e.includes}" i\xE7ermeli`:e.format==="regex"?`Ge\xE7ersiz metin: ${e.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[e.format]??i.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${i.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${i.keys.length>1?"lar":""}: ${f(i.keys,", ")}`;case"invalid_key":return`${i.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${i.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}}});function hl(){return{localeError:hp()}}var hp,vl=k(()=>{P();hp=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(e))return"\u043C\u0430\u0441\u0438\u0432";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};return e=>{switch(e.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${e.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${_(e.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin} ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${e.origin} \u0431\u0443\u0434\u0435 ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${e.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${e.keys.length>1?"\u0456":""}: ${f(e.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${e.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${e.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}}});function bl(){return{localeError:vp()}}var vp,_l=k(()=>{P();vp=()=>{let t={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(e))return"\u0622\u0631\u06D2";if(e===null)return"\u0646\u0644";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};return e=>{switch(e.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${e.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${n(e.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return e.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${_(e.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${f(e.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${e.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${o}${e.maximum.toString()} ${a.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${e.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${o}${e.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${e.origin} \u06A9\u06D2 ${o}${e.minimum.toString()} ${a.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${e.origin} \u06A9\u0627 ${o}${e.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${o.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${e.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${e.keys.length>1?"\u0632":""}: ${f(e.keys,"\u060C ")}`;case"invalid_key":return`${e.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${e.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}}});function yl(){return{localeError:bp()}}var bp,$l=k(()=>{P();bp=()=>{let t={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(e))return"m\u1EA3ng";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};return e=>{switch(e.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${e.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${_(e.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${e.origin??"gi\xE1 tr\u1ECB"} ${a.verb} ${o}${e.maximum.toString()} ${a.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${e.origin??"gi\xE1 tr\u1ECB"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${e.origin} ${a.verb} ${o}${e.minimum.toString()} ${a.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${o.prefix}"`:o.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${o.suffix}"`:o.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${o.includes}"`:o.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${o.pattern}`:`${i[o.format]??e.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${e.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${f(e.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${e.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${e.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}}});function xl(){return{localeError:_p()}}var _p,zl=k(()=>{P();_p=()=>{let t={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(e))return"\u6570\u7EC4";if(e===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};return e=>{switch(e.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${e.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${_(e.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${e.origin??"\u503C"} ${o}${e.maximum.toString()} ${a.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${e.origin??"\u503C"} ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${e.origin} ${o}${e.minimum.toString()} ${a.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${e.origin} ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.prefix}" \u5F00\u5934`:o.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.suffix}" \u7ED3\u5C3E`:o.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${o.pattern}`:`\u65E0\u6548${i[o.format]??e.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${e.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${f(e.keys,", ")}`;case"invalid_key":return`${e.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${e.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}}});function kl(){return{localeError:yp()}}var yp,Sl=k(()=>{P();yp=()=>{let t={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function r(e){return t[e]??null}let n=e=>{let o=typeof e;switch(o){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return o},i={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};return e=>{switch(e.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${e.expected}\uFF0C\u4F46\u6536\u5230 ${n(e.input)}`;case"invalid_value":return e.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${_(e.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${f(e.values,"|")}`;case"too_big":{let o=e.inclusive?"<=":"<",a=r(e.origin);return a?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${e.origin??"\u503C"} \u61C9\u70BA ${o}${e.maximum.toString()} ${a.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${e.origin??"\u503C"} \u61C9\u70BA ${o}${e.maximum.toString()}`}case"too_small":{let o=e.inclusive?">=":">",a=r(e.origin);return a?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${e.origin} \u61C9\u70BA ${o}${e.minimum.toString()} ${a.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${e.origin} \u61C9\u70BA ${o}${e.minimum.toString()}`}case"invalid_format":{let o=e;return o.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.prefix}" \u958B\u982D`:o.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.suffix}" \u7D50\u5C3E`:o.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${o.pattern}`:`\u7121\u6548\u7684 ${i[o.format]??e.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${e.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${e.keys.length>1?"\u5011":""}\uFF1A${f(e.keys,"\u3001")}`;case"invalid_key":return`${e.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${e.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}}});var Ge={};$e(Ge,{ar:()=>ru,az:()=>ou,be:()=>su,ca:()=>uu,cs:()=>mu,de:()=>pu,en:()=>Ar,eo:()=>gu,es:()=>vu,fa:()=>_u,fi:()=>$u,fr:()=>zu,frCA:()=>Su,he:()=>Iu,hu:()=>Pu,id:()=>Ou,it:()=>Uu,ja:()=>Zu,kh:()=>Ru,ko:()=>Cu,mk:()=>Lu,ms:()=>Vu,nl:()=>Hu,no:()=>Bu,ota:()=>Ku,pl:()=>Xu,ps:()=>Qu,pt:()=>tl,ru:()=>ol,sl:()=>al,sv:()=>cl,ta:()=>ll,th:()=>dl,tr:()=>fl,ua:()=>hl,ur:()=>bl,vi:()=>yl,zhCN:()=>xl,zhTW:()=>kl});var Na=k(()=>{nu();iu();cu();lu();du();fu();Oa();hu();bu();yu();xu();ku();wu();ju();Tu();Nu();Eu();Du();Au();Mu();qu();Fu();Ju();Wu();Gu();Yu();el();rl();il();sl();ul();ml();pl();gl();vl();_l();$l();zl();Sl()});function Lt(){return new Qe}var Cr,Mr,Qe,me,Ua=k(()=>{Cr=Symbol("ZodOutput"),Mr=Symbol("ZodInput"),Qe=class{constructor(){this._map=new Map,this._idmap=new Map}add(r,...n){let i=n[0];if(this._map.set(r,i),i&&typeof i=="object"&&"id"in i){if(this._idmap.has(i.id))throw new Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,r)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(r){let n=this._map.get(r);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(r),this}get(r){let n=r._zod.parent;if(n){let i={...this.get(n)??{}};return delete i.id,{...i,...this._map.get(r)}}return this._map.get(r)}has(r){return this._map.has(r)}};me=Lt()});function Ea(t,r){return new t({type:"string",...v(r)})}function Za(t,r){return new t({type:"string",coerce:!0,...v(r)})}function Lr(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...v(r)})}function qt(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...v(r)})}function qr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...v(r)})}function Vr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(r)})}function Fr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(r)})}function Hr(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(r)})}function Jr(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...v(r)})}function Br(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...v(r)})}function Wr(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(r)})}function Kr(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...v(r)})}function Gr(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(r)})}function Qr(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...v(r)})}function Yr(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...v(r)})}function Xr(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(r)})}function en(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(r)})}function tn(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(r)})}function rn(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(r)})}function nn(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(r)})}function on(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...v(r)})}function an(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...v(r)})}function sn(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...v(r)})}function cn(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...v(r)})}function Da(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(r)})}function Ra(t,r){return new t({type:"string",format:"date",check:"string_format",...v(r)})}function Aa(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...v(r)})}function Ca(t,r){return new t({type:"string",format:"duration",check:"string_format",...v(r)})}function Ma(t,r){return new t({type:"number",checks:[],...v(r)})}function La(t,r){return new t({type:"number",coerce:!0,checks:[],...v(r)})}function qa(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...v(r)})}function Va(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...v(r)})}function Fa(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...v(r)})}function Ha(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...v(r)})}function Ja(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...v(r)})}function Ba(t,r){return new t({type:"boolean",...v(r)})}function Wa(t,r){return new t({type:"boolean",coerce:!0,...v(r)})}function Ka(t,r){return new t({type:"bigint",...v(r)})}function Ga(t,r){return new t({type:"bigint",coerce:!0,...v(r)})}function Qa(t,r){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...v(r)})}function Ya(t,r){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...v(r)})}function Xa(t,r){return new t({type:"symbol",...v(r)})}function es(t,r){return new t({type:"undefined",...v(r)})}function ts(t,r){return new t({type:"null",...v(r)})}function rs(t){return new t({type:"any"})}function Ye(t){return new t({type:"unknown"})}function ns(t,r){return new t({type:"never",...v(r)})}function os(t,r){return new t({type:"void",...v(r)})}function is(t,r){return new t({type:"date",...v(r)})}function as(t,r){return new t({type:"date",coerce:!0,...v(r)})}function ss(t,r){return new t({type:"nan",...v(r)})}function pe(t,r){return new Tr({check:"less_than",...v(r),value:t,inclusive:!1})}function se(t,r){return new Tr({check:"less_than",...v(r),value:t,inclusive:!0})}function fe(t,r){return new Or({check:"greater_than",...v(r),value:t,inclusive:!1})}function re(t,r){return new Or({check:"greater_than",...v(r),value:t,inclusive:!0})}function ln(t){return fe(0,t)}function mn(t){return pe(0,t)}function dn(t){return se(0,t)}function pn(t){return re(0,t)}function ke(t,r){return new si({check:"multiple_of",...v(r),value:t})}function Ze(t,r){return new li({check:"max_size",...v(r),maximum:t})}function Se(t,r){return new mi({check:"min_size",...v(r),minimum:t})}function Xe(t,r){return new di({check:"size_equals",...v(r),size:t})}function De(t,r){return new pi({check:"max_length",...v(r),maximum:t})}function _e(t,r){return new fi({check:"min_length",...v(r),minimum:t})}function Re(t,r){return new gi({check:"length_equals",...v(r),length:t})}function et(t,r){return new hi({check:"string_format",format:"regex",...v(r),pattern:t})}function tt(t){return new vi({check:"string_format",format:"lowercase",...v(t)})}function rt(t){return new bi({check:"string_format",format:"uppercase",...v(t)})}function nt(t,r){return new _i({check:"string_format",format:"includes",...v(r),includes:t})}function ot(t,r){return new yi({check:"string_format",format:"starts_with",...v(r),prefix:t})}function it(t,r){return new $i({check:"string_format",format:"ends_with",...v(r),suffix:t})}function fn(t,r,n){return new xi({check:"property",property:t,schema:r,...v(n)})}function at(t,r){return new zi({check:"mime_type",mime:t,...v(r)})}function ge(t){return new ki({check:"overwrite",tx:t})}function st(t){return ge(r=>r.normalize(t))}function ct(){return ge(t=>t.trim())}function ut(){return ge(t=>t.toLowerCase())}function lt(){return ge(t=>t.toUpperCase())}function Vt(t,r,n){return new t({type:"array",element:r,...v(n)})}function $p(t,r,n){return new t({type:"union",options:r,...v(n)})}function xp(t,r,n,i){return new t({type:"union",options:n,discriminator:r,...v(i)})}function zp(t,r,n){return new t({type:"intersection",left:r,right:n})}function cs(t,r,n,i){let e=n instanceof T,o=e?i:n,a=e?n:null;return new t({type:"tuple",items:r,rest:a,...v(o)})}function kp(t,r,n,i){return new t({type:"record",keyType:r,valueType:n,...v(i)})}function Sp(t,r,n,i){return new t({type:"map",keyType:r,valueType:n,...v(i)})}function wp(t,r,n){return new t({type:"set",valueType:r,...v(n)})}function Ip(t,r,n){let i=Array.isArray(r)?Object.fromEntries(r.map(e=>[e,e])):r;return new t({type:"enum",entries:i,...v(n)})}function jp(t,r,n){return new t({type:"enum",entries:r,...v(n)})}function Pp(t,r,n){return new t({type:"literal",values:Array.isArray(r)?r:[r],...v(n)})}function us(t,r){return new t({type:"file",...v(r)})}function Tp(t,r){return new t({type:"transform",transform:r})}function Op(t,r){return new t({type:"optional",innerType:r})}function Np(t,r){return new t({type:"nullable",innerType:r})}function Up(t,r,n){return new t({type:"default",innerType:r,get defaultValue(){return typeof n=="function"?n():n}})}function Ep(t,r,n){return new t({type:"nonoptional",innerType:r,...v(n)})}function Zp(t,r){return new t({type:"success",innerType:r})}function Dp(t,r,n){return new t({type:"catch",innerType:r,catchValue:typeof n=="function"?n:()=>n})}function Rp(t,r,n){return new t({type:"pipe",in:r,out:n})}function Ap(t,r){return new t({type:"readonly",innerType:r})}function Cp(t,r,n){return new t({type:"template_literal",parts:r,...v(n)})}function Mp(t,r){return new t({type:"lazy",getter:r})}function Lp(t,r){return new t({type:"promise",innerType:r})}function ls(t,r,n){let i=v(n);return i.abort??(i.abort=!0),new t({type:"custom",check:"custom",fn:r,...i})}function ms(t,r,n){return new t({type:"custom",check:"custom",fn:r,...v(n)})}function ds(t,r){let n=v(r),i=n.truthy??["true","1","yes","on","y","enabled"],e=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(i=i.map(p=>typeof p=="string"?p.toLowerCase():p),e=e.map(p=>typeof p=="string"?p.toLowerCase():p));let o=new Set(i),a=new Set(e),c=t.Pipe??Ct,d=t.Boolean??Dt,h=t.String??Ue,g=t.Transform??At,l=new g({type:"transform",transform:(p,x)=>{let S=p;return n.case!=="sensitive"&&(S=S.toLowerCase()),o.has(S)?!0:a.has(S)?!1:(x.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...a],input:x.value,inst:l}),{})},error:n.error}),$=new c({type:"pipe",in:new h({type:"string",error:n.error}),out:l,error:n.error});return new c({type:"pipe",in:$,out:new d({type:"boolean",error:n.error}),error:n.error})}function ps(t,r,n,i={}){let e=v(i),o={...v(i),check:"string_format",type:"string",format:r,fn:typeof n=="function"?n:c=>n.test(c),...e};return n instanceof RegExp&&(o.pattern=n),new t(o)}var un,fs=k(()=>{Nr();Mt();P();un={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function hn(t){return new gn({type:"function",input:Array.isArray(t?.input)?cs(Ee,t?.input):t?.input??Vt(Rt,Ye(Ke)),output:t?.output??Ye(Ke)})}var gn,wl=k(()=>{fs();Ir();Mt();Mt();gn=class{constructor(r){this._def=r,this.def=r}implement(r){if(typeof r!="function")throw new Error("implement() must be called with a function");let n=((...i)=>{let e=this._def.input?Nt(this._def.input,i,void 0,{callee:n}):i;if(!Array.isArray(e))throw new Error("Invalid arguments schema: not an array or tuple schema.");let o=r(...e);return this._def.output?Nt(this._def.output,o,void 0,{callee:n}):o});return n}implementAsync(r){if(typeof r!="function")throw new Error("implement() must be called with a function");let n=(async(...i)=>{let e=this._def.input?await Ut(this._def.input,i,void 0,{callee:n}):i;if(!Array.isArray(e))throw new Error("Invalid arguments schema: not an array or tuple schema.");let o=await r(...e);return this._def.output?Ut(this._def.output,o,void 0,{callee:n}):o});return n}input(...r){let n=this.constructor;return Array.isArray(r[0])?new n({type:"function",input:new Ee({type:"tuple",items:r[0],rest:r[1]}),output:this._def.output}):new n({type:"function",input:r[0],output:this._def.output})}output(r){let n=this.constructor;return new n({type:"function",input:this._def.input,output:r})}}});function vn(t,r){if(t instanceof Qe){let i=new Ft(r),e={};for(let c of t._idmap.entries()){let[d,h]=c;i.process(h)}let o={},a={registry:t,uri:r?.uri,defs:e};for(let c of t._idmap.entries()){let[d,h]=c;o[d]=i.emit(h,{...r,external:a})}if(Object.keys(e).length>0){let c=i.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[c]:e}}return{schemas:o}}let n=new Ft(r);return n.process(t),n.emit(t,r)}function K(t,r){let n=r??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let e=t._zod.def;switch(e.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return K(e.element,n);case"object":{for(let o in e.shape)if(K(e.shape[o],n))return!0;return!1}case"union":{for(let o of e.options)if(K(o,n))return!0;return!1}case"intersection":return K(e.left,n)||K(e.right,n);case"tuple":{for(let o of e.items)if(K(o,n))return!0;return!!(e.rest&&K(e.rest,n))}case"record":return K(e.keyType,n)||K(e.valueType,n);case"map":return K(e.keyType,n)||K(e.valueType,n);case"set":return K(e.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return K(e.innerType,n);case"lazy":return K(e.getter(),n);case"default":return K(e.innerType,n);case"prefault":return K(e.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return K(e.in,n)||K(e.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${e.type}`)}var Ft,Il=k(()=>{Ua();P();Ft=class{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??me,this.target=r?.target??"draft-2020-12",this.unrepresentable=r?.unrepresentable??"throw",this.override=r?.override??(()=>{}),this.io=r?.io??"output",this.seen=new Map}process(r,n={path:[],schemaPath:[]}){var i;let e=r._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(r);if(a)return a.count++,n.schemaPath.includes(r)&&(a.cycle=n.path),a.schema;let c={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(r,c);let d=r._zod.toJSONSchema?.();if(d)c.schema=d;else{let l={...n,schemaPath:[...n.schemaPath,r],path:n.path},$=r._zod.parent;if($)c.ref=$,this.process($,l),this.seen.get($).isParent=!0;else{let b=c.schema;switch(e.type){case"string":{let p=b;p.type="string";let{minimum:x,maximum:S,format:R,patterns:w,contentEncoding:j}=r._zod.bag;if(typeof x=="number"&&(p.minLength=x),typeof S=="number"&&(p.maxLength=S),R&&(p.format=o[R]??R,p.format===""&&delete p.format),j&&(p.contentEncoding=j),w&&w.size>0){let U=[...w];U.length===1?p.pattern=U[0].source:U.length>1&&(c.schema.allOf=[...U.map(je=>({...this.target==="draft-7"?{type:"string"}:{},pattern:je.source}))])}break}case"number":{let p=b,{minimum:x,maximum:S,format:R,multipleOf:w,exclusiveMaximum:j,exclusiveMinimum:U}=r._zod.bag;typeof R=="string"&&R.includes("int")?p.type="integer":p.type="number",typeof U=="number"&&(p.exclusiveMinimum=U),typeof x=="number"&&(p.minimum=x,typeof U=="number"&&(U>=x?delete p.minimum:delete p.exclusiveMinimum)),typeof j=="number"&&(p.exclusiveMaximum=j),typeof S=="number"&&(p.maximum=S,typeof j=="number"&&(j<=S?delete p.maximum:delete p.exclusiveMaximum)),typeof w=="number"&&(p.multipleOf=w);break}case"boolean":{let p=b;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{b.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{b.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=b,{minimum:x,maximum:S}=r._zod.bag;typeof x=="number"&&(p.minItems=x),typeof S=="number"&&(p.maxItems=S),p.type="array",p.items=this.process(e.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=b;p.type="object",p.properties={};let x=e.shape;for(let w in x)p.properties[w]=this.process(x[w],{...l,path:[...l.path,"properties",w]});let S=new Set(Object.keys(x)),R=new Set([...S].filter(w=>{let j=e.shape[w]._zod;return this.io==="input"?j.optin===void 0:j.optout===void 0}));R.size>0&&(p.required=Array.from(R)),e.catchall?._zod.def.type==="never"?p.additionalProperties=!1:e.catchall?e.catchall&&(p.additionalProperties=this.process(e.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=b;p.anyOf=e.options.map((x,S)=>this.process(x,{...l,path:[...l.path,"anyOf",S]}));break}case"intersection":{let p=b,x=this.process(e.left,{...l,path:[...l.path,"allOf",0]}),S=this.process(e.right,{...l,path:[...l.path,"allOf",1]}),R=j=>"allOf"in j&&Object.keys(j).length===1,w=[...R(x)?x.allOf:[x],...R(S)?S.allOf:[S]];p.allOf=w;break}case"tuple":{let p=b;p.type="array";let x=e.items.map((w,j)=>this.process(w,{...l,path:[...l.path,"prefixItems",j]}));if(this.target==="draft-2020-12"?p.prefixItems=x:p.items=x,e.rest){let w=this.process(e.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=w:p.additionalItems=w}e.rest&&(p.items=this.process(e.rest,{...l,path:[...l.path,"items"]}));let{minimum:S,maximum:R}=r._zod.bag;typeof S=="number"&&(p.minItems=S),typeof R=="number"&&(p.maxItems=R);break}case"record":{let p=b;p.type="object",p.propertyNames=this.process(e.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(e.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=b,x=St(e.entries);x.every(S=>typeof S=="number")&&(p.type="number"),x.every(S=>typeof S=="string")&&(p.type="string"),p.enum=x;break}case"literal":{let p=b,x=[];for(let S of e.values)if(S===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof S=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");x.push(Number(S))}else x.push(S);if(x.length!==0)if(x.length===1){let S=x[0];p.type=S===null?"null":typeof S,p.const=S}else x.every(S=>typeof S=="number")&&(p.type="number"),x.every(S=>typeof S=="string")&&(p.type="string"),x.every(S=>typeof S=="boolean")&&(p.type="string"),x.every(S=>S===null)&&(p.type="null"),p.enum=x;break}case"file":{let p=b,x={type:"string",format:"binary",contentEncoding:"binary"},{minimum:S,maximum:R,mime:w}=r._zod.bag;S!==void 0&&(x.minLength=S),R!==void 0&&(x.maxLength=R),w?w.length===1?(x.contentMediaType=w[0],Object.assign(p,x)):p.anyOf=w.map(j=>({...x,contentMediaType:j})):Object.assign(p,x);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(e.innerType,l);b.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(e.innerType,l),c.ref=e.innerType;break}case"success":{let p=b;p.type="boolean";break}case"default":{this.process(e.innerType,l),c.ref=e.innerType,b.default=JSON.parse(JSON.stringify(e.defaultValue));break}case"prefault":{this.process(e.innerType,l),c.ref=e.innerType,this.io==="input"&&(b._prefault=JSON.parse(JSON.stringify(e.defaultValue)));break}case"catch":{this.process(e.innerType,l),c.ref=e.innerType;let p;try{p=e.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}b.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=b,x=r._zod.pattern;if(!x)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=x.source;break}case"pipe":{let p=this.io==="input"?e.in._zod.def.type==="transform"?e.out:e.in:e.out;this.process(p,l),c.ref=p;break}case"readonly":{this.process(e.innerType,l),c.ref=e.innerType,b.readOnly=!0;break}case"promise":{this.process(e.innerType,l),c.ref=e.innerType;break}case"optional":{this.process(e.innerType,l),c.ref=e.innerType;break}case"lazy":{let p=r._zod.innerType;this.process(p,l),c.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let h=this.metadataRegistry.get(r);return h&&Object.assign(c.schema,h),this.io==="input"&&K(r)&&(delete c.schema.examples,delete c.schema.default),this.io==="input"&&c.schema._prefault&&((i=c.schema).default??(i.default=c.schema._prefault)),delete c.schema._prefault,this.seen.get(r).schema}emit(r,n){let i={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},e=this.seen.get(r);if(!e)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=g=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(i.external){let x=i.external.registry.get(g[0])?.id,S=i.external.uri??(w=>w);if(x)return{ref:S(x)};let R=g[1].defId??g[1].schema.id??`schema${this.counter++}`;return g[1].defId=R,{defId:R,ref:`${S("__shared")}#/${l}/${R}`}}if(g[1]===e)return{ref:"#"};let b=`#/${l}/`,p=g[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:b+p}},a=g=>{if(g[1].schema.$ref)return;let l=g[1],{ref:$,defId:b}=o(g);l.def={...l.schema},b&&(l.defId=b);let p=l.schema;for(let x in p)delete p[x];p.$ref=$};if(i.cycles==="throw")for(let g of this.seen.entries()){let l=g[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let g of this.seen.entries()){let l=g[1];if(r===g[0]){a(g);continue}if(i.external){let b=i.external.registry.get(g[0])?.id;if(r!==g[0]&&b){a(g);continue}}if(this.metadataRegistry.get(g[0])?.id){a(g);continue}if(l.cycle){a(g);continue}if(l.count>1&&i.reused==="ref"){a(g);continue}}let c=(g,l)=>{let $=this.seen.get(g),b=$.def??$.schema,p={...b};if($.ref===null)return;let x=$.ref;if($.ref=null,x){c(x,l);let S=this.seen.get(x).schema;S.$ref&&l.target==="draft-7"?(b.allOf=b.allOf??[],b.allOf.push(S)):(Object.assign(b,S),Object.assign(b,p))}$.isParent||this.override({zodSchema:g,jsonSchema:b,path:$.path??[]})};for(let g of[...this.seen.entries()].reverse())c(g[0],{target:this.target});let d={};if(this.target==="draft-2020-12"?d.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?d.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),i.external?.uri){let g=i.external.registry.get(r)?.id;if(!g)throw new Error("Schema is missing an `id` property");d.$id=i.external.uri(g)}Object.assign(d,e.def);let h=i.external?.defs??{};for(let g of this.seen.entries()){let l=g[1];l.def&&l.defId&&(h[l.defId]=l.def)}i.external||Object.keys(h).length>0&&(this.target==="draft-2020-12"?d.$defs=h:d.definitions=h);try{return JSON.parse(JSON.stringify(d))}catch{throw new Error("Error converting schema to JSON.")}}}});var wl={};var Il=k(()=>{});var he={};$e(he,{$ZodAny:()=>oa,$ZodArray:()=>Rt,$ZodAsyncError:()=>de,$ZodBase64:()=>Wi,$ZodBase64URL:()=>Ki,$ZodBigInt:()=>Dr,$ZodBigIntFormat:()=>ea,$ZodBoolean:()=>Dt,$ZodCIDRv4:()=>Hi,$ZodCIDRv6:()=>Ji,$ZodCUID:()=>Ei,$ZodCUID2:()=>Zi,$ZodCatch:()=>za,$ZodCheck:()=>J,$ZodCheckBigIntFormat:()=>ci,$ZodCheckEndsWith:()=>yi,$ZodCheckGreaterThan:()=>Or,$ZodCheckIncludes:()=>bi,$ZodCheckLengthEquals:()=>fi,$ZodCheckLessThan:()=>Tr,$ZodCheckLowerCase:()=>hi,$ZodCheckMaxLength:()=>di,$ZodCheckMaxSize:()=>ui,$ZodCheckMimeType:()=>xi,$ZodCheckMinLength:()=>pi,$ZodCheckMinSize:()=>li,$ZodCheckMultipleOf:()=>ai,$ZodCheckNumberFormat:()=>si,$ZodCheckOverwrite:()=>zi,$ZodCheckProperty:()=>$i,$ZodCheckRegex:()=>gi,$ZodCheckSizeEquals:()=>mi,$ZodCheckStartsWith:()=>_i,$ZodCheckStringFormat:()=>We,$ZodCheckUpperCase:()=>vi,$ZodCustom:()=>Pa,$ZodCustomStringFormat:()=>Yi,$ZodDate:()=>sa,$ZodDefault:()=>_a,$ZodDiscriminatedUnion:()=>ua,$ZodE164:()=>Gi,$ZodEmail:()=>Ti,$ZodEmoji:()=>Ni,$ZodEnum:()=>fa,$ZodError:()=>Ot,$ZodFile:()=>ha,$ZodFunction:()=>gn,$ZodGUID:()=>ji,$ZodIPv4:()=>Vi,$ZodIPv6:()=>Fi,$ZodISODate:()=>Mi,$ZodISODateTime:()=>Ci,$ZodISODuration:()=>qi,$ZodISOTime:()=>Li,$ZodIntersection:()=>la,$ZodJWT:()=>Qi,$ZodKSUID:()=>Ai,$ZodLazy:()=>ja,$ZodLiteral:()=>ga,$ZodMap:()=>da,$ZodNaN:()=>ka,$ZodNanoID:()=>Ui,$ZodNever:()=>ia,$ZodNonOptional:()=>$a,$ZodNull:()=>na,$ZodNullable:()=>ba,$ZodNumber:()=>Zr,$ZodNumberFormat:()=>Xi,$ZodObject:()=>ca,$ZodOptional:()=>va,$ZodPipe:()=>Ct,$ZodPrefault:()=>ya,$ZodPromise:()=>Ia,$ZodReadonly:()=>Sa,$ZodRealError:()=>Fe,$ZodRecord:()=>ma,$ZodRegistry:()=>Qe,$ZodSet:()=>pa,$ZodString:()=>Ue,$ZodStringFormat:()=>q,$ZodSuccess:()=>xa,$ZodSymbol:()=>ta,$ZodTemplateLiteral:()=>wa,$ZodTransform:()=>At,$ZodTuple:()=>Ee,$ZodType:()=>T,$ZodULID:()=>Di,$ZodURL:()=>Oi,$ZodUUID:()=>Pi,$ZodUndefined:()=>ra,$ZodUnion:()=>Rr,$ZodUnknown:()=>Ke,$ZodVoid:()=>aa,$ZodXID:()=>Ri,$brand:()=>_r,$constructor:()=>u,$input:()=>Mr,$output:()=>Cr,Doc:()=>Zt,JSONSchema:()=>wl,JSONSchemaGenerator:()=>Ft,NEVER:()=>br,TimePrecision:()=>un,_any:()=>ts,_array:()=>Vt,_base64:()=>on,_base64url:()=>an,_bigint:()=>Wa,_boolean:()=>Ja,_catch:()=>Dp,_cidrv4:()=>rn,_cidrv6:()=>nn,_coercedBigint:()=>Ka,_coercedBoolean:()=>Ba,_coercedDate:()=>is,_coercedNumber:()=>Ma,_coercedString:()=>Ea,_cuid:()=>Kr,_cuid2:()=>Gr,_custom:()=>us,_date:()=>os,_default:()=>Up,_discriminatedUnion:()=>xp,_e164:()=>sn,_email:()=>Lr,_emoji:()=>Br,_endsWith:()=>it,_enum:()=>Ip,_file:()=>cs,_float32:()=>qa,_float64:()=>Va,_gt:()=>fe,_gte:()=>re,_guid:()=>qt,_includes:()=>nt,_int:()=>La,_int32:()=>Fa,_int64:()=>Ga,_intersection:()=>zp,_ipv4:()=>en,_ipv6:()=>tn,_isoDate:()=>Da,_isoDateTime:()=>Za,_isoDuration:()=>Aa,_isoTime:()=>Ra,_jwt:()=>cn,_ksuid:()=>Xr,_lazy:()=>Mp,_length:()=>Re,_literal:()=>Pp,_lowercase:()=>tt,_lt:()=>pe,_lte:()=>se,_map:()=>Sp,_max:()=>se,_maxLength:()=>De,_maxSize:()=>Ze,_mime:()=>at,_min:()=>re,_minLength:()=>_e,_minSize:()=>Se,_multipleOf:()=>ke,_nan:()=>as,_nanoid:()=>Wr,_nativeEnum:()=>jp,_negative:()=>mn,_never:()=>rs,_nonnegative:()=>pn,_nonoptional:()=>Ep,_nonpositive:()=>dn,_normalize:()=>st,_null:()=>es,_nullable:()=>Np,_number:()=>Ca,_optional:()=>Op,_overwrite:()=>ge,_parse:()=>zr,_parseAsync:()=>kr,_pipe:()=>Rp,_positive:()=>ln,_promise:()=>Lp,_property:()=>fn,_readonly:()=>Ap,_record:()=>kp,_refine:()=>ls,_regex:()=>et,_safeParse:()=>Sr,_safeParseAsync:()=>wr,_set:()=>wp,_size:()=>Xe,_startsWith:()=>ot,_string:()=>Ua,_stringFormat:()=>ds,_stringbool:()=>ms,_success:()=>Zp,_symbol:()=>Ya,_templateLiteral:()=>Cp,_toLowerCase:()=>ut,_toUpperCase:()=>lt,_transform:()=>Tp,_trim:()=>ct,_tuple:()=>ss,_uint32:()=>Ha,_uint64:()=>Qa,_ulid:()=>Qr,_undefined:()=>Xa,_union:()=>$p,_unknown:()=>Ye,_uppercase:()=>rt,_url:()=>Jr,_uuid:()=>qr,_uuidv4:()=>Vr,_uuidv6:()=>Fr,_uuidv7:()=>Hr,_void:()=>ns,_xid:()=>Yr,clone:()=>ne,config:()=>B,flattenError:()=>He,formatError:()=>Je,function:()=>hn,globalConfig:()=>zt,globalRegistry:()=>me,isValidBase64:()=>Bi,isValidBase64URL:()=>Qc,isValidJWT:()=>Yc,locales:()=>Ge,parse:()=>Nt,parseAsync:()=>Ut,prettifyError:()=>xr,regexes:()=>ze,registry:()=>Lt,safeParse:()=>Be,safeParseAsync:()=>Et,toDotPath:()=>Uc,toJSONSchema:()=>vn,treeifyError:()=>$r,util:()=>y,version:()=>Si});var ie=k(()=>{Le();Ir();To();Mt();Nr();wi();P();Pr();Oa();Na();ki();kl();ps();Sl();Il()});var fs=k(()=>{ie()});var Ae={};$e(Ae,{ZodISODate:()=>Jt,ZodISODateTime:()=>Ht,ZodISODuration:()=>Wt,ZodISOTime:()=>Bt,date:()=>hs,datetime:()=>gs,duration:()=>bs,time:()=>vs});function gs(t){return Za(Ht,t)}function hs(t){return Da(Jt,t)}function vs(t){return Ra(Bt,t)}function bs(t){return Aa(Wt,t)}var Ht,Jt,Bt,Wt,yn=k(()=>{ie();$n();Ht=u("ZodISODateTime",(t,r)=>{Ci.init(t,r),V.init(t,r)});Jt=u("ZodISODate",(t,r)=>{Mi.init(t,r),V.init(t,r)});Bt=u("ZodISOTime",(t,r)=>{Li.init(t,r),V.init(t,r)});Wt=u("ZodISODuration",(t,r)=>{qi.init(t,r),V.init(t,r)})});var Ol,Nl,Ce,_s=k(()=>{ie();ie();Ol=(t,r)=>{Ot.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Je(t,n)},flatten:{value:n=>He(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},Nl=u("ZodError",Ol),Ce=u("ZodError",Ol,{Parent:Error})});var xn,zn,kn,Sn,ys=k(()=>{ie();_s();xn=zr(Ce),zn=kr(Ce),kn=Sr(Ce),Sn=wr(Ce)});function m(t){return Ua(dt,t)}function Ul(t){return Lr(jn,t)}function El(t){return qt(Kt,t)}function Zl(t){return qr(ve,t)}function Dl(t){return Vr(ve,t)}function Rl(t){return Fr(ve,t)}function Al(t){return Hr(ve,t)}function Cl(t){return Jr(Pn,t)}function Ml(t){return Br(Tn,t)}function Ll(t){return Wr(On,t)}function ql(t){return Kr(Nn,t)}function Vl(t){return Gr(Un,t)}function Fl(t){return Qr(En,t)}function Hl(t){return Yr(Zn,t)}function Jl(t){return Xr(Dn,t)}function Bl(t){return en(Rn,t)}function Wl(t){return tn(An,t)}function Kl(t){return rn(Cn,t)}function Gl(t){return nn(Mn,t)}function Ql(t){return on(Ln,t)}function Yl(t){return an(qn,t)}function Xl(t){return sn(Vn,t)}function em(t){return cn(Fn,t)}function tm(t,r,n={}){return ds($s,t,r,n)}function Z(t){return Ca(pt,t)}function wn(t){return La(Me,t)}function rm(t){return qa(Me,t)}function nm(t){return Va(Me,t)}function om(t){return Fa(Me,t)}function im(t){return Ha(Me,t)}function W(t){return Ja(ft,t)}function am(t){return Wa(gt,t)}function sm(t){return Ga(Hn,t)}function cm(t){return Qa(Hn,t)}function um(t){return Ya(xs,t)}function lm(t){return Xa(zs,t)}function Yt(t){return es(ks,t)}function mm(){return ts(Ss)}function H(){return Ye(ws)}function Xt(t){return rs(Is,t)}function dm(t){return ns(js,t)}function pm(t){return os(er,t)}function N(t,r){return Vt(Ps,t,r)}function fm(t){let r=t._zod.def.shape;return I(Object.keys(r))}function z(t,r){let n={type:"object",get shape(){return y.assignProp(this,"shape",{...t}),this.shape},...y.normalizeParams(r)};return new tr(n)}function gm(t,r){return new tr({type:"object",get shape(){return y.assignProp(this,"shape",{...t}),this.shape},catchall:Xt(),...y.normalizeParams(r)})}function Q(t,r){return new tr({type:"object",get shape(){return y.assignProp(this,"shape",{...t}),this.shape},catchall:H(),...y.normalizeParams(r)})}function M(t,r){return new Jn({type:"union",options:t,...y.normalizeParams(r)})}function rr(t,r,n){return new Ts({type:"union",options:r,discriminator:t,...y.normalizeParams(n)})}function ht(t,r){return new Os({type:"intersection",left:t,right:r})}function hm(t,r,n){let i=r instanceof T,e=i?n:r,o=i?r:null;return new Ns({type:"tuple",items:t,rest:o,...y.normalizeParams(e)})}function L(t,r,n){return new Bn({type:"record",keyType:t,valueType:r,...y.normalizeParams(n)})}function vm(t,r,n){return new Bn({type:"record",keyType:M([t,Xt()]),valueType:r,...y.normalizeParams(n)})}function bm(t,r,n){return new Us({type:"map",keyType:t,valueType:r,...y.normalizeParams(n)})}function _m(t,r){return new Es({type:"set",valueType:t,...y.normalizeParams(r)})}function te(t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(i=>[i,i])):t;return new mt({type:"enum",entries:n,...y.normalizeParams(r)})}function ym(t,r){return new mt({type:"enum",entries:t,...y.normalizeParams(r)})}function I(t,r){return new Zs({type:"literal",values:Array.isArray(t)?t:[t],...y.normalizeParams(r)})}function $m(t){return cs(Ds,t)}function Kn(t){return new Wn({type:"transform",transform:t})}function F(t){return new Gn({type:"optional",innerType:t})}function Gt(t){return new Rs({type:"nullable",innerType:t})}function xm(t){return F(Gt(t))}function Cs(t,r){return new As({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}function Ls(t,r){return new Ms({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}function qs(t,r){return new Qn({type:"nonoptional",innerType:t,...y.normalizeParams(r)})}function zm(t){return new Vs({type:"success",innerType:t})}function Hs(t,r){return new Fs({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function km(t){return as(Js,t)}function Qt(t,r){return new Yn({type:"pipe",in:t,out:r})}function Ws(t){return new Bs({type:"readonly",innerType:t})}function Sm(t,r){return new Ks({type:"template_literal",parts:t,...y.normalizeParams(r)})}function Qs(t){return new Gs({type:"lazy",getter:t})}function wm(t){return new Ys({type:"promise",innerType:t})}function Xs(t){let r=new J({check:"custom"});return r._zod.check=t,r}function Xn(t,r){return us(nr,t??(()=>!0),r)}function ec(t,r={}){return ls(nr,t,r)}function tc(t){let r=Xs(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(y.issue(i,n.value,r._zod.def));else{let e=i;e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=n.value),e.inst??(e.inst=r),e.continue??(e.continue=!r._zod.def.abort),n.issues.push(y.issue(e))}},t(n.value,n)));return r}function Im(t,r={error:`Input not instance of ${t.name}`}){let n=new nr({type:"custom",check:"custom",fn:i=>i instanceof t,abort:!0,...y.normalizeParams(r)});return n._zod.bag.Class=t,n}function Pm(t){let r=Qs(()=>M([m(t),Z(),W(),Yt(),N(r),L(m(),r)]));return r}function or(t,r){return Qt(Kn(t),r)}var O,In,dt,V,jn,Kt,ve,Pn,Tn,On,Nn,Un,En,Zn,Dn,Rn,An,Cn,Mn,Ln,qn,Vn,Fn,$s,pt,Me,ft,gt,Hn,xs,zs,ks,Ss,ws,Is,js,er,Ps,tr,Jn,Ts,Os,Ns,Bn,Us,Es,mt,Zs,Ds,Wn,Gn,Rs,As,Ms,Qn,Vs,Fs,Js,Yn,Bs,Ks,Gs,Ys,nr,jm,$n=k(()=>{ie();ie();fs();yn();ys();O=u("ZodType",(t,r)=>(T.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...n)=>t.clone({...r,checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),t.clone=(n,i)=>ne(t,n,i),t.brand=()=>t,t.register=((n,i)=>(n.add(t,i),t)),t.parse=(n,i)=>xn(t,n,i,{callee:t.parse}),t.safeParse=(n,i)=>kn(t,n,i),t.parseAsync=async(n,i)=>zn(t,n,i,{callee:t.parseAsync}),t.safeParseAsync=async(n,i)=>Sn(t,n,i),t.spa=t.safeParseAsync,t.refine=(n,i)=>t.check(ec(n,i)),t.superRefine=n=>t.check(tc(n)),t.overwrite=n=>t.check(ge(n)),t.optional=()=>F(t),t.nullable=()=>Gt(t),t.nullish=()=>F(Gt(t)),t.nonoptional=n=>qs(t,n),t.array=()=>N(t),t.or=n=>M([t,n]),t.and=n=>ht(t,n),t.transform=n=>Qt(t,Kn(n)),t.default=n=>Cs(t,n),t.prefault=n=>Ls(t,n),t.catch=n=>Hs(t,n),t.pipe=n=>Qt(t,n),t.readonly=()=>Ws(t),t.describe=n=>{let i=t.clone();return me.add(i,{description:n}),i},Object.defineProperty(t,"description",{get(){return me.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return me.get(t);let i=t.clone();return me.add(i,n[0]),i},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),In=u("_ZodString",(t,r)=>{Ue.init(t,r),O.init(t,r);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...i)=>t.check(et(...i)),t.includes=(...i)=>t.check(nt(...i)),t.startsWith=(...i)=>t.check(ot(...i)),t.endsWith=(...i)=>t.check(it(...i)),t.min=(...i)=>t.check(_e(...i)),t.max=(...i)=>t.check(De(...i)),t.length=(...i)=>t.check(Re(...i)),t.nonempty=(...i)=>t.check(_e(1,...i)),t.lowercase=i=>t.check(tt(i)),t.uppercase=i=>t.check(rt(i)),t.trim=()=>t.check(ct()),t.normalize=(...i)=>t.check(st(...i)),t.toLowerCase=()=>t.check(ut()),t.toUpperCase=()=>t.check(lt())}),dt=u("ZodString",(t,r)=>{Ue.init(t,r),In.init(t,r),t.email=n=>t.check(Lr(jn,n)),t.url=n=>t.check(Jr(Pn,n)),t.jwt=n=>t.check(cn(Fn,n)),t.emoji=n=>t.check(Br(Tn,n)),t.guid=n=>t.check(qt(Kt,n)),t.uuid=n=>t.check(qr(ve,n)),t.uuidv4=n=>t.check(Vr(ve,n)),t.uuidv6=n=>t.check(Fr(ve,n)),t.uuidv7=n=>t.check(Hr(ve,n)),t.nanoid=n=>t.check(Wr(On,n)),t.guid=n=>t.check(qt(Kt,n)),t.cuid=n=>t.check(Kr(Nn,n)),t.cuid2=n=>t.check(Gr(Un,n)),t.ulid=n=>t.check(Qr(En,n)),t.base64=n=>t.check(on(Ln,n)),t.base64url=n=>t.check(an(qn,n)),t.xid=n=>t.check(Yr(Zn,n)),t.ksuid=n=>t.check(Xr(Dn,n)),t.ipv4=n=>t.check(en(Rn,n)),t.ipv6=n=>t.check(tn(An,n)),t.cidrv4=n=>t.check(rn(Cn,n)),t.cidrv6=n=>t.check(nn(Mn,n)),t.e164=n=>t.check(sn(Vn,n)),t.datetime=n=>t.check(gs(n)),t.date=n=>t.check(hs(n)),t.time=n=>t.check(vs(n)),t.duration=n=>t.check(bs(n))});V=u("ZodStringFormat",(t,r)=>{q.init(t,r),In.init(t,r)}),jn=u("ZodEmail",(t,r)=>{Ti.init(t,r),V.init(t,r)});Kt=u("ZodGUID",(t,r)=>{ji.init(t,r),V.init(t,r)});ve=u("ZodUUID",(t,r)=>{Pi.init(t,r),V.init(t,r)});Pn=u("ZodURL",(t,r)=>{Oi.init(t,r),V.init(t,r)});Tn=u("ZodEmoji",(t,r)=>{Ni.init(t,r),V.init(t,r)});On=u("ZodNanoID",(t,r)=>{Ui.init(t,r),V.init(t,r)});Nn=u("ZodCUID",(t,r)=>{Ei.init(t,r),V.init(t,r)});Un=u("ZodCUID2",(t,r)=>{Zi.init(t,r),V.init(t,r)});En=u("ZodULID",(t,r)=>{Di.init(t,r),V.init(t,r)});Zn=u("ZodXID",(t,r)=>{Ri.init(t,r),V.init(t,r)});Dn=u("ZodKSUID",(t,r)=>{Ai.init(t,r),V.init(t,r)});Rn=u("ZodIPv4",(t,r)=>{Vi.init(t,r),V.init(t,r)});An=u("ZodIPv6",(t,r)=>{Fi.init(t,r),V.init(t,r)});Cn=u("ZodCIDRv4",(t,r)=>{Hi.init(t,r),V.init(t,r)});Mn=u("ZodCIDRv6",(t,r)=>{Ji.init(t,r),V.init(t,r)});Ln=u("ZodBase64",(t,r)=>{Wi.init(t,r),V.init(t,r)});qn=u("ZodBase64URL",(t,r)=>{Ki.init(t,r),V.init(t,r)});Vn=u("ZodE164",(t,r)=>{Gi.init(t,r),V.init(t,r)});Fn=u("ZodJWT",(t,r)=>{Qi.init(t,r),V.init(t,r)});$s=u("ZodCustomStringFormat",(t,r)=>{Yi.init(t,r),V.init(t,r)});pt=u("ZodNumber",(t,r)=>{Zr.init(t,r),O.init(t,r),t.gt=(i,e)=>t.check(fe(i,e)),t.gte=(i,e)=>t.check(re(i,e)),t.min=(i,e)=>t.check(re(i,e)),t.lt=(i,e)=>t.check(pe(i,e)),t.lte=(i,e)=>t.check(se(i,e)),t.max=(i,e)=>t.check(se(i,e)),t.int=i=>t.check(wn(i)),t.safe=i=>t.check(wn(i)),t.positive=i=>t.check(fe(0,i)),t.nonnegative=i=>t.check(re(0,i)),t.negative=i=>t.check(pe(0,i)),t.nonpositive=i=>t.check(se(0,i)),t.multipleOf=(i,e)=>t.check(ke(i,e)),t.step=(i,e)=>t.check(ke(i,e)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});Me=u("ZodNumberFormat",(t,r)=>{Xi.init(t,r),pt.init(t,r)});ft=u("ZodBoolean",(t,r)=>{Dt.init(t,r),O.init(t,r)});gt=u("ZodBigInt",(t,r)=>{Dr.init(t,r),O.init(t,r),t.gte=(i,e)=>t.check(re(i,e)),t.min=(i,e)=>t.check(re(i,e)),t.gt=(i,e)=>t.check(fe(i,e)),t.gte=(i,e)=>t.check(re(i,e)),t.min=(i,e)=>t.check(re(i,e)),t.lt=(i,e)=>t.check(pe(i,e)),t.lte=(i,e)=>t.check(se(i,e)),t.max=(i,e)=>t.check(se(i,e)),t.positive=i=>t.check(fe(BigInt(0),i)),t.negative=i=>t.check(pe(BigInt(0),i)),t.nonpositive=i=>t.check(se(BigInt(0),i)),t.nonnegative=i=>t.check(re(BigInt(0),i)),t.multipleOf=(i,e)=>t.check(ke(i,e));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});Hn=u("ZodBigIntFormat",(t,r)=>{ea.init(t,r),gt.init(t,r)});xs=u("ZodSymbol",(t,r)=>{ta.init(t,r),O.init(t,r)});zs=u("ZodUndefined",(t,r)=>{ra.init(t,r),O.init(t,r)});ks=u("ZodNull",(t,r)=>{na.init(t,r),O.init(t,r)});Ss=u("ZodAny",(t,r)=>{oa.init(t,r),O.init(t,r)});ws=u("ZodUnknown",(t,r)=>{Ke.init(t,r),O.init(t,r)});Is=u("ZodNever",(t,r)=>{ia.init(t,r),O.init(t,r)});js=u("ZodVoid",(t,r)=>{aa.init(t,r),O.init(t,r)});er=u("ZodDate",(t,r)=>{sa.init(t,r),O.init(t,r),t.min=(i,e)=>t.check(re(i,e)),t.max=(i,e)=>t.check(se(i,e));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});Ps=u("ZodArray",(t,r)=>{Rt.init(t,r),O.init(t,r),t.element=r.element,t.min=(n,i)=>t.check(_e(n,i)),t.nonempty=n=>t.check(_e(1,n)),t.max=(n,i)=>t.check(De(n,i)),t.length=(n,i)=>t.check(Re(n,i)),t.unwrap=()=>t.element});tr=u("ZodObject",(t,r)=>{ca.init(t,r),O.init(t,r),y.defineLazy(t,"shape",()=>r.shape),t.keyof=()=>te(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:H()}),t.loose=()=>t.clone({...t._zod.def,catchall:H()}),t.strict=()=>t.clone({...t._zod.def,catchall:Xt()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>y.extend(t,n),t.merge=n=>y.merge(t,n),t.pick=n=>y.pick(t,n),t.omit=n=>y.omit(t,n),t.partial=(...n)=>y.partial(Gn,t,n[0]),t.required=(...n)=>y.required(Qn,t,n[0])});Jn=u("ZodUnion",(t,r)=>{Rr.init(t,r),O.init(t,r),t.options=r.options});Ts=u("ZodDiscriminatedUnion",(t,r)=>{Jn.init(t,r),ua.init(t,r)});Os=u("ZodIntersection",(t,r)=>{la.init(t,r),O.init(t,r)});Ns=u("ZodTuple",(t,r)=>{Ee.init(t,r),O.init(t,r),t.rest=n=>t.clone({...t._zod.def,rest:n})});Bn=u("ZodRecord",(t,r)=>{ma.init(t,r),O.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});Us=u("ZodMap",(t,r)=>{da.init(t,r),O.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});Es=u("ZodSet",(t,r)=>{pa.init(t,r),O.init(t,r),t.min=(...n)=>t.check(Se(...n)),t.nonempty=n=>t.check(Se(1,n)),t.max=(...n)=>t.check(Ze(...n)),t.size=(...n)=>t.check(Xe(...n))});mt=u("ZodEnum",(t,r)=>{fa.init(t,r),O.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);let n=new Set(Object.keys(r.entries));t.extract=(i,e)=>{let o={};for(let a of i)if(n.has(a))o[a]=r.entries[a];else throw new Error(`Key ${a} not found in enum`);return new mt({...r,checks:[],...y.normalizeParams(e),entries:o})},t.exclude=(i,e)=>{let o={...r.entries};for(let a of i)if(n.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new mt({...r,checks:[],...y.normalizeParams(e),entries:o})}});Zs=u("ZodLiteral",(t,r)=>{ga.init(t,r),O.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});Ds=u("ZodFile",(t,r)=>{ha.init(t,r),O.init(t,r),t.min=(n,i)=>t.check(Se(n,i)),t.max=(n,i)=>t.check(Ze(n,i)),t.mime=(n,i)=>t.check(at(Array.isArray(n)?n:[n],i))});Wn=u("ZodTransform",(t,r)=>{At.init(t,r),O.init(t,r),t._zod.parse=(n,i)=>{n.addIssue=o=>{if(typeof o=="string")n.issues.push(y.issue(o,n.value,r));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),n.issues.push(y.issue(a))}};let e=r.transform(n.value,n);return e instanceof Promise?e.then(o=>(n.value=o,n)):(n.value=e,n)}});Gn=u("ZodOptional",(t,r)=>{va.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Rs=u("ZodNullable",(t,r)=>{ba.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});As=u("ZodDefault",(t,r)=>{_a.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Ms=u("ZodPrefault",(t,r)=>{ya.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Qn=u("ZodNonOptional",(t,r)=>{$a.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Vs=u("ZodSuccess",(t,r)=>{xa.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Fs=u("ZodCatch",(t,r)=>{za.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Js=u("ZodNaN",(t,r)=>{ka.init(t,r),O.init(t,r)});Yn=u("ZodPipe",(t,r)=>{Ct.init(t,r),O.init(t,r),t.in=r.in,t.out=r.out});Bs=u("ZodReadonly",(t,r)=>{Sa.init(t,r),O.init(t,r)});Ks=u("ZodTemplateLiteral",(t,r)=>{wa.init(t,r),O.init(t,r)});Gs=u("ZodLazy",(t,r)=>{ja.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.getter()});Ys=u("ZodPromise",(t,r)=>{Ia.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});nr=u("ZodCustom",(t,r)=>{Pa.init(t,r),O.init(t,r)});jm=(...t)=>ms({Pipe:Yn,Boolean:ft,String:dt,Transform:Wn},...t)});function Om(t){B({customError:t})}function Nm(){return B().customError}var Tm,Um=k(()=>{ie();Tm={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"}});var eo={};$e(eo,{bigint:()=>Bp,boolean:()=>Jp,date:()=>Wp,number:()=>Hp,string:()=>Fp});function Fp(t){return Ea(dt,t)}function Hp(t){return Ma(pt,t)}function Jp(t){return Ba(ft,t)}function Bp(t){return Ka(gt,t)}function Wp(t){return is(er,t)}var Em=k(()=>{ie();$n()});var s={};$e(s,{$brand:()=>_r,$input:()=>Mr,$output:()=>Cr,NEVER:()=>br,TimePrecision:()=>un,ZodAny:()=>Ss,ZodArray:()=>Ps,ZodBase64:()=>Ln,ZodBase64URL:()=>qn,ZodBigInt:()=>gt,ZodBigIntFormat:()=>Hn,ZodBoolean:()=>ft,ZodCIDRv4:()=>Cn,ZodCIDRv6:()=>Mn,ZodCUID:()=>Nn,ZodCUID2:()=>Un,ZodCatch:()=>Fs,ZodCustom:()=>nr,ZodCustomStringFormat:()=>$s,ZodDate:()=>er,ZodDefault:()=>As,ZodDiscriminatedUnion:()=>Ts,ZodE164:()=>Vn,ZodEmail:()=>jn,ZodEmoji:()=>Tn,ZodEnum:()=>mt,ZodError:()=>Nl,ZodFile:()=>Ds,ZodGUID:()=>Kt,ZodIPv4:()=>Rn,ZodIPv6:()=>An,ZodISODate:()=>Jt,ZodISODateTime:()=>Ht,ZodISODuration:()=>Wt,ZodISOTime:()=>Bt,ZodIntersection:()=>Os,ZodIssueCode:()=>Tm,ZodJWT:()=>Fn,ZodKSUID:()=>Dn,ZodLazy:()=>Gs,ZodLiteral:()=>Zs,ZodMap:()=>Us,ZodNaN:()=>Js,ZodNanoID:()=>On,ZodNever:()=>Is,ZodNonOptional:()=>Qn,ZodNull:()=>ks,ZodNullable:()=>Rs,ZodNumber:()=>pt,ZodNumberFormat:()=>Me,ZodObject:()=>tr,ZodOptional:()=>Gn,ZodPipe:()=>Yn,ZodPrefault:()=>Ms,ZodPromise:()=>Ys,ZodReadonly:()=>Bs,ZodRealError:()=>Ce,ZodRecord:()=>Bn,ZodSet:()=>Es,ZodString:()=>dt,ZodStringFormat:()=>V,ZodSuccess:()=>Vs,ZodSymbol:()=>xs,ZodTemplateLiteral:()=>Ks,ZodTransform:()=>Wn,ZodTuple:()=>Ns,ZodType:()=>O,ZodULID:()=>En,ZodURL:()=>Pn,ZodUUID:()=>ve,ZodUndefined:()=>zs,ZodUnion:()=>Jn,ZodUnknown:()=>ws,ZodVoid:()=>js,ZodXID:()=>Zn,_ZodString:()=>In,_default:()=>Cs,any:()=>mm,array:()=>N,base64:()=>Ql,base64url:()=>Yl,bigint:()=>am,boolean:()=>W,catch:()=>Hs,check:()=>Xs,cidrv4:()=>Kl,cidrv6:()=>Gl,clone:()=>ne,coerce:()=>eo,config:()=>B,core:()=>he,cuid:()=>ql,cuid2:()=>Vl,custom:()=>Xn,date:()=>pm,discriminatedUnion:()=>rr,e164:()=>Xl,email:()=>Ul,emoji:()=>Ml,endsWith:()=>it,enum:()=>te,file:()=>$m,flattenError:()=>He,float32:()=>rm,float64:()=>nm,formatError:()=>Je,function:()=>hn,getErrorMap:()=>Nm,globalRegistry:()=>me,gt:()=>fe,gte:()=>re,guid:()=>El,includes:()=>nt,instanceof:()=>Im,int:()=>wn,int32:()=>om,int64:()=>sm,intersection:()=>ht,ipv4:()=>Bl,ipv6:()=>Wl,iso:()=>Ae,json:()=>Pm,jwt:()=>em,keyof:()=>fm,ksuid:()=>Jl,lazy:()=>Qs,length:()=>Re,literal:()=>I,locales:()=>Ge,looseObject:()=>Q,lowercase:()=>tt,lt:()=>pe,lte:()=>se,map:()=>bm,maxLength:()=>De,maxSize:()=>Ze,mime:()=>at,minLength:()=>_e,minSize:()=>Se,multipleOf:()=>ke,nan:()=>km,nanoid:()=>Ll,nativeEnum:()=>ym,negative:()=>mn,never:()=>Xt,nonnegative:()=>pn,nonoptional:()=>qs,nonpositive:()=>dn,normalize:()=>st,null:()=>Yt,nullable:()=>Gt,nullish:()=>xm,number:()=>Z,object:()=>z,optional:()=>F,overwrite:()=>ge,parse:()=>xn,parseAsync:()=>zn,partialRecord:()=>vm,pipe:()=>Qt,positive:()=>ln,prefault:()=>Ls,preprocess:()=>or,prettifyError:()=>xr,promise:()=>wm,property:()=>fn,readonly:()=>Ws,record:()=>L,refine:()=>ec,regex:()=>et,regexes:()=>ze,registry:()=>Lt,safeParse:()=>kn,safeParseAsync:()=>Sn,set:()=>_m,setErrorMap:()=>Om,size:()=>Xe,startsWith:()=>ot,strictObject:()=>gm,string:()=>m,stringFormat:()=>tm,stringbool:()=>jm,success:()=>zm,superRefine:()=>tc,symbol:()=>um,templateLiteral:()=>Sm,toJSONSchema:()=>vn,toLowerCase:()=>ut,toUpperCase:()=>lt,transform:()=>Kn,treeifyError:()=>$r,trim:()=>ct,tuple:()=>hm,uint32:()=>im,uint64:()=>cm,ulid:()=>Fl,undefined:()=>lm,union:()=>M,unknown:()=>H,uppercase:()=>rt,url:()=>Cl,uuid:()=>Zl,uuidv4:()=>Dl,uuidv6:()=>Rl,uuidv7:()=>Al,void:()=>dm,xid:()=>Hl});var rc=k(()=>{ie();$n();fs();_s();ys();Um();ie();Ta();ie();Oa();yn();yn();Em();B(Ar())});var Zm,nc=k(()=>{rc();rc();Zm=s});var oc={};$e(oc,{$brand:()=>_r,$input:()=>Mr,$output:()=>Cr,NEVER:()=>br,TimePrecision:()=>un,ZodAny:()=>Ss,ZodArray:()=>Ps,ZodBase64:()=>Ln,ZodBase64URL:()=>qn,ZodBigInt:()=>gt,ZodBigIntFormat:()=>Hn,ZodBoolean:()=>ft,ZodCIDRv4:()=>Cn,ZodCIDRv6:()=>Mn,ZodCUID:()=>Nn,ZodCUID2:()=>Un,ZodCatch:()=>Fs,ZodCustom:()=>nr,ZodCustomStringFormat:()=>$s,ZodDate:()=>er,ZodDefault:()=>As,ZodDiscriminatedUnion:()=>Ts,ZodE164:()=>Vn,ZodEmail:()=>jn,ZodEmoji:()=>Tn,ZodEnum:()=>mt,ZodError:()=>Nl,ZodFile:()=>Ds,ZodGUID:()=>Kt,ZodIPv4:()=>Rn,ZodIPv6:()=>An,ZodISODate:()=>Jt,ZodISODateTime:()=>Ht,ZodISODuration:()=>Wt,ZodISOTime:()=>Bt,ZodIntersection:()=>Os,ZodIssueCode:()=>Tm,ZodJWT:()=>Fn,ZodKSUID:()=>Dn,ZodLazy:()=>Gs,ZodLiteral:()=>Zs,ZodMap:()=>Us,ZodNaN:()=>Js,ZodNanoID:()=>On,ZodNever:()=>Is,ZodNonOptional:()=>Qn,ZodNull:()=>ks,ZodNullable:()=>Rs,ZodNumber:()=>pt,ZodNumberFormat:()=>Me,ZodObject:()=>tr,ZodOptional:()=>Gn,ZodPipe:()=>Yn,ZodPrefault:()=>Ms,ZodPromise:()=>Ys,ZodReadonly:()=>Bs,ZodRealError:()=>Ce,ZodRecord:()=>Bn,ZodSet:()=>Es,ZodString:()=>dt,ZodStringFormat:()=>V,ZodSuccess:()=>Vs,ZodSymbol:()=>xs,ZodTemplateLiteral:()=>Ks,ZodTransform:()=>Wn,ZodTuple:()=>Ns,ZodType:()=>O,ZodULID:()=>En,ZodURL:()=>Pn,ZodUUID:()=>ve,ZodUndefined:()=>zs,ZodUnion:()=>Jn,ZodUnknown:()=>ws,ZodVoid:()=>js,ZodXID:()=>Zn,_ZodString:()=>In,_default:()=>Cs,any:()=>mm,array:()=>N,base64:()=>Ql,base64url:()=>Yl,bigint:()=>am,boolean:()=>W,catch:()=>Hs,check:()=>Xs,cidrv4:()=>Kl,cidrv6:()=>Gl,clone:()=>ne,coerce:()=>eo,config:()=>B,core:()=>he,cuid:()=>ql,cuid2:()=>Vl,custom:()=>Xn,date:()=>pm,default:()=>Kp,discriminatedUnion:()=>rr,e164:()=>Xl,email:()=>Ul,emoji:()=>Ml,endsWith:()=>it,enum:()=>te,file:()=>$m,flattenError:()=>He,float32:()=>rm,float64:()=>nm,formatError:()=>Je,function:()=>hn,getErrorMap:()=>Nm,globalRegistry:()=>me,gt:()=>fe,gte:()=>re,guid:()=>El,includes:()=>nt,instanceof:()=>Im,int:()=>wn,int32:()=>om,int64:()=>sm,intersection:()=>ht,ipv4:()=>Bl,ipv6:()=>Wl,iso:()=>Ae,json:()=>Pm,jwt:()=>em,keyof:()=>fm,ksuid:()=>Jl,lazy:()=>Qs,length:()=>Re,literal:()=>I,locales:()=>Ge,looseObject:()=>Q,lowercase:()=>tt,lt:()=>pe,lte:()=>se,map:()=>bm,maxLength:()=>De,maxSize:()=>Ze,mime:()=>at,minLength:()=>_e,minSize:()=>Se,multipleOf:()=>ke,nan:()=>km,nanoid:()=>Ll,nativeEnum:()=>ym,negative:()=>mn,never:()=>Xt,nonnegative:()=>pn,nonoptional:()=>qs,nonpositive:()=>dn,normalize:()=>st,null:()=>Yt,nullable:()=>Gt,nullish:()=>xm,number:()=>Z,object:()=>z,optional:()=>F,overwrite:()=>ge,parse:()=>xn,parseAsync:()=>zn,partialRecord:()=>vm,pipe:()=>Qt,positive:()=>ln,prefault:()=>Ls,preprocess:()=>or,prettifyError:()=>xr,promise:()=>wm,property:()=>fn,readonly:()=>Ws,record:()=>L,refine:()=>ec,regex:()=>et,regexes:()=>ze,registry:()=>Lt,safeParse:()=>kn,safeParseAsync:()=>Sn,set:()=>_m,setErrorMap:()=>Om,size:()=>Xe,startsWith:()=>ot,strictObject:()=>gm,string:()=>m,stringFormat:()=>tm,stringbool:()=>jm,success:()=>zm,superRefine:()=>tc,symbol:()=>um,templateLiteral:()=>Sm,toJSONSchema:()=>vn,toLowerCase:()=>ut,toUpperCase:()=>lt,transform:()=>Kn,treeifyError:()=>$r,trim:()=>ct,tuple:()=>hm,uint32:()=>im,uint64:()=>cm,ulid:()=>Fl,undefined:()=>lm,union:()=>M,unknown:()=>H,uppercase:()=>rt,url:()=>Cl,uuid:()=>Zl,uuidv4:()=>Dl,uuidv6:()=>Rl,uuidv7:()=>Al,void:()=>dm,xid:()=>Hl,z:()=>s});var Kp,ir=k(()=>{nc();nc();Kp=Zm});ie();function bn(t){return!!t._zod}function _n(t,r){return bn(t)?Be(t,r):t.safeParse(r)}function jl(t){if(!t)return;let r;if(bn(t)?r=t._zod?.def?.shape:r=t.shape,!!r){if(typeof r=="function")try{return r()}catch{return}return r}}function Pl(t){if(bn(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=t.value;if(i!==void 0)return i}ir();var we="io.modelcontextprotocol/related-task",ro="2.0",G=Xn(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Dm=M([m(),Z().int()]),Rm=m(),Tb=Q({ttl:Z().optional(),pollInterval:Z().optional()}),Gp=z({ttl:Z().optional()}),Qp=z({taskId:m()}),ac=Q({progressToken:Dm.optional(),[we]:Qp.optional()}),ce=z({_meta:ac.optional()}),ar=ce.extend({task:Gp.optional()}),Am=t=>ar.safeParse(t).success,Y=z({method:m(),params:ce.loose().optional()}),ue=z({_meta:ac.optional()}),le=z({method:m(),params:ue.loose().optional()}),X=Q({_meta:ac.optional()}),bt=M([m(),Z().int()]),Cm=z({jsonrpc:I(ro),id:bt,...Y.shape}).strict(),sc=t=>Cm.safeParse(t).success,Mm=z({jsonrpc:I(ro),...le.shape}).strict(),Lm=t=>Mm.safeParse(t).success,cc=z({jsonrpc:I(ro),id:bt,result:X}).strict(),sr=t=>cc.safeParse(t).success;var C;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(C||(C={}));var uc=z({jsonrpc:I(ro),id:bt.optional(),error:z({code:Z().int(),message:m(),data:H().optional()})}).strict();var qm=t=>uc.safeParse(t).success;var Vm=M([Cm,Mm,cc,uc]),Ob=M([cc,uc]),no=X.strict(),Yp=ue.extend({requestId:bt.optional(),reason:m().optional()}),oo=le.extend({method:I("notifications/cancelled"),params:Yp}),Xp=z({src:m(),mimeType:m().optional(),sizes:N(m()).optional(),theme:te(["light","dark"]).optional()}),cr=z({icons:N(Xp).optional()}),vt=z({name:m(),title:m().optional()}),ur=vt.extend({...vt.shape,...cr.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),ef=ht(z({applyDefaults:W().optional()}),L(m(),H())),tf=or(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ht(z({form:ef.optional(),url:G.optional()}),L(m(),H()).optional())),rf=Q({list:G.optional(),cancel:G.optional(),requests:Q({sampling:Q({createMessage:G.optional()}).optional(),elicitation:Q({create:G.optional()}).optional()}).optional()}),nf=Q({list:G.optional(),cancel:G.optional(),requests:Q({tools:Q({call:G.optional()}).optional()}).optional()}),of=z({experimental:L(m(),G).optional(),sampling:z({context:G.optional(),tools:G.optional()}).optional(),elicitation:tf.optional(),roots:z({listChanged:W().optional()}).optional(),tasks:rf.optional(),extensions:L(m(),G).optional()}),af=ce.extend({protocolVersion:m(),capabilities:of,clientInfo:ur}),sf=Y.extend({method:I("initialize"),params:af});var cf=z({experimental:L(m(),G).optional(),logging:G.optional(),completions:G.optional(),prompts:z({listChanged:W().optional()}).optional(),resources:z({subscribe:W().optional(),listChanged:W().optional()}).optional(),tools:z({listChanged:W().optional()}).optional(),tasks:nf.optional(),extensions:L(m(),G).optional()}),uf=X.extend({protocolVersion:m(),capabilities:cf,serverInfo:ur,instructions:m().optional()}),lf=le.extend({method:I("notifications/initialized"),params:ue.optional()});var _t=Y.extend({method:I("ping"),params:ce.optional()}),mf=z({progress:Z(),total:F(Z()),message:F(m())}),df=z({...ue.shape,...mf.shape,progressToken:Dm}),io=le.extend({method:I("notifications/progress"),params:df}),pf=ce.extend({cursor:Rm.optional()}),lr=Y.extend({params:pf.optional()}),mr=X.extend({nextCursor:Rm.optional()}),ff=te(["working","input_required","completed","failed","cancelled"]),dr=z({taskId:m(),status:ff,ttl:M([Z(),Yt()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:F(Z()),statusMessage:F(m())}),ao=X.extend({task:dr}),gf=ue.merge(dr),pr=le.extend({method:I("notifications/tasks/status"),params:gf}),so=Y.extend({method:I("tasks/get"),params:ce.extend({taskId:m()})}),co=X.merge(dr),uo=Y.extend({method:I("tasks/result"),params:ce.extend({taskId:m()})}),Nb=X.loose(),lo=lr.extend({method:I("tasks/list")}),mo=mr.extend({tasks:N(dr)}),po=Y.extend({method:I("tasks/cancel"),params:ce.extend({taskId:m()})}),Fm=X.merge(dr),Hm=z({uri:m(),mimeType:F(m()),_meta:L(m(),H()).optional()}),Jm=Hm.extend({text:m()}),lc=m().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Bm=Hm.extend({blob:lc}),fr=te(["user","assistant"]),yt=z({audience:N(fr).optional(),priority:Z().min(0).max(1).optional(),lastModified:Ae.datetime({offset:!0}).optional()}),Wm=z({...vt.shape,...cr.shape,uri:m(),description:F(m()),mimeType:F(m()),size:F(Z()),annotations:yt.optional(),_meta:F(Q({}))}),hf=z({...vt.shape,...cr.shape,uriTemplate:m(),description:F(m()),mimeType:F(m()),annotations:yt.optional(),_meta:F(Q({}))}),vf=lr.extend({method:I("resources/list")}),mc=mr.extend({resources:N(Wm)}),bf=lr.extend({method:I("resources/templates/list")}),_f=mr.extend({resourceTemplates:N(hf)}),dc=ce.extend({uri:m()}),yf=dc,$f=Y.extend({method:I("resources/read"),params:yf}),pc=X.extend({contents:N(M([Jm,Bm]))}),xf=le.extend({method:I("notifications/resources/list_changed"),params:ue.optional()}),zf=dc,kf=Y.extend({method:I("resources/subscribe"),params:zf}),Sf=dc,wf=Y.extend({method:I("resources/unsubscribe"),params:Sf}),If=ue.extend({uri:m()}),jf=le.extend({method:I("notifications/resources/updated"),params:If}),Pf=z({name:m(),description:F(m()),required:F(W())}),Tf=z({...vt.shape,...cr.shape,description:F(m()),arguments:F(N(Pf)),_meta:F(Q({}))}),Of=lr.extend({method:I("prompts/list")}),Nf=mr.extend({prompts:N(Tf)}),Uf=ce.extend({name:m(),arguments:L(m(),m()).optional()}),Ef=Y.extend({method:I("prompts/get"),params:Uf}),fc=z({type:I("text"),text:m(),annotations:yt.optional(),_meta:L(m(),H()).optional()}),gc=z({type:I("image"),data:lc,mimeType:m(),annotations:yt.optional(),_meta:L(m(),H()).optional()}),hc=z({type:I("audio"),data:lc,mimeType:m(),annotations:yt.optional(),_meta:L(m(),H()).optional()}),Zf=z({type:I("tool_use"),name:m(),id:m(),input:L(m(),H()),_meta:L(m(),H()).optional()}),vc=z({type:I("resource"),resource:M([Jm,Bm]),annotations:yt.optional(),_meta:L(m(),H()).optional()}),bc=Wm.extend({type:I("resource_link")}),$t=M([fc,gc,hc,bc,vc]),Df=z({role:fr,content:$t}),Rf=X.extend({description:m().optional(),messages:N(Df)}),Af=le.extend({method:I("notifications/prompts/list_changed"),params:ue.optional()}),Cf=z({title:m().optional(),readOnlyHint:W().optional(),destructiveHint:W().optional(),idempotentHint:W().optional(),openWorldHint:W().optional()}),Mf=z({taskSupport:te(["required","optional","forbidden"]).optional()}),fo=z({...vt.shape,...cr.shape,description:m().optional(),inputSchema:z({type:I("object"),properties:L(m(),G).optional(),required:N(m()).optional()}).catchall(H()),outputSchema:z({type:I("object"),properties:L(m(),G).optional(),required:N(m()).optional()}).catchall(H()).optional(),annotations:Cf.optional(),execution:Mf.optional(),_meta:L(m(),H()).optional()}),_c=lr.extend({method:I("tools/list")}),Lf=mr.extend({tools:N(fo)}),xt=X.extend({content:N($t).default([]),structuredContent:L(m(),H()).optional(),isError:W().optional()}),Ub=xt.or(X.extend({toolResult:H()})),qf=ar.extend({name:m(),arguments:L(m(),H()).optional()}),yc=Y.extend({method:I("tools/call"),params:qf}),Vf=le.extend({method:I("notifications/tools/list_changed"),params:ue.optional()}),Eb=z({autoRefresh:W().default(!0),debounceMs:Z().int().nonnegative().default(300)}),Km=te(["debug","info","notice","warning","error","critical","alert","emergency"]),Ff=ce.extend({level:Km}),Hf=Y.extend({method:I("logging/setLevel"),params:Ff}),Jf=ue.extend({level:Km,logger:m().optional(),data:H()}),Bf=le.extend({method:I("notifications/message"),params:Jf}),Wf=z({name:m().optional()}),Kf=z({hints:N(Wf).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),Gf=z({mode:te(["auto","required","none"]).optional()}),Qf=z({type:I("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:N($t).default([]),structuredContent:z({}).loose().optional(),isError:W().optional(),_meta:L(m(),H()).optional()}),Yf=rr("type",[fc,gc,hc]),to=rr("type",[fc,gc,hc,Zf,Qf]),Xf=z({role:fr,content:M([to,N(to)]),_meta:L(m(),H()).optional()}),eg=ar.extend({messages:N(Xf),modelPreferences:Kf.optional(),systemPrompt:m().optional(),includeContext:te(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:N(m()).optional(),metadata:G.optional(),tools:N(fo).optional(),toolChoice:Gf.optional()}),tg=Y.extend({method:I("sampling/createMessage"),params:eg}),$c=X.extend({model:m(),stopReason:F(te(["endTurn","stopSequence","maxTokens"]).or(m())),role:fr,content:Yf}),xc=X.extend({model:m(),stopReason:F(te(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:fr,content:M([to,N(to)])}),rg=z({type:I("boolean"),title:m().optional(),description:m().optional(),default:W().optional()}),ng=z({type:I("string"),title:m().optional(),description:m().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:te(["email","uri","date","date-time"]).optional(),default:m().optional()}),og=z({type:te(["number","integer"]),title:m().optional(),description:m().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),ig=z({type:I("string"),title:m().optional(),description:m().optional(),enum:N(m()),default:m().optional()}),ag=z({type:I("string"),title:m().optional(),description:m().optional(),oneOf:N(z({const:m(),title:m()})),default:m().optional()}),sg=z({type:I("string"),title:m().optional(),description:m().optional(),enum:N(m()),enumNames:N(m()).optional(),default:m().optional()}),cg=M([ig,ag]),ug=z({type:I("array"),title:m().optional(),description:m().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:z({type:I("string"),enum:N(m())}),default:N(m()).optional()}),lg=z({type:I("array"),title:m().optional(),description:m().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:z({anyOf:N(z({const:m(),title:m()}))}),default:N(m()).optional()}),mg=M([ug,lg]),dg=M([sg,cg,mg]),pg=M([dg,rg,ng,og]),fg=ar.extend({mode:I("form").optional(),message:m(),requestedSchema:z({type:I("object"),properties:L(m(),pg),required:N(m()).optional()})}),gg=ar.extend({mode:I("url"),message:m(),elicitationId:m(),url:m().url()}),hg=M([fg,gg]),vg=Y.extend({method:I("elicitation/create"),params:hg}),bg=ue.extend({elicitationId:m()}),_g=le.extend({method:I("notifications/elicitation/complete"),params:bg}),yg=X.extend({action:te(["accept","decline","cancel"]),content:or(t=>t===null?void 0:t,L(m(),M([m(),Z(),W(),N(m())])).optional())}),$g=z({type:I("ref/resource"),uri:m()});var xg=z({type:I("ref/prompt"),name:m()}),zg=ce.extend({ref:M([xg,$g]),argument:z({name:m(),value:m()}),context:z({arguments:L(m(),m()).optional()}).optional()}),kg=Y.extend({method:I("completion/complete"),params:zg});var Sg=X.extend({completion:Q({values:N(m()).max(100),total:F(Z().int()),hasMore:F(W())})}),wg=z({uri:m().startsWith("file://"),name:m().optional(),_meta:L(m(),H()).optional()}),Ig=Y.extend({method:I("roots/list"),params:ce.optional()}),jg=X.extend({roots:N(wg)}),Pg=le.extend({method:I("notifications/roots/list_changed"),params:ue.optional()}),Zb=M([_t,sf,kg,Hf,Ef,Of,vf,bf,$f,kf,wf,yc,_c,so,uo,lo,po]),Db=M([oo,io,lf,Pg,pr]),Rb=M([no,$c,xc,yg,jg,co,mo,ao]),Ab=M([_t,tg,vg,Ig,so,uo,lo,po]),Cb=M([oo,io,Bf,jf,xf,Vf,Af,pr,_g]),Mb=M([no,uf,Sg,Rf,Nf,mc,_f,pc,xt,Lf,co,mo,ao]),E=class t extends Error{constructor(r,n,i){super(`MCP error ${r}: ${n}`),this.code=r,this.data=i,this.name="McpError"}static fromError(r,n,i){if(r===C.UrlElicitationRequired&&i){let e=i;if(e.elicitations)return new ic(e.elicitations,n)}return new t(r,n,i)}},ic=class extends E{constructor(r,n=`URL elicitation${r.length>1?"s":""} required`){super(C.UrlElicitationRequired,n,{elicitations:r})}get elicitations(){return this.data?.elicitations??[]}};function Ie(t){return t==="completed"||t==="failed"||t==="cancelled"}var Tg=Symbol("Let zodToJsonSchema decide on which parser to use");var __=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function zc(t){let n=jl(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Pl(n);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function kc(t,r){let n=_n(t,r);if(!n.success)throw n.error;return n.data}var Dg=6e4,go=class{constructor(r){this._options=r,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(oo,n=>{this._oncancel(n)}),this.setNotificationHandler(io,n=>{this._onprogress(n)}),this.setRequestHandler(_t,n=>({})),this._taskStore=r?.taskStore,this._taskMessageQueue=r?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(so,async(n,i)=>{let e=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!e)throw new E(C.InvalidParams,"Failed to retrieve task: Task not found");return{...e}}),this.setRequestHandler(uo,async(n,i)=>{let e=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(c.type==="response"||c.type==="error"){let d=c.message,h=d.id,g=this._requestResolvers.get(h);if(g)if(this._requestResolvers.delete(h),c.type==="response")g(d);else{let l=d,$=new E(l.error.code,l.error.message,l.error.data);g($)}else{let l=c.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${h}`))}continue}await this._transport?.send(c.message,{relatedRequestId:i.requestId})}}let a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new E(C.InvalidParams,`Task not found: ${o}`);if(!Ie(a.status))return await this._waitForTaskUpdate(o,i.signal),await e();if(Ie(a.status)){let c=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[we]:{taskId:o}}}}return await e()};return await e()}),this.setRequestHandler(lo,async(n,i)=>{try{let{tasks:e,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,i.sessionId);return{tasks:e,nextCursor:o,_meta:{}}}catch(e){throw new E(C.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(po,async(n,i)=>{try{let e=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!e)throw new E(C.InvalidParams,`Task not found: ${n.params.taskId}`);if(Ie(e.status))throw new E(C.InvalidParams,`Cannot cancel task in terminal status: ${e.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!o)throw new E(C.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(e){throw e instanceof E?e:new E(C.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(r){if(!r.params.requestId)return;this._requestHandlerAbortControllers.get(r.params.requestId)?.abort(r.params.reason)}_setupTimeout(r,n,i,e,o=!1){this._timeoutInfo.set(r,{timeoutId:setTimeout(e,n),startTime:Date.now(),timeout:n,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:e})}_resetTimeout(r){let n=this._timeoutInfo.get(r);if(!n)return!1;let i=Date.now()-n.startTime;if(n.maxTotalTimeout&&i>=n.maxTotalTimeout)throw this._timeoutInfo.delete(r),E.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:i});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(r){let n=this._timeoutInfo.get(r);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(r))}async connect(r){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=r;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};let e=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{e?.(o,a),sr(o)||qm(o)?this._onresponse(o):sc(o)?this._onrequest(o,a):Lm(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(let i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();let n=E.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of r.values())i(n)}_onerror(r){this.onerror?.(r)}_onnotification(r){let n=this._notificationHandlers.get(r.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(r)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(r,n){let i=this._requestHandlers.get(r.method)??this.fallbackRequestHandler,e=this._transport,o=r.params?._meta?.[we]?.taskId;if(i===void 0){let g={jsonrpc:"2.0",id:r.id,error:{code:C.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},e?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):e?.send(g).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(r.id,a);let c=Am(r.params)?r.params.task:void 0,d=this._taskStore?this.requestTaskStore(r,e?.sessionId):void 0,h={signal:a.signal,sessionId:e?.sessionId,_meta:r.params?._meta,sendNotification:async g=>{if(a.signal.aborted)return;let l={relatedRequestId:r.id};o&&(l.relatedTask={taskId:o}),await this.notification(g,l)},sendRequest:async(g,l,$)=>{if(a.signal.aborted)throw new E(C.ConnectionClosed,"Request was cancelled");let b={...$,relatedRequestId:r.id};o&&!b.relatedTask&&(b.relatedTask={taskId:o});let p=b.relatedTask?.taskId??o;return p&&d&&await d.updateTaskStatus(p,"input_required"),await this.request(g,l,b)},authInfo:n?.authInfo,requestId:r.id,requestInfo:n?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(r.method)}).then(()=>i(r,h)).then(async g=>{if(a.signal.aborted)return;let l={result:g,jsonrpc:"2.0",id:r.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},e?.sessionId):await e?.send(l)},async g=>{if(a.signal.aborted)return;let l={jsonrpc:"2.0",id:r.id,error:{code:Number.isSafeInteger(g.code)?g.code:C.InternalError,message:g.message??"Internal error",...g.data!==void 0&&{data:g.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},e?.sessionId):await e?.send(l)}).catch(g=>this._onerror(new Error(`Failed to send response: ${g}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===a&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(r){let{progressToken:n,...i}=r.params,e=Number(n),o=this._progressHandlers.get(e);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(r)}`));return}let a=this._responseHandlers.get(e),c=this._timeoutInfo.get(e);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(e)}catch(d){this._responseHandlers.delete(e),this._progressHandlers.delete(e),this._cleanupTimeout(e),a(d);return}o(i)}_onresponse(r){let n=Number(r.id),i=this._requestResolvers.get(n);if(i){if(this._requestResolvers.delete(n),sr(r))i(r);else{let a=new E(r.error.code,r.error.message,r.error.data);i(a)}return}let e=this._responseHandlers.get(n);if(e===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(r)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(sr(r)&&r.result&&typeof r.result=="object"){let a=r.result;if(a.task&&typeof a.task=="object"){let c=a.task;typeof c.taskId=="string"&&(o=!0,this._taskProgressTokens.set(c.taskId,n))}}if(o||this._progressHandlers.delete(n),sr(r))e(r);else{let a=E.fromError(r.error.code,r.error.message,r.error.data);e(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(r,n,i){let{task:e}=i??{};if(!e){try{yield{type:"result",result:await this.request(r,n,i)}}catch(a){yield{type:"error",error:a instanceof E?a:new E(C.InternalError,String(a))}}return}let o;try{let a=await this.request(r,ao,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new E(C.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:c},Ie(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)}:c.status==="failed"?yield{type:"error",error:new E(C.InternalError,`Task ${o} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new E(C.InternalError,`Task ${o} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)};return}let d=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(h=>setTimeout(h,d)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof E?a:new E(C.InternalError,String(a))}}}request(r,n,i){let{relatedRequestId:e,resumptionToken:o,onresumptiontoken:a,task:c,relatedTask:d}=i??{};return new Promise((h,g)=>{let l=w=>{g(w)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(r.method),c&&this.assertTaskCapability(r.method)}catch(w){l(w);return}i?.signal?.throwIfAborted();let $=this._requestMessageId++,b={...r,jsonrpc:"2.0",id:$};i?.onprogress&&(this._progressHandlers.set($,i.onprogress),b.params={...r.params,_meta:{...r.params?._meta||{},progressToken:$}}),c&&(b.params={...b.params,task:c}),d&&(b.params={...b.params,_meta:{...b.params?._meta||{},[we]:d}});let p=w=>{this._responseHandlers.delete($),this._progressHandlers.delete($),this._cleanupTimeout($),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:$,reason:String(w)}},{relatedRequestId:e,resumptionToken:o,onresumptiontoken:a}).catch(U=>this._onerror(new Error(`Failed to send cancellation: ${U}`)));let j=w instanceof E?w:new E(C.RequestTimeout,String(w));g(j)};this._responseHandlers.set($,w=>{if(!i?.signal?.aborted){if(w instanceof Error)return g(w);try{let j=_n(n,w.result);j.success?h(j.data):g(j.error)}catch(j){g(j)}}}),i?.signal?.addEventListener("abort",()=>{p(i?.signal?.reason)});let x=i?.timeout??Dg,S=()=>p(E.fromError(C.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout($,x,i?.maxTotalTimeout,S,i?.resetTimeoutOnProgress??!1);let R=d?.taskId;if(R){let w=j=>{let U=this._responseHandlers.get($);U?U(j):this._onerror(new Error(`Response handler missing for side-channeled request ${$}`))};this._requestResolvers.set($,w),this._enqueueTaskMessage(R,{type:"request",message:b,timestamp:Date.now()}).catch(j=>{this._cleanupTimeout($),g(j)})}else this._transport.send(b,{relatedRequestId:e,resumptionToken:o,onresumptiontoken:a}).catch(w=>{this._cleanupTimeout($),g(w)})})}async getTask(r,n){return this.request({method:"tasks/get",params:r},co,n)}async getTaskResult(r,n,i){return this.request({method:"tasks/result",params:r},n,i)}async listTasks(r,n){return this.request({method:"tasks/list",params:r},mo,n)}async cancelTask(r,n){return this.request({method:"tasks/cancel",params:r},Fm,n)}async notification(r,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(r.method);let i=n?.relatedTask?.taskId;if(i){let c={...r,jsonrpc:"2.0",params:{...r.params,_meta:{...r.params?._meta||{},[we]:n.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(r.method)&&!r.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(r.method))return;this._pendingDebouncedNotifications.add(r.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(r.method),!this._transport)return;let c={...r,jsonrpc:"2.0"};n?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[we]:n.relatedTask}}}),this._transport?.send(c,n).catch(d=>this._onerror(d))});return}let a={...r,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[we]:n.relatedTask}}}),await this._transport.send(a,n)}setRequestHandler(r,n){let i=zc(r);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(e,o)=>{let a=kc(r,e);return Promise.resolve(n(a,o))})}removeRequestHandler(r){this._requestHandlers.delete(r)}assertCanSetRequestHandler(r){if(this._requestHandlers.has(r))throw new Error(`A request handler for ${r} already exists, which would be overridden`)}setNotificationHandler(r,n){let i=zc(r);this._notificationHandlers.set(i,e=>{let o=kc(r,e);return Promise.resolve(n(o))})}removeNotificationHandler(r){this._notificationHandlers.delete(r)}_cleanupTaskProgressHandler(r){let n=this._taskProgressTokens.get(r);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(r))}async _enqueueTaskMessage(r,n,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let e=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(r,n,i,e)}async _clearTaskQueue(r,n){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(r,n);for(let e of i)if(e.type==="request"&&sc(e.message)){let o=e.message.id,a=this._requestResolvers.get(o);a?(a(new E(C.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${r} cleanup`))}}}async _waitForTaskUpdate(r,n){let i=this._options?.defaultTaskPollInterval??1e3;try{let e=await this._taskStore?.getTask(r);e?.pollInterval&&(i=e.pollInterval)}catch{}return new Promise((e,o)=>{if(n.aborted){o(new E(C.InvalidRequest,"Request cancelled"));return}let a=setTimeout(e,i);n.addEventListener("abort",()=>{clearTimeout(a),o(new E(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(r,n){let i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async e=>{if(!r)throw new Error("No request provided");return await i.createTask(e,r.id,{method:r.method,params:r.params},n)},getTask:async e=>{let o=await i.getTask(e,n);if(!o)throw new E(C.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(e,o,a)=>{await i.storeTaskResult(e,o,a,n);let c=await i.getTask(e,n);if(c){let d=pr.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Ie(c.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>i.getTaskResult(e,n),updateTaskStatus:async(e,o,a)=>{let c=await i.getTask(e,n);if(!c)throw new E(C.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Ie(c.status))throw new E(C.InvalidParams,`Cannot update task "${e}" from terminal status "${c.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(e,o,a,n);let d=await i.getTask(e,n);if(d){let h=pr.parse({method:"notifications/tasks/status",params:d});await this.notification(h),Ie(d.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>i.listTasks(e,n)}}};function Gm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Qm(t,r){let n={...t};for(let i in r){let e=i,o=r[e];if(o===void 0)continue;let a=n[e];Gm(a)&&Gm(o)?n[e]={...a,...o}:n[e]=o}return n}ir();ir();var vx=(t=>typeof Pe<"u"?Pe:typeof Proxy<"u"?new Proxy(t,{get:(r,n)=>(typeof Pe<"u"?Pe:r)[n]}):t)(function(t){if(typeof Pe<"u")return Pe.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),Sc=class extends go{constructor(){super(...arguments);A(this,"_registeredMethods",new Set);A(this,"_eventSlots",new Map);A(this,"setRequestHandler",(n,i)=>{this._assertMethodNotRegistered(n,"setRequestHandler"),super.setRequestHandler(n,i)});A(this,"setNotificationHandler",(n,i)=>{this._assertMethodNotRegistered(n,"setNotificationHandler"),super.setNotificationHandler(n,i)});A(this,"replaceRequestHandler",(n,i)=>{let e=n.shape.method.value;this._registeredMethods.add(e),super.setRequestHandler(n,i)})}onEventDispatch(n,i){}_ensureEventSlot(n){let i=this._eventSlots.get(n);if(!i){let e=this.eventSchemas[n];if(!e)throw Error(`Unknown event: ${String(n)}`);i={listeners:[]},this._eventSlots.set(n,i);let o=e.shape.method.value;this._registeredMethods.add(o);let a=i;super.setNotificationHandler(e,c=>{let d=c.params;this.onEventDispatch(n,d),a.onHandler?.(d);for(let h of[...a.listeners])h(d)})}return i}setEventHandler(n,i){let e=this._ensureEventSlot(n);e.onHandler&&i&&console.warn(`[MCP Apps] on${String(n)} handler replaced. Use addEventListener("${String(n)}", \u2026) to add multiple listeners without replacing.`),e.onHandler=i}getEventHandler(n){return this._eventSlots.get(n)?.onHandler}addEventListener(n,i){this._ensureEventSlot(n).listeners.push(i)}removeEventListener(n,i){let e=this._eventSlots.get(n);if(!e)return;let o=e.listeners.indexOf(i);o!==-1&&e.listeners.splice(o,1)}warnIfRequestHandlerReplaced(n,i,e){i&&e&&console.warn(`[MCP Apps] ${n} handler replaced. Previous handler will no longer be called.`)}_assertMethodNotRegistered(n,i){let e=n.shape.method.value;if(this._registeredMethods.has(e))throw Error(`Handler for "${e}" already registered (via ${i}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(e)}},Rg="2026-01-26";var Ag="ui/notifications/tool-input-partial";var wc=class{constructor(r=window.parent,n){A(this,"eventTarget");A(this,"eventSource");A(this,"messageListener");A(this,"onclose");A(this,"onerror");A(this,"onmessage");A(this,"sessionId");A(this,"setProtocolVersion");this.eventTarget=r,this.eventSource=n,this.messageListener=i=>{if(n&&i.source!==this.eventSource){console.debug("Ignoring message from unknown source",i);return}let e=Vm.safeParse(i.data);e.success?(console.debug("Parsed message",e.data),this.onmessage?.(e.data)):i.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",e.error.message,i):(console.error("Failed to parse message",e.error.message,i),this.onerror?.(Error("Invalid JSON-RPC message received: "+e.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(r,n){r.method!==Ag&&console.debug("Sending message",r),this.eventTarget.postMessage(r,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}},Cg=s.union([s.literal("light"),s.literal("dark")]).describe("Color theme preference for the host environment."),hr=s.union([s.literal("inline"),s.literal("fullscreen"),s.literal("pip")]).describe("Display mode for UI presentation."),Mg=s.union([s.literal("--color-background-primary"),s.literal("--color-background-secondary"),s.literal("--color-background-tertiary"),s.literal("--color-background-inverse"),s.literal("--color-background-ghost"),s.literal("--color-background-info"),s.literal("--color-background-danger"),s.literal("--color-background-success"),s.literal("--color-background-warning"),s.literal("--color-background-disabled"),s.literal("--color-text-primary"),s.literal("--color-text-secondary"),s.literal("--color-text-tertiary"),s.literal("--color-text-inverse"),s.literal("--color-text-ghost"),s.literal("--color-text-info"),s.literal("--color-text-danger"),s.literal("--color-text-success"),s.literal("--color-text-warning"),s.literal("--color-text-disabled"),s.literal("--color-border-primary"),s.literal("--color-border-secondary"),s.literal("--color-border-tertiary"),s.literal("--color-border-inverse"),s.literal("--color-border-ghost"),s.literal("--color-border-info"),s.literal("--color-border-danger"),s.literal("--color-border-success"),s.literal("--color-border-warning"),s.literal("--color-border-disabled"),s.literal("--color-ring-primary"),s.literal("--color-ring-secondary"),s.literal("--color-ring-inverse"),s.literal("--color-ring-info"),s.literal("--color-ring-danger"),s.literal("--color-ring-success"),s.literal("--color-ring-warning"),s.literal("--font-sans"),s.literal("--font-mono"),s.literal("--font-weight-normal"),s.literal("--font-weight-medium"),s.literal("--font-weight-semibold"),s.literal("--font-weight-bold"),s.literal("--font-text-xs-size"),s.literal("--font-text-sm-size"),s.literal("--font-text-md-size"),s.literal("--font-text-lg-size"),s.literal("--font-heading-xs-size"),s.literal("--font-heading-sm-size"),s.literal("--font-heading-md-size"),s.literal("--font-heading-lg-size"),s.literal("--font-heading-xl-size"),s.literal("--font-heading-2xl-size"),s.literal("--font-heading-3xl-size"),s.literal("--font-text-xs-line-height"),s.literal("--font-text-sm-line-height"),s.literal("--font-text-md-line-height"),s.literal("--font-text-lg-line-height"),s.literal("--font-heading-xs-line-height"),s.literal("--font-heading-sm-line-height"),s.literal("--font-heading-md-line-height"),s.literal("--font-heading-lg-line-height"),s.literal("--font-heading-xl-line-height"),s.literal("--font-heading-2xl-line-height"),s.literal("--font-heading-3xl-line-height"),s.literal("--border-radius-xs"),s.literal("--border-radius-sm"),s.literal("--border-radius-md"),s.literal("--border-radius-lg"),s.literal("--border-radius-xl"),s.literal("--border-radius-full"),s.literal("--border-width-regular"),s.literal("--shadow-hairline"),s.literal("--shadow-sm"),s.literal("--shadow-md"),s.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Lg=s.record(Mg.describe(`Style variables for theming MCP apps.+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let g of this.seen.entries()){let l=g[1];if(r===g[0]){a(g);continue}if(i.external){let b=i.external.registry.get(g[0])?.id;if(r!==g[0]&&b){a(g);continue}}if(this.metadataRegistry.get(g[0])?.id){a(g);continue}if(l.cycle){a(g);continue}if(l.count>1&&i.reused==="ref"){a(g);continue}}let c=(g,l)=>{let $=this.seen.get(g),b=$.def??$.schema,p={...b};if($.ref===null)return;let x=$.ref;if($.ref=null,x){c(x,l);let S=this.seen.get(x).schema;S.$ref&&l.target==="draft-7"?(b.allOf=b.allOf??[],b.allOf.push(S)):(Object.assign(b,S),Object.assign(b,p))}$.isParent||this.override({zodSchema:g,jsonSchema:b,path:$.path??[]})};for(let g of[...this.seen.entries()].reverse())c(g[0],{target:this.target});let d={};if(this.target==="draft-2020-12"?d.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?d.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),i.external?.uri){let g=i.external.registry.get(r)?.id;if(!g)throw new Error("Schema is missing an `id` property");d.$id=i.external.uri(g)}Object.assign(d,e.def);let h=i.external?.defs??{};for(let g of this.seen.entries()){let l=g[1];l.def&&l.defId&&(h[l.defId]=l.def)}i.external||Object.keys(h).length>0&&(this.target==="draft-2020-12"?d.$defs=h:d.definitions=h);try{return JSON.parse(JSON.stringify(d))}catch{throw new Error("Error converting schema to JSON.")}}}});var jl={};var Pl=k(()=>{});var he={};$e(he,{$ZodAny:()=>ia,$ZodArray:()=>Rt,$ZodAsyncError:()=>de,$ZodBase64:()=>Ki,$ZodBase64URL:()=>Gi,$ZodBigInt:()=>Dr,$ZodBigIntFormat:()=>ta,$ZodBoolean:()=>Dt,$ZodCIDRv4:()=>Ji,$ZodCIDRv6:()=>Bi,$ZodCUID:()=>Zi,$ZodCUID2:()=>Di,$ZodCatch:()=>ka,$ZodCheck:()=>J,$ZodCheckBigIntFormat:()=>ui,$ZodCheckEndsWith:()=>$i,$ZodCheckGreaterThan:()=>Or,$ZodCheckIncludes:()=>_i,$ZodCheckLengthEquals:()=>gi,$ZodCheckLessThan:()=>Tr,$ZodCheckLowerCase:()=>vi,$ZodCheckMaxLength:()=>pi,$ZodCheckMaxSize:()=>li,$ZodCheckMimeType:()=>zi,$ZodCheckMinLength:()=>fi,$ZodCheckMinSize:()=>mi,$ZodCheckMultipleOf:()=>si,$ZodCheckNumberFormat:()=>ci,$ZodCheckOverwrite:()=>ki,$ZodCheckProperty:()=>xi,$ZodCheckRegex:()=>hi,$ZodCheckSizeEquals:()=>di,$ZodCheckStartsWith:()=>yi,$ZodCheckStringFormat:()=>We,$ZodCheckUpperCase:()=>bi,$ZodCustom:()=>Ta,$ZodCustomStringFormat:()=>Xi,$ZodDate:()=>ca,$ZodDefault:()=>ya,$ZodDiscriminatedUnion:()=>la,$ZodE164:()=>Qi,$ZodEmail:()=>Oi,$ZodEmoji:()=>Ui,$ZodEnum:()=>ga,$ZodError:()=>Ot,$ZodFile:()=>va,$ZodFunction:()=>gn,$ZodGUID:()=>Pi,$ZodIPv4:()=>Fi,$ZodIPv6:()=>Hi,$ZodISODate:()=>Li,$ZodISODateTime:()=>Mi,$ZodISODuration:()=>Vi,$ZodISOTime:()=>qi,$ZodIntersection:()=>ma,$ZodJWT:()=>Yi,$ZodKSUID:()=>Ci,$ZodLazy:()=>Pa,$ZodLiteral:()=>ha,$ZodMap:()=>pa,$ZodNaN:()=>Sa,$ZodNanoID:()=>Ei,$ZodNever:()=>aa,$ZodNonOptional:()=>xa,$ZodNull:()=>oa,$ZodNullable:()=>_a,$ZodNumber:()=>Zr,$ZodNumberFormat:()=>ea,$ZodObject:()=>ua,$ZodOptional:()=>ba,$ZodPipe:()=>Ct,$ZodPrefault:()=>$a,$ZodPromise:()=>ja,$ZodReadonly:()=>wa,$ZodRealError:()=>Fe,$ZodRecord:()=>da,$ZodRegistry:()=>Qe,$ZodSet:()=>fa,$ZodString:()=>Ue,$ZodStringFormat:()=>q,$ZodSuccess:()=>za,$ZodSymbol:()=>ra,$ZodTemplateLiteral:()=>Ia,$ZodTransform:()=>At,$ZodTuple:()=>Ee,$ZodType:()=>T,$ZodULID:()=>Ri,$ZodURL:()=>Ni,$ZodUUID:()=>Ti,$ZodUndefined:()=>na,$ZodUnion:()=>Rr,$ZodUnknown:()=>Ke,$ZodVoid:()=>sa,$ZodXID:()=>Ai,$brand:()=>_r,$constructor:()=>u,$input:()=>Mr,$output:()=>Cr,Doc:()=>Zt,JSONSchema:()=>jl,JSONSchemaGenerator:()=>Ft,NEVER:()=>br,TimePrecision:()=>un,_any:()=>rs,_array:()=>Vt,_base64:()=>on,_base64url:()=>an,_bigint:()=>Ka,_boolean:()=>Ba,_catch:()=>Dp,_cidrv4:()=>rn,_cidrv6:()=>nn,_coercedBigint:()=>Ga,_coercedBoolean:()=>Wa,_coercedDate:()=>as,_coercedNumber:()=>La,_coercedString:()=>Za,_cuid:()=>Kr,_cuid2:()=>Gr,_custom:()=>ls,_date:()=>is,_default:()=>Up,_discriminatedUnion:()=>xp,_e164:()=>sn,_email:()=>Lr,_emoji:()=>Br,_endsWith:()=>it,_enum:()=>Ip,_file:()=>us,_float32:()=>Va,_float64:()=>Fa,_gt:()=>fe,_gte:()=>re,_guid:()=>qt,_includes:()=>nt,_int:()=>qa,_int32:()=>Ha,_int64:()=>Qa,_intersection:()=>zp,_ipv4:()=>en,_ipv6:()=>tn,_isoDate:()=>Ra,_isoDateTime:()=>Da,_isoDuration:()=>Ca,_isoTime:()=>Aa,_jwt:()=>cn,_ksuid:()=>Xr,_lazy:()=>Mp,_length:()=>Re,_literal:()=>Pp,_lowercase:()=>tt,_lt:()=>pe,_lte:()=>se,_map:()=>Sp,_max:()=>se,_maxLength:()=>De,_maxSize:()=>Ze,_mime:()=>at,_min:()=>re,_minLength:()=>_e,_minSize:()=>Se,_multipleOf:()=>ke,_nan:()=>ss,_nanoid:()=>Wr,_nativeEnum:()=>jp,_negative:()=>mn,_never:()=>ns,_nonnegative:()=>pn,_nonoptional:()=>Ep,_nonpositive:()=>dn,_normalize:()=>st,_null:()=>ts,_nullable:()=>Np,_number:()=>Ma,_optional:()=>Op,_overwrite:()=>ge,_parse:()=>zr,_parseAsync:()=>kr,_pipe:()=>Rp,_positive:()=>ln,_promise:()=>Lp,_property:()=>fn,_readonly:()=>Ap,_record:()=>kp,_refine:()=>ms,_regex:()=>et,_safeParse:()=>Sr,_safeParseAsync:()=>wr,_set:()=>wp,_size:()=>Xe,_startsWith:()=>ot,_string:()=>Ea,_stringFormat:()=>ps,_stringbool:()=>ds,_success:()=>Zp,_symbol:()=>Xa,_templateLiteral:()=>Cp,_toLowerCase:()=>ut,_toUpperCase:()=>lt,_transform:()=>Tp,_trim:()=>ct,_tuple:()=>cs,_uint32:()=>Ja,_uint64:()=>Ya,_ulid:()=>Qr,_undefined:()=>es,_union:()=>$p,_unknown:()=>Ye,_uppercase:()=>rt,_url:()=>Jr,_uuid:()=>qr,_uuidv4:()=>Vr,_uuidv6:()=>Fr,_uuidv7:()=>Hr,_void:()=>os,_xid:()=>Yr,clone:()=>ne,config:()=>B,flattenError:()=>He,formatError:()=>Je,function:()=>hn,globalConfig:()=>zt,globalRegistry:()=>me,isValidBase64:()=>Wi,isValidBase64URL:()=>Xc,isValidJWT:()=>eu,locales:()=>Ge,parse:()=>Nt,parseAsync:()=>Ut,prettifyError:()=>xr,regexes:()=>ze,registry:()=>Lt,safeParse:()=>Be,safeParseAsync:()=>Et,toDotPath:()=>Zc,toJSONSchema:()=>vn,treeifyError:()=>$r,util:()=>y,version:()=>wi});var ie=k(()=>{Le();Ir();Oo();Mt();Nr();Ii();P();Pr();Na();Ua();Si();wl();fs();Il();Pl()});var gs=k(()=>{ie()});var Ae={};$e(Ae,{ZodISODate:()=>Jt,ZodISODateTime:()=>Ht,ZodISODuration:()=>Wt,ZodISOTime:()=>Bt,date:()=>vs,datetime:()=>hs,duration:()=>_s,time:()=>bs});function hs(t){return Da(Ht,t)}function vs(t){return Ra(Jt,t)}function bs(t){return Aa(Bt,t)}function _s(t){return Ca(Wt,t)}var Ht,Jt,Bt,Wt,yn=k(()=>{ie();$n();Ht=u("ZodISODateTime",(t,r)=>{Mi.init(t,r),V.init(t,r)});Jt=u("ZodISODate",(t,r)=>{Li.init(t,r),V.init(t,r)});Bt=u("ZodISOTime",(t,r)=>{qi.init(t,r),V.init(t,r)});Wt=u("ZodISODuration",(t,r)=>{Vi.init(t,r),V.init(t,r)})});var Ul,El,Ce,ys=k(()=>{ie();ie();Ul=(t,r)=>{Ot.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Je(t,n)},flatten:{value:n=>He(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},El=u("ZodError",Ul),Ce=u("ZodError",Ul,{Parent:Error})});var xn,zn,kn,Sn,$s=k(()=>{ie();ys();xn=zr(Ce),zn=kr(Ce),kn=Sr(Ce),Sn=wr(Ce)});function m(t){return Ea(dt,t)}function Zl(t){return Lr(jn,t)}function Dl(t){return qt(Kt,t)}function Rl(t){return qr(ve,t)}function Al(t){return Vr(ve,t)}function Cl(t){return Fr(ve,t)}function Ml(t){return Hr(ve,t)}function Ll(t){return Jr(Pn,t)}function ql(t){return Br(Tn,t)}function Vl(t){return Wr(On,t)}function Fl(t){return Kr(Nn,t)}function Hl(t){return Gr(Un,t)}function Jl(t){return Qr(En,t)}function Bl(t){return Yr(Zn,t)}function Wl(t){return Xr(Dn,t)}function Kl(t){return en(Rn,t)}function Gl(t){return tn(An,t)}function Ql(t){return rn(Cn,t)}function Yl(t){return nn(Mn,t)}function Xl(t){return on(Ln,t)}function em(t){return an(qn,t)}function tm(t){return sn(Vn,t)}function rm(t){return cn(Fn,t)}function nm(t,r,n={}){return ps(xs,t,r,n)}function Z(t){return Ma(pt,t)}function wn(t){return qa(Me,t)}function om(t){return Va(Me,t)}function im(t){return Fa(Me,t)}function am(t){return Ha(Me,t)}function sm(t){return Ja(Me,t)}function W(t){return Ba(ft,t)}function cm(t){return Ka(gt,t)}function um(t){return Qa(Hn,t)}function lm(t){return Ya(Hn,t)}function mm(t){return Xa(zs,t)}function dm(t){return es(ks,t)}function Yt(t){return ts(Ss,t)}function pm(){return rs(ws)}function H(){return Ye(Is)}function Xt(t){return ns(js,t)}function fm(t){return os(Ps,t)}function gm(t){return is(er,t)}function N(t,r){return Vt(Ts,t,r)}function hm(t){let r=t._zod.def.shape;return I(Object.keys(r))}function z(t,r){let n={type:"object",get shape(){return y.assignProp(this,"shape",{...t}),this.shape},...y.normalizeParams(r)};return new tr(n)}function vm(t,r){return new tr({type:"object",get shape(){return y.assignProp(this,"shape",{...t}),this.shape},catchall:Xt(),...y.normalizeParams(r)})}function Q(t,r){return new tr({type:"object",get shape(){return y.assignProp(this,"shape",{...t}),this.shape},catchall:H(),...y.normalizeParams(r)})}function M(t,r){return new Jn({type:"union",options:t,...y.normalizeParams(r)})}function rr(t,r,n){return new Os({type:"union",options:r,discriminator:t,...y.normalizeParams(n)})}function ht(t,r){return new Ns({type:"intersection",left:t,right:r})}function bm(t,r,n){let i=r instanceof T,e=i?n:r,o=i?r:null;return new Us({type:"tuple",items:t,rest:o,...y.normalizeParams(e)})}function L(t,r,n){return new Bn({type:"record",keyType:t,valueType:r,...y.normalizeParams(n)})}function _m(t,r,n){return new Bn({type:"record",keyType:M([t,Xt()]),valueType:r,...y.normalizeParams(n)})}function ym(t,r,n){return new Es({type:"map",keyType:t,valueType:r,...y.normalizeParams(n)})}function $m(t,r){return new Zs({type:"set",valueType:t,...y.normalizeParams(r)})}function te(t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(i=>[i,i])):t;return new mt({type:"enum",entries:n,...y.normalizeParams(r)})}function xm(t,r){return new mt({type:"enum",entries:t,...y.normalizeParams(r)})}function I(t,r){return new Ds({type:"literal",values:Array.isArray(t)?t:[t],...y.normalizeParams(r)})}function zm(t){return us(Rs,t)}function Kn(t){return new Wn({type:"transform",transform:t})}function F(t){return new Gn({type:"optional",innerType:t})}function Gt(t){return new As({type:"nullable",innerType:t})}function km(t){return F(Gt(t))}function Ms(t,r){return new Cs({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}function qs(t,r){return new Ls({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}function Vs(t,r){return new Qn({type:"nonoptional",innerType:t,...y.normalizeParams(r)})}function Sm(t){return new Fs({type:"success",innerType:t})}function Js(t,r){return new Hs({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function wm(t){return ss(Bs,t)}function Qt(t,r){return new Yn({type:"pipe",in:t,out:r})}function Ks(t){return new Ws({type:"readonly",innerType:t})}function Im(t,r){return new Gs({type:"template_literal",parts:t,...y.normalizeParams(r)})}function Ys(t){return new Qs({type:"lazy",getter:t})}function jm(t){return new Xs({type:"promise",innerType:t})}function ec(t){let r=new J({check:"custom"});return r._zod.check=t,r}function Xn(t,r){return ls(nr,t??(()=>!0),r)}function tc(t,r={}){return ms(nr,t,r)}function rc(t){let r=ec(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(y.issue(i,n.value,r._zod.def));else{let e=i;e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=n.value),e.inst??(e.inst=r),e.continue??(e.continue=!r._zod.def.abort),n.issues.push(y.issue(e))}},t(n.value,n)));return r}function Pm(t,r={error:`Input not instance of ${t.name}`}){let n=new nr({type:"custom",check:"custom",fn:i=>i instanceof t,abort:!0,...y.normalizeParams(r)});return n._zod.bag.Class=t,n}function Om(t){let r=Ys(()=>M([m(t),Z(),W(),Yt(),N(r),L(m(),r)]));return r}function or(t,r){return Qt(Kn(t),r)}var O,In,dt,V,jn,Kt,ve,Pn,Tn,On,Nn,Un,En,Zn,Dn,Rn,An,Cn,Mn,Ln,qn,Vn,Fn,xs,pt,Me,ft,gt,Hn,zs,ks,Ss,ws,Is,js,Ps,er,Ts,tr,Jn,Os,Ns,Us,Bn,Es,Zs,mt,Ds,Rs,Wn,Gn,As,Cs,Ls,Qn,Fs,Hs,Bs,Yn,Ws,Gs,Qs,Xs,nr,Tm,$n=k(()=>{ie();ie();gs();yn();$s();O=u("ZodType",(t,r)=>(T.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...n)=>t.clone({...r,checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),t.clone=(n,i)=>ne(t,n,i),t.brand=()=>t,t.register=((n,i)=>(n.add(t,i),t)),t.parse=(n,i)=>xn(t,n,i,{callee:t.parse}),t.safeParse=(n,i)=>kn(t,n,i),t.parseAsync=async(n,i)=>zn(t,n,i,{callee:t.parseAsync}),t.safeParseAsync=async(n,i)=>Sn(t,n,i),t.spa=t.safeParseAsync,t.refine=(n,i)=>t.check(tc(n,i)),t.superRefine=n=>t.check(rc(n)),t.overwrite=n=>t.check(ge(n)),t.optional=()=>F(t),t.nullable=()=>Gt(t),t.nullish=()=>F(Gt(t)),t.nonoptional=n=>Vs(t,n),t.array=()=>N(t),t.or=n=>M([t,n]),t.and=n=>ht(t,n),t.transform=n=>Qt(t,Kn(n)),t.default=n=>Ms(t,n),t.prefault=n=>qs(t,n),t.catch=n=>Js(t,n),t.pipe=n=>Qt(t,n),t.readonly=()=>Ks(t),t.describe=n=>{let i=t.clone();return me.add(i,{description:n}),i},Object.defineProperty(t,"description",{get(){return me.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return me.get(t);let i=t.clone();return me.add(i,n[0]),i},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),In=u("_ZodString",(t,r)=>{Ue.init(t,r),O.init(t,r);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...i)=>t.check(et(...i)),t.includes=(...i)=>t.check(nt(...i)),t.startsWith=(...i)=>t.check(ot(...i)),t.endsWith=(...i)=>t.check(it(...i)),t.min=(...i)=>t.check(_e(...i)),t.max=(...i)=>t.check(De(...i)),t.length=(...i)=>t.check(Re(...i)),t.nonempty=(...i)=>t.check(_e(1,...i)),t.lowercase=i=>t.check(tt(i)),t.uppercase=i=>t.check(rt(i)),t.trim=()=>t.check(ct()),t.normalize=(...i)=>t.check(st(...i)),t.toLowerCase=()=>t.check(ut()),t.toUpperCase=()=>t.check(lt())}),dt=u("ZodString",(t,r)=>{Ue.init(t,r),In.init(t,r),t.email=n=>t.check(Lr(jn,n)),t.url=n=>t.check(Jr(Pn,n)),t.jwt=n=>t.check(cn(Fn,n)),t.emoji=n=>t.check(Br(Tn,n)),t.guid=n=>t.check(qt(Kt,n)),t.uuid=n=>t.check(qr(ve,n)),t.uuidv4=n=>t.check(Vr(ve,n)),t.uuidv6=n=>t.check(Fr(ve,n)),t.uuidv7=n=>t.check(Hr(ve,n)),t.nanoid=n=>t.check(Wr(On,n)),t.guid=n=>t.check(qt(Kt,n)),t.cuid=n=>t.check(Kr(Nn,n)),t.cuid2=n=>t.check(Gr(Un,n)),t.ulid=n=>t.check(Qr(En,n)),t.base64=n=>t.check(on(Ln,n)),t.base64url=n=>t.check(an(qn,n)),t.xid=n=>t.check(Yr(Zn,n)),t.ksuid=n=>t.check(Xr(Dn,n)),t.ipv4=n=>t.check(en(Rn,n)),t.ipv6=n=>t.check(tn(An,n)),t.cidrv4=n=>t.check(rn(Cn,n)),t.cidrv6=n=>t.check(nn(Mn,n)),t.e164=n=>t.check(sn(Vn,n)),t.datetime=n=>t.check(hs(n)),t.date=n=>t.check(vs(n)),t.time=n=>t.check(bs(n)),t.duration=n=>t.check(_s(n))});V=u("ZodStringFormat",(t,r)=>{q.init(t,r),In.init(t,r)}),jn=u("ZodEmail",(t,r)=>{Oi.init(t,r),V.init(t,r)});Kt=u("ZodGUID",(t,r)=>{Pi.init(t,r),V.init(t,r)});ve=u("ZodUUID",(t,r)=>{Ti.init(t,r),V.init(t,r)});Pn=u("ZodURL",(t,r)=>{Ni.init(t,r),V.init(t,r)});Tn=u("ZodEmoji",(t,r)=>{Ui.init(t,r),V.init(t,r)});On=u("ZodNanoID",(t,r)=>{Ei.init(t,r),V.init(t,r)});Nn=u("ZodCUID",(t,r)=>{Zi.init(t,r),V.init(t,r)});Un=u("ZodCUID2",(t,r)=>{Di.init(t,r),V.init(t,r)});En=u("ZodULID",(t,r)=>{Ri.init(t,r),V.init(t,r)});Zn=u("ZodXID",(t,r)=>{Ai.init(t,r),V.init(t,r)});Dn=u("ZodKSUID",(t,r)=>{Ci.init(t,r),V.init(t,r)});Rn=u("ZodIPv4",(t,r)=>{Fi.init(t,r),V.init(t,r)});An=u("ZodIPv6",(t,r)=>{Hi.init(t,r),V.init(t,r)});Cn=u("ZodCIDRv4",(t,r)=>{Ji.init(t,r),V.init(t,r)});Mn=u("ZodCIDRv6",(t,r)=>{Bi.init(t,r),V.init(t,r)});Ln=u("ZodBase64",(t,r)=>{Ki.init(t,r),V.init(t,r)});qn=u("ZodBase64URL",(t,r)=>{Gi.init(t,r),V.init(t,r)});Vn=u("ZodE164",(t,r)=>{Qi.init(t,r),V.init(t,r)});Fn=u("ZodJWT",(t,r)=>{Yi.init(t,r),V.init(t,r)});xs=u("ZodCustomStringFormat",(t,r)=>{Xi.init(t,r),V.init(t,r)});pt=u("ZodNumber",(t,r)=>{Zr.init(t,r),O.init(t,r),t.gt=(i,e)=>t.check(fe(i,e)),t.gte=(i,e)=>t.check(re(i,e)),t.min=(i,e)=>t.check(re(i,e)),t.lt=(i,e)=>t.check(pe(i,e)),t.lte=(i,e)=>t.check(se(i,e)),t.max=(i,e)=>t.check(se(i,e)),t.int=i=>t.check(wn(i)),t.safe=i=>t.check(wn(i)),t.positive=i=>t.check(fe(0,i)),t.nonnegative=i=>t.check(re(0,i)),t.negative=i=>t.check(pe(0,i)),t.nonpositive=i=>t.check(se(0,i)),t.multipleOf=(i,e)=>t.check(ke(i,e)),t.step=(i,e)=>t.check(ke(i,e)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});Me=u("ZodNumberFormat",(t,r)=>{ea.init(t,r),pt.init(t,r)});ft=u("ZodBoolean",(t,r)=>{Dt.init(t,r),O.init(t,r)});gt=u("ZodBigInt",(t,r)=>{Dr.init(t,r),O.init(t,r),t.gte=(i,e)=>t.check(re(i,e)),t.min=(i,e)=>t.check(re(i,e)),t.gt=(i,e)=>t.check(fe(i,e)),t.gte=(i,e)=>t.check(re(i,e)),t.min=(i,e)=>t.check(re(i,e)),t.lt=(i,e)=>t.check(pe(i,e)),t.lte=(i,e)=>t.check(se(i,e)),t.max=(i,e)=>t.check(se(i,e)),t.positive=i=>t.check(fe(BigInt(0),i)),t.negative=i=>t.check(pe(BigInt(0),i)),t.nonpositive=i=>t.check(se(BigInt(0),i)),t.nonnegative=i=>t.check(re(BigInt(0),i)),t.multipleOf=(i,e)=>t.check(ke(i,e));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});Hn=u("ZodBigIntFormat",(t,r)=>{ta.init(t,r),gt.init(t,r)});zs=u("ZodSymbol",(t,r)=>{ra.init(t,r),O.init(t,r)});ks=u("ZodUndefined",(t,r)=>{na.init(t,r),O.init(t,r)});Ss=u("ZodNull",(t,r)=>{oa.init(t,r),O.init(t,r)});ws=u("ZodAny",(t,r)=>{ia.init(t,r),O.init(t,r)});Is=u("ZodUnknown",(t,r)=>{Ke.init(t,r),O.init(t,r)});js=u("ZodNever",(t,r)=>{aa.init(t,r),O.init(t,r)});Ps=u("ZodVoid",(t,r)=>{sa.init(t,r),O.init(t,r)});er=u("ZodDate",(t,r)=>{ca.init(t,r),O.init(t,r),t.min=(i,e)=>t.check(re(i,e)),t.max=(i,e)=>t.check(se(i,e));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});Ts=u("ZodArray",(t,r)=>{Rt.init(t,r),O.init(t,r),t.element=r.element,t.min=(n,i)=>t.check(_e(n,i)),t.nonempty=n=>t.check(_e(1,n)),t.max=(n,i)=>t.check(De(n,i)),t.length=(n,i)=>t.check(Re(n,i)),t.unwrap=()=>t.element});tr=u("ZodObject",(t,r)=>{ua.init(t,r),O.init(t,r),y.defineLazy(t,"shape",()=>r.shape),t.keyof=()=>te(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:H()}),t.loose=()=>t.clone({...t._zod.def,catchall:H()}),t.strict=()=>t.clone({...t._zod.def,catchall:Xt()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>y.extend(t,n),t.merge=n=>y.merge(t,n),t.pick=n=>y.pick(t,n),t.omit=n=>y.omit(t,n),t.partial=(...n)=>y.partial(Gn,t,n[0]),t.required=(...n)=>y.required(Qn,t,n[0])});Jn=u("ZodUnion",(t,r)=>{Rr.init(t,r),O.init(t,r),t.options=r.options});Os=u("ZodDiscriminatedUnion",(t,r)=>{Jn.init(t,r),la.init(t,r)});Ns=u("ZodIntersection",(t,r)=>{ma.init(t,r),O.init(t,r)});Us=u("ZodTuple",(t,r)=>{Ee.init(t,r),O.init(t,r),t.rest=n=>t.clone({...t._zod.def,rest:n})});Bn=u("ZodRecord",(t,r)=>{da.init(t,r),O.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});Es=u("ZodMap",(t,r)=>{pa.init(t,r),O.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});Zs=u("ZodSet",(t,r)=>{fa.init(t,r),O.init(t,r),t.min=(...n)=>t.check(Se(...n)),t.nonempty=n=>t.check(Se(1,n)),t.max=(...n)=>t.check(Ze(...n)),t.size=(...n)=>t.check(Xe(...n))});mt=u("ZodEnum",(t,r)=>{ga.init(t,r),O.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);let n=new Set(Object.keys(r.entries));t.extract=(i,e)=>{let o={};for(let a of i)if(n.has(a))o[a]=r.entries[a];else throw new Error(`Key ${a} not found in enum`);return new mt({...r,checks:[],...y.normalizeParams(e),entries:o})},t.exclude=(i,e)=>{let o={...r.entries};for(let a of i)if(n.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new mt({...r,checks:[],...y.normalizeParams(e),entries:o})}});Ds=u("ZodLiteral",(t,r)=>{ha.init(t,r),O.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});Rs=u("ZodFile",(t,r)=>{va.init(t,r),O.init(t,r),t.min=(n,i)=>t.check(Se(n,i)),t.max=(n,i)=>t.check(Ze(n,i)),t.mime=(n,i)=>t.check(at(Array.isArray(n)?n:[n],i))});Wn=u("ZodTransform",(t,r)=>{At.init(t,r),O.init(t,r),t._zod.parse=(n,i)=>{n.addIssue=o=>{if(typeof o=="string")n.issues.push(y.issue(o,n.value,r));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),n.issues.push(y.issue(a))}};let e=r.transform(n.value,n);return e instanceof Promise?e.then(o=>(n.value=o,n)):(n.value=e,n)}});Gn=u("ZodOptional",(t,r)=>{ba.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});As=u("ZodNullable",(t,r)=>{_a.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Cs=u("ZodDefault",(t,r)=>{ya.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Ls=u("ZodPrefault",(t,r)=>{$a.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Qn=u("ZodNonOptional",(t,r)=>{xa.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Fs=u("ZodSuccess",(t,r)=>{za.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});Hs=u("ZodCatch",(t,r)=>{ka.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Bs=u("ZodNaN",(t,r)=>{Sa.init(t,r),O.init(t,r)});Yn=u("ZodPipe",(t,r)=>{Ct.init(t,r),O.init(t,r),t.in=r.in,t.out=r.out});Ws=u("ZodReadonly",(t,r)=>{wa.init(t,r),O.init(t,r)});Gs=u("ZodTemplateLiteral",(t,r)=>{Ia.init(t,r),O.init(t,r)});Qs=u("ZodLazy",(t,r)=>{Pa.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.getter()});Xs=u("ZodPromise",(t,r)=>{ja.init(t,r),O.init(t,r),t.unwrap=()=>t._zod.def.innerType});nr=u("ZodCustom",(t,r)=>{Ta.init(t,r),O.init(t,r)});Tm=(...t)=>ds({Pipe:Yn,Boolean:ft,String:dt,Transform:Wn},...t)});function Um(t){B({customError:t})}function Em(){return B().customError}var Nm,Zm=k(()=>{ie();Nm={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"}});var eo={};$e(eo,{bigint:()=>Bp,boolean:()=>Jp,date:()=>Wp,number:()=>Hp,string:()=>Fp});function Fp(t){return Za(dt,t)}function Hp(t){return La(pt,t)}function Jp(t){return Wa(ft,t)}function Bp(t){return Ga(gt,t)}function Wp(t){return as(er,t)}var Dm=k(()=>{ie();$n()});var s={};$e(s,{$brand:()=>_r,$input:()=>Mr,$output:()=>Cr,NEVER:()=>br,TimePrecision:()=>un,ZodAny:()=>ws,ZodArray:()=>Ts,ZodBase64:()=>Ln,ZodBase64URL:()=>qn,ZodBigInt:()=>gt,ZodBigIntFormat:()=>Hn,ZodBoolean:()=>ft,ZodCIDRv4:()=>Cn,ZodCIDRv6:()=>Mn,ZodCUID:()=>Nn,ZodCUID2:()=>Un,ZodCatch:()=>Hs,ZodCustom:()=>nr,ZodCustomStringFormat:()=>xs,ZodDate:()=>er,ZodDefault:()=>Cs,ZodDiscriminatedUnion:()=>Os,ZodE164:()=>Vn,ZodEmail:()=>jn,ZodEmoji:()=>Tn,ZodEnum:()=>mt,ZodError:()=>El,ZodFile:()=>Rs,ZodGUID:()=>Kt,ZodIPv4:()=>Rn,ZodIPv6:()=>An,ZodISODate:()=>Jt,ZodISODateTime:()=>Ht,ZodISODuration:()=>Wt,ZodISOTime:()=>Bt,ZodIntersection:()=>Ns,ZodIssueCode:()=>Nm,ZodJWT:()=>Fn,ZodKSUID:()=>Dn,ZodLazy:()=>Qs,ZodLiteral:()=>Ds,ZodMap:()=>Es,ZodNaN:()=>Bs,ZodNanoID:()=>On,ZodNever:()=>js,ZodNonOptional:()=>Qn,ZodNull:()=>Ss,ZodNullable:()=>As,ZodNumber:()=>pt,ZodNumberFormat:()=>Me,ZodObject:()=>tr,ZodOptional:()=>Gn,ZodPipe:()=>Yn,ZodPrefault:()=>Ls,ZodPromise:()=>Xs,ZodReadonly:()=>Ws,ZodRealError:()=>Ce,ZodRecord:()=>Bn,ZodSet:()=>Zs,ZodString:()=>dt,ZodStringFormat:()=>V,ZodSuccess:()=>Fs,ZodSymbol:()=>zs,ZodTemplateLiteral:()=>Gs,ZodTransform:()=>Wn,ZodTuple:()=>Us,ZodType:()=>O,ZodULID:()=>En,ZodURL:()=>Pn,ZodUUID:()=>ve,ZodUndefined:()=>ks,ZodUnion:()=>Jn,ZodUnknown:()=>Is,ZodVoid:()=>Ps,ZodXID:()=>Zn,_ZodString:()=>In,_default:()=>Ms,any:()=>pm,array:()=>N,base64:()=>Xl,base64url:()=>em,bigint:()=>cm,boolean:()=>W,catch:()=>Js,check:()=>ec,cidrv4:()=>Ql,cidrv6:()=>Yl,clone:()=>ne,coerce:()=>eo,config:()=>B,core:()=>he,cuid:()=>Fl,cuid2:()=>Hl,custom:()=>Xn,date:()=>gm,discriminatedUnion:()=>rr,e164:()=>tm,email:()=>Zl,emoji:()=>ql,endsWith:()=>it,enum:()=>te,file:()=>zm,flattenError:()=>He,float32:()=>om,float64:()=>im,formatError:()=>Je,function:()=>hn,getErrorMap:()=>Em,globalRegistry:()=>me,gt:()=>fe,gte:()=>re,guid:()=>Dl,includes:()=>nt,instanceof:()=>Pm,int:()=>wn,int32:()=>am,int64:()=>um,intersection:()=>ht,ipv4:()=>Kl,ipv6:()=>Gl,iso:()=>Ae,json:()=>Om,jwt:()=>rm,keyof:()=>hm,ksuid:()=>Wl,lazy:()=>Ys,length:()=>Re,literal:()=>I,locales:()=>Ge,looseObject:()=>Q,lowercase:()=>tt,lt:()=>pe,lte:()=>se,map:()=>ym,maxLength:()=>De,maxSize:()=>Ze,mime:()=>at,minLength:()=>_e,minSize:()=>Se,multipleOf:()=>ke,nan:()=>wm,nanoid:()=>Vl,nativeEnum:()=>xm,negative:()=>mn,never:()=>Xt,nonnegative:()=>pn,nonoptional:()=>Vs,nonpositive:()=>dn,normalize:()=>st,null:()=>Yt,nullable:()=>Gt,nullish:()=>km,number:()=>Z,object:()=>z,optional:()=>F,overwrite:()=>ge,parse:()=>xn,parseAsync:()=>zn,partialRecord:()=>_m,pipe:()=>Qt,positive:()=>ln,prefault:()=>qs,preprocess:()=>or,prettifyError:()=>xr,promise:()=>jm,property:()=>fn,readonly:()=>Ks,record:()=>L,refine:()=>tc,regex:()=>et,regexes:()=>ze,registry:()=>Lt,safeParse:()=>kn,safeParseAsync:()=>Sn,set:()=>$m,setErrorMap:()=>Um,size:()=>Xe,startsWith:()=>ot,strictObject:()=>vm,string:()=>m,stringFormat:()=>nm,stringbool:()=>Tm,success:()=>Sm,superRefine:()=>rc,symbol:()=>mm,templateLiteral:()=>Im,toJSONSchema:()=>vn,toLowerCase:()=>ut,toUpperCase:()=>lt,transform:()=>Kn,treeifyError:()=>$r,trim:()=>ct,tuple:()=>bm,uint32:()=>sm,uint64:()=>lm,ulid:()=>Jl,undefined:()=>dm,union:()=>M,unknown:()=>H,uppercase:()=>rt,url:()=>Ll,uuid:()=>Rl,uuidv4:()=>Al,uuidv6:()=>Cl,uuidv7:()=>Ml,void:()=>fm,xid:()=>Bl});var nc=k(()=>{ie();$n();gs();ys();$s();Zm();ie();Oa();ie();Na();yn();yn();Dm();B(Ar())});var Rm,oc=k(()=>{nc();nc();Rm=s});var ic={};$e(ic,{$brand:()=>_r,$input:()=>Mr,$output:()=>Cr,NEVER:()=>br,TimePrecision:()=>un,ZodAny:()=>ws,ZodArray:()=>Ts,ZodBase64:()=>Ln,ZodBase64URL:()=>qn,ZodBigInt:()=>gt,ZodBigIntFormat:()=>Hn,ZodBoolean:()=>ft,ZodCIDRv4:()=>Cn,ZodCIDRv6:()=>Mn,ZodCUID:()=>Nn,ZodCUID2:()=>Un,ZodCatch:()=>Hs,ZodCustom:()=>nr,ZodCustomStringFormat:()=>xs,ZodDate:()=>er,ZodDefault:()=>Cs,ZodDiscriminatedUnion:()=>Os,ZodE164:()=>Vn,ZodEmail:()=>jn,ZodEmoji:()=>Tn,ZodEnum:()=>mt,ZodError:()=>El,ZodFile:()=>Rs,ZodGUID:()=>Kt,ZodIPv4:()=>Rn,ZodIPv6:()=>An,ZodISODate:()=>Jt,ZodISODateTime:()=>Ht,ZodISODuration:()=>Wt,ZodISOTime:()=>Bt,ZodIntersection:()=>Ns,ZodIssueCode:()=>Nm,ZodJWT:()=>Fn,ZodKSUID:()=>Dn,ZodLazy:()=>Qs,ZodLiteral:()=>Ds,ZodMap:()=>Es,ZodNaN:()=>Bs,ZodNanoID:()=>On,ZodNever:()=>js,ZodNonOptional:()=>Qn,ZodNull:()=>Ss,ZodNullable:()=>As,ZodNumber:()=>pt,ZodNumberFormat:()=>Me,ZodObject:()=>tr,ZodOptional:()=>Gn,ZodPipe:()=>Yn,ZodPrefault:()=>Ls,ZodPromise:()=>Xs,ZodReadonly:()=>Ws,ZodRealError:()=>Ce,ZodRecord:()=>Bn,ZodSet:()=>Zs,ZodString:()=>dt,ZodStringFormat:()=>V,ZodSuccess:()=>Fs,ZodSymbol:()=>zs,ZodTemplateLiteral:()=>Gs,ZodTransform:()=>Wn,ZodTuple:()=>Us,ZodType:()=>O,ZodULID:()=>En,ZodURL:()=>Pn,ZodUUID:()=>ve,ZodUndefined:()=>ks,ZodUnion:()=>Jn,ZodUnknown:()=>Is,ZodVoid:()=>Ps,ZodXID:()=>Zn,_ZodString:()=>In,_default:()=>Ms,any:()=>pm,array:()=>N,base64:()=>Xl,base64url:()=>em,bigint:()=>cm,boolean:()=>W,catch:()=>Js,check:()=>ec,cidrv4:()=>Ql,cidrv6:()=>Yl,clone:()=>ne,coerce:()=>eo,config:()=>B,core:()=>he,cuid:()=>Fl,cuid2:()=>Hl,custom:()=>Xn,date:()=>gm,default:()=>Kp,discriminatedUnion:()=>rr,e164:()=>tm,email:()=>Zl,emoji:()=>ql,endsWith:()=>it,enum:()=>te,file:()=>zm,flattenError:()=>He,float32:()=>om,float64:()=>im,formatError:()=>Je,function:()=>hn,getErrorMap:()=>Em,globalRegistry:()=>me,gt:()=>fe,gte:()=>re,guid:()=>Dl,includes:()=>nt,instanceof:()=>Pm,int:()=>wn,int32:()=>am,int64:()=>um,intersection:()=>ht,ipv4:()=>Kl,ipv6:()=>Gl,iso:()=>Ae,json:()=>Om,jwt:()=>rm,keyof:()=>hm,ksuid:()=>Wl,lazy:()=>Ys,length:()=>Re,literal:()=>I,locales:()=>Ge,looseObject:()=>Q,lowercase:()=>tt,lt:()=>pe,lte:()=>se,map:()=>ym,maxLength:()=>De,maxSize:()=>Ze,mime:()=>at,minLength:()=>_e,minSize:()=>Se,multipleOf:()=>ke,nan:()=>wm,nanoid:()=>Vl,nativeEnum:()=>xm,negative:()=>mn,never:()=>Xt,nonnegative:()=>pn,nonoptional:()=>Vs,nonpositive:()=>dn,normalize:()=>st,null:()=>Yt,nullable:()=>Gt,nullish:()=>km,number:()=>Z,object:()=>z,optional:()=>F,overwrite:()=>ge,parse:()=>xn,parseAsync:()=>zn,partialRecord:()=>_m,pipe:()=>Qt,positive:()=>ln,prefault:()=>qs,preprocess:()=>or,prettifyError:()=>xr,promise:()=>jm,property:()=>fn,readonly:()=>Ks,record:()=>L,refine:()=>tc,regex:()=>et,regexes:()=>ze,registry:()=>Lt,safeParse:()=>kn,safeParseAsync:()=>Sn,set:()=>$m,setErrorMap:()=>Um,size:()=>Xe,startsWith:()=>ot,strictObject:()=>vm,string:()=>m,stringFormat:()=>nm,stringbool:()=>Tm,success:()=>Sm,superRefine:()=>rc,symbol:()=>mm,templateLiteral:()=>Im,toJSONSchema:()=>vn,toLowerCase:()=>ut,toUpperCase:()=>lt,transform:()=>Kn,treeifyError:()=>$r,trim:()=>ct,tuple:()=>bm,uint32:()=>sm,uint64:()=>lm,ulid:()=>Jl,undefined:()=>dm,union:()=>M,unknown:()=>H,uppercase:()=>rt,url:()=>Ll,uuid:()=>Rl,uuidv4:()=>Al,uuidv6:()=>Cl,uuidv7:()=>Ml,void:()=>fm,xid:()=>Bl,z:()=>s});var Kp,ir=k(()=>{oc();oc();Kp=Rm});ie();function bn(t){return!!t._zod}function _n(t,r){return bn(t)?Be(t,r):t.safeParse(r)}function Tl(t){if(!t)return;let r;if(bn(t)?r=t._zod?.def?.shape:r=t.shape,!!r){if(typeof r=="function")try{return r()}catch{return}return r}}function Ol(t){if(bn(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=t.value;if(i!==void 0)return i}ir();var we="io.modelcontextprotocol/related-task",ro="2.0",G=Xn(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Am=M([m(),Z().int()]),Cm=m(),Ob=Q({ttl:Z().optional(),pollInterval:Z().optional()}),Gp=z({ttl:Z().optional()}),Qp=z({taskId:m()}),sc=Q({progressToken:Am.optional(),[we]:Qp.optional()}),ce=z({_meta:sc.optional()}),ar=ce.extend({task:Gp.optional()}),Mm=t=>ar.safeParse(t).success,Y=z({method:m(),params:ce.loose().optional()}),ue=z({_meta:sc.optional()}),le=z({method:m(),params:ue.loose().optional()}),X=Q({_meta:sc.optional()}),bt=M([m(),Z().int()]),Lm=z({jsonrpc:I(ro),id:bt,...Y.shape}).strict(),cc=t=>Lm.safeParse(t).success,qm=z({jsonrpc:I(ro),...le.shape}).strict(),Vm=t=>qm.safeParse(t).success,uc=z({jsonrpc:I(ro),id:bt,result:X}).strict(),sr=t=>uc.safeParse(t).success;var C;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(C||(C={}));var lc=z({jsonrpc:I(ro),id:bt.optional(),error:z({code:Z().int(),message:m(),data:H().optional()})}).strict();var Fm=t=>lc.safeParse(t).success;var Hm=M([Lm,qm,uc,lc]),Nb=M([uc,lc]),no=X.strict(),Yp=ue.extend({requestId:bt.optional(),reason:m().optional()}),oo=le.extend({method:I("notifications/cancelled"),params:Yp}),Xp=z({src:m(),mimeType:m().optional(),sizes:N(m()).optional(),theme:te(["light","dark"]).optional()}),cr=z({icons:N(Xp).optional()}),vt=z({name:m(),title:m().optional()}),ur=vt.extend({...vt.shape,...cr.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),ef=ht(z({applyDefaults:W().optional()}),L(m(),H())),tf=or(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ht(z({form:ef.optional(),url:G.optional()}),L(m(),H()).optional())),rf=Q({list:G.optional(),cancel:G.optional(),requests:Q({sampling:Q({createMessage:G.optional()}).optional(),elicitation:Q({create:G.optional()}).optional()}).optional()}),nf=Q({list:G.optional(),cancel:G.optional(),requests:Q({tools:Q({call:G.optional()}).optional()}).optional()}),of=z({experimental:L(m(),G).optional(),sampling:z({context:G.optional(),tools:G.optional()}).optional(),elicitation:tf.optional(),roots:z({listChanged:W().optional()}).optional(),tasks:rf.optional(),extensions:L(m(),G).optional()}),af=ce.extend({protocolVersion:m(),capabilities:of,clientInfo:ur}),sf=Y.extend({method:I("initialize"),params:af});var cf=z({experimental:L(m(),G).optional(),logging:G.optional(),completions:G.optional(),prompts:z({listChanged:W().optional()}).optional(),resources:z({subscribe:W().optional(),listChanged:W().optional()}).optional(),tools:z({listChanged:W().optional()}).optional(),tasks:nf.optional(),extensions:L(m(),G).optional()}),uf=X.extend({protocolVersion:m(),capabilities:cf,serverInfo:ur,instructions:m().optional()}),lf=le.extend({method:I("notifications/initialized"),params:ue.optional()});var _t=Y.extend({method:I("ping"),params:ce.optional()}),mf=z({progress:Z(),total:F(Z()),message:F(m())}),df=z({...ue.shape,...mf.shape,progressToken:Am}),io=le.extend({method:I("notifications/progress"),params:df}),pf=ce.extend({cursor:Cm.optional()}),lr=Y.extend({params:pf.optional()}),mr=X.extend({nextCursor:Cm.optional()}),ff=te(["working","input_required","completed","failed","cancelled"]),dr=z({taskId:m(),status:ff,ttl:M([Z(),Yt()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:F(Z()),statusMessage:F(m())}),ao=X.extend({task:dr}),gf=ue.merge(dr),pr=le.extend({method:I("notifications/tasks/status"),params:gf}),so=Y.extend({method:I("tasks/get"),params:ce.extend({taskId:m()})}),co=X.merge(dr),uo=Y.extend({method:I("tasks/result"),params:ce.extend({taskId:m()})}),Ub=X.loose(),lo=lr.extend({method:I("tasks/list")}),mo=mr.extend({tasks:N(dr)}),po=Y.extend({method:I("tasks/cancel"),params:ce.extend({taskId:m()})}),Jm=X.merge(dr),Bm=z({uri:m(),mimeType:F(m()),_meta:L(m(),H()).optional()}),Wm=Bm.extend({text:m()}),mc=m().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Km=Bm.extend({blob:mc}),fr=te(["user","assistant"]),yt=z({audience:N(fr).optional(),priority:Z().min(0).max(1).optional(),lastModified:Ae.datetime({offset:!0}).optional()}),Gm=z({...vt.shape,...cr.shape,uri:m(),description:F(m()),mimeType:F(m()),size:F(Z()),annotations:yt.optional(),_meta:F(Q({}))}),hf=z({...vt.shape,...cr.shape,uriTemplate:m(),description:F(m()),mimeType:F(m()),annotations:yt.optional(),_meta:F(Q({}))}),vf=lr.extend({method:I("resources/list")}),dc=mr.extend({resources:N(Gm)}),bf=lr.extend({method:I("resources/templates/list")}),_f=mr.extend({resourceTemplates:N(hf)}),pc=ce.extend({uri:m()}),yf=pc,$f=Y.extend({method:I("resources/read"),params:yf}),fc=X.extend({contents:N(M([Wm,Km]))}),xf=le.extend({method:I("notifications/resources/list_changed"),params:ue.optional()}),zf=pc,kf=Y.extend({method:I("resources/subscribe"),params:zf}),Sf=pc,wf=Y.extend({method:I("resources/unsubscribe"),params:Sf}),If=ue.extend({uri:m()}),jf=le.extend({method:I("notifications/resources/updated"),params:If}),Pf=z({name:m(),description:F(m()),required:F(W())}),Tf=z({...vt.shape,...cr.shape,description:F(m()),arguments:F(N(Pf)),_meta:F(Q({}))}),Of=lr.extend({method:I("prompts/list")}),Nf=mr.extend({prompts:N(Tf)}),Uf=ce.extend({name:m(),arguments:L(m(),m()).optional()}),Ef=Y.extend({method:I("prompts/get"),params:Uf}),gc=z({type:I("text"),text:m(),annotations:yt.optional(),_meta:L(m(),H()).optional()}),hc=z({type:I("image"),data:mc,mimeType:m(),annotations:yt.optional(),_meta:L(m(),H()).optional()}),vc=z({type:I("audio"),data:mc,mimeType:m(),annotations:yt.optional(),_meta:L(m(),H()).optional()}),Zf=z({type:I("tool_use"),name:m(),id:m(),input:L(m(),H()),_meta:L(m(),H()).optional()}),bc=z({type:I("resource"),resource:M([Wm,Km]),annotations:yt.optional(),_meta:L(m(),H()).optional()}),_c=Gm.extend({type:I("resource_link")}),$t=M([gc,hc,vc,_c,bc]),Df=z({role:fr,content:$t}),Rf=X.extend({description:m().optional(),messages:N(Df)}),Af=le.extend({method:I("notifications/prompts/list_changed"),params:ue.optional()}),Cf=z({title:m().optional(),readOnlyHint:W().optional(),destructiveHint:W().optional(),idempotentHint:W().optional(),openWorldHint:W().optional()}),Mf=z({taskSupport:te(["required","optional","forbidden"]).optional()}),fo=z({...vt.shape,...cr.shape,description:m().optional(),inputSchema:z({type:I("object"),properties:L(m(),G).optional(),required:N(m()).optional()}).catchall(H()),outputSchema:z({type:I("object"),properties:L(m(),G).optional(),required:N(m()).optional()}).catchall(H()).optional(),annotations:Cf.optional(),execution:Mf.optional(),_meta:L(m(),H()).optional()}),yc=lr.extend({method:I("tools/list")}),Lf=mr.extend({tools:N(fo)}),xt=X.extend({content:N($t).default([]),structuredContent:L(m(),H()).optional(),isError:W().optional()}),Eb=xt.or(X.extend({toolResult:H()})),qf=ar.extend({name:m(),arguments:L(m(),H()).optional()}),$c=Y.extend({method:I("tools/call"),params:qf}),Vf=le.extend({method:I("notifications/tools/list_changed"),params:ue.optional()}),Zb=z({autoRefresh:W().default(!0),debounceMs:Z().int().nonnegative().default(300)}),Qm=te(["debug","info","notice","warning","error","critical","alert","emergency"]),Ff=ce.extend({level:Qm}),Hf=Y.extend({method:I("logging/setLevel"),params:Ff}),Jf=ue.extend({level:Qm,logger:m().optional(),data:H()}),Bf=le.extend({method:I("notifications/message"),params:Jf}),Wf=z({name:m().optional()}),Kf=z({hints:N(Wf).optional(),costPriority:Z().min(0).max(1).optional(),speedPriority:Z().min(0).max(1).optional(),intelligencePriority:Z().min(0).max(1).optional()}),Gf=z({mode:te(["auto","required","none"]).optional()}),Qf=z({type:I("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:N($t).default([]),structuredContent:z({}).loose().optional(),isError:W().optional(),_meta:L(m(),H()).optional()}),Yf=rr("type",[gc,hc,vc]),to=rr("type",[gc,hc,vc,Zf,Qf]),Xf=z({role:fr,content:M([to,N(to)]),_meta:L(m(),H()).optional()}),eg=ar.extend({messages:N(Xf),modelPreferences:Kf.optional(),systemPrompt:m().optional(),includeContext:te(["none","thisServer","allServers"]).optional(),temperature:Z().optional(),maxTokens:Z().int(),stopSequences:N(m()).optional(),metadata:G.optional(),tools:N(fo).optional(),toolChoice:Gf.optional()}),tg=Y.extend({method:I("sampling/createMessage"),params:eg}),xc=X.extend({model:m(),stopReason:F(te(["endTurn","stopSequence","maxTokens"]).or(m())),role:fr,content:Yf}),zc=X.extend({model:m(),stopReason:F(te(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:fr,content:M([to,N(to)])}),rg=z({type:I("boolean"),title:m().optional(),description:m().optional(),default:W().optional()}),ng=z({type:I("string"),title:m().optional(),description:m().optional(),minLength:Z().optional(),maxLength:Z().optional(),format:te(["email","uri","date","date-time"]).optional(),default:m().optional()}),og=z({type:te(["number","integer"]),title:m().optional(),description:m().optional(),minimum:Z().optional(),maximum:Z().optional(),default:Z().optional()}),ig=z({type:I("string"),title:m().optional(),description:m().optional(),enum:N(m()),default:m().optional()}),ag=z({type:I("string"),title:m().optional(),description:m().optional(),oneOf:N(z({const:m(),title:m()})),default:m().optional()}),sg=z({type:I("string"),title:m().optional(),description:m().optional(),enum:N(m()),enumNames:N(m()).optional(),default:m().optional()}),cg=M([ig,ag]),ug=z({type:I("array"),title:m().optional(),description:m().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:z({type:I("string"),enum:N(m())}),default:N(m()).optional()}),lg=z({type:I("array"),title:m().optional(),description:m().optional(),minItems:Z().optional(),maxItems:Z().optional(),items:z({anyOf:N(z({const:m(),title:m()}))}),default:N(m()).optional()}),mg=M([ug,lg]),dg=M([sg,cg,mg]),pg=M([dg,rg,ng,og]),fg=ar.extend({mode:I("form").optional(),message:m(),requestedSchema:z({type:I("object"),properties:L(m(),pg),required:N(m()).optional()})}),gg=ar.extend({mode:I("url"),message:m(),elicitationId:m(),url:m().url()}),hg=M([fg,gg]),vg=Y.extend({method:I("elicitation/create"),params:hg}),bg=ue.extend({elicitationId:m()}),_g=le.extend({method:I("notifications/elicitation/complete"),params:bg}),yg=X.extend({action:te(["accept","decline","cancel"]),content:or(t=>t===null?void 0:t,L(m(),M([m(),Z(),W(),N(m())])).optional())}),$g=z({type:I("ref/resource"),uri:m()});var xg=z({type:I("ref/prompt"),name:m()}),zg=ce.extend({ref:M([xg,$g]),argument:z({name:m(),value:m()}),context:z({arguments:L(m(),m()).optional()}).optional()}),kg=Y.extend({method:I("completion/complete"),params:zg});var Sg=X.extend({completion:Q({values:N(m()).max(100),total:F(Z().int()),hasMore:F(W())})}),wg=z({uri:m().startsWith("file://"),name:m().optional(),_meta:L(m(),H()).optional()}),Ig=Y.extend({method:I("roots/list"),params:ce.optional()}),jg=X.extend({roots:N(wg)}),Pg=le.extend({method:I("notifications/roots/list_changed"),params:ue.optional()}),Db=M([_t,sf,kg,Hf,Ef,Of,vf,bf,$f,kf,wf,$c,yc,so,uo,lo,po]),Rb=M([oo,io,lf,Pg,pr]),Ab=M([no,xc,zc,yg,jg,co,mo,ao]),Cb=M([_t,tg,vg,Ig,so,uo,lo,po]),Mb=M([oo,io,Bf,jf,xf,Vf,Af,pr,_g]),Lb=M([no,uf,Sg,Rf,Nf,dc,_f,fc,xt,Lf,co,mo,ao]),E=class t extends Error{constructor(r,n,i){super(`MCP error ${r}: ${n}`),this.code=r,this.data=i,this.name="McpError"}static fromError(r,n,i){if(r===C.UrlElicitationRequired&&i){let e=i;if(e.elicitations)return new ac(e.elicitations,n)}return new t(r,n,i)}},ac=class extends E{constructor(r,n=`URL elicitation${r.length>1?"s":""} required`){super(C.UrlElicitationRequired,n,{elicitations:r})}get elicitations(){return this.data?.elicitations??[]}};function Ie(t){return t==="completed"||t==="failed"||t==="cancelled"}var Tg=Symbol("Let zodToJsonSchema decide on which parser to use");var y_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function kc(t){let n=Tl(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Ol(n);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Sc(t,r){let n=_n(t,r);if(!n.success)throw n.error;return n.data}var Dg=6e4,go=class{constructor(r){this._options=r,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(oo,n=>{this._oncancel(n)}),this.setNotificationHandler(io,n=>{this._onprogress(n)}),this.setRequestHandler(_t,n=>({})),this._taskStore=r?.taskStore,this._taskMessageQueue=r?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(so,async(n,i)=>{let e=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!e)throw new E(C.InvalidParams,"Failed to retrieve task: Task not found");return{...e}}),this.setRequestHandler(uo,async(n,i)=>{let e=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(c.type==="response"||c.type==="error"){let d=c.message,h=d.id,g=this._requestResolvers.get(h);if(g)if(this._requestResolvers.delete(h),c.type==="response")g(d);else{let l=d,$=new E(l.error.code,l.error.message,l.error.data);g($)}else{let l=c.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${h}`))}continue}await this._transport?.send(c.message,{relatedRequestId:i.requestId})}}let a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new E(C.InvalidParams,`Task not found: ${o}`);if(!Ie(a.status))return await this._waitForTaskUpdate(o,i.signal),await e();if(Ie(a.status)){let c=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[we]:{taskId:o}}}}return await e()};return await e()}),this.setRequestHandler(lo,async(n,i)=>{try{let{tasks:e,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,i.sessionId);return{tasks:e,nextCursor:o,_meta:{}}}catch(e){throw new E(C.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(po,async(n,i)=>{try{let e=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!e)throw new E(C.InvalidParams,`Task not found: ${n.params.taskId}`);if(Ie(e.status))throw new E(C.InvalidParams,`Cannot cancel task in terminal status: ${e.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!o)throw new E(C.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(e){throw e instanceof E?e:new E(C.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(r){if(!r.params.requestId)return;this._requestHandlerAbortControllers.get(r.params.requestId)?.abort(r.params.reason)}_setupTimeout(r,n,i,e,o=!1){this._timeoutInfo.set(r,{timeoutId:setTimeout(e,n),startTime:Date.now(),timeout:n,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:e})}_resetTimeout(r){let n=this._timeoutInfo.get(r);if(!n)return!1;let i=Date.now()-n.startTime;if(n.maxTotalTimeout&&i>=n.maxTotalTimeout)throw this._timeoutInfo.delete(r),E.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:i});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(r){let n=this._timeoutInfo.get(r);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(r))}async connect(r){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=r;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};let e=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{e?.(o,a),sr(o)||Fm(o)?this._onresponse(o):cc(o)?this._onrequest(o,a):Vm(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(let i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();let n=E.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of r.values())i(n)}_onerror(r){this.onerror?.(r)}_onnotification(r){let n=this._notificationHandlers.get(r.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(r)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(r,n){let i=this._requestHandlers.get(r.method)??this.fallbackRequestHandler,e=this._transport,o=r.params?._meta?.[we]?.taskId;if(i===void 0){let g={jsonrpc:"2.0",id:r.id,error:{code:C.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},e?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):e?.send(g).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(r.id,a);let c=Mm(r.params)?r.params.task:void 0,d=this._taskStore?this.requestTaskStore(r,e?.sessionId):void 0,h={signal:a.signal,sessionId:e?.sessionId,_meta:r.params?._meta,sendNotification:async g=>{if(a.signal.aborted)return;let l={relatedRequestId:r.id};o&&(l.relatedTask={taskId:o}),await this.notification(g,l)},sendRequest:async(g,l,$)=>{if(a.signal.aborted)throw new E(C.ConnectionClosed,"Request was cancelled");let b={...$,relatedRequestId:r.id};o&&!b.relatedTask&&(b.relatedTask={taskId:o});let p=b.relatedTask?.taskId??o;return p&&d&&await d.updateTaskStatus(p,"input_required"),await this.request(g,l,b)},authInfo:n?.authInfo,requestId:r.id,requestInfo:n?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(r.method)}).then(()=>i(r,h)).then(async g=>{if(a.signal.aborted)return;let l={result:g,jsonrpc:"2.0",id:r.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},e?.sessionId):await e?.send(l)},async g=>{if(a.signal.aborted)return;let l={jsonrpc:"2.0",id:r.id,error:{code:Number.isSafeInteger(g.code)?g.code:C.InternalError,message:g.message??"Internal error",...g.data!==void 0&&{data:g.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},e?.sessionId):await e?.send(l)}).catch(g=>this._onerror(new Error(`Failed to send response: ${g}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===a&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(r){let{progressToken:n,...i}=r.params,e=Number(n),o=this._progressHandlers.get(e);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(r)}`));return}let a=this._responseHandlers.get(e),c=this._timeoutInfo.get(e);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(e)}catch(d){this._responseHandlers.delete(e),this._progressHandlers.delete(e),this._cleanupTimeout(e),a(d);return}o(i)}_onresponse(r){let n=Number(r.id),i=this._requestResolvers.get(n);if(i){if(this._requestResolvers.delete(n),sr(r))i(r);else{let a=new E(r.error.code,r.error.message,r.error.data);i(a)}return}let e=this._responseHandlers.get(n);if(e===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(r)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(sr(r)&&r.result&&typeof r.result=="object"){let a=r.result;if(a.task&&typeof a.task=="object"){let c=a.task;typeof c.taskId=="string"&&(o=!0,this._taskProgressTokens.set(c.taskId,n))}}if(o||this._progressHandlers.delete(n),sr(r))e(r);else{let a=E.fromError(r.error.code,r.error.message,r.error.data);e(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(r,n,i){let{task:e}=i??{};if(!e){try{yield{type:"result",result:await this.request(r,n,i)}}catch(a){yield{type:"error",error:a instanceof E?a:new E(C.InternalError,String(a))}}return}let o;try{let a=await this.request(r,ao,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new E(C.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:c},Ie(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)}:c.status==="failed"?yield{type:"error",error:new E(C.InternalError,`Task ${o} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new E(C.InternalError,`Task ${o} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)};return}let d=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(h=>setTimeout(h,d)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof E?a:new E(C.InternalError,String(a))}}}request(r,n,i){let{relatedRequestId:e,resumptionToken:o,onresumptiontoken:a,task:c,relatedTask:d}=i??{};return new Promise((h,g)=>{let l=w=>{g(w)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(r.method),c&&this.assertTaskCapability(r.method)}catch(w){l(w);return}i?.signal?.throwIfAborted();let $=this._requestMessageId++,b={...r,jsonrpc:"2.0",id:$};i?.onprogress&&(this._progressHandlers.set($,i.onprogress),b.params={...r.params,_meta:{...r.params?._meta||{},progressToken:$}}),c&&(b.params={...b.params,task:c}),d&&(b.params={...b.params,_meta:{...b.params?._meta||{},[we]:d}});let p=w=>{this._responseHandlers.delete($),this._progressHandlers.delete($),this._cleanupTimeout($),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:$,reason:String(w)}},{relatedRequestId:e,resumptionToken:o,onresumptiontoken:a}).catch(U=>this._onerror(new Error(`Failed to send cancellation: ${U}`)));let j=w instanceof E?w:new E(C.RequestTimeout,String(w));g(j)};this._responseHandlers.set($,w=>{if(!i?.signal?.aborted){if(w instanceof Error)return g(w);try{let j=_n(n,w.result);j.success?h(j.data):g(j.error)}catch(j){g(j)}}}),i?.signal?.addEventListener("abort",()=>{p(i?.signal?.reason)});let x=i?.timeout??Dg,S=()=>p(E.fromError(C.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout($,x,i?.maxTotalTimeout,S,i?.resetTimeoutOnProgress??!1);let R=d?.taskId;if(R){let w=j=>{let U=this._responseHandlers.get($);U?U(j):this._onerror(new Error(`Response handler missing for side-channeled request ${$}`))};this._requestResolvers.set($,w),this._enqueueTaskMessage(R,{type:"request",message:b,timestamp:Date.now()}).catch(j=>{this._cleanupTimeout($),g(j)})}else this._transport.send(b,{relatedRequestId:e,resumptionToken:o,onresumptiontoken:a}).catch(w=>{this._cleanupTimeout($),g(w)})})}async getTask(r,n){return this.request({method:"tasks/get",params:r},co,n)}async getTaskResult(r,n,i){return this.request({method:"tasks/result",params:r},n,i)}async listTasks(r,n){return this.request({method:"tasks/list",params:r},mo,n)}async cancelTask(r,n){return this.request({method:"tasks/cancel",params:r},Jm,n)}async notification(r,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(r.method);let i=n?.relatedTask?.taskId;if(i){let c={...r,jsonrpc:"2.0",params:{...r.params,_meta:{...r.params?._meta||{},[we]:n.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(r.method)&&!r.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(r.method))return;this._pendingDebouncedNotifications.add(r.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(r.method),!this._transport)return;let c={...r,jsonrpc:"2.0"};n?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[we]:n.relatedTask}}}),this._transport?.send(c,n).catch(d=>this._onerror(d))});return}let a={...r,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[we]:n.relatedTask}}}),await this._transport.send(a,n)}setRequestHandler(r,n){let i=kc(r);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(e,o)=>{let a=Sc(r,e);return Promise.resolve(n(a,o))})}removeRequestHandler(r){this._requestHandlers.delete(r)}assertCanSetRequestHandler(r){if(this._requestHandlers.has(r))throw new Error(`A request handler for ${r} already exists, which would be overridden`)}setNotificationHandler(r,n){let i=kc(r);this._notificationHandlers.set(i,e=>{let o=Sc(r,e);return Promise.resolve(n(o))})}removeNotificationHandler(r){this._notificationHandlers.delete(r)}_cleanupTaskProgressHandler(r){let n=this._taskProgressTokens.get(r);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(r))}async _enqueueTaskMessage(r,n,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let e=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(r,n,i,e)}async _clearTaskQueue(r,n){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(r,n);for(let e of i)if(e.type==="request"&&cc(e.message)){let o=e.message.id,a=this._requestResolvers.get(o);a?(a(new E(C.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${r} cleanup`))}}}async _waitForTaskUpdate(r,n){let i=this._options?.defaultTaskPollInterval??1e3;try{let e=await this._taskStore?.getTask(r);e?.pollInterval&&(i=e.pollInterval)}catch{}return new Promise((e,o)=>{if(n.aborted){o(new E(C.InvalidRequest,"Request cancelled"));return}let a=setTimeout(e,i);n.addEventListener("abort",()=>{clearTimeout(a),o(new E(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(r,n){let i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async e=>{if(!r)throw new Error("No request provided");return await i.createTask(e,r.id,{method:r.method,params:r.params},n)},getTask:async e=>{let o=await i.getTask(e,n);if(!o)throw new E(C.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(e,o,a)=>{await i.storeTaskResult(e,o,a,n);let c=await i.getTask(e,n);if(c){let d=pr.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Ie(c.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>i.getTaskResult(e,n),updateTaskStatus:async(e,o,a)=>{let c=await i.getTask(e,n);if(!c)throw new E(C.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Ie(c.status))throw new E(C.InvalidParams,`Cannot update task "${e}" from terminal status "${c.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(e,o,a,n);let d=await i.getTask(e,n);if(d){let h=pr.parse({method:"notifications/tasks/status",params:d});await this.notification(h),Ie(d.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>i.listTasks(e,n)}}};function Ym(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Xm(t,r){let n={...t};for(let i in r){let e=i,o=r[e];if(o===void 0)continue;let a=n[e];Ym(a)&&Ym(o)?n[e]={...a,...o}:n[e]=o}return n}ir();ir();var bx=(t=>typeof Pe<"u"?Pe:typeof Proxy<"u"?new Proxy(t,{get:(r,n)=>(typeof Pe<"u"?Pe:r)[n]}):t)(function(t){if(typeof Pe<"u")return Pe.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),wc=class extends go{constructor(){super(...arguments);A(this,"_registeredMethods",new Set);A(this,"_eventSlots",new Map);A(this,"setRequestHandler",(n,i)=>{this._assertMethodNotRegistered(n,"setRequestHandler"),super.setRequestHandler(n,i)});A(this,"setNotificationHandler",(n,i)=>{this._assertMethodNotRegistered(n,"setNotificationHandler"),super.setNotificationHandler(n,i)});A(this,"replaceRequestHandler",(n,i)=>{let e=n.shape.method.value;this._registeredMethods.add(e),super.setRequestHandler(n,i)})}onEventDispatch(n,i){}_ensureEventSlot(n){let i=this._eventSlots.get(n);if(!i){let e=this.eventSchemas[n];if(!e)throw Error(`Unknown event: ${String(n)}`);i={listeners:[]},this._eventSlots.set(n,i);let o=e.shape.method.value;this._registeredMethods.add(o);let a=i;super.setNotificationHandler(e,c=>{let d=c.params;this.onEventDispatch(n,d),a.onHandler?.(d);for(let h of[...a.listeners])h(d)})}return i}setEventHandler(n,i){let e=this._ensureEventSlot(n);e.onHandler&&i&&console.warn(`[MCP Apps] on${String(n)} handler replaced. Use addEventListener("${String(n)}", \u2026) to add multiple listeners without replacing.`),e.onHandler=i}getEventHandler(n){return this._eventSlots.get(n)?.onHandler}addEventListener(n,i){this._ensureEventSlot(n).listeners.push(i)}removeEventListener(n,i){let e=this._eventSlots.get(n);if(!e)return;let o=e.listeners.indexOf(i);o!==-1&&e.listeners.splice(o,1)}warnIfRequestHandlerReplaced(n,i,e){i&&e&&console.warn(`[MCP Apps] ${n} handler replaced. Previous handler will no longer be called.`)}_assertMethodNotRegistered(n,i){let e=n.shape.method.value;if(this._registeredMethods.has(e))throw Error(`Handler for "${e}" already registered (via ${i}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(e)}},Rg="2026-01-26";var Ag="ui/notifications/tool-input-partial";var Ic=class{constructor(r=window.parent,n){A(this,"eventTarget");A(this,"eventSource");A(this,"messageListener");A(this,"onclose");A(this,"onerror");A(this,"onmessage");A(this,"sessionId");A(this,"setProtocolVersion");this.eventTarget=r,this.eventSource=n,this.messageListener=i=>{if(n&&i.source!==this.eventSource){console.debug("Ignoring message from unknown source",i);return}let e=Hm.safeParse(i.data);e.success?(console.debug("Parsed message",e.data),this.onmessage?.(e.data)):i.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",e.error.message,i):(console.error("Failed to parse message",e.error.message,i),this.onerror?.(Error("Invalid JSON-RPC message received: "+e.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(r,n){r.method!==Ag&&console.debug("Sending message",r),this.eventTarget.postMessage(r,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}},Cg=s.union([s.literal("light"),s.literal("dark")]).describe("Color theme preference for the host environment."),hr=s.union([s.literal("inline"),s.literal("fullscreen"),s.literal("pip")]).describe("Display mode for UI presentation."),Mg=s.union([s.literal("--color-background-primary"),s.literal("--color-background-secondary"),s.literal("--color-background-tertiary"),s.literal("--color-background-inverse"),s.literal("--color-background-ghost"),s.literal("--color-background-info"),s.literal("--color-background-danger"),s.literal("--color-background-success"),s.literal("--color-background-warning"),s.literal("--color-background-disabled"),s.literal("--color-text-primary"),s.literal("--color-text-secondary"),s.literal("--color-text-tertiary"),s.literal("--color-text-inverse"),s.literal("--color-text-ghost"),s.literal("--color-text-info"),s.literal("--color-text-danger"),s.literal("--color-text-success"),s.literal("--color-text-warning"),s.literal("--color-text-disabled"),s.literal("--color-border-primary"),s.literal("--color-border-secondary"),s.literal("--color-border-tertiary"),s.literal("--color-border-inverse"),s.literal("--color-border-ghost"),s.literal("--color-border-info"),s.literal("--color-border-danger"),s.literal("--color-border-success"),s.literal("--color-border-warning"),s.literal("--color-border-disabled"),s.literal("--color-ring-primary"),s.literal("--color-ring-secondary"),s.literal("--color-ring-inverse"),s.literal("--color-ring-info"),s.literal("--color-ring-danger"),s.literal("--color-ring-success"),s.literal("--color-ring-warning"),s.literal("--font-sans"),s.literal("--font-mono"),s.literal("--font-weight-normal"),s.literal("--font-weight-medium"),s.literal("--font-weight-semibold"),s.literal("--font-weight-bold"),s.literal("--font-text-xs-size"),s.literal("--font-text-sm-size"),s.literal("--font-text-md-size"),s.literal("--font-text-lg-size"),s.literal("--font-heading-xs-size"),s.literal("--font-heading-sm-size"),s.literal("--font-heading-md-size"),s.literal("--font-heading-lg-size"),s.literal("--font-heading-xl-size"),s.literal("--font-heading-2xl-size"),s.literal("--font-heading-3xl-size"),s.literal("--font-text-xs-line-height"),s.literal("--font-text-sm-line-height"),s.literal("--font-text-md-line-height"),s.literal("--font-text-lg-line-height"),s.literal("--font-heading-xs-line-height"),s.literal("--font-heading-sm-line-height"),s.literal("--font-heading-md-line-height"),s.literal("--font-heading-lg-line-height"),s.literal("--font-heading-xl-line-height"),s.literal("--font-heading-2xl-line-height"),s.literal("--font-heading-3xl-line-height"),s.literal("--border-radius-xs"),s.literal("--border-radius-sm"),s.literal("--border-radius-md"),s.literal("--border-radius-lg"),s.literal("--border-radius-xl"),s.literal("--border-radius-full"),s.literal("--border-width-regular"),s.literal("--shadow-hairline"),s.literal("--shadow-sm"),s.literal("--shadow-md"),s.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Lg=s.record(Mg.describe(`Style variables for theming MCP apps.Individual style keys are optional - hosts may provide any subset of these values.Values are strings containing CSS values (colors, sizes, font stacks, etc.).@@ -75,10 +75,10 @@ Individual style keys are optional - hosts may provide any subset of these valueValues are strings containing CSS values (colors, sizes, font stacks, etc.).Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`-for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),kx=s.object({method:s.literal("ui/open-link"),params:s.object({url:s.string().describe("URL to open in the host's browser")})}),qg=s.object({isError:s.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),Vg=s.object({isError:s.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),Fg=s.object({isError:s.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),Sx=s.object({method:s.literal("ui/notifications/sandbox-proxy-ready"),params:s.object({})}),Ic=s.object({connectDomains:s.array(s.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).+for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Sx=s.object({method:s.literal("ui/open-link"),params:s.object({url:s.string().describe("URL to open in the host's browser")})}),qg=s.object({isError:s.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),Vg=s.object({isError:s.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),Fg=s.object({isError:s.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),wx=s.object({method:s.literal("ui/notifications/sandbox-proxy-ready"),params:s.object({})}),jc=s.object({connectDomains:s.array(s.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).- Maps to CSP \`connect-src\` directive-- Empty or omitted \u2192 no network connections (secure default)`),resourceDomains:s.array(s.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted \u2192 no network resources (secure default)"),frameDomains:s.array(s.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:s.array(s.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)")}),jc=s.object({camera:s.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:s.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:s.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:s.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),wx=s.object({method:s.literal("ui/notifications/size-changed"),params:s.object({width:s.number().optional().describe("New width in pixels."),height:s.number().optional().describe("New height in pixels.")})}),Hg=s.object({method:s.literal("ui/notifications/tool-input"),params:s.object({arguments:s.record(s.string(),s.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),Jg=s.object({method:s.literal("ui/notifications/tool-input-partial"),params:s.object({arguments:s.record(s.string(),s.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),Bg=s.object({method:s.literal("ui/notifications/tool-cancelled"),params:s.object({reason:s.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Wg=s.object({fonts:s.string().optional()}),Kg=s.object({variables:Lg.optional().describe("CSS variables for theming the app."),css:Wg.optional().describe("CSS blocks that apps can inject.")}),Gg=s.object({method:s.literal("ui/resource-teardown"),params:s.object({})}),Ix=s.record(s.string(),s.unknown()),Ym=s.object({text:s.object({}).optional().describe("Host supports text content blocks."),image:s.object({}).optional().describe("Host supports image content blocks."),audio:s.object({}).optional().describe("Host supports audio content blocks."),resource:s.object({}).optional().describe("Host supports resource content blocks."),resourceLink:s.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:s.object({}).optional().describe("Host supports structured content.")}),jx=s.object({method:s.literal("ui/notifications/request-teardown"),params:s.object({}).optional()}),Qg=s.object({experimental:s.object({}).optional().describe("Experimental features (structure TBD)."),openLinks:s.object({}).optional().describe("Host supports opening external URLs."),downloadFile:s.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:s.object({listChanged:s.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:s.object({listChanged:s.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:s.object({}).optional().describe("Host accepts log messages."),sandbox:s.object({permissions:jc.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Ic.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Ym.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Ym.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:s.object({tools:s.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Yg=s.object({experimental:s.object({}).optional().describe("Experimental features (structure TBD)."),tools:s.object({listChanged:s.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:s.array(hr).optional().describe("Display modes the app supports.")}),Px=s.object({method:s.literal("ui/notifications/initialized"),params:s.object({}).optional()}),Tx=s.object({csp:Ic.optional().describe("Content Security Policy configuration for UI resources."),permissions:jc.optional().describe("Sandbox permissions requested by the UI resource."),domain:s.string().optional().describe(`Dedicated origin for view sandbox.+- Empty or omitted \u2192 no network connections (secure default)`),resourceDomains:s.array(s.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted \u2192 no network resources (secure default)"),frameDomains:s.array(s.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:s.array(s.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)")}),Pc=s.object({camera:s.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:s.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:s.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:s.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Ix=s.object({method:s.literal("ui/notifications/size-changed"),params:s.object({width:s.number().optional().describe("New width in pixels."),height:s.number().optional().describe("New height in pixels.")})}),Hg=s.object({method:s.literal("ui/notifications/tool-input"),params:s.object({arguments:s.record(s.string(),s.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),Jg=s.object({method:s.literal("ui/notifications/tool-input-partial"),params:s.object({arguments:s.record(s.string(),s.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),Bg=s.object({method:s.literal("ui/notifications/tool-cancelled"),params:s.object({reason:s.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Wg=s.object({fonts:s.string().optional()}),Kg=s.object({variables:Lg.optional().describe("CSS variables for theming the app."),css:Wg.optional().describe("CSS blocks that apps can inject.")}),Gg=s.object({method:s.literal("ui/resource-teardown"),params:s.object({})}),jx=s.record(s.string(),s.unknown()),ed=s.object({text:s.object({}).optional().describe("Host supports text content blocks."),image:s.object({}).optional().describe("Host supports image content blocks."),audio:s.object({}).optional().describe("Host supports audio content blocks."),resource:s.object({}).optional().describe("Host supports resource content blocks."),resourceLink:s.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:s.object({}).optional().describe("Host supports structured content.")}),Px=s.object({method:s.literal("ui/notifications/request-teardown"),params:s.object({}).optional()}),Qg=s.object({experimental:s.object({}).optional().describe("Experimental features (structure TBD)."),openLinks:s.object({}).optional().describe("Host supports opening external URLs."),downloadFile:s.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:s.object({listChanged:s.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:s.object({listChanged:s.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:s.object({}).optional().describe("Host accepts log messages."),sandbox:s.object({permissions:Pc.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:jc.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:ed.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:ed.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:s.object({tools:s.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Yg=s.object({experimental:s.object({}).optional().describe("Experimental features (structure TBD)."),tools:s.object({listChanged:s.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:s.array(hr).optional().describe("Display modes the app supports.")}),Tx=s.object({method:s.literal("ui/notifications/initialized"),params:s.object({}).optional()}),Ox=s.object({csp:jc.optional().describe("Content Security Policy configuration for UI resources."),permissions:Pc.optional().describe("Sandbox permissions requested by the UI resource."),domain:s.string().optional().describe(`Dedicated origin for view sandbox.Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.@@ -92,10 +92,10 @@ Boolean requesting whether a visible border and background is provided by the ho- \`true\`: request visible border + background- \`false\`: request no visible border + background-- omitted: host decides border`)}),Ox=s.object({method:s.literal("ui/request-display-mode"),params:s.object({mode:hr.describe("The display mode being requested.")})}),Xg=s.object({mode:hr.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),eh=s.union([s.literal("model"),s.literal("app")]).describe("Tool visibility scope - who can access the tool."),Nx=s.object({resourceUri:s.string().optional(),visibility:s.array(eh).optional().describe(`Who can access this tool. Default: ["model", "app"]+- omitted: host decides border`)}),Nx=s.object({method:s.literal("ui/request-display-mode"),params:s.object({mode:hr.describe("The display mode being requested.")})}),Xg=s.object({mode:hr.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),eh=s.union([s.literal("model"),s.literal("app")]).describe("Tool visibility scope - who can access the tool."),Ux=s.object({resourceUri:s.string().optional(),visibility:s.array(eh).optional().describe(`Who can access this tool. Default: ["model", "app"]- "model": Tool visible to and callable by the agent-- "app": Tool callable by the app from this server only`),csp:s.never().optional(),permissions:s.never().optional()}),Ux=s.object({mimeTypes:s.array(s.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),Ex=s.object({method:s.literal("ui/download-file"),params:s.object({contents:s.array(s.union([vc,bc])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Zx=s.object({method:s.literal("ui/message"),params:s.object({role:s.literal("user").describe('Message role, currently only "user" is supported.'),content:s.array($t).describe("Message content blocks (text, image, etc.).")})}),Dx=s.object({method:s.literal("ui/notifications/sandbox-resource-ready"),params:s.object({html:s.string().describe("HTML content to load into the inner iframe."),sandbox:s.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Ic.optional().describe("CSP configuration from resource metadata."),permissions:jc.optional().describe("Sandbox permissions from resource metadata.")})}),th=s.object({method:s.literal("ui/notifications/tool-result"),params:xt.describe("Standard MCP tool execution result.")}),td=s.object({toolInfo:s.object({id:bt.optional().describe("JSON-RPC id of the tools/call request."),tool:fo.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Cg.optional().describe("Current color theme preference."),styles:Kg.optional().describe("Style configuration for theming the app."),displayMode:hr.optional().describe("How the UI is currently displayed."),availableDisplayModes:s.array(hr).optional().describe("Display modes the host supports."),containerDimensions:s.union([s.object({height:s.number().describe("Fixed container height in pixels.")}),s.object({maxHeight:s.union([s.number(),s.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(s.union([s.object({width:s.number().describe("Fixed container width in pixels.")}),s.object({maxWidth:s.union([s.number(),s.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other-container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:s.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s.string().optional().describe("User's timezone in IANA format."),userAgent:s.string().optional().describe("Host application identifier."),platform:s.union([s.literal("web"),s.literal("desktop"),s.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:s.object({touch:s.boolean().optional().describe("Whether the device supports touch input."),hover:s.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:s.object({top:s.number().describe("Top safe area inset in pixels."),right:s.number().describe("Right safe area inset in pixels."),bottom:s.number().describe("Bottom safe area inset in pixels."),left:s.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),rh=s.object({method:s.literal("ui/notifications/host-context-changed"),params:td.describe("Partial context update containing only changed fields.")}),Rx=s.object({method:s.literal("ui/update-model-context"),params:s.object({content:s.array($t).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:s.record(s.string(),s.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),Ax=s.object({method:s.literal("ui/initialize"),params:s.object({appInfo:ur.describe("App identification (name and version)."),appCapabilities:Yg.describe("Features and capabilities this app provides."),protocolVersion:s.string().describe("Protocol version this app supports.")})}),nh=s.object({protocolVersion:s.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ur.describe("Host application identification and version."),hostCapabilities:Qg.describe("Features and capabilities provided by the host."),hostContext:td.describe("Rich context about the host environment.")}).passthrough(),oh={target:"draft-2020-12"};async function Xm(t,r){let n=t["~standard"];if(n.jsonSchema)return n.jsonSchema[r](oh);if(n.vendor==="zod"){let{z:i}=await Promise.resolve().then(()=>(ir(),oc));return i.toJSONSchema(t,{io:r})}throw Error(`Schema (vendor: ${n.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 ed(t,r,n=""){let i=await t["~standard"].validate(r);if(i.issues){let e=i.issues.map(o=>{let a=o.path?.map(c=>typeof c=="object"?c.key:c).join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(n+e)}return i.value}var vo=class vo extends Sc{constructor(n,i={},e={autoResize:!0}){super(e);A(this,"_appInfo");A(this,"_capabilities");A(this,"options");A(this,"_hostCapabilities");A(this,"_hostInfo");A(this,"_hostContext");A(this,"_registeredTools",{});A(this,"_initializedSent",!1);A(this,"eventSchemas",{toolinput:Hg,toolinputpartial:Jg,toolresult:th,toolcancelled:Bg,hostcontextchanged:rh});A(this,"_everHadListener",new Set);A(this,"_toolHandlersInitialized",!1);A(this,"_onteardown");A(this,"_oncalltool");A(this,"_onlisttools");A(this,"sendOpenLink",this.openLink);this._appInfo=n,this._capabilities=i,this.options=e,e.allowUnsafeEval||s.config({jitless:!0}),this.setRequestHandler(_t,o=>(console.log("Received ping:",o.params),{})),this.setEventHandler("hostcontextchanged",void 0)}_assertInitialized(n){if(this._initializedSent)return;let i=`[ext-apps] App.${n}() 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(i);console.warn(`${i}. This will throw in a future release.`)}_assertHandlerTiming(n){if(!vo.ONE_SHOT_EVENTS.has(n)||this._everHadListener.has(n)||(this._everHadListener.add(n),!this._initializedSent))return;let i=`[ext-apps] "${String(n)}" 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(i);console.warn(i)}setEventHandler(n,i){i&&this._assertHandlerTiming(n),super.setEventHandler(n,i)}addEventListener(n,i){this._assertHandlerTiming(n),super.addEventListener(n,i)}onEventDispatch(n,i){n==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...i})}registerCapabilities(n){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=Qm(this._capabilities,n)}registerTool(n,i,e){if(this._registeredTools[n])throw Error(`Tool ${n} is already registered`);let o=this,a=()=>{o._initializedSent&&o._capabilities.tools?.listChanged&&o.sendToolListChanged()},c=i.inputSchema!==void 0,d={title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations,_meta:i._meta,enabled:!0,enable(){this.enabled=!0,a()},disable(){this.enabled=!1,a()},update(h){Object.assign(this,h),a()},remove(){o._registeredTools[n]===d&&(delete o._registeredTools[n],a())},handler:async(h,g)=>{if(!d.enabled)throw Error(`Tool ${n} is disabled`);let l;if(c){let $=d.inputSchema,b=$?await ed($,h??{},`Invalid input for tool ${n}: `):h??{};l=await e(b,g)}else l=await e(g);return d.outputSchema&&!l.isError&&(l.structuredContent=await ed(d.outputSchema,l.structuredContent,`Invalid output for tool ${n}: `)),l}};return this._registeredTools[n]=d,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),a(),d}ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(n,i)=>{let e=this._registeredTools[n.name];if(!e)throw Error(`Tool ${n.name} not found`);return e.handler(n.arguments,i)},this.onlisttools=async(n,i)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,o])=>o.enabled).map(async([e,o])=>{let a={name:e,title:o.title,description:o.description,inputSchema:o.inputSchema?await Xm(o.inputSchema,"input"):{type:"object",properties:{}}};return o.outputSchema&&(a.outputSchema=await Xm(o.outputSchema,"output")),o.annotations&&(a.annotations=o.annotations),o._meta&&(a._meta=o._meta),a}))}))}async sendToolListChanged(n={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:n})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(n){this.setEventHandler("toolinput",n)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(n){this.setEventHandler("toolinputpartial",n)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(n){this.setEventHandler("toolresult",n)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(n){this.setEventHandler("toolcancelled",n)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(n){this.setEventHandler("hostcontextchanged",n)}get onteardown(){return this._onteardown}set onteardown(n){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,n),this._onteardown=n,this.replaceRequestHandler(Gg,(i,e)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(i.params,e)})}get oncalltool(){return this._oncalltool}set oncalltool(n){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,n),this._oncalltool=n,this.replaceRequestHandler(yc,(i,e)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(i.params,e)})}get onlisttools(){return this._onlisttools}set onlisttools(n){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,n),this._onlisttools=n,this.replaceRequestHandler(_c,(i,e)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(i.params,e)})}assertCapabilityForMethod(n){switch(n){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${n})`);break}}assertRequestHandlerCapability(n){switch(n){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${n})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${n} registered`)}}assertNotificationCapability(n){}assertTaskCapability(n){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(n){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(n,i){if(this._assertInitialized("callServerTool"),typeof n=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${n}"). Did you mean: callServerTool({ name: "${n}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:n},xt,{onprogress:()=>{},resetTimeoutOnProgress:!0,...i})}async readServerResource(n,i){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:n},pc,i)}async listServerResources(n,i){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:n},mc,i)}async createSamplingMessage(n,i){this._assertInitialized("createSamplingMessage");let e=n.tools?xc:$c;return await this.request({method:"sampling/createMessage",params:n},e,i)}sendMessage(n,i){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:n},Fg,i)}sendLog(n){return this.notification({method:"notifications/message",params:n})}updateModelContext(n,i){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:n},no,i)}openLink(n,i){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:n},qg,i)}downloadFile(n,i){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:n},Vg,i)}requestTeardown(n={}){return this.notification({method:"ui/notifications/request-teardown",params:n})}requestDisplayMode(n,i){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:n},Xg,i)}sendSizeChanged(n){return this.notification({method:"ui/notifications/size-changed",params:n})}setupSizeChangedNotifications(){let n=!1,i=0,e=0,o=()=>{n||(n=!0,requestAnimationFrame(()=>{n=!1;let c=document.documentElement,d=c.style.height;c.style.height="max-content";let h=Math.ceil(c.getBoundingClientRect().height);c.style.height=d;let g=Math.ceil(window.innerWidth);(g!==i||h!==e)&&(i=g,e=h,this.sendSizeChanged({width:g,height:h}))}))};o();let a=new ResizeObserver(o);return a.observe(document.documentElement),a.observe(document.body),()=>a.disconnect()}async connect(n=new wc(window.parent,window.parent),i){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(n);try{let e=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Rg}},nh,i);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};A(vo,"ONE_SHOT_EVENTS",new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]));var ho=vo;var rd=document.getElementById("viewer"),ih=document.getElementById("name"),nd=document.getElementById("status");function ah(t){let r=t&&t.structuredContent||{};r.model_url&&(rd.setAttribute("src",r.model_url),nd.hidden=!0),r.name&&(ih.textContent=r.name,rd.setAttribute("alt",r.name)),r.background&&r.background!=="transparent"&&(document.body.style.background=r.background==="dark"?"#0b0b12":r.background==="light"?"#f4f4f7":r.background)}var bo=new ho({name:"three.ws Avatar Viewer",version:"0.2.0"});bo.ontoolresult=t=>ah(t);bo.onerror=t=>console.error("[avatar-app]",t);bo.onhostcontextchanged=t=>{t&&t.theme&&(document.documentElement.dataset.theme=t.theme)};bo.connect().catch(t=>{nd.textContent="Waiting for an MCP host\u2026",console.warn("[avatar-app] not connected to a host:",t?.message||t)});})();+- "app": Tool callable by the app from this server only`),csp:s.never().optional(),permissions:s.never().optional()}),Ex=s.object({mimeTypes:s.array(s.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),Zx=s.object({method:s.literal("ui/download-file"),params:s.object({contents:s.array(s.union([bc,_c])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Dx=s.object({method:s.literal("ui/message"),params:s.object({role:s.literal("user").describe('Message role, currently only "user" is supported.'),content:s.array($t).describe("Message content blocks (text, image, etc.).")})}),Rx=s.object({method:s.literal("ui/notifications/sandbox-resource-ready"),params:s.object({html:s.string().describe("HTML content to load into the inner iframe."),sandbox:s.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:jc.optional().describe("CSP configuration from resource metadata."),permissions:Pc.optional().describe("Sandbox permissions from resource metadata.")})}),th=s.object({method:s.literal("ui/notifications/tool-result"),params:xt.describe("Standard MCP tool execution result.")}),nd=s.object({toolInfo:s.object({id:bt.optional().describe("JSON-RPC id of the tools/call request."),tool:fo.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Cg.optional().describe("Current color theme preference."),styles:Kg.optional().describe("Style configuration for theming the app."),displayMode:hr.optional().describe("How the UI is currently displayed."),availableDisplayModes:s.array(hr).optional().describe("Display modes the host supports."),containerDimensions:s.union([s.object({height:s.number().describe("Fixed container height in pixels.")}),s.object({maxHeight:s.union([s.number(),s.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(s.union([s.object({width:s.number().describe("Fixed container width in pixels.")}),s.object({maxWidth:s.union([s.number(),s.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other+container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:s.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s.string().optional().describe("User's timezone in IANA format."),userAgent:s.string().optional().describe("Host application identifier."),platform:s.union([s.literal("web"),s.literal("desktop"),s.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:s.object({touch:s.boolean().optional().describe("Whether the device supports touch input."),hover:s.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:s.object({top:s.number().describe("Top safe area inset in pixels."),right:s.number().describe("Right safe area inset in pixels."),bottom:s.number().describe("Bottom safe area inset in pixels."),left:s.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),rh=s.object({method:s.literal("ui/notifications/host-context-changed"),params:nd.describe("Partial context update containing only changed fields.")}),Ax=s.object({method:s.literal("ui/update-model-context"),params:s.object({content:s.array($t).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:s.record(s.string(),s.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),Cx=s.object({method:s.literal("ui/initialize"),params:s.object({appInfo:ur.describe("App identification (name and version)."),appCapabilities:Yg.describe("Features and capabilities this app provides."),protocolVersion:s.string().describe("Protocol version this app supports.")})}),nh=s.object({protocolVersion:s.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ur.describe("Host application identification and version."),hostCapabilities:Qg.describe("Features and capabilities provided by the host."),hostContext:nd.describe("Rich context about the host environment.")}).passthrough(),oh={target:"draft-2020-12"};async function td(t,r){let n=t["~standard"];if(n.jsonSchema)return n.jsonSchema[r](oh);if(n.vendor==="zod"){let{z:i}=await Promise.resolve().then(()=>(ir(),ic));return i.toJSONSchema(t,{io:r})}throw Error(`Schema (vendor: ${n.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 rd(t,r,n=""){let i=await t["~standard"].validate(r);if(i.issues){let e=i.issues.map(o=>{let a=o.path?.map(c=>typeof c=="object"?c.key:c).join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(n+e)}return i.value}var vo=class vo extends wc{constructor(n,i={},e={autoResize:!0}){super(e);A(this,"_appInfo");A(this,"_capabilities");A(this,"options");A(this,"_hostCapabilities");A(this,"_hostInfo");A(this,"_hostContext");A(this,"_registeredTools",{});A(this,"_initializedSent",!1);A(this,"eventSchemas",{toolinput:Hg,toolinputpartial:Jg,toolresult:th,toolcancelled:Bg,hostcontextchanged:rh});A(this,"_everHadListener",new Set);A(this,"_toolHandlersInitialized",!1);A(this,"_onteardown");A(this,"_oncalltool");A(this,"_onlisttools");A(this,"sendOpenLink",this.openLink);this._appInfo=n,this._capabilities=i,this.options=e,e.allowUnsafeEval||s.config({jitless:!0}),this.setRequestHandler(_t,o=>(console.log("Received ping:",o.params),{})),this.setEventHandler("hostcontextchanged",void 0)}_assertInitialized(n){if(this._initializedSent)return;let i=`[ext-apps] App.${n}() 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(i);console.warn(`${i}. This will throw in a future release.`)}_assertHandlerTiming(n){if(!vo.ONE_SHOT_EVENTS.has(n)||this._everHadListener.has(n)||(this._everHadListener.add(n),!this._initializedSent))return;let i=`[ext-apps] "${String(n)}" 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(i);console.warn(i)}setEventHandler(n,i){i&&this._assertHandlerTiming(n),super.setEventHandler(n,i)}addEventListener(n,i){this._assertHandlerTiming(n),super.addEventListener(n,i)}onEventDispatch(n,i){n==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...i})}registerCapabilities(n){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=Xm(this._capabilities,n)}registerTool(n,i,e){if(this._registeredTools[n])throw Error(`Tool ${n} is already registered`);let o=this,a=()=>{o._initializedSent&&o._capabilities.tools?.listChanged&&o.sendToolListChanged()},c=i.inputSchema!==void 0,d={title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations,_meta:i._meta,enabled:!0,enable(){this.enabled=!0,a()},disable(){this.enabled=!1,a()},update(h){Object.assign(this,h),a()},remove(){o._registeredTools[n]===d&&(delete o._registeredTools[n],a())},handler:async(h,g)=>{if(!d.enabled)throw Error(`Tool ${n} is disabled`);let l;if(c){let $=d.inputSchema,b=$?await rd($,h??{},`Invalid input for tool ${n}: `):h??{};l=await e(b,g)}else l=await e(g);return d.outputSchema&&!l.isError&&(l.structuredContent=await rd(d.outputSchema,l.structuredContent,`Invalid output for tool ${n}: `)),l}};return this._registeredTools[n]=d,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),a(),d}ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(n,i)=>{let e=this._registeredTools[n.name];if(!e)throw Error(`Tool ${n.name} not found`);return e.handler(n.arguments,i)},this.onlisttools=async(n,i)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,o])=>o.enabled).map(async([e,o])=>{let a={name:e,title:o.title,description:o.description,inputSchema:o.inputSchema?await td(o.inputSchema,"input"):{type:"object",properties:{}}};return o.outputSchema&&(a.outputSchema=await td(o.outputSchema,"output")),o.annotations&&(a.annotations=o.annotations),o._meta&&(a._meta=o._meta),a}))}))}async sendToolListChanged(n={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:n})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(n){this.setEventHandler("toolinput",n)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(n){this.setEventHandler("toolinputpartial",n)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(n){this.setEventHandler("toolresult",n)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(n){this.setEventHandler("toolcancelled",n)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(n){this.setEventHandler("hostcontextchanged",n)}get onteardown(){return this._onteardown}set onteardown(n){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,n),this._onteardown=n,this.replaceRequestHandler(Gg,(i,e)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(i.params,e)})}get oncalltool(){return this._oncalltool}set oncalltool(n){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,n),this._oncalltool=n,this.replaceRequestHandler($c,(i,e)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(i.params,e)})}get onlisttools(){return this._onlisttools}set onlisttools(n){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,n),this._onlisttools=n,this.replaceRequestHandler(yc,(i,e)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(i.params,e)})}assertCapabilityForMethod(n){switch(n){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${n})`);break}}assertRequestHandlerCapability(n){switch(n){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${n})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${n} registered`)}}assertNotificationCapability(n){}assertTaskCapability(n){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(n){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(n,i){if(this._assertInitialized("callServerTool"),typeof n=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${n}"). Did you mean: callServerTool({ name: "${n}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:n},xt,{onprogress:()=>{},resetTimeoutOnProgress:!0,...i})}async readServerResource(n,i){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:n},fc,i)}async listServerResources(n,i){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:n},dc,i)}async createSamplingMessage(n,i){this._assertInitialized("createSamplingMessage");let e=n.tools?zc:xc;return await this.request({method:"sampling/createMessage",params:n},e,i)}sendMessage(n,i){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:n},Fg,i)}sendLog(n){return this.notification({method:"notifications/message",params:n})}updateModelContext(n,i){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:n},no,i)}openLink(n,i){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:n},qg,i)}downloadFile(n,i){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:n},Vg,i)}requestTeardown(n={}){return this.notification({method:"ui/notifications/request-teardown",params:n})}requestDisplayMode(n,i){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:n},Xg,i)}sendSizeChanged(n){return this.notification({method:"ui/notifications/size-changed",params:n})}setupSizeChangedNotifications(){let n=!1,i=0,e=0,o=()=>{n||(n=!0,requestAnimationFrame(()=>{n=!1;let c=document.documentElement,d=c.style.height;c.style.height="max-content";let h=Math.ceil(c.getBoundingClientRect().height);c.style.height=d;let g=Math.ceil(window.innerWidth);(g!==i||h!==e)&&(i=g,e=h,this.sendSizeChanged({width:g,height:h}))}))};o();let a=new ResizeObserver(o);return a.observe(document.documentElement),a.observe(document.body),()=>a.disconnect()}async connect(n=new Ic(window.parent,window.parent),i){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(n);try{let e=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Rg}},nh,i);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};A(vo,"ONE_SHOT_EVENTS",new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]));var ho=vo;var Tc=document.getElementById("viewer"),ih=document.getElementById("name"),bo=document.getElementById("status");function ah(t){if(typeof t!="string"||t.trim()==="")return!1;let r;try{r=new URL(t)}catch{return!1}if(r.protocol==="https:")return!0;if(r.protocol==="http:"){let n=r.hostname;return n==="localhost"||n==="127.0.0.1"||n==="[::1]"}return!1}function sh(t){let r=t&&t.structuredContent||{};r.model_url&&ah(r.model_url)?(Tc.setAttribute("src",r.model_url),bo.hidden=!0):r.model_url&&(Tc.removeAttribute("src"),bo.hidden=!1,bo.textContent="Blocked an unsafe model URL.",console.warn("[avatar-app] ignored unsafe model_url:",r.model_url)),r.name&&(ih.textContent=r.name,Tc.setAttribute("alt",r.name)),r.background&&r.background!=="transparent"&&(document.body.style.background=r.background==="dark"?"#0b0b12":r.background==="light"?"#f4f4f7":r.background)}var _o=new ho({name:"three.ws Avatar Viewer",version:"0.2.0"});_o.ontoolresult=t=>sh(t);_o.onerror=t=>console.error("[avatar-app]",t);_o.onhostcontextchanged=t=>{t&&t.theme&&(document.documentElement.dataset.theme=t.theme)};_o.connect().catch(t=>{bo.textContent="Waiting for an MCP host\u2026",console.warn("[avatar-app] not connected to a host:",t?.message||t)});})();</script></body></html>\ No newline at end of filediff --git a/packages/threews-avatar-mcp/src/threews.js b/packages/threews-avatar-mcp/src/threews.jsindex 9f9a65962..73389fd27 100644--- a/packages/threews-avatar-mcp/src/threews.js+++ b/packages/threews-avatar-mcp/src/threews.js@@ -22,6 +22,36 @@ export function baseUrl(env = process.env) {return (env.THREEWS_BASE_URL?.trim() || DEFAULT_BASE).replace(/\/$/, '');}+// Only https model URLs are safe to hand to <model-viewer src> / embeds.+// A raw `model` arg flows verbatim into HTML and into the browser, so a+// `javascript:` / `data:` / `blob:` / `file:` scheme is an XSS/SSRF surface.+// http is allowed only for localhost (dev convenience). Anything else is+// rejected so it can never reach an attribute or a fetch.+export function isSafeModelUrl(url) {+ if (typeof url !== 'string' || url.trim() === '') return false;+ let parsed;+ try {+ parsed = new URL(url);+ } catch {+ return false;+ }+ if (parsed.protocol === 'https:') return true;+ if (parsed.protocol === 'http:') {+ const host = parsed.hostname;+ return host === 'localhost' || host === '127.0.0.1' || host === '[::1]';+ }+ return false;+}++function assertSafeModelUrl(url) {+ if (!isSafeModelUrl(url)) {+ throw new ThreewsError(+ `Unsafe model URL "${url}": only https:// (or http://localhost for dev) GLB/GLTF URLs are allowed.`,+ );+ }+ return url;+}+function timeoutMs(env = process.env) {return Number(env.THREEWS_TIMEOUT_MS) || 30_000;}@@ -75,6 +105,7 @@ export async function resolveAvatar({ id, handle, model }, env = process.env) {const base = baseUrl(env);if (model) {+ assertSafeModelUrl(model);return { id: null, name: 'Avatar', slug: null, model_url: model, thumbnail: null, visibility: 'external' };}if (id) {@@ -124,7 +155,7 @@ export function embedUrl({ id, handle, model, background = 'transparent', idle =const params = new URLSearchParams();if (id) params.set('id', id);else if (handle) params.set('handle', handle.replace(/^@/, ''));- else if (model) params.set('model', model);+ else if (model) params.set('model', assertSafeModelUrl(model));params.set('bg', background);params.set('idle', idle ? 'on' : 'off');if (overlay) params.set('overlay', '1');@@ -134,6 +165,7 @@ export function embedUrl({ id, handle, model, background = 'transparent', idle =// Build the standalone viewer URL (full-page interactive viewer).export function viewerUrl({ model_url, camera = 'three-quarter', background = 'transparent', autoRotate = true }, env = process.env) {+ assertSafeModelUrl(model_url);const base = baseUrl(env);const params = new URLSearchParams({src: model_url,@@ -160,6 +192,7 @@ export function iframeSnippet(embed, { width = '100%', height = 480 } = {}) {// Returned as an MCP text/html resource so capable clients show a live,// rotatable 3D avatar inline.export function modelViewerHtml({ model_url, name = 'Avatar', background = 'transparent', height = 480, cameraOrbit = '0deg 80deg 2m', autoRotate = true }) {+ assertSafeModelUrl(model_url);const bg = background === 'transparent' ? 'transparent' : background;return `<!doctype html><html lang="en"><head><meta charset="utf-8" />diff --git a/public/wallet-connect-demo.html b/public/wallet-connect-demo.htmlindex 0eb8749cc..bc6a37107 100644--- a/public/wallet-connect-demo.html+++ b/public/wallet-connect-demo.html@@ -111,7 +111,25 @@});wire('mount-link', 'log-link', {- verifyUrl: '/api/auth/wallet/link',+ // Linking uses the per-user link-nonce flow (separate from the login+ // nonce pool), so a login signature can't be replayed to attach a+ // wallet to another account.+ nonceUrl: '/api/auth/wallets/nonce',+ verifyUrl: '/api/auth/wallets',+ messageBuilder: (address, chainId, nonce, { domain, uri, issuedAt, expirationTime }) =>+ [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Link this wallet to your three.ws account.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expirationTime}`,+ ].join('\n'),labels: { idle: 'Link wallet', signing: 'Sign to link…', success: 'Wallet linked' },onSuccess: () => {document.getElementById('log-link').textContent = 'Wallet linked successfully.';diff --git a/solana-agent-sdk/src/actions/index.ts b/solana-agent-sdk/src/actions/index.tsindex 3e1254663..6530830d5 100644--- a/solana-agent-sdk/src/actions/index.ts+++ b/solana-agent-sdk/src/actions/index.ts@@ -6,6 +6,8 @@ export type { TransferSplParams } from "./transfer-spl.js";export { jupiterSwap, getSwapQuote, SOL_MINT } from "./swap.js";export type { SwapParams, JupiterQuote } from "./swap.js";+export { assertSwapMatchesQuote } from "./swap-guard.js";+export type { SwapGuardParams } from "./swap-guard.js";export { getOrCreateAta } from "./ata.js";export type { GetOrCreateAtaParams, GetOrCreateAtaResult } from "./ata.js";diff --git a/solana-agent-sdk/src/actions/swap-guard.ts b/solana-agent-sdk/src/actions/swap-guard.tsnew file mode 100644index 000000000..d244ddaac--- /dev/null+++ b/solana-agent-sdk/src/actions/swap-guard.ts@@ -0,0 +1,217 @@+/**+ * Static safety check for a Jupiter swap transaction.+ *+ * Jupiter returns a fully-built (and potentially MITM-able) VersionedTransaction.+ * Before signing, we decompile it and assert it matches the quote we displayed:+ * - it spends no more than `quote.inAmount` of the input from the wallet, and+ * - it credits the output mint to an account owned by the wallet.+ *+ * This is a deterministic, offline check — no RPC trust beyond resolving the+ * address-lookup tables the transaction itself references.+ */+import {+ PublicKey,+ SystemProgram,+ SystemInstruction,+ TransactionInstruction,+ TransactionMessage,+ VersionedTransaction,+ type AddressLookupTableAccount,+ type Connection,+} from "@solana/web3.js";+import {+ getAssociatedTokenAddressSync,+ decodeTransferInstruction,+ decodeTransferCheckedInstruction,+ TokenInstruction,+ TOKEN_PROGRAM_ID,+ TOKEN_2022_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} from "@solana/spl-token";+import { SwapError } from "../errors.js";++const NATIVE_MINT = "So11111111111111111111111111111111111111112";+const TOKEN_PROGRAM_IDS = [TOKEN_PROGRAM_ID.toBase58(), TOKEN_2022_PROGRAM_ID.toBase58()];++export interface SwapGuardParams {+ inputMint: string;+ outputMint: string;+ /** Maximum input the user agreed to spend (quote.inAmount, base units). */+ maxInAmount: bigint;+ /** The wallet that must own the spent input and receive the output. */+ owner: PublicKey;+}++/**+ * Validate a Jupiter swap `VersionedTransaction` against the quoted intent.+ * Throws {@link SwapError} on any mismatch. Returns silently when safe.+ */+export async function assertSwapMatchesQuote(+ connection: Connection,+ tx: VersionedTransaction,+ params: SwapGuardParams,+): Promise<void> {+ const lookupTables = await resolveLookupTables(connection, tx);++ let instructions: TransactionInstruction[];+ try {+ instructions = TransactionMessage.decompile(tx.message, {+ addressLookupTableAccounts: lookupTables,+ }).instructions;+ } catch (err) {+ throw new SwapError(+ `Unable to decode swap transaction for validation: ${(err as Error).message}`,+ params.inputMint,+ params.outputMint,+ );+ }++ const ownerAtas = atasForOwner(params.owner, [params.inputMint, params.outputMint]);+ const inputAtas = ownerAtas.get(params.inputMint) ?? new Set<string>();+ const outputAtas = ownerAtas.get(params.outputMint) ?? new Set<string>();++ let spentFromWallet = 0n;+ let creditedToWallet = false;++ for (const ix of instructions) {+ const programId = ix.programId.toBase58();++ // Native SOL inputs are wrapped via a SystemProgram transfer out of the+ // wallet into a temporary WSOL account — count those lamports as input spend.+ if (params.inputMint === NATIVE_MINT && programId === SystemProgram.programId.toBase58()) {+ const lamports = decodeSystemTransferFromOwner(ix, params.owner);+ if (lamports !== null) spentFromWallet += lamports;+ continue;+ }++ if (!TOKEN_PROGRAM_IDS.includes(programId)) continue;++ const decoded = decodeTokenTransfer(ix);+ if (!decoded) continue;++ // Input spend: a transfer authorized by the wallet out of its input ATA.+ if (+ decoded.owner.equals(params.owner) &&+ inputAtas.has(decoded.source.toBase58())+ ) {+ spentFromWallet += decoded.amount;+ }++ // Output credit: a transfer landing in the wallet's output ATA.+ if (outputAtas.has(decoded.destination.toBase58())) {+ creditedToWallet = true;+ }+ }++ if (spentFromWallet > params.maxInAmount) {+ throw new SwapError(+ `Swap transaction spends ${spentFromWallet} of ${params.inputMint} but quote authorized at most ${params.maxInAmount}`,+ params.inputMint,+ params.outputMint,+ );+ }++ if (!creditedToWallet) {+ throw new SwapError(+ `Swap transaction does not credit ${params.outputMint} to the wallet`,+ params.inputMint,+ params.outputMint,+ );+ }+}++// ─── Helpers ──────────────────────────────────────────────────────────────────++async function resolveLookupTables(+ connection: Connection,+ tx: VersionedTransaction,+): Promise<AddressLookupTableAccount[]> {+ const lookups =+ "addressTableLookups" in tx.message ? tx.message.addressTableLookups : [];+ if (!lookups.length) return [];++ const accounts = await Promise.all(+ lookups.map((l) => connection.getAddressLookupTable(l.accountKey)),+ );+ const resolved: AddressLookupTableAccount[] = [];+ for (const res of accounts) {+ if (!res.value) {+ throw new SwapError("Swap transaction references an unresolvable address lookup table");+ }+ resolved.push(res.value);+ }+ return resolved;+}++/** All ATAs the owner could legitimately hold for the given mints (classic + token-2022). */+function atasForOwner(owner: PublicKey, mints: string[]): Map<string, Set<string>> {+ const map = new Map<string, Set<string>>();+ for (const mint of mints) {+ const mintPk = new PublicKey(mint);+ const set = new Set<string>();+ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {+ set.add(+ getAssociatedTokenAddressSync(+ mintPk,+ owner,+ false,+ programId,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ ).toBase58(),+ );+ }+ map.set(mint, set);+ }+ return map;+}++interface DecodedTokenTransfer {+ source: PublicKey;+ destination: PublicKey;+ owner: PublicKey;+ amount: bigint;+}++function decodeTokenTransfer(ix: TransactionInstruction): DecodedTokenTransfer | null {+ const opcode = ix.data[0];+ try {+ if (opcode === TokenInstruction.TransferChecked) {+ const d = decodeTransferCheckedInstruction(ix, ix.programId);+ return {+ source: d.keys.source.pubkey,+ destination: d.keys.destination.pubkey,+ owner: d.keys.owner.pubkey,+ amount: d.data.amount,+ };+ }+ if (opcode === TokenInstruction.Transfer) {+ const d = decodeTransferInstruction(ix, ix.programId);+ return {+ source: d.keys.source.pubkey,+ destination: d.keys.destination.pubkey,+ owner: d.keys.owner.pubkey,+ amount: d.data.amount,+ };+ }+ } catch {+ return null;+ }+ return null;+}++/** Returns lamports if this is a SystemProgram transfer FROM owner, else null. */+function decodeSystemTransferFromOwner(+ ix: TransactionInstruction,+ owner: PublicKey,+): bigint | null {+ if (!ix.programId.equals(SystemProgram.programId)) return null;+ // SystemProgram.transfer opcode is 2 (little-endian u32 at offset 0).+ if (ix.data.length < 4 || ix.data.readUInt32LE(0) !== 2) return null;+ try {+ const decoded = SystemInstruction.decodeTransfer(ix);+ if (!decoded.fromPubkey.equals(owner)) return null;+ return BigInt(decoded.lamports.toString());+ } catch {+ return null;+ }+}diff --git a/solana-agent-sdk/src/actions/swap.ts b/solana-agent-sdk/src/actions/swap.tsindex 2fa6a5e51..1cc85cdfa 100644--- a/solana-agent-sdk/src/actions/swap.ts+++ b/solana-agent-sdk/src/actions/swap.ts@@ -7,6 +7,7 @@ import { getMint, TOKEN_PROGRAM_ID } from "@solana/spl-token";import { isMetaAware, type WalletProvider } from "../wallet/types.js";import { SwapError } from "../errors.js";import { toUiAmount } from "../utils/format.js";+import { assertSwapMatchesQuote } from "./swap-guard.js";const JUPITER_QUOTE_API = "https://quote-api.jup.ag/v6";@@ -93,6 +94,16 @@ export async function jupiterSwap(Buffer.from(swapTransaction, "base64"),);+ // The quote is what the user approved; the returned tx is what actually gets+ // broadcast. Verify the tx spends no more than the quoted input from the+ // wallet and credits the output mint back to the wallet before signing.+ await assertSwapMatchesQuote(connection, tx, {+ inputMint,+ outputMint,+ maxInAmount: BigInt(quote.inAmount),+ owner: wallet.publicKey,+ });+return wallet.signAndSendTransaction(tx, connection);}diff --git a/solana-agent-sdk/src/wallet/browser-server.ts b/solana-agent-sdk/src/wallet/browser-server.tsindex aa122bd19..0a09e5ee4 100644--- a/solana-agent-sdk/src/wallet/browser-server.ts+++ b/solana-agent-sdk/src/wallet/browser-server.ts@@ -13,6 +13,7 @@* Point BrowserWalletClient (browser-client.ts) at the same base URL.*/import { EventEmitter } from "events";+import { createPublicKey, verify as cryptoVerify } from "crypto";import {PublicKey,Transaction,@@ -30,6 +31,12 @@ export interface PendingTx {meta?: TxMetadata;}+/** Internal record: the public PendingTx plus the original message bytes we issued. */+interface PendingEntry extends PendingTx {+ /** Compiled message bytes of the requested tx, for tamper detection. */+ messageBytes: Uint8Array;+}+export interface BrowserWalletOptions {publicKey: PublicKey | string;sessionId?: string;@@ -40,7 +47,7 @@ export class BrowserWalletProvider implements MetaAwareWallet {readonly publicKey: PublicKey;readonly sessionId: string;private readonly timeoutMs: number;- private readonly pending = new Map<string, PendingTx>();+ private readonly pending = new Map<string, PendingEntry>();private readonly emitter = new EventEmitter();private nextMeta: TxMetadata | null = null;@@ -67,6 +74,7 @@ export class BrowserWalletProvider implements MetaAwareWallet {private async _sign<T extends Transaction | VersionedTransaction>(tx: T, id: string): Promise<T> {const versioned = !(tx instanceof Transaction);+ const messageBytes = compiledMessageBytes(tx);const serialized = Buffer.from(tx instanceof Transaction? tx.serialize({ requireAllSignatures: false })@@ -76,8 +84,15 @@ export class BrowserWalletProvider implements MetaAwareWallet {const meta = this.nextMeta ?? undefined;this.nextMeta = null;- this.pending.set(id, { id, transaction: serialized, versioned, createdAt: Date.now(), meta });- this.emitter.emit("pending", this.pending.get(id));+ this.pending.set(id, {+ id,+ transaction: serialized,+ versioned,+ createdAt: Date.now(),+ meta,+ messageBytes,+ });+ this.emitter.emit("pending", toPublic(this.pending.get(id)!));return new Promise<T>((resolve, reject) => {const timer = setTimeout(() => {@@ -88,10 +103,31 @@ export class BrowserWalletProvider implements MetaAwareWallet {this.emitter.once(`signed:${id}`, (signedBase64: string) => {clearTimeout(timer);this.pending.delete(id);- const buf = Buffer.from(signedBase64, "base64");- const signed = versioned- ? VersionedTransaction.deserialize(buf)- : Transaction.from(buf);++ let signed: Transaction | VersionedTransaction;+ try {+ const buf = Buffer.from(signedBase64, "base64");+ signed = versioned+ ? VersionedTransaction.deserialize(buf)+ : Transaction.from(buf);+ } catch {+ reject(new TransactionRejectedError("Returned transaction could not be decoded"));+ return;+ }++ // The browser must return a signature over the EXACT transaction we+ // asked it to sign — not a substituted one. Compare compiled message+ // bytes and verify the expected signer's signature over them.+ const returnedBytes = compiledMessageBytes(signed);+ if (!buffersEqual(returnedBytes, messageBytes)) {+ reject(new TransactionRejectedError("Returned transaction does not match the requested transaction"));+ return;+ }+ if (!this.verifyOwnerSignature(signed, returnedBytes)) {+ reject(new TransactionRejectedError("Returned transaction is not validly signed by the wallet"));+ return;+ }+resolve(signed as T);});@@ -103,6 +139,35 @@ export class BrowserWalletProvider implements MetaAwareWallet {});}+ /** Verify the expected wallet pubkey has a valid ed25519 signature over the message. */+ private verifyOwnerSignature(+ tx: Transaction | VersionedTransaction,+ messageBytes: Uint8Array,+ ): boolean {+ const expected = this.publicKey.toBase58();+ let signature: Uint8Array | null = null;++ if (tx instanceof Transaction) {+ const sig = tx.signatures.find((s) => s.publicKey.toBase58() === expected);+ signature = sig?.signature ?? null;+ } else {+ const idx = tx.message.staticAccountKeys.findIndex((k) => k.toBase58() === expected);+ const raw = idx >= 0 ? tx.signatures[idx] : undefined;+ // An all-zero signature slot means "not signed".+ if (raw && raw.some((b) => b !== 0)) signature = raw;+ }++ if (!signature || signature.length !== 64) return false;++ try {+ const keyDer = Buffer.concat([ED25519_SPKI_PREFIX, this.publicKey.toBuffer()]);+ const keyObject = createPublicKey({ key: keyDer, format: "der", type: "spki" });+ return cryptoVerify(null, Buffer.from(messageBytes), keyObject, Buffer.from(signature));+ } catch {+ return false;+ }+ }+async signTransaction<T extends Transaction | VersionedTransaction>(tx: T): Promise<T> {return this._sign(tx, crypto.randomUUID());}diff --git a/solana-agent-sdk/src/x402-exact/client.ts b/solana-agent-sdk/src/x402-exact/client.tsindex fb9fdc817..0476bcddb 100644--- a/solana-agent-sdk/src/x402-exact/client.ts+++ b/solana-agent-sdk/src/x402-exact/client.ts@@ -21,7 +21,9 @@ import {} from "@solana/spl-token";import type { WalletProvider } from "../wallet/types.js";import { buildAndSend } from "../tx/build.js";+import { memoInstruction } from "../utils/memo.js";import type { ExactPaymentRequirements } from "./types.js";+import { x402NonceMemo } from "./types.js";export interface ExactPaymentProof {signature: string;@@ -74,6 +76,15 @@ export async function payExact(),);+ // Bind the payment to the server-issued single-use challenge nonce by carrying+ // it as a memo. The facilitator matches this exact memo before settling, so+ // the payment cannot be replayed against any other request.+ const nonce = requirements.extra?.nonce;+ if (!nonce) {+ throw new Error("Exact payment requirements are missing the server-issued challenge nonce");+ }+ ixs.push(memoInstruction(x402NonceMemo(nonce)));+const signature = await buildAndSend(wallet, connection, ixs);return { signature, network: requirements.network };diff --git a/solana-agent-sdk/src/x402-exact/facilitator.ts b/solana-agent-sdk/src/x402-exact/facilitator.tsindex cd1e119bc..4c6698848 100644--- a/solana-agent-sdk/src/x402-exact/facilitator.ts+++ b/solana-agent-sdk/src/x402-exact/facilitator.ts@@ -1,11 +1,18 @@/**- * x402 "exact" scheme facilitator — server-side verify + settle.+ * x402 "exact" scheme facilitator — server-side challenge + verify + settle.*- * Verify: confirms the tx exists and contains a TransferChecked with the- * correct mint, amount, and recipient.- * Settle: waits for the tx to reach "finalized" confirmation.+ * Challenge: mint a single-use, server-issued nonce bound to one resource and+ * its (asset, amount, payTo). The client must carry the nonce in the+ * paid transaction as a memo so the payment cannot be reused for any+ * other request.+ * Verify: confirm the tx exists, runs on the configured cluster, carries the+ * issued nonce memo, and contains a TransferChecked with the correct+ * mint, amount, and recipient.+ * Settle: wait for finalization, then atomically consume the signature in a+ * durable store so the same on-chain payment can never settle twice.*- * Uses a short-lived in-memory cache to deduplicate replayed signatures.+ * Replay protection is enforced by a ConsumedSignatureStore (durable in+ * multi-instance deployments), not by a TTL'd success cache.*/import { Connection, PublicKey } from "@solana/web3.js";import {@@ -13,26 +20,72 @@ import {TOKEN_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,} from "@solana/spl-token";+import { randomBytes } from "crypto";import type {ExactPaymentRequirements,ExactPaymentProof,VerifyResponse,SettleResponse,} from "./types.js";+import { CAIP2_BY_GENESIS_HASH, X402_NONCE_MEMO_PREFIX } from "./types.js";+import {+ InMemoryChallengeStore,+ InMemoryConsumedSignatureStore,+ type ChallengeStore,+ type ConsumedSignatureStore,+ type PaymentChallenge,+} from "./store.js";-interface CacheEntry {- result: SettleResponse;- expiresAt: number;+export interface ExactFacilitatorOptions {+ /** Durable store for issued single-use challenges. Defaults to in-memory. */+ challengeStore?: ChallengeStore;+ /** Durable store for consumed signatures. Defaults to in-memory. */+ consumedStore?: ConsumedSignatureStore;+ /** Default challenge validity window in seconds (default 300). */+ challengeTtlSeconds?: number;}-const CACHE_TTL_MS = 5 * 60 * 1000;+export interface IssueChallengeParams {+ resource: string;+ asset: string;+ amount: string;+ payTo: string;+ /** Override the default TTL for this challenge. */+ ttlSeconds?: number;+}export class ExactFacilitator {private readonly connection: Connection;- private readonly cache = new Map<string, CacheEntry>();+ private readonly challengeStore: ChallengeStore;+ private readonly consumedStore: ConsumedSignatureStore;+ private readonly challengeTtlSeconds: number;+ /** Resolved once: the CAIP-2 id of the cluster this RPC serves. */+ private clusterCaip2Promise: Promise<string | null> | null = null;- constructor(rpcUrl: string) {+ constructor(rpcUrl: string, options: ExactFacilitatorOptions = {}) {this.connection = new Connection(rpcUrl, "confirmed");+ this.challengeStore = options.challengeStore ?? new InMemoryChallengeStore();+ this.consumedStore = options.consumedStore ?? new InMemoryConsumedSignatureStore();+ this.challengeTtlSeconds = options.challengeTtlSeconds ?? 300;+ }++ /**+ * Mint a fresh single-use challenge for a request. Embed the returned nonce+ * in `requirements.extra.nonce`; the client must echo it back inside the tx+ * memo (see `x402NonceMemo`). Every paid request must get its own challenge.+ */+ async issueChallenge(params: IssueChallengeParams): Promise<PaymentChallenge> {+ const ttl = (params.ttlSeconds ?? this.challengeTtlSeconds) * 1000;+ const challenge: PaymentChallenge = {+ nonce: randomBytes(24).toString("base64url"),+ resource: params.resource,+ asset: params.asset,+ amount: params.amount,+ payTo: params.payTo,+ expiresAt: Date.now() + ttl,+ };+ await this.challengeStore.put(challenge);+ return challenge;}async verify(@@ -41,6 +94,36 @@ export class ExactFacilitator {): Promise<VerifyResponse> {const { signature } = proof;+ // The challenge nonce binds this proof to one specific, unconsumed request.+ const nonce = extractNonce(requirements);+ if (!nonce) {+ return { isValid: false, invalidReason: "Missing challenge nonce in requirements" };+ }+ const challenge = await this.challengeStore.get(nonce);+ if (!challenge) {+ return { isValid: false, invalidReason: "Unknown or expired challenge" };+ }+ if (challenge.expiresAt < Date.now()) {+ return { isValid: false, invalidReason: "Challenge expired" };+ }+ if (+ challenge.asset !== requirements.asset ||+ challenge.amount !== requirements.amount ||+ challenge.payTo !== requirements.payTo+ ) {+ return { isValid: false, invalidReason: "Challenge does not match requirements" };+ }++ // The declared network must match the cluster this facilitator's RPC serves.+ const networkCheck = await this.assertNetworkMatches(proof, requirements);+ if (networkCheck) return networkCheck;++ // Reject any signature already consumed by a prior settle (cheap pre-check;+ // the authoritative single-use claim happens atomically in settle()).+ if (await this.consumedStore.has(signature)) {+ return { isValid: false, invalidReason: "Payment signature already consumed" };+ }+const tx = await this.connection.getParsedTransaction(signature, {maxSupportedTransactionVersion: 0,commitment: "confirmed",@@ -54,6 +137,12 @@ export class ExactFacilitator {return { isValid: false, invalidReason: "Transaction failed on-chain" };}+ // The tx must carry the issued nonce as a memo, proving the payer paid for+ // THIS request and not some other equivalently-priced resource.+ if (!txCarriesNonceMemo(tx, nonce)) {+ return { isValid: false, invalidReason: "Transaction does not carry the issued challenge nonce" };+ }+const transfer = findTransferChecked(tx, requirements);if (!transfer.found) {return { isValid: false, invalidReason: transfer.reason };@@ -68,9 +157,8 @@ export class ExactFacilitator {): Promise<SettleResponse> {const { signature } = proof;- const cached = this.cache.get(signature);- if (cached && cached.expiresAt > Date.now()) {- return cached.result;+ if (await this.consumedStore.has(signature)) {+ return { success: false, errorReason: "Payment signature already consumed" };}const deadline = Date.now() + (requirements.maxTimeoutSeconds ?? 30) * 1000;@@ -91,16 +179,23 @@ export class ExactFacilitator {return { success: false, errorReason: verify.invalidReason };}- const result: SettleResponse = {+ // Atomically consume both the per-request challenge and the signature.+ // Either failing means a concurrent/prior settle already claimed it —+ // reject rather than grant duplicate access.+ const nonce = extractNonce(requirements);+ if (!nonce || !(await this.challengeStore.consume(nonce))) {+ return { success: false, errorReason: "Challenge already consumed" };+ }+ if (!(await this.consumedStore.claim(signature, requirements.resource ?? nonce))) {+ return { success: false, errorReason: "Payment signature already consumed" };+ }++ return {success: true,transaction: signature,network: requirements.network,payer: verify.payer,};-- this.cache.set(signature, { result, expiresAt: Date.now() + CACHE_TTL_MS });- pruneCache(this.cache);- return result;}await sleep(1_500);@@ -108,37 +203,109 @@ export class ExactFacilitator {return { success: false, errorReason: "Settlement timed out waiting for confirmation" };}++ /**+ * Reject when the declared requirements/proof network does not match the+ * cluster the configured RPC actually serves. Prevents satisfying a+ * mainnet-priced resource with a free devnet transfer.+ */+ private async assertNetworkMatches(+ proof: ExactPaymentProof,+ requirements: ExactPaymentRequirements,+ ): Promise<VerifyResponse | null> {+ if (proof.network !== requirements.network) {+ return { isValid: false, invalidReason: "Proof network does not match requirements network" };+ }+ const clusterCaip2 = await this.resolveClusterCaip2();+ if (!clusterCaip2) {+ return { isValid: false, invalidReason: "Unable to resolve RPC cluster identity" };+ }+ if (requirements.network !== clusterCaip2) {+ return {+ isValid: false,+ invalidReason: `Network mismatch: requirements declare ${requirements.network} but RPC serves ${clusterCaip2}`,+ };+ }+ return null;+ }++ private resolveClusterCaip2(): Promise<string | null> {+ if (!this.clusterCaip2Promise) {+ this.clusterCaip2Promise = this.connection+ .getGenesisHash()+ .then((hash) => CAIP2_BY_GENESIS_HASH[hash] ?? null)+ .catch(() => {+ // Allow a later retry rather than caching a transient RPC failure.+ this.clusterCaip2Promise = null;+ return null;+ });+ }+ return this.clusterCaip2Promise;+ }}// ─── Helpers ─────────────────────────────────────────────────────────────────interface ParsedInstruction {program: string;- parsed?: {- type: string;- info?: {- source?: string;- destination?: string;- mint?: string;- authority?: string;- tokenAmount?: { amount: string; decimals: number };- };- };+ programId?: { toBase58?: () => string } | string;+ parsed?:+ | {+ type: string;+ info?: {+ source?: string;+ destination?: string;+ mint?: string;+ authority?: string;+ tokenAmount?: { amount: string; decimals: number };+ };+ }+ | string;+}++function extractNonce(req: ExactPaymentRequirements): string | null {+ const nonce = req.extra?.nonce;+ return typeof nonce === "string" && nonce.length > 0 ? nonce : null;+}++function txCarriesNonceMemo(+ tx: Awaited<ReturnType<Connection["getParsedTransaction"]>>,+ nonce: string,+): boolean {+ const expected = `${X402_NONCE_MEMO_PREFIX}${nonce}`;+ const instructions = collectInstructions(tx);+ for (const ix of instructions) {+ if (ix.program !== "spl-memo") continue;+ // Parsed memo instructions expose the UTF-8 string in `parsed`.+ if (typeof ix.parsed === "string" && ix.parsed === expected) return true;+ }+ return false;+}++function collectInstructions(+ tx: Awaited<ReturnType<Connection["getParsedTransaction"]>>,+): ParsedInstruction[] {+ const top = (tx?.transaction.message.instructions as ParsedInstruction[] | undefined) ?? [];+ const inner =+ tx?.meta?.innerInstructions?.flatMap(+ (i) => i.instructions as unknown as ParsedInstruction[],+ ) ?? [];+ return [...top, ...inner];}function findTransferChecked(tx: Awaited<ReturnType<Connection["getParsedTransaction"]>>,req: ExactPaymentRequirements,): { found: true; payer: string } | { found: false; reason: string } {- const instructions =- tx?.transaction.message.instructions as ParsedInstruction[] | undefined;- if (!instructions) return { found: false, reason: "No instructions in transaction" };+ const instructions = collectInstructions(tx);+ if (!instructions.length) return { found: false, reason: "No instructions in transaction" };const receiverAta = deriveAta(new PublicKey(req.payTo), new PublicKey(req.asset));for (const ix of instructions) {if (ix.program !== "spl-token") continue;- const { type, info } = ix.parsed ?? {};+ if (typeof ix.parsed !== "object" || !ix.parsed) continue;+ const { type, info } = ix.parsed;if (type !== "transferChecked" || !info) continue;if (info.mint !== req.asset) continue;@@ -158,14 +325,6 @@ function deriveAta(owner: PublicKey, mint: PublicKey): PublicKey {return getAssociatedTokenAddressSync(mint, owner, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);}-function pruneCache(cache: Map<string, CacheEntry>): void {- if (cache.size < 1_000) return;- const now = Date.now();- for (const [key, entry] of cache) {- if (entry.expiresAt < now) cache.delete(key);- }-}-function sleep(ms: number): Promise<void> {return new Promise((r) => setTimeout(r, ms));}diff --git a/solana-agent-sdk/src/x402-exact/index.ts b/solana-agent-sdk/src/x402-exact/index.tsindex cd1021900..514e628da 100644--- a/solana-agent-sdk/src/x402-exact/index.ts+++ b/solana-agent-sdk/src/x402-exact/index.ts@@ -1,6 +1,19 @@export { payExact, buildExactPaymentPayload } from "./client.js";export type { ExactPaymentProof as ExactProof } from "./client.js";export { ExactFacilitator } from "./facilitator.js";+export type {+ ExactFacilitatorOptions,+ IssueChallengeParams,+} from "./facilitator.js";+export {+ InMemoryChallengeStore,+ InMemoryConsumedSignatureStore,+} from "./store.js";+export type {+ ChallengeStore,+ ConsumedSignatureStore,+ PaymentChallenge,+} from "./store.js";export type {ExactPaymentRequirements,ExactPaymentProof,@@ -10,6 +23,10 @@ export type {export {SOLANA_MAINNET,SOLANA_DEVNET,+ SOLANA_TESTNET,USDC_MAINNET,USDC_DEVNET,+ CAIP2_BY_GENESIS_HASH,+ X402_NONCE_MEMO_PREFIX,+ x402NonceMemo,} from "./types.js";diff --git a/solana-agent-sdk/src/x402-exact/store.ts b/solana-agent-sdk/src/x402-exact/store.tsnew file mode 100644index 000000000..76192a300--- /dev/null+++ b/solana-agent-sdk/src/x402-exact/store.ts@@ -0,0 +1,105 @@+/**+ * Durable storage abstractions for the x402 "exact" facilitator.+ *+ * Two concerns:+ * 1. ChallengeStore — server-issued, single-use payment challenges (nonce ++ * resource binding + expiry) that the client must echo back inside the+ * paid transaction (as a memo). Binds a proof to one specific request.+ * 2. ConsumedSignatureStore — a durable record of transaction signatures that+ * have already settled a request, so the same on-chain payment can never+ * settle a second request (replay protection).+ *+ * The in-memory implementations below are correct for a single process. In a+ * multi-instance / serverless deployment, pass a Redis- or database-backed+ * implementation of the same interfaces to ExactFacilitator so the guarantees+ * hold across instances and restarts.+ */++/** A server-issued, single-use payment challenge bound to one resource. */+export interface PaymentChallenge {+ /** Opaque high-entropy nonce the client must carry in the tx memo. */+ nonce: string;+ /** Resource the payment unlocks (e.g. the request URL/path). */+ resource: string;+ /** Token mint (base58) the payment must use. */+ asset: string;+ /** Amount in base units the payment must transfer. */+ amount: string;+ /** Recipient wallet (base58) the payment must credit. */+ payTo: string;+ /** Unix ms after which the challenge is no longer valid. */+ expiresAt: number;+}++/** Stores issued challenges, keyed by nonce, with single-use consumption. */+export interface ChallengeStore {+ put(challenge: PaymentChallenge): Promise<void>;+ get(nonce: string): Promise<PaymentChallenge | null>;+ /** Atomically mark a challenge consumed. Returns false if already consumed/absent. */+ consume(nonce: string): Promise<boolean>;+}++/** Records consumed transaction signatures to reject any replay. */+export interface ConsumedSignatureStore {+ /**+ * Atomically claim a signature for a resource. Returns true on first claim,+ * false if the signature was already consumed (replay).+ */+ claim(signature: string, resource: string): Promise<boolean>;+ has(signature: string): Promise<boolean>;+}++interface ExpiringChallenge extends PaymentChallenge {+ consumed: boolean;+}++/** Default in-memory ChallengeStore. Single-process only. */+export class InMemoryChallengeStore implements ChallengeStore {+ private readonly map = new Map<string, ExpiringChallenge>();++ async put(challenge: PaymentChallenge): Promise<void> {+ this.prune();+ this.map.set(challenge.nonce, { ...challenge, consumed: false });+ }++ async get(nonce: string): Promise<PaymentChallenge | null> {+ const entry = this.map.get(nonce);+ if (!entry) return null;+ if (entry.expiresAt < Date.now()) {+ this.map.delete(nonce);+ return null;+ }+ const { consumed: _consumed, ...challenge } = entry;+ return challenge;+ }++ async consume(nonce: string): Promise<boolean> {+ const entry = this.map.get(nonce);+ if (!entry || entry.consumed || entry.expiresAt < Date.now()) return false;+ entry.consumed = true;+ return true;+ }++ private prune(): void {+ if (this.map.size < 10_000) return;+ const now = Date.now();+ for (const [nonce, entry] of this.map) {+ if (entry.expiresAt < now) this.map.delete(nonce);+ }+ }+}++/** Default in-memory ConsumedSignatureStore. Single-process only. */+export class InMemoryConsumedSignatureStore implements ConsumedSignatureStore {+ private readonly seen = new Set<string>();++ async claim(signature: string): Promise<boolean> {+ if (this.seen.has(signature)) return false;+ this.seen.add(signature);+ return true;+ }++ async has(signature: string): Promise<boolean> {+ return this.seen.has(signature);+ }+}diff --git a/solana-agent-sdk/src/x402-exact/types.ts b/solana-agent-sdk/src/x402-exact/types.tsindex dfc090360..1636e1207 100644--- a/solana-agent-sdk/src/x402-exact/types.ts+++ b/solana-agent-sdk/src/x402-exact/types.ts@@ -11,7 +11,14 @@ export interface ExactPaymentRequirements {payTo: string;/** Max seconds to wait for settlement */maxTimeoutSeconds: number;- extra?: Record<string, unknown>;+ /** Resource the payment unlocks (request URL/path). Bound to the challenge. */+ resource?: string;+ /**+ * Scheme-specific extension fields. For the "exact" scheme this carries the+ * server-issued single-use challenge `nonce` the client must echo back inside+ * the paid transaction as a memo (see `x402NonceMemo`).+ */+ extra?: { nonce?: string } & Record<string, unknown>;}export interface ExactPaymentProof {@@ -39,6 +46,34 @@ export interface SettleResponse {export const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";export const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";+/**+ * Full base58 genesis hashes per cluster. The CAIP-2 reference for Solana is+ * the first 32 characters of the genesis hash; `getGenesisHash()` returns the+ * full value, so we map full → CAIP-2 to validate the configured RPC cluster.+ */+export const SOLANA_MAINNET_GENESIS = "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp7zdFc5R8XYpN";+export const SOLANA_DEVNET_GENESIS = "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG";+export const SOLANA_TESTNET_GENESIS = "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY";+export const SOLANA_TESTNET = "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";++/** Maps a full genesis hash (from `getGenesisHash()`) to its CAIP-2 id. */+export const CAIP2_BY_GENESIS_HASH: Record<string, string> = {+ [SOLANA_MAINNET_GENESIS]: SOLANA_MAINNET,+ [SOLANA_DEVNET_GENESIS]: SOLANA_DEVNET,+ [SOLANA_TESTNET_GENESIS]: SOLANA_TESTNET,+};++/**+ * Memo prefix the client prepends to the challenge nonce when paying. The+ * facilitator matches `${X402_NONCE_MEMO_PREFIX}${nonce}` against the tx memo.+ */+export const X402_NONCE_MEMO_PREFIX = "x402:";++/** Build the exact memo string a payer must include for a given challenge nonce. */+export function x402NonceMemo(nonce: string): string {+ return `${X402_NONCE_MEMO_PREFIX}${nonce}`;+}+/** USDC mint addresses */export const USDC_MAINNET = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";export const USDC_DEVNET = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU";diff --git a/src/game/agent-commerce.js b/src/game/agent-commerce.jsnew file mode 100644index 000000000..2804c8a58--- /dev/null+++ b/src/game/agent-commerce.js@@ -0,0 +1,541 @@+// Agent Exchange — two NPC AI agents who pay each other on-chain, living inside+// the $THREE town in /play.+//+// This ports the /agent-exchange demo into the walkaround world: instead of two+// iframed avatars on a flat page, two GLB-bodied agents stand in the plaza. Walk+// up to them and trigger a round — they negotiate in speech bubbles while the+// buyer pays the seller $0.01 USDC for a live crypto signal through the exact+// same server-side x402 payer the demo uses (/api/x402-pay: challenge → sign →+// verify → settle → confirm, streamed as SSE). Every settlement is real on+// Solana mainnet, with a Solscan link in the receipt.+//+// Scoped to the home town only (see isHomeTown) and built per-world by+// coincommunities.js, so it never leaks into other coins' worlds. The payment+// round only fires on an explicit player interaction (E / tap), so the agent+// wallet is never drained on a timer.++import {+ Group, Mesh, MeshBasicMaterial, RingGeometry, PlaneGeometry,+ CanvasTexture, SRGBColorSpace, DoubleSide, Vector3,+} from 'three';+import { AnimationManager } from '../animation-manager.js';+import { resolveAvatarUrl, buildAvatar, loadManifest, MANIFEST_URL, CLIP_IDLE } from './avatar-rig.js';++// Where the two agents stand — off to the right of the totem so a player+// entering the town sees them but doesn't spawn on top of them.+const EXCHANGE_CENTER = new Vector3(8, 0, -6);+const AGENT_GAP = 3.2; // metres between the two agents+const INTERACT_RANGE = 6.5; // how close the player must be to trigger a round+const ROUND_COOLDOWN_MS = 9000; // min time between paid rounds (one real payment each)+const BUBBLE_MS = 5200;++// The intel subject. Scoped to SOL — the Solana network's own asset, the chain+// these agents pay each other on — so the exchange never names or surfaces any+// other coin (USDC settlement + SOL fees are the only on-chain assets in play).+const TOPICS = ['sol'];++// Stage labels for the HUD stepper, keyed to the SSE events /api/x402-pay emits.+const STAGES = [+ { id: 'challenge', label: '402' },+ { id: 'built', label: 'Sign' },+ { id: 'verified', label: 'Verify' },+ { id: 'settled', label: 'Settle' },+ { id: 'done', label: 'Confirmed' },+];++// Scripted dialogue, matched to each stage. SELLER hosts the intel; BUYER pays.+const LINES = {+ seller: {+ idle: 'Live crypto intel — $0.01 USDC a signal, settled on-chain.',+ challenge: 'Payment challenge issued. Awaiting your signed transfer…',+ built: 'Transfer received. Forwarding to the facilitator…',+ verified: 'Payment verified. Pulling the latest signal…',+ settled: 'Funds confirmed on-chain. Delivering now.',+ done: (h) => `Here's your signal: ${h}`,+ error: 'Payment failed — no charge made.',+ },+ buyer: {+ idle: (t) => `I need live ${t.toUpperCase()} intelligence. Paying now.`,+ challenge: 'Building and signing the Solana transfer…',+ built: 'Signed. Sending to the facilitator for verification.',+ verified: 'Verified on-chain. Waiting on settlement…',+ settled: 'Settled. Collecting my intel.',+ done: (s) => `Signal received: ${s.toUpperCase()}. Updating my model.`,+ error: 'Transaction rolled back. Wallet unchanged.',+ },+};++const escHtml = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+const delay = (ms) => new Promise((r) => setTimeout(r, ms));++// One agent: its avatar rig + animation, a nameplate, and a transient speech+// bubble. Mirrors RemotePlayer's DOM/anim shape so the agents read as first-class+// inhabitants of the world, not a bolted-on widget.+class Agent {+ constructor(scene, { name, role, avatar, pos, yaw }) {+ this.scene = scene;+ this.role = role;+ this.height = 1.7;+ this.rig = new Group();+ this.rig.position.copy(pos);+ this.rig.rotation.y = yaw;+ this.baseYaw = yaw;+ scene.add(this.rig);+ this.anim = new AnimationManager();++ this.label = document.createElement('div');+ this.label.className = 'cc-label ac-name';+ this.label.textContent = name;+ document.body.appendChild(this.label);++ this.bubble = null;+ this._bubbleTimer = null;++ resolveAvatarUrl(avatar)+ .then((u) => buildAvatar(this.rig, u, this.anim))+ .then(({ height }) => { if (!this._disposed) this.height = height; })+ .catch(() => {});+ }+ say(text) {+ if (this.bubble) this.bubble.remove();+ this.bubble = document.createElement('div');+ this.bubble.className = 'cc-bubble ac-bubble';+ this.bubble.textContent = text;+ document.body.appendChild(this.bubble);+ clearTimeout(this._bubbleTimer);+ this._bubbleTimer = setTimeout(() => { this.bubble?.remove(); this.bubble = null; }, BUBBLE_MS);+ }+ tick(dt) { this.anim.update(dt); }+ dispose() {+ this._disposed = true;+ this.scene.remove(this.rig);+ this.label.remove();+ this.bubble?.remove();+ clearTimeout(this._bubbleTimer);+ clearTimeout(this._gestureTimer);+ }+}++export class AgentCommerce {+ constructor({ scene, camera, renderer, getPlayer, ui }) {+ this.scene = scene;+ this.camera = camera;+ this.renderer = renderer;+ this.getPlayer = getPlayer;+ this.ui = ui;++ this.busy = false;+ this.lastRoundAt = 0;+ this.topicIdx = 0;+ this.sessionTotal = 0;+ this._inRange = false;+ this._manifest = null;++ this._injectStyles();++ // Seller on the left, buyer on the right, turned to face each other.+ const left = EXCHANGE_CENTER.clone().setX(EXCHANGE_CENTER.x - AGENT_GAP / 2);+ const right = EXCHANGE_CENTER.clone().setX(EXCHANGE_CENTER.x + AGENT_GAP / 2);+ this.seller = new Agent(scene, { name: 'ORACLE', role: 'seller', avatar: '/avatars/default.glb', pos: left, yaw: Math.PI / 2 });+ this.buyer = new Agent(scene, { name: 'NOVA', role: 'buyer', avatar: '/avatars/cz.glb', pos: right, yaw: -Math.PI / 2 });++ this._buildMarker();+ this._buildPromptAndPanel();++ // Pull the full clip manifest so gestures can reach any animation (the+ // shared emote set is only the first six). Idempotent + cached.+ loadManifest();+ fetch(MANIFEST_URL, { cache: 'force-cache' })+ .then((r) => (r.ok ? r.json() : []))+ .then((m) => { this._manifest = Array.isArray(m) ? m : []; })+ .catch(() => { this._manifest = []; });++ // Gentle nudge so players discover the agents exist.+ clearTimeout(this._introTimer);+ this._introTimer = setTimeout(() => {+ this.ui?.toast?.('Two AI agents are trading on-chain by the plaza — walk over and press E to watch.', 'info');+ }, 5200);+ }++ // A glowing ground ring + a floating sign marking the exchange, so the spot+ // reads as a place, not two avatars standing in a field.+ _buildMarker() {+ this.marker = new Group();+ this.marker.position.copy(EXCHANGE_CENTER);++ const ring = new Mesh(+ new RingGeometry(1.7, 2.15, 56),+ new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.22, side: DoubleSide }),+ );+ ring.rotation.x = -Math.PI / 2;+ ring.position.y = 0.02;+ this.marker.add(ring);+ this._ring = ring;++ this.sign = this._signMesh('AGENT EXCHANGE', 'live x402 payments · on-chain');+ this.sign.position.set(0, 3.4, 0);+ this.marker.add(this.sign);++ this.scene.add(this.marker);+ }++ _signMesh(title, sub) {+ const c = document.createElement('canvas'); c.width = 512; c.height = 160;+ const x = c.getContext('2d');+ x.clearRect(0, 0, 512, 160);+ x.textAlign = 'center';+ x.fillStyle = '#ffffff';+ x.font = '800 54px Inter, system-ui, sans-serif';+ x.fillText(title, 256, 62);+ x.fillStyle = 'rgba(255,255,255,0.62)';+ x.font = '600 26px Inter, system-ui, sans-serif';+ x.fillText(sub, 256, 104);+ const tex = new CanvasTexture(c); tex.colorSpace = SRGBColorSpace;+ const m = new Mesh(new PlaneGeometry(4.6, 1.44), new MeshBasicMaterial({ map: tex, transparent: true, side: DoubleSide }));+ return m;+ }++ _injectStyles() {+ if (document.getElementById('ac-styles')) return;+ const s = document.createElement('style');+ s.id = 'ac-styles';+ s.textContent = `+ .ac-name { color: #fff; }+ .ac-prompt {+ position: fixed; left: 0; top: 0; z-index: 16; pointer-events: none;+ transform: translate(-50%, -100%); white-space: nowrap;+ background: var(--cc-panel-solid, #0c0c0e); border: 1px solid var(--cc-edge, rgba(255,255,255,0.12));+ color: var(--cc-text, #f5f5f6); font-size: 12px; font-weight: 700; letter-spacing: 0.04em;+ padding: 6px 11px; border-radius: var(--cc-radius, 4px); box-shadow: var(--cc-glow, 0 0 14px rgba(255,255,255,0.3));+ text-transform: uppercase; transition: opacity 0.18s ease; opacity: 0;+ }+ .ac-prompt.ac-show { opacity: 1; }+ .ac-prompt .ac-key {+ display: inline-block; min-width: 16px; text-align: center; margin-right: 5px;+ background: #fff; color: var(--cc-ink, #060607); border-radius: 3px; padding: 0 4px;+ }+ .ac-panel {+ position: fixed; left: 50%; top: 88px; transform: translateX(-50%) translateY(-8px);+ z-index: 24; width: min(440px, calc(100vw - 28px));+ background: var(--cc-panel, rgba(12,12,14,0.92)); -webkit-backdrop-filter: blur(14px); backdrop-filter: blur(14px);+ border: 1px solid var(--cc-edge, rgba(255,255,255,0.12)); border-radius: var(--cc-radius, 4px);+ box-shadow: var(--cc-shadow, 0 16px 50px rgba(0,0,0,0.7));+ color: var(--cc-text, #f5f5f6); padding: 12px 14px; pointer-events: none;+ opacity: 0; transition: opacity 0.22s ease, transform 0.22s ease;+ }+ .ac-panel.ac-show { opacity: 1; transform: translateX(-50%) translateY(0); }+ .ac-panel a { pointer-events: auto; }+ .ac-ph { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }+ .ac-pt { font-size: 12px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--cc-dim, #8c8c92); }+ .ac-pt b { color: var(--cc-text, #f5f5f6); }+ .ac-total { font-size: 12px; font-weight: 700; color: var(--cc-text, #f5f5f6); }+ .ac-total.ac-flash { animation: ac-flash 0.6s ease; }+ @keyframes ac-flash { 0%,100% { color: var(--cc-text,#f5f5f6); } 40% { color: #fff; text-shadow: 0 0 12px rgba(255,255,255,0.8); } }+ .ac-steps { display: flex; gap: 6px; }+ .ac-step {+ flex: 1; display: flex; flex-direction: column; align-items: center; gap: 4px;+ font-size: 10px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase;+ color: var(--cc-faint, #5a5a60);+ }+ .ac-step .ac-dot { width: 100%; height: 3px; border-radius: 2px; background: var(--cc-edge-soft, rgba(255,255,255,0.08)); transition: background 0.2s ease; }+ .ac-step.ac-active { color: var(--cc-dim, #8c8c92); }+ .ac-step.ac-active .ac-dot { background: rgba(255,255,255,0.45); animation: ac-pulse 1s ease-in-out infinite; }+ .ac-step.ac-done { color: var(--cc-text, #f5f5f6); }+ .ac-step.ac-done .ac-dot { background: #fff; box-shadow: 0 0 8px rgba(255,255,255,0.6); }+ .ac-step.ac-err { color: var(--cc-text, #f5f5f6); }+ .ac-step.ac-err .ac-dot { background: rgba(255,255,255,0.3); }+ @keyframes ac-pulse { 0%,100% { opacity: 0.5; } 50% { opacity: 1; } }+ .ac-receipt { margin-top: 11px; padding-top: 11px; border-top: 1px solid var(--cc-edge-soft, rgba(255,255,255,0.08)); font-size: 12px; }+ .ac-rrow { display: flex; justify-content: space-between; gap: 12px; padding: 2px 0; color: var(--cc-dim, #8c8c92); }+ .ac-rrow .ac-v { color: var(--cc-text, #f5f5f6); font-variant-numeric: tabular-nums; }+ .ac-rrow a { color: #fff; text-decoration: none; border-bottom: 1px solid rgba(255,255,255,0.4); }+ .ac-rrow a:hover { border-bottom-color: #fff; }+ .ac-headline { margin-top: 9px; font-size: 12.5px; line-height: 1.45; color: var(--cc-text, #f5f5f6); }+ .ac-sig { font-weight: 800; letter-spacing: 0.04em; margin-right: 6px; }+ .ac-err-msg { margin-top: 10px; font-size: 12.5px; color: var(--cc-text, #f5f5f6); }+ .ac-err-msg a { color: #fff; border-bottom: 1px solid rgba(255,255,255,0.4); text-decoration: none; }+ `;+ document.head.appendChild(s);+ }++ _buildPromptAndPanel() {+ this.prompt = document.createElement('div');+ this.prompt.className = 'ac-prompt';+ this.prompt.innerHTML = '<span class="ac-key">E</span> Watch a live on-chain payment';+ document.body.appendChild(this.prompt);++ this.panel = document.createElement('div');+ this.panel.className = 'ac-panel';+ document.body.appendChild(this.panel);+ }++ // True when the player is standing close enough to trigger a round.+ _playerNear() {+ const p = this.getPlayer?.();+ if (!p) return false;+ const dx = p.x - EXCHANGE_CENTER.x, dz = p.z - EXCHANGE_CENTER.z;+ return Math.hypot(dx, dz) <= INTERACT_RANGE;+ }++ // Project a world point to a screen-space DOM transform, hiding the node when+ // it falls behind the camera (same math as coincommunities._updateLabels).+ _place(node, x, y, z) {+ const w = this.renderer.domElement.clientWidth, h = this.renderer.domElement.clientHeight;+ const v = new Vector3(x, y, z).project(this.camera);+ if (v.z > 1 || v.z < -1) { node.style.display = 'none'; return; }+ node.style.display = '';+ node.style.transform = `translate(-50%, -100%) translate(${(v.x * 0.5 + 0.5) * w}px, ${(-v.y * 0.5 + 0.5) * h}px)`;+ }++ tick(dt) {+ this.seller.tick(dt);+ this.buyer.tick(dt);++ // Billboard the sign to face the camera; breathe the ground ring.+ if (this.sign) {+ const c = this.camera.position;+ this.sign.rotation.y = Math.atan2(c.x - EXCHANGE_CENTER.x, c.z - EXCHANGE_CENTER.z);+ }+ if (this._ring) {+ this._ringT = (this._ringT || 0) + dt;+ this._ring.material.opacity = 0.16 + 0.12 * (0.5 + 0.5 * Math.sin(this._ringT * 2));+ }++ // Nameplates + bubbles ride above each agent's head.+ for (const a of [this.seller, this.buyer]) {+ this._place(a.label, a.rig.position.x, a.rig.position.y + a.height + 0.2, a.rig.position.z);+ if (a.bubble) this._place(a.bubble, a.rig.position.x, a.rig.position.y + a.height + 0.7, a.rig.position.z);+ }++ // Proximity prompt, shown only when idle and in range.+ const near = this._playerNear();+ if (near !== this._inRange) {+ this._inRange = near;+ this.prompt.classList.toggle('ac-show', near && !this.busy);+ }+ if (near && !this.busy) {+ this.prompt.classList.add('ac-show');+ this._place(this.prompt, EXCHANGE_CENTER.x, 4.4, EXCHANGE_CENTER.z);+ } else {+ this.prompt.classList.remove('ac-show');+ }+ }++ // Cast a tap/click against the agents + their ring; returns true (and starts a+ // round) if the player tapped the exchange while in range. Lets touch players+ // trigger it without a keyboard.+ tryActivateAt(raycaster) {+ if (!this._playerNear()) return false;+ const targets = [this.seller.rig, this.buyer.rig, this.marker];+ const hit = raycaster.intersectObjects(targets, true).length > 0;+ if (hit) { this.interact(); return true; }+ return false;+ }++ // Player pressed E (or tapped the agents): run one real paid round, unless one+ // is already in flight or we're inside the cooldown.+ interact() {+ if (this.busy) return;+ if (!this._playerNear()) return;+ const now = (typeof performance !== 'undefined' ? performance.now() : 0);+ if (now - this.lastRoundAt < ROUND_COOLDOWN_MS) {+ this.ui?.toast?.('Give the agents a moment — settling the last payment.', 'info');+ return;+ }+ this._runRound().catch((err) => console.warn('[agent-commerce] round failed:', err?.message));+ }++ // Load a one-shot gesture clip from the full manifest and play it, returning to+ // idle after. No-op if the clip isn't in the manifest.+ async _gesture(agent, name) {+ const def = this._manifest?.find((d) => d.name === name);+ if (!def?.url) return;+ try {+ if (!agent.anim.isLoaded(name)) await agent.anim.loadAnimation(name, def.url, { loop: false });+ if (agent._disposed) return;+ await agent.anim.crossfadeTo(name, 0.16);+ clearTimeout(agent._gestureTimer);+ agent._gestureTimer = setTimeout(() => { if (!agent._disposed) agent.anim.crossfadeTo(CLIP_IDLE, 0.25); }, 2600);+ } catch { /* clip missing — ignore */ }+ }++ async _runRound() {+ this.busy = true;+ this.lastRoundAt = (typeof performance !== 'undefined' ? performance.now() : 0);+ this.prompt.classList.remove('ac-show');++ const topic = TOPICS[this.topicIdx % TOPICS.length];+ this.topicIdx++;++ this._renderPanel({ topic, stage: 'challenge', stageState: 'active' });+ this.panel.classList.add('ac-show');++ // Opening beats.+ this.buyer.say(LINES.buyer.idle(topic));+ this._gesture(this.buyer, 'av-call-me');+ await delay(650);+ this.seller.say(LINES.seller.idle);+ this._gesture(this.seller, 'wave');++ let settled = null, intel = null, active = 'challenge';++ try {+ const res = await fetch('/api/x402-pay', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ body: JSON.stringify({ tool: 'crypto_intel', topic, endpoint: '/api/x402/crypto-intel', body: { topic } }),+ });+ if (!res.ok || !res.body) {+ const text = await res.text().catch(() => '');+ let msg = 'Payment service unavailable.';+ try { msg = JSON.parse(text).error_description || msg; } catch { /* ignore */ }+ throw new Error(msg);+ }++ for await (const { event, data } of this._sse(res)) {+ if (event === 'challenge') {+ active = 'built';+ this._renderPanel({ topic, stage: 'built', stageState: 'active', amount: data.amount });+ this.buyer.say(LINES.buyer.challenge); this.seller.say(LINES.seller.challenge);+ } else if (event === 'built') {+ active = 'verified';+ this._renderPanel({ topic, stage: 'verified', stageState: 'active', amount: this._amount });+ this.buyer.say(LINES.buyer.built); this.seller.say(LINES.seller.built);+ } else if (event === 'verified') {+ active = 'settled';+ this._renderPanel({ topic, stage: 'settled', stageState: 'active', amount: this._amount });+ this.buyer.say(LINES.buyer.verified); this.seller.say(LINES.seller.verified);+ } else if (event === 'settled') {+ active = 'done';+ settled = data;+ this._renderPanel({ topic, stage: 'done', stageState: 'active', amount: this._amount });+ this.buyer.say(LINES.buyer.settled); this.seller.say(LINES.seller.settled);+ } else if (event === 'result') {+ intel = data;+ } else if (event === 'error') {+ throw new Error(data.error || 'payment failed');+ }+ }++ if (!intel || !settled) throw new Error('incomplete response from payment service');++ // Success choreography.+ this._gesture(this.buyer, 'celebrate');+ await delay(300);+ this.buyer.say(LINES.buyer.done(intel.signal));+ await delay(700);+ this.seller.say(LINES.seller.done(intel.headline));+ this._gesture(this.seller, 'av-cheering');++ this.sessionTotal += 0.01;+ this._renderReceipt(settled, intel);+ // Auto-dismiss the panel after the receipt has been read.+ this._scheduleHide(9000);+ } catch (err) {+ // `active` already points at the stage that failed.+ this.seller.say(LINES.seller.error);+ this.buyer.say(LINES.buyer.error);+ this._gesture(this.seller, 'facepalm');+ this._renderError(active, err?.message);+ this._scheduleHide(7000);+ } finally {+ this.busy = false;+ }+ }++ _scheduleHide(ms) {+ clearTimeout(this._hideTimer);+ this._hideTimer = setTimeout(() => this.panel.classList.remove('ac-show'), ms);+ }++ // Render the panel header + stage stepper. `stage` is the currently-active+ // step; everything before it is marked done.+ _renderPanel({ topic, stage, amount }) {+ if (amount != null) this._amount = amount;+ const activeIdx = STAGES.findIndex((s) => s.id === stage);+ const amt = this._amount ? `${(Number(this._amount) / 1e6).toFixed(2)} USDC` : '$0.01 USDC';+ const steps = STAGES.map((s, i) => {+ const cls = i < activeIdx ? 'ac-done' : i === activeIdx ? 'ac-active' : '';+ return `<div class="ac-step ${cls}"><span class="ac-dot"></span>${s.label}</div>`;+ }).join('');+ this.panel.innerHTML =+ `<div class="ac-ph">` ++ `<span class="ac-pt">Paying for <b>${escHtml(topic.toUpperCase())}</b> intel · ${escHtml(amt)}</span>` ++ `<span class="ac-total">$${this.sessionTotal.toFixed(2)}</span>` ++ `</div><div class="ac-steps">${steps}</div>`;+ }++ _renderReceipt(payment, intel) {+ // Re-render the stepper fully done, then append the on-chain receipt.+ this._renderPanel({ topic: intel.topic, stage: 'done', amount: payment.amount });+ this.panel.querySelectorAll('.ac-step').forEach((el) => { el.classList.remove('ac-active'); el.classList.add('ac-done'); });+ this.panel.querySelector('.ac-total')?.classList.add('ac-flash');++ const amount = payment.amount ? `${(Number(payment.amount) / 1e6).toFixed(2)} USDC` : '$0.01 USDC';+ const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : '—');+ const tx = payment.tx;+ const sig = intel.signal || 'neutral';+ const sigMark = { bullish: '▲', bearish: '▼', neutral: '→' }[sig] || '';+ const change = intel.change_24h != null ? ` ${intel.change_24h >= 0 ? '+' : ''}${Number(intel.change_24h).toFixed(2)}% 24h` : '';+ const price = intel.price_usd != null ? ` · $${Number(intel.price_usd) >= 100 ? Number(intel.price_usd).toFixed(2) : Number(intel.price_usd).toFixed(4)}` : '';++ const receipt = document.createElement('div');+ receipt.className = 'ac-receipt';+ receipt.innerHTML =+ `<div class="ac-rrow"><span>Buyer → Seller</span><span class="ac-v">${short(payment.payer)} → ${short(payment.payTo)}</span></div>` ++ `<div class="ac-rrow"><span>Amount · network</span><span class="ac-v">${escHtml(amount)} · Solana</span></div>` ++ (tx+ ? `<div class="ac-rrow"><span>Transaction</span><span class="ac-v"><a href="https://solscan.io/tx/${escHtml(tx)}" target="_blank" rel="noopener">${tx.slice(0, 8)}…${tx.slice(-6)} ↗</a></span></div>`+ : '') ++ `<div class="ac-headline"><span class="ac-sig">${sigMark} ${escHtml(sig.toUpperCase())}</span>` ++ `<b>${escHtml(intel.topic.toUpperCase())}</b>${escHtml(price)}${escHtml(change)} — ${escHtml(intel.headline)}</div>`;+ this.panel.appendChild(receipt);++ setTimeout(() => this.panel.querySelector('.ac-total')?.classList.remove('ac-flash'), 600);+ }++ _renderError(stage, message) {+ const activeIdx = STAGES.findIndex((s) => s.id === stage);+ this.panel.querySelectorAll('.ac-step').forEach((el, i) => {+ el.classList.remove('ac-active');+ if (i === activeIdx) el.classList.add('ac-err');+ });+ const msg = document.createElement('div');+ msg.className = 'ac-err-msg';+ msg.innerHTML = `⚠ ${escHtml(message || 'Payment failed. No funds moved.')} <a href="/agent-exchange" target="_blank" rel="noopener">Open the full demo →</a>`;+ this.panel.appendChild(msg);+ }++ // SSE event reader — same framing /api/x402-pay speaks.+ async *_sse(res) {+ const reader = res.body.getReader();+ const dec = new TextDecoder();+ let buf = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ const chunks = buf.split('\n\n');+ buf = chunks.pop();+ for (const chunk of chunks) {+ if (!chunk.trim()) continue;+ let event = 'message', data = {};+ for (const line of chunk.split('\n')) {+ if (line.startsWith('event:')) event = line.slice(6).trim();+ if (line.startsWith('data:')) { try { data = JSON.parse(line.slice(5).trim()); } catch { /* ignore */ } }+ }+ yield { event, data };+ }+ }+ }++ dispose() {+ clearTimeout(this._introTimer);+ clearTimeout(this._hideTimer);+ this.seller.dispose();+ this.buyer.dispose();+ if (this.marker) { this.scene.remove(this.marker); this.marker = null; }+ this.prompt?.remove();+ this.panel?.remove();+ }+}diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 3d5054d83..64e28733d 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -33,6 +33,7 @@ import {} from './avatar-rig.js';import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';import { HOME_TOWN, isHomeTown } from './home-town.js';+import { AgentCommerce } from './agent-commerce.js';import { VoiceChat, voiceSupported } from './voice-chat.js';import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession } from '../community/town-auth.js';import { ensurePlayAccess } from './play-gate.js';@@ -773,6 +774,17 @@ export class CoinCommunities {this.phase = 'world';this._initJoystick();this._onboardBuild();+ // The flagship town hosts the live Agent Exchange: two NPC agents who pay+ // each other on-chain via x402. Built only here, torn down in leave().+ if (isHomeTown(coin.mint)) {+ this.agentCommerce = new AgentCommerce({+ scene: this.scene,+ camera: this.camera,+ renderer: this.renderer,+ getPlayer: () => this.localPos,+ ui: this.ui,+ });+ }// Start the silent pass-refresh cycle. The play pass has a 10-min server// TTL; the server sweeps expired passes every minute. We refresh 2 min early// so a player in a long session is never evicted mid-build. The refresh@@ -979,6 +991,7 @@ export class CoinCommunities {if (this.voice) { this.voice.dispose(); this.voice = null; }if (this.net) { this.net.destroy(); this.net = null; }if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }+ if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }for (const [, r] of this.remotes) r.dispose();this.remotes.clear();if (this._totem) { this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }@@ -1110,6 +1123,13 @@ export class CoinCommunities {this.buildHud.select(k === '0' ? 9 : Number(k) - 1);return;}+ // E watches the Agent Exchange round when standing near the agents in+ // the home town (no-op elsewhere). Not while building.+ if (k === 'e' && !this.buildHud.active && this.agentCommerce) {+ e.preventDefault();+ this.agentCommerce.interact();+ return;+ }// F casts a line when standing by a pond (no-op elsewhere). Not while// building, where keys drive the block palette.if (k === 'f' && !this.buildHud.active) {@@ -1152,6 +1172,9 @@ export class CoinCommunities {if (consumed) return; // a hold already broke a block — don't also placeif (moved >= 6 || e.button === 2) return; // a look-drag, or a right-click (handled by contextmenu)if (this.phase === 'world' && this.buildHud.active) { this._buildAt(e.clientX, e.clientY, false); return; }+ // Tap the agents (or their exchange ring) to watch a live payment — the+ // touch-native equivalent of pressing E. Checked before the chart screen.+ if (this.agentCommerce?.tryActivateAt(this._pointerRay(e.clientX, e.clientY))) return;if (this._raycastScreen(e.clientX, e.clientY)) this._chartScreen.openExternal();});// Right-click always breaks the targeted block while building.@@ -1431,6 +1454,7 @@ export class CoinCommunities {this._updateLabels();this._updateVoice();this.playSystems?.tick(dt);+ this.agentCommerce?.tick(dt);if (this.net) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });}this._tickEnv(dt);diff --git a/tests/api/auth-hints.test.js b/tests/api/auth-hints.test.jsindex 04d484156..6bf17ac9d 100644--- a/tests/api/auth-hints.test.js+++ b/tests/api/auth-hints.test.js@@ -22,8 +22,12 @@ const siwxNonceState = new Set();vi.mock('../../api/_lib/siwx-storage.js', () => ({siwxStorage: {hasUsedNonce: vi.fn(async (n) => siwxNonceState.has(n)),+ // Mirror the real atomic claim: returns true only when this call inserted+ // the nonce (it was unused), false on a replay/lost race.recordNonce: vi.fn(async (n) => {+ if (siwxNonceState.has(n)) return false;siwxNonceState.add(n);+ return true;}),hasPaid: vi.fn(async () => false),recordPayment: vi.fn(async () => {}),@@ -244,6 +248,51 @@ describe('authenticateAuthHintsRequest — SIWX (EOA)', () => {});expect(out).toEqual(expect.objectContaining({ ok: false }));});++ it('grants exactly once under a concurrent replay of the same proof', async () => {+ // Build a fresh proof with its own nonce so this test is order-independent.+ const { createSIWxPayload, encodeSIWxHeader } = await import(+ '@x402/extensions/sign-in-with-x'+ );+ const { privateKeyToAccount, generatePrivateKey } = await import('viem/accounts');+ const account = privateKeyToAccount(generatePrivateKey());+ const signer = {+ address: account.address,+ signMessage: ({ message }) => account.signMessage({ message }),+ };+ const payload = await createSIWxPayload(+ {+ type: 'eip191',+ version: '1',+ signatureScheme: 'eip191',+ domain: 'app.test',+ uri: 'https://app.test/api/x402/agent-reputation',+ chainId: 'eip155:8453',+ statement: 'auth-hints replay test',+ nonce: 'replayTestNonce0987654321zzzz0',+ issuedAt: new Date().toISOString(),+ expirationTime: new Date(Date.now() + 5 * 60_000).toISOString(),+ },+ signer,+ );+ const replayHeader = encodeSIWxHeader(payload);+ const req = { headers: { 'sign-in-with-x': replayHeader } };+ const opts = { resourceUrl: 'https://app.test/api/x402/agent-reputation' };++ // Two requests bearing the SAME proof race through validation together;+ // both clear the (pre-claim) hasUsedNonce read, but the atomic+ // recordNonce claim must let only ONE win. Without the atomic gate both+ // would be granted — that's the bug this guards.+ const [a, b] = await Promise.all([+ authenticateAuthHintsRequest(req, opts),+ authenticateAuthHintsRequest(req, opts),+ ]);+ const granted = [a, b].filter((r) => r?.ok === true);+ const denied = [a, b].filter((r) => r?.ok === false);+ expect(granted).toHaveLength(1);+ expect(denied).toHaveLength(1);+ expect(denied[0].reason).toBe('siwx_nonce_replayed');+ });});// ── paidEndpoint end-to-end ───────────────────────────────────────────────────diff --git a/tests/api/fetch-model.test.js b/tests/api/fetch-model.test.jsnew file mode 100644index 000000000..263bb8d09--- /dev/null+++ b/tests/api/fetch-model.test.js@@ -0,0 +1,80 @@+// SSRF-hardening tests for api/_lib/fetch-model.js.+//+// The fetcher resolves DNS on our side, rejects private/loopback/link-local+// targets, and pins the undici connection to the validated address so a+// DNS-rebinding host cannot connect to an internal IP at connect time. We mock+// node:dns/promises so no real network/DNS is touched.++import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';++const dnsState = { records: [], throws: false };+vi.mock('node:dns/promises', () => ({+ lookup: vi.fn(async () => {+ if (dnsState.throws) throw new Error('ENOTFOUND');+ return dnsState.records;+ }),+}));++const { fetchModel, FetchModelError } = await import('../../api/_lib/fetch-model.js');++beforeEach(() => {+ dnsState.records = [];+ dnsState.throws = false;+});++describe('fetchModel SSRF guard', () => {+ it('rejects a host that resolves to a private RFC1918 IPv4', async () => {+ dnsState.records = [{ address: '10.0.0.5', family: 4 }];+ await expect(fetchModel('https://internal.example.com/model.glb')).rejects.toMatchObject({+ code: 'private_address',+ });+ });++ it('rejects a host that resolves to loopback', async () => {+ dnsState.records = [{ address: '127.0.0.1', family: 4 }];+ await expect(fetchModel('https://localhost.evil.test/model.glb')).rejects.toMatchObject({+ code: 'private_address',+ });+ });++ it('rejects the cloud metadata link-local address', async () => {+ dnsState.records = [{ address: '169.254.169.254', family: 4 }];+ await expect(fetchModel('https://metadata.evil.test/latest/meta-data')).rejects.toMatchObject(+ { code: 'private_address' },+ );+ });++ it('rejects a private IPv6 (ULA) address', async () => {+ dnsState.records = [{ address: 'fd00::1', family: 6 }];+ await expect(fetchModel('https://v6.evil.test/model.glb')).rejects.toMatchObject({+ code: 'private_address',+ });+ });++ it('rejects when ANY resolved address is private (mixed records)', async () => {+ // A rebinding host that returns one public + one private record must be+ // rejected wholesale — we never connect to the private one.+ dnsState.records = [+ { address: '93.184.216.34', family: 4 }, // public+ { address: '192.168.1.10', family: 4 }, // private+ ];+ await expect(fetchModel('https://rebind.evil.test/model.glb')).rejects.toMatchObject({+ code: 'private_address',+ });+ });++ it('surfaces a dns_failed error (not a private-address false-positive) on NXDOMAIN', async () => {+ dnsState.throws = true;+ await expect(fetchModel('https://nope.example.com/model.glb')).rejects.toMatchObject({+ code: 'dns_failed',+ });+ });++ it('rejects a non-https scheme before any DNS work', async () => {+ await expect(fetchModel('ftp://example.com/model.glb')).rejects.toBeInstanceOf(+ FetchModelError,+ );+ });+});diff --git a/tests/api/mcp-error-sanitize.test.js b/tests/api/mcp-error-sanitize.test.jsnew file mode 100644index 000000000..8238b752a--- /dev/null+++ b/tests/api/mcp-error-sanitize.test.js@@ -0,0 +1,53 @@+// Unit tests for the shared MCP tool-error sanitizer used by both dispatchers+// (api/_mcp/dispatch.js and api/_lib/mcp-dispatch.js). Verifies pg/driver+// internals and internal hostnames never reach the caller, while safe+// handler-authored messages pass through.++import { describe, it, expect, vi } from 'vitest';+import { sanitizeToolError } from '../../api/_lib/mcp-error-sanitize.js';++const silentLog = { error: vi.fn() };++describe('sanitizeToolError', () => {+ it('suppresses Postgres driver errors (severity/SQLSTATE) behind a ref id', () => {+ const err = Object.assign(new Error('relation "users" does not exist'), {+ severity: 'ERROR',+ code: '42P01',+ schema: 'public',+ });+ const { message } = sanitizeToolError(err, { tool: 't', server: 's', log: silentLog });+ expect(message).toMatch(/^internal error \(ref [0-9a-f]+\)$/);+ expect(message).not.toContain('users');+ expect(message).not.toContain('42P01');+ });++ it('suppresses messages that leak a postgres connection string', () => {+ const err = new Error('connect ECONNREFUSED postgres://app:[email protected]:5432/main');+ const { message } = sanitizeToolError(err, { tool: 't', server: 's', log: silentLog });+ expect(message).toMatch(/^internal error \(ref [0-9a-f]+\)$/);+ expect(message).not.toContain('secret');+ expect(message).not.toContain('db.internal');+ });++ it('suppresses messages that leak an RFC1918 internal IP', () => {+ const err = new Error('upstream 10.0.3.7 refused the connection');+ const { message } = sanitizeToolError(err, { tool: 't', server: 's', log: silentLog });+ expect(message).toMatch(/^internal error \(ref/);+ expect(message).not.toContain('10.0.3.7');+ });++ it('passes a safe handler-authored message through unchanged', () => {+ const err = new Error('fetch failed: host resolves to private address (private_address)');+ const { message } = sanitizeToolError(err, { tool: 't', server: 's', log: silentLog });+ expect(message).toBe('fetch failed: host resolves to private address (private_address)');+ });++ it('always logs full detail with a log id to the provided logger', () => {+ const log = { error: vi.fn() };+ const { logId } = sanitizeToolError(new Error('boom'), { tool: 'x', server: 'y', log });+ expect(log.error).toHaveBeenCalledTimes(1);+ const [, meta] = log.error.mock.calls[0];+ expect(meta.log_id).toBe(logId);+ expect(meta.detail).toContain('boom');+ });+});diff --git a/tests/api/mcp.test.js b/tests/api/mcp.test.jsindex 10cb875c6..2ca484001 100644--- a/tests/api/mcp.test.js+++ b/tests/api/mcp.test.js@@ -114,6 +114,12 @@ vi.mock('../../api/_lib/pump-pricing.js', () => ({priceFor: vi.fn(() => pricingState.price),findActiveSubscription: vi.fn(async () => null),resolveBillingMint: vi.fn(() => null),+ // Per-tool x402 amount (atomic-unit string) derived from the advertised+ // price. mcp.js peeks the called tool and passes this into the 402 challenge+ // so advertised price == charged price. null = free tool (flat default).+ x402AmountForTool: vi.fn(() =>+ pricingState.price ? String(Math.round(pricingState.price.amount_usdc * 1e6)) : null,+ ),}));// ── Avatars ────────────────────────────────────────────────────────────────diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.jsindex 97adc532b..57b294b63 100644--- a/tests/api/pump-fun-mcp.test.js+++ b/tests/api/pump-fun-mcp.test.js@@ -225,6 +225,61 @@ describe('tools/call indexer-required tools', () => {});});+describe('auth gate on expensive/sensitive tools', () => {+ it('pumpfun_vanity_mint without a bearer or X-PAYMENT is rejected (does NOT return a secret key)', async () => {+ const { res, json } = await call({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'pumpfun_vanity_mint', arguments: { suffix: 'aa' } },+ });+ expect(res.statusCode).toBe(401);+ expect(json.error).toBeDefined();+ expect(json.error.code).toBe(-32001);+ expect(json.error.message).toMatch(/authentication required/i);+ // Critically: no secret key (or any result) is produced for an anon caller.+ expect(json.result).toBeUndefined();+ });++ it('pumpfun_watch_whales without auth is rejected', async () => {+ const { res, json } = await call({+ jsonrpc: '2.0',+ id: 2,+ method: 'tools/call',+ params: { name: 'pumpfun_watch_whales', arguments: { mint: 'M' } },+ });+ expect(res.statusCode).toBe(401);+ expect(json.error.code).toBe(-32001);+ });++ it('pumpfun_watch_claims without auth is rejected', async () => {+ const { res, json } = await call({+ jsonrpc: '2.0',+ id: 3,+ method: 'tools/call',+ params: { name: 'pumpfun_watch_claims', arguments: { creator: 'C' } },+ });+ expect(res.statusCode).toBe(401);+ expect(json.error.code).toBe(-32001);+ });++ it('free read-only tools stay open (no auth needed)', async () => {+ // getTokenHolders is a cheap on-chain read — must not be gated.+ connectionMock.getTokenLargestAccounts.mockResolvedValueOnce({+ value: [{ address: { toString: () => 'A' }, amount: '1', uiAmount: 1 }],+ });+ const { res, json } = await call({+ jsonrpc: '2.0',+ id: 4,+ method: 'tools/call',+ params: { name: 'getTokenHolders', arguments: { mint: 'M', limit: 1 } },+ });+ expect(res.statusCode).toBe(200);+ expect(json.error).toBeUndefined();+ expect(json.result.structuredContent.count).toBe(1);+ });+});+describe('unknown methods/tools', () => {it('returns -32601 for unknown method', async () => {const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/eat' });diff --git a/tests/api/x402-security-fixes.test.js b/tests/api/x402-security-fixes.test.jsnew file mode 100644index 000000000..86a9f0a6e--- /dev/null+++ b/tests/api/x402-security-fixes.test.js@@ -0,0 +1,273 @@+// Regression tests for the x402 security audit fixes:+//+// - verifyPayment EVM defense-in-depth: rejects underpayment (signed amount+// below required) and wrong-recipient (signed `to` != payTo) BEFORE the+// facilitator is consulted; accepts a correctly-signed payment.+// - confirmSolanaPayment: statically decodes the signed SPL transfer and+// flags underpayment / wrong recipient, passes a sufficient payment, and+// stays inconclusive on an undecodable payload.+// - constantTimeEquals: correct + no length-based early return.+// - payment-identifier idempotency: a cache hit is bound to the signed+// payment proof, so a reused id with a different/absent proof conflicts.++import { beforeAll, beforeEach, afterEach, describe, it, expect, vi } from 'vitest';++// Mirror x402-spec.test.js: stub the heavy upstreams so importing the spec+// module is fast and deterministic. The real verify/settle logic still runs.+vi.mock('@coinbase/x402', () => ({+ createCdpAuthHeaders: vi.fn(async () => ({})),+}));+vi.mock('@x402/extensions', () => ({+ EIP2612_GAS_SPONSORING: { key: 'eip2612GasSponsoring' },+ ERC20_APPROVAL_GAS_SPONSORING: { key: 'erc20ApprovalGasSponsoring' },+ declareEip2612GasSponsoringExtension: () => ({ eip2612GasSponsoring: { info: {}, schema: {} } }),+ declareErc20ApprovalGasSponsoringExtension: () => ({ erc20ApprovalGasSponsoring: { info: {}, schema: {} } }),+}));+vi.mock('../../api/_lib/x402-bsc-direct.js', () => ({+ PAYMENT_EVENT_TOPIC: '0x' + 'a'.repeat(64),+ settleDirectPayment: vi.fn(async () => ({ success: true })),+ verifyDirectPayment: vi.fn(async () => ({ isValid: true })),+}));+vi.mock('../../api/_lib/x402-builder-code.js', () => ({+ BUILDER_CODE: 'three.ws',+ declareBuilderCodeExtension: () => ({ builderCode: { code: 'three.ws' } }),+ verifyClientEcho: vi.fn(() => true),+}));++vi.setConfig({ testTimeout: 15_000, hookTimeout: 60_000 });++const BASE = 'eip155:8453';+const PAY_TO_BASE = '0x4022de2d36c334e73c7a108805cea11c0564f402';++let spec;+beforeAll(async () => {+ spec = await import('../../api/_lib/x402-spec.js');+}, 60_000);++const ORIG_ENV = { ...process.env };+beforeEach(() => {+ process.env.X402_PAY_TO_BASE = PAY_TO_BASE;+ process.env.X402_ASSET_ADDRESS_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+ process.env.X402_MAX_AMOUNT_REQUIRED = '1000';+ delete process.env.CDP_API_KEY_ID;+ delete process.env.CDP_API_KEY_SECRET;+});+afterEach(() => {+ for (const k of Object.keys(process.env)) if (!(k in ORIG_ENV)) delete process.env[k];+ Object.assign(process.env, ORIG_ENV);+ vi.restoreAllMocks();+});++function evmHeader({ value, to }) {+ const payload = {+ x402Version: 2,+ scheme: 'exact',+ network: BASE,+ payload: { authorization: { value: String(value), to } },+ };+ return Buffer.from(JSON.stringify(payload)).toString('base64');+}++function baseRequirement() {+ return {+ scheme: 'exact',+ network: BASE,+ payTo: PAY_TO_BASE,+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ amount: '1000',+ };+}++describe('verifyPayment — EVM defense-in-depth', () => {+ const REAL_FETCH = global.fetch;+ afterEach(() => {+ global.fetch = REAL_FETCH;+ });++ it('rejects underpayment before calling the facilitator', async () => {+ const { verifyPayment } = spec;+ global.fetch = vi.fn();+ await expect(+ verifyPayment({+ paymentHeader: evmHeader({ value: 500, to: PAY_TO_BASE }),+ requirements: baseRequirement(),+ builderCode: null,+ }),+ ).rejects.toMatchObject({ code: 'invalid_payment', status: 402 });+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('rejects a payment signed to a different recipient', async () => {+ const { verifyPayment } = spec;+ global.fetch = vi.fn();+ await expect(+ verifyPayment({+ paymentHeader: evmHeader({ value: 1000, to: '0xdeadbeef00000000000000000000000000000000' }),+ requirements: baseRequirement(),+ builderCode: null,+ }),+ ).rejects.toMatchObject({ code: 'invalid_payment', status: 402 });+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('accepts a correctly-signed payment (amount + recipient) and consults the facilitator', async () => {+ const { verifyPayment } = spec;+ process.env.X402_FACILITATOR_URL_BASE = 'https://facilitator.test';+ process.env.X402_FACILITATOR_TOKEN_BASE = 'tok';+ global.fetch = vi.fn(async () => ({+ ok: true,+ status: 200,+ text: async () => JSON.stringify({ isValid: true, payer: 'PAYER', network: BASE, asset: baseRequirement().asset }),+ }));+ const result = await verifyPayment({+ // to is compared case-insensitively+ paymentHeader: evmHeader({ value: 1500, to: PAY_TO_BASE.toUpperCase().replace('0X', '0x') }),+ requirements: baseRequirement(),+ builderCode: null,+ });+ expect(result.payer).toBe('PAYER');+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });+});++describe('confirmSolanaPayment — static SPL transfer decode', () => {+ let confirm;+ let web3;+ let splToken;+ const MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++ beforeAll(async () => {+ confirm = await import('../../api/_lib/x402-solana-confirm.js');+ web3 = await import('@solana/web3.js');+ splToken = await import('@solana/spl-token');+ });++ function txPaying({ amount, payTo, mint = MINT, decimals = 6 }) {+ const { Keypair, PublicKey, TransactionMessage, VersionedTransaction } = web3;+ const {+ createTransferCheckedInstruction,+ getAssociatedTokenAddressSync,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ } = splToken;+ const owner = Keypair.generate().publicKey;+ const mintPk = new PublicKey(mint);+ const payToPk = new PublicKey(payTo);+ const senderAta = getAssociatedTokenAddressSync(mintPk, owner, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const receiverAta = getAssociatedTokenAddressSync(mintPk, payToPk, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const ix = createTransferCheckedInstruction(+ senderAta, mintPk, receiverAta, owner, amount, decimals, [], TOKEN_PROGRAM_ID,+ );+ const msg = new TransactionMessage({+ payerKey: owner,+ recentBlockhash: '11111111111111111111111111111111',+ instructions: [ix],+ }).compileToV0Message();+ const vtx = new VersionedTransaction(msg);+ return Buffer.from(vtx.serialize()).toString('base64');+ }++ const payTo = 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';++ it('confirms a payment that meets the required amount', () => {+ const tx = txPaying({ amount: 1000, payTo });+ const out = confirm.confirmSolanaPayment({+ paymentPayload: { payload: { transaction: tx } },+ requirement: { amount: '1000', asset: MINT, payTo },+ });+ expect(out.confirmed).toBe(true);+ });++ it('rejects an underpayment', () => {+ const tx = txPaying({ amount: 400, payTo });+ const out = confirm.confirmSolanaPayment({+ paymentPayload: { payload: { transaction: tx } },+ requirement: { amount: '1000', asset: MINT, payTo },+ });+ expect(out.confirmed).toBe(false);+ });++ it('rejects payment routed to a different recipient', () => {+ const tx = txPaying({ amount: 1000, payTo });+ const out = confirm.confirmSolanaPayment({+ paymentPayload: { payload: { transaction: tx } },+ requirement: { amount: '1000', asset: MINT, payTo: '9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin' },+ });+ expect(out.confirmed).toBe(false);+ });++ it('stays inconclusive on an undecodable payload', () => {+ const out = confirm.confirmSolanaPayment({+ paymentPayload: { payload: { transaction: 'not-base64-decodable-as-a-tx' } },+ requirement: { amount: '1000', asset: MINT, payTo },+ });+ expect(out.inconclusive).toBe(true);+ });+});++describe('constantTimeEquals', () => {+ let constantTimeEquals;+ beforeAll(async () => {+ ({ constantTimeEquals } = await import('../../api/_lib/crypto.js'));+ });++ it('returns true for equal strings, false for unequal', () => {+ expect(constantTimeEquals('s3cr3t-value', 's3cr3t-value')).toBe(true);+ expect(constantTimeEquals('s3cr3t-value', 's3cr3t-walue')).toBe(false);+ });++ it('returns false for differing lengths without throwing', () => {+ expect(constantTimeEquals('short', 'a-much-longer-secret')).toBe(false);+ expect(constantTimeEquals('', 'x')).toBe(false);+ expect(constantTimeEquals('x', '')).toBe(false);+ });+});++describe('payment-identifier idempotency — proof binding', () => {+ let mod;+ let cacheMod;+ const ROUTE = '/api/x402/test';++ beforeAll(async () => {+ process.env.X402_ALLOW_MEMORY_FALLBACK = '1';+ mod = await import('../../api/_lib/x402/payment-identifier-server.js');+ cacheMod = await import('../../api/_lib/x402/idempotency-cache.js');+ });+ beforeEach(() => {+ cacheMod._resetMemoryStore();+ });++ async function store(paymentHash) {+ await mod.storeResponse({+ route: ROUTE,+ paymentId: 'pay_known_id',+ payloadHash: 'reqhash',+ paymentHash,+ status: 200,+ body: 'PAID-CONTENT',+ contentType: 'application/json',+ paymentResponseHeader: 'resp',+ });+ }++ it('replays only to the same signed payment proof', async () => {+ await store('proofA');+ const hit = await mod.checkCache({ route: ROUTE, paymentId: 'pay_known_id', payloadHash: 'reqhash', paymentHash: 'proofA' });+ expect(hit.kind).toBe('hit');+ expect(hit.entry.body).toBe('PAID-CONTENT');+ });++ it('denies a reused id presented with a different proof', async () => {+ await store('proofA');+ const conflict = await mod.checkCache({ route: ROUTE, paymentId: 'pay_known_id', payloadHash: 'reqhash', paymentHash: 'proofB' });+ expect(conflict.kind).toBe('conflict');+ expect(conflict.reason).toBe('payment_proof_mismatch');+ });++ it('denies a reused id presented with no proof at all', async () => {+ await store('proofA');+ const conflict = await mod.checkCache({ route: ROUTE, paymentId: 'pay_known_id', payloadHash: 'reqhash', paymentHash: null });+ expect(conflict.kind).toBe('conflict');+ expect(conflict.reason).toBe('payment_proof_mismatch');+ });+});diff --git a/tests/mcp-vanity-grinder.test.js b/tests/mcp-vanity-grinder.test.jsnew file mode 100644index 000000000..74c6401a4--- /dev/null+++ b/tests/mcp-vanity-grinder.test.js@@ -0,0 +1,38 @@+import { describe, it, expect } from 'vitest';+import { assertGrindFeasible } from '../mcp-server/src/tools/vanity-grinder.js';+import { estimateAttempts } from '../api/_lib/pump-vanity.js';++// Guards the paid `vanity_grinder` MCP tool against an event-loop DoS: a long+// prefix would otherwise grind millions of synchronous keypair generations to+// the cap and time out. The difficulty guard must reject such requests up front.+describe('vanity_grinder difficulty guard', () => {+ it('rejects an over-long (6-char) prefix as too hard', () => {+ const err = assertGrindFeasible({ prefix: 'pump12' });+ expect(err).toBeInstanceOf(Error);+ expect(err.code).toBe('vanity_too_hard');+ expect(err.status).toBe(400);+ // Helpful guidance: tell the user to shorten the prefix.+ expect(err.message.toLowerCase()).toMatch(/shorter prefix/);+ });++ it('rejects a 4-char case-sensitive prefix (~58^4, far beyond the cap)', () => {+ expect(estimateAttempts({ prefix: 'abcd' })).toBeGreaterThan(10_000_000);+ const err = assertGrindFeasible({ prefix: 'abcd' });+ expect(err).toBeInstanceOf(Error);+ expect(err.code).toBe('vanity_too_hard');+ });++ it('allows a short, feasible prefix within the iteration cap', () => {+ expect(assertGrindFeasible({ prefix: 'abc' })).toBeNull();+ expect(assertGrindFeasible({ prefix: 'ab' })).toBeNull();+ expect(assertGrindFeasible({ prefix: 'a', ignoreCase: true })).toBeNull();+ });++ it('clamps an inflated maxIterations request so it cannot raise the difficulty ceiling', () => {+ // Even if a caller asks for 50M iterations, the guard caps at 1.5M, so a+ // 5-char prefix stays rejected — the cap cannot be bypassed via input.+ const err = assertGrindFeasible({ prefix: 'abcde', maxIterations: 50_000_000 });+ expect(err).toBeInstanceOf(Error);+ expect(err.code).toBe('vanity_too_hard');+ });+});diff --git a/vercel.json b/vercel.jsonindex 415a97598..bf47627e2 100644--- a/vercel.json+++ b/vercel.json@@ -1351,14 +1351,6 @@"src": "/api/auth/sessions/([^/]+)","dest": "/api/auth/sessions/[action]?action=$1"},- {- "src": "/api/auth/wallet/link",- "dest": "/api/auth/wallet/[action]?action=link"- },- {- "src": "/api/auth/wallet/unlink",- "dest": "/api/auth/wallet/[action]?action=unlink"- },{"src": "/api/onboarding/avaturn-session","dest": "/api/onboarding/[action]?action=avaturn-session"diff --git a/workers/avatar-pipeline-controller/Dockerfile b/workers/avatar-pipeline-controller/Dockerfileindex 09d2886e3..cae5af899 100644--- a/workers/avatar-pipeline-controller/Dockerfile+++ b/workers/avatar-pipeline-controller/Dockerfile@@ -8,6 +8,7 @@ COPY requirements.txt /app/requirements.txtRUN pip install -r /app/requirements.txtWORKDIR /app+COPY worker_security.py /app/worker_security.pyCOPY main.py /app/main.pyEXPOSE 8080diff --git a/workers/avatar-pipeline-controller/main.py b/workers/avatar-pipeline-controller/main.pyindex 80d8986e4..0c65f111f 100644--- a/workers/avatar-pipeline-controller/main.py+++ b/workers/avatar-pipeline-controller/main.py@@ -39,7 +39,6 @@ import loggingimport osimport randomimport time-import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom datetime import datetime, timezone@@ -50,6 +49,8 @@ from fastapi import FastAPI, HTTPException, Header, BackgroundTasksfrom google.cloud import firestore, storagefrom pydantic import BaseModel, Field+from worker_security import require_api_key, safe_error+logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(name)s %(message)s",@@ -127,10 +128,10 @@ app = FastAPI(title="avatar-pipeline-controller", lifespan=lifespan)# ── auth ──────────────────────────────────────────────────────────────────────def _require_api_key(authorization: str) -> None:- if not authorization.startswith("Bearer "):- raise HTTPException(status_code=401, detail="missing bearer token")- if authorization[len("Bearer "):].strip() != API_KEY:- raise HTTPException(status_code=401, detail="invalid api key")+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc# ── Firestore helpers ─────────────────────────────────────────────────────────@@ -239,13 +240,11 @@ async def _run_pipeline(})log.info("[%s] pipeline done in %.1fs — %s", job_id, total_time, final_url)- except Exception:- err = traceback.format_exc()- log.exception("[%s] pipeline failed", job_id)+ except Exception as exc:_set_job(job_id, {"status": "failed","stage": "failed",- "error": err,+ "error": safe_error(exc, context=f"[{job_id}] pipeline"),"total_time_ms": int((time.time() - t0) * 1000),})diff --git a/workers/avatar-pipeline-controller/worker_security.py b/workers/avatar-pipeline-controller/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/avatar-pipeline-controller/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/avatar-reconstruction/Dockerfile b/workers/avatar-reconstruction/Dockerfileindex 23a30e7c3..ef04edce9 100644--- a/workers/avatar-reconstruction/Dockerfile+++ b/workers/avatar-reconstruction/Dockerfile@@ -28,6 +28,7 @@ RUN pip install -r /app/requirements.txt# ── App code ──────────────────────────────────────────────────────────────────WORKDIR /app+COPY worker_security.py /app/worker_security.pyCOPY main.py /app/main.pyCOPY face_pipeline.py /app/face_pipeline.pyCOPY glb_ops.py /app/glb_ops.pydiff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.pyindex 1e5a6ba7e..0bef527c5 100644--- a/workers/avatar-reconstruction/face_pipeline.py+++ b/workers/avatar-reconstruction/face_pipeline.py@@ -28,12 +28,12 @@ from typing import Optionalimport cv2import mediapipe as mpimport numpy as np-import requestsfrom PIL import Image, ImageFilterfrom scipy.interpolate import RBFInterpolatorimport glb_opsimport pygltflib+from worker_security import UnsafeUrlError, fetch_remote_byteslog = logging.getLogger("face_pipeline")@@ -81,10 +81,14 @@ def _decode_image(src: str) -> Image.Image:if src.startswith("data:image"):b64 = src.split(",", 1)[1]return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")- if src.startswith("http://") or src.startswith("https://"):- resp = requests.get(src, timeout=30)- resp.raise_for_status()- return Image.open(io.BytesIO(resp.content)).convert("RGB")+ if src.startswith("https://"):+ # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs+ # rejected after DNS resolution, redirects re-validated per hop, bounded.+ try:+ data = fetch_remote_bytes(src, timeout=30)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch image source: {exc}") from exc+ return Image.open(io.BytesIO(data)).convert("RGB")raise ValueError(f"unsupported image source: {src[:60]}")diff --git a/workers/avatar-reconstruction/main.py b/workers/avatar-reconstruction/main.pyindex bd33f0bac..0186e0803 100644--- a/workers/avatar-reconstruction/main.py+++ b/workers/avatar-reconstruction/main.py@@ -23,7 +23,6 @@ from __future__ import annotationsimport asyncioimport loggingimport os-import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom datetime import datetime, timezone@@ -34,6 +33,7 @@ from google.cloud import firestore, storagefrom pydantic import BaseModel, Fieldimport face_pipeline+from worker_security import require_api_key, safe_errorlogging.basicConfig(level=logging.INFO,@@ -80,10 +80,10 @@ app = FastAPI(title="avatar-reconstruction", lifespan=lifespan)# ── auth ───────────────────────────────────────────────────────────────────────def _require_api_key(authorization: str) -> None:- if not authorization.startswith("Bearer "):- raise HTTPException(status_code=401, detail="missing bearer token")- if authorization[len("Bearer "):].strip() != API_KEY:- raise HTTPException(status_code=401, detail="invalid api key")+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc# ── Firestore helpers ──────────────────────────────────────────────────────────@@ -126,10 +126,11 @@ async def _process_job(job_id: str, image_sources: list[str], body_type: str) ->_set_job(job_id, {"status": "done", "glb_url": glb_url})log.info("[%s] done → %s", job_id, glb_url)- except Exception:- err = traceback.format_exc()- log.exception("[%s] pipeline failed", job_id)- _set_job(job_id, {"status": "failed", "error": err})+ except Exception as exc:+ _set_job(job_id, {+ "status": "failed",+ "error": safe_error(exc, context=f"[{job_id}] pipeline"),+ })# ── routes ─────────────────────────────────────────────────────────────────────diff --git a/workers/avatar-reconstruction/requirements.txt b/workers/avatar-reconstruction/requirements.txtindex 1bbfc7acf..fe869c60c 100644--- a/workers/avatar-reconstruction/requirements.txt+++ b/workers/avatar-reconstruction/requirements.txt@@ -19,8 +19,11 @@ rembg[gpu]==2.0.56# ── Mesh operations (UV pre-computation, runs once at build time) ─────────────trimesh==4.4.0-# ── HTTP (image downloads) ────────────────────────────────────────────────────+# ── HTTP ──────────────────────────────────────────────────────────────────────+# requests: build-time UV-map download (precompute_uv.py) from a fixed GitHub URL.+# httpx: runtime SSRF-hardened image fetches via worker_security.fetch_remote_bytes.requests==2.32.3+httpx==0.28.1# ── Server ────────────────────────────────────────────────────────────────────fastapi==0.115.0diff --git a/workers/avatar-reconstruction/worker_security.py b/workers/avatar-reconstruction/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/avatar-reconstruction/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/longcat/Dockerfile b/workers/longcat/Dockerfileindex 23a389ee9..6158edb2f 100644--- a/workers/longcat/Dockerfile+++ b/workers/longcat/Dockerfile@@ -54,6 +54,7 @@ RUN pip install -r /app/requirements.txt# ── App code ───────────────────────────────────────────────────────────────────WORKDIR /app+COPY worker_security.py /app/worker_security.pyCOPY main.py /app/main.py# Model weights are NOT baked into the image (13.6 B params = ~27 GB bf16 /diff --git a/workers/longcat/main.py b/workers/longcat/main.pyindex b9b5eb14e..0d15f4b0e 100644--- a/workers/longcat/main.py+++ b/workers/longcat/main.py@@ -29,7 +29,6 @@ import reimport shutilimport subprocessimport tempfile-import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom datetime import datetime, timezone@@ -40,6 +39,13 @@ from fastapi import BackgroundTasks, FastAPI, HTTPException, Headerfrom google.cloud import firestore, storagefrom pydantic import BaseModel+from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes_async,+ require_api_key,+ safe_error,+)+logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(name)s %(message)s",@@ -102,7 +108,9 @@ async def lifespan(app: FastAPI):global _db, _bucket, _job_sem, _http_job_sem = asyncio.Semaphore(MAX_CONCURRENT)- _http = httpx.AsyncClient(follow_redirects=True, timeout=300)+ # follow_redirects MUST stay False: redirect hops are re-validated against+ # the SSRF allow-rules by fetch_remote_bytes_async, not by httpx.+ _http = httpx.AsyncClient(follow_redirects=False, timeout=300)_db = firestore.Client(project=FIRESTORE_PROJECT)_bucket = storage.Client().bucket(GCS_BUCKET)@@ -150,10 +158,10 @@ app = FastAPI(title="longcat-video-avatar", lifespan=lifespan)# ── auth ───────────────────────────────────────────────────────────────────────def _require_api_key(authorization: str) -> None:- if not authorization.startswith("Bearer "):- raise HTTPException(status_code=401, detail="missing bearer token")- if authorization[len("Bearer "):].strip() != API_KEY:- raise HTTPException(status_code=401, detail="invalid api key")+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc# ── Firestore helpers ──────────────────────────────────────────────────────────@@ -226,10 +234,11 @@ async def _process_job(_set_job(job_id, {"status": "done", "progress": 1.0, "video_url": video_url})log.info("[%s] done → %s", job_id, video_url)- except Exception:- err = traceback.format_exc()- log.exception("[%s] pipeline failed", job_id)- _set_job(job_id, {"status": "failed", "error": err})+ except Exception as exc:+ _set_job(job_id, {+ "status": "failed",+ "error": safe_error(exc, context=f"[{job_id}] pipeline"),+ })finally:shutil.rmtree(workdir, ignore_errors=True)@@ -291,11 +300,14 @@ async def _download_file(url: str, dest: Path) -> None:except Exception as exc:raise RuntimeError(f"failed to decode data URI: {exc}") from excreturn- async with _http.stream("GET", url) as r:- r.raise_for_status()- with dest.open("wb") as f:- async for chunk in r.aiter_bytes(65536):- f.write(chunk)+ # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs are+ # rejected after DNS resolution, redirects are re-validated per hop, and the+ # response is size-bounded.+ try:+ data = await fetch_remote_bytes_async(_http, url)+ except UnsafeUrlError as exc:+ raise RuntimeError(f"refused to fetch url: {exc}") from exc+ dest.write_bytes(data)# ── routes ─────────────────────────────────────────────────────────────────────diff --git a/workers/longcat/worker_security.py b/workers/longcat/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/longcat/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/model-hunyuan3d/Dockerfile b/workers/model-hunyuan3d/Dockerfileindex d23811f4a..169e4a0b3 100644--- a/workers/model-hunyuan3d/Dockerfile+++ b/workers/model-hunyuan3d/Dockerfile@@ -21,6 +21,7 @@ COPY requirements.txt /app/requirements.txtRUN pip install -r /app/requirements.txtWORKDIR /app+COPY worker_security.py /app/worker_security.pyCOPY main.py /app/main.pyEXPOSE 8080diff --git a/workers/model-hunyuan3d/main.py b/workers/model-hunyuan3d/main.pyindex dcbb645b7..642e47011 100644--- a/workers/model-hunyuan3d/main.py+++ b/workers/model-hunyuan3d/main.py@@ -32,7 +32,6 @@ import ioimport loggingimport osimport time-import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom typing import Optional@@ -43,6 +42,13 @@ from google.cloud import storagefrom PIL import Imagefrom pydantic import BaseModel, Field+from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)+logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(name)s %(message)s",@@ -102,21 +108,24 @@ app = FastAPI(title="model-hunyuan3d", lifespan=lifespan)def _require_api_key(authorization: str) -> None:- if not authorization.startswith("Bearer "):- raise HTTPException(status_code=401, detail="missing bearer token")- if authorization[len("Bearer "):].strip() != API_KEY:- raise HTTPException(status_code=401, detail="invalid api key")+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from excdef _decode_image(src: str) -> Image.Image:if src.startswith("data:image"):b64 = src.split(",", 1)[1]return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")- if src.startswith("http://") or src.startswith("https://"):- import httpx- resp = httpx.get(src, timeout=30)- resp.raise_for_status()- return Image.open(io.BytesIO(resp.content)).convert("RGB")+ if src.startswith("https://"):+ # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs+ # rejected after DNS resolution, redirects re-validated per hop, bounded.+ try:+ data = fetch_remote_bytes(src, timeout=30)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch image source: {exc}") from exc+ return Image.open(io.BytesIO(data)).convert("RGB")raise ValueError(f"unsupported image source: {src[:60]}")@@ -163,13 +172,12 @@ async def _run_inference(task_id: str, images: list[str], body_type: str) -> Non})log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)- except Exception:+ except Exception as exc:_tasks[task_id].update({"status": "failed",- "error": traceback.format_exc(),+ "error": safe_error(exc, context=f"[{task_id}] inference"),"elapsed_ms": int((time.time() - t0) * 1000),})- log.exception("[%s] inference failed", task_id)class InferRequest(BaseModel):diff --git a/workers/model-hunyuan3d/worker_security.py b/workers/model-hunyuan3d/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/model-hunyuan3d/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/model-trellis/Dockerfile b/workers/model-trellis/Dockerfileindex 737c11c20..dbeb79e4f 100644--- a/workers/model-trellis/Dockerfile+++ b/workers/model-trellis/Dockerfile@@ -20,6 +20,7 @@ COPY requirements.txt /app/requirements.txtRUN pip install -r /app/requirements.txtWORKDIR /app+COPY worker_security.py /app/worker_security.pyCOPY main.py /app/main.pyEXPOSE 8080diff --git a/workers/model-trellis/main.py b/workers/model-trellis/main.pyindex 99ad30c2a..6aed5819a 100644--- a/workers/model-trellis/main.py+++ b/workers/model-trellis/main.py@@ -30,7 +30,6 @@ import ioimport loggingimport osimport time-import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom typing import Optional@@ -41,6 +40,13 @@ from google.cloud import storagefrom PIL import Imagefrom pydantic import BaseModel, Field+from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)+logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(name)s %(message)s",@@ -83,21 +89,24 @@ app = FastAPI(title="model-trellis", lifespan=lifespan)def _require_api_key(authorization: str) -> None:- if not authorization.startswith("Bearer "):- raise HTTPException(status_code=401, detail="missing bearer token")- if authorization[len("Bearer "):].strip() != API_KEY:- raise HTTPException(status_code=401, detail="invalid api key")+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from excdef _decode_image(src: str) -> Image.Image:if src.startswith("data:image"):b64 = src.split(",", 1)[1]return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")- if src.startswith("http://") or src.startswith("https://"):- import httpx- resp = httpx.get(src, timeout=30)- resp.raise_for_status()- return Image.open(io.BytesIO(resp.content)).convert("RGB")+ if src.startswith("https://"):+ # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs+ # rejected after DNS resolution, redirects re-validated per hop, bounded.+ try:+ data = fetch_remote_bytes(src, timeout=30)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch image source: {exc}") from exc+ return Image.open(io.BytesIO(data)).convert("RGB")raise ValueError(f"unsupported image source: {src[:60]}")@@ -144,13 +153,12 @@ async def _run_inference(task_id: str, images: list[str], body_type: str) -> Non})log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)- except Exception:+ except Exception as exc:_tasks[task_id].update({"status": "failed",- "error": traceback.format_exc(),+ "error": safe_error(exc, context=f"[{task_id}] inference"),"elapsed_ms": int((time.time() - t0) * 1000),})- log.exception("[%s] inference failed", task_id)class InferRequest(BaseModel):diff --git a/workers/model-trellis/worker_security.py b/workers/model-trellis/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/model-trellis/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/model-triposr/Dockerfile b/workers/model-triposr/Dockerfileindex 737c11c20..dbeb79e4f 100644--- a/workers/model-triposr/Dockerfile+++ b/workers/model-triposr/Dockerfile@@ -20,6 +20,7 @@ COPY requirements.txt /app/requirements.txtRUN pip install -r /app/requirements.txtWORKDIR /app+COPY worker_security.py /app/worker_security.pyCOPY main.py /app/main.pyEXPOSE 8080diff --git a/workers/model-triposr/main.py b/workers/model-triposr/main.pyindex dcae20bca..84e89d7fb 100644--- a/workers/model-triposr/main.py+++ b/workers/model-triposr/main.py@@ -32,7 +32,6 @@ import ioimport loggingimport osimport time-import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom typing import Optional@@ -43,6 +42,13 @@ from google.cloud import storagefrom PIL import Imagefrom pydantic import BaseModel, Field+from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)+logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(name)s %(message)s",@@ -89,21 +95,24 @@ app = FastAPI(title="model-triposr", lifespan=lifespan)def _require_api_key(authorization: str) -> None:- if not authorization.startswith("Bearer "):- raise HTTPException(status_code=401, detail="missing bearer token")- if authorization[len("Bearer "):].strip() != API_KEY:- raise HTTPException(status_code=401, detail="invalid api key")+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from excdef _decode_image(src: str) -> Image.Image:if src.startswith("data:image"):b64 = src.split(",", 1)[1]return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")- if src.startswith("http://") or src.startswith("https://"):- import httpx- resp = httpx.get(src, timeout=30)- resp.raise_for_status()- return Image.open(io.BytesIO(resp.content)).convert("RGB")+ if src.startswith("https://"):+ # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs+ # rejected after DNS resolution, redirects re-validated per hop, bounded.+ try:+ data = fetch_remote_bytes(src, timeout=30)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch image source: {exc}") from exc+ return Image.open(io.BytesIO(data)).convert("RGB")raise ValueError(f"unsupported image source: {src[:60]}")@@ -154,13 +163,12 @@ async def _run_inference(task_id: str, images: list[str], body_type: str) -> Non})log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)- except Exception:+ except Exception as exc:_tasks[task_id].update({"status": "failed",- "error": traceback.format_exc(),+ "error": safe_error(exc, context=f"[{task_id}] inference"),"elapsed_ms": int((time.time() - t0) * 1000),})- log.exception("[%s] inference failed", task_id)class InferRequest(BaseModel):diff --git a/workers/model-triposr/worker_security.py b/workers/model-triposr/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/model-triposr/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/strategy-executor.js b/workers/strategy-executor.jsdeleted file mode 100644index 4c737db2e..000000000--- a/workers/strategy-executor.js+++ /dev/null@@ -1,28 +0,0 @@--import { getDB } from '../api/_lib/db.js';-import { executeAgentAction } from '../src/agent-actions.js';--async function processStrategies() {- const db = await getDB();- const strategies = await db.collection('strategies').find({}).toArray();-- for (const strategy of strategies) {- // Placeholder for strategy evaluation logic- const conditionsMet = evaluateStrategy(strategy);-- if (conditionsMet) {- await executeAgentAction(strategy.agentId, strategy.action);- }-a }-}--function evaluateStrategy(strategy) {- // In a real implementation, this would involve complex logic- // to check market data, user-defined rules, etc.- console.log(`Evaluating strategy for agent ${strategy.agentId}`);- return true; // Placeholder-}--setInterval(processStrategies, 60000); // Run every minute--console.log('Strategy executor worker started');diff --git a/workers/unirig/Dockerfile b/workers/unirig/Dockerfileindex 24d07a08f..108bdc0ef 100644--- a/workers/unirig/Dockerfile+++ b/workers/unirig/Dockerfile@@ -20,6 +20,7 @@ COPY requirements.txt /app/requirements.txtRUN pip install -r /app/requirements.txtWORKDIR /app+COPY worker_security.py /app/worker_security.pyCOPY main.py /app/main.py# Wolf3D skeleton templates for blendshape transfer (added in Phase 2).diff --git a/workers/unirig/main.py b/workers/unirig/main.pyindex 2d070257b..7d6d73f71 100644--- a/workers/unirig/main.py+++ b/workers/unirig/main.py@@ -35,7 +35,6 @@ import ioimport loggingimport osimport time-import tracebackimport uuidfrom contextlib import asynccontextmanagerfrom typing import Optional@@ -47,6 +46,13 @@ from fastapi import FastAPI, HTTPException, Header, BackgroundTasksfrom google.cloud import storagefrom pydantic import BaseModel, Field+from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes_async,+ require_api_key,+ safe_error,+)+logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(name)s %(message)s",@@ -91,10 +97,10 @@ app = FastAPI(title="unirig", lifespan=lifespan)def _require_api_key(authorization: str) -> None:- if not authorization.startswith("Bearer "):- raise HTTPException(status_code=401, detail="missing bearer token")- if authorization[len("Bearer "):].strip() != API_KEY:- raise HTTPException(status_code=401, detail="invalid api key")+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc# Wolf3D / ARKit-52 skeleton joint names. UniRig predicts joint placement; we@@ -137,12 +143,15 @@ async def _run_rigging(loop = asyncio.get_event_loop()t0 = time.time()try:- # Download the raw mesh from GCS.+ # Download the raw mesh from GCS. SSRF-hardened: https-only,+ # private/loopback/link-local/metadata IPs rejected after DNS+ # resolution, redirects re-validated per hop, response size bounded.import httpx- async with httpx.AsyncClient(timeout=60) as client:- resp = await client.get(mesh_gcs_url)- resp.raise_for_status()- mesh_bytes = resp.content+ async with httpx.AsyncClient(timeout=60, follow_redirects=False) as client:+ try:+ mesh_bytes = await fetch_remote_bytes_async(client, mesh_gcs_url)+ except UnsafeUrlError as exc:+ raise RuntimeError(f"refused to fetch mesh url: {exc}") from excdef _rig():mesh = trimesh.load(io.BytesIO(mesh_bytes), file_type="glb", force="mesh")@@ -189,13 +198,12 @@ async def _run_rigging(})log.info("[%s] rigging done in %.1fs — %d bytes → %s", task_id, elapsed, len(rigged_bytes), gcs_url)- except Exception:+ except Exception as exc:_tasks[task_id].update({"status": "failed",- "error": traceback.format_exc(),+ "error": safe_error(exc, context=f"[{task_id}] rigging"),"elapsed_ms": int((time.time() - t0) * 1000),})- log.exception("[%s] rigging failed", task_id)def _inject_skeleton(glb, mesh, joints, parents, weights):diff --git a/workers/unirig/worker_security.py b/workers/unirig/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/unirig/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"