@barndoor-ai/sdk 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{spawn as e}from"child_process";import t from"os";import r from"crypto";import a from"http";import s,{fileURLToPath as o}from"url";import n,{dirname as i,join as c}from"path";import l from"fs/promises";import{jwtVerify as d,createRemoteJWKSet as u}from"jose";import h from"pkce-challenge";import{readFileSync as p}from"fs";class f extends Error{constructor(e){super(e),this.name="BarndoorError"}}class m extends f{constructor(e,t=null){super(e),this.name="AuthenticationError",this.errorCode=t}}class v extends m{constructor(e,t=null){let r=e;r+=t?` ${t}`:" Run 'barndoor-login' to authenticate.",super(r),this.name="TokenError",this.helpText=t}}class g extends v{}class y extends v{}class _ extends f{constructor(e,t){let r;const a=t.toString().toLowerCase();r=a.includes("timeout")?`Connection to ${e} timed out. Please check your internet connection and try again.`:a.includes("connection refused")?`Could not connect to ${e}. The service may be unavailable.`:a.includes("name resolution")||a.includes("getaddrinfo")?`Could not resolve hostname for ${e}. Please check the URL and your DNS settings.`:`Failed to connect to ${e}. Please check your internet connection.`,super(r),this.url=e,this.originalError=t}}class w extends f{constructor(e,t,r=null){super(w._createUserFriendlyMessage(e,t,r)),this.name="HTTPError",this.statusCode=e,this.responseBody=r}static _createUserFriendlyMessage(e,t,r){const a=`Request failed (HTTP ${e})`;return 400===e?`${a}: Invalid request. Please check your input parameters.`:401===e?`${a}: Authentication failed. Please check your token or re-authenticate.`:403===e?`${a}: Access denied. You don't have permission for this operation.`:404===e?`${a}: Resource not found. Please check the server ID or URL.`:429===e?`${a}: Rate limit exceeded. Please wait before making more requests.`:e>=500&&e<600?`${a}: Server error. Please try again later or contact support.`:`${a}: ${t}`}}class b extends f{constructor(e,t=null){let r=`Server '${e}' not found`;r+=t?`. Available servers: ${t.join(", ")}`:". Use listServers() to see available servers.",super(r),this.serverIdentifier=e,this.availableServers=t}}let P=class extends m{};class E extends f{}class k extends f{}class x{constructor(e=30,t=10){this.read=1e3*e,this.connect=1e3*t}}class S{constructor(e=new x,t=3){this.timeoutConfig=e,this.maxRetries=t,this.closed=!1}async request(e,t,r={}){if(this.closed)throw new Error("HTTP client has been closed");const{headers:a={},json:s,params:o,...n}=r,i=this._buildUrl(t,o),c={method:e.toUpperCase(),headers:{"Content-Type":"application/json","User-Agent":"barndoor-js-sdk/0.1.0",...a},...n};let l;s&&(c.body=JSON.stringify(s));for(let t=0;t<=this.maxRetries;t++){const r=new AbortController,a=this.timeoutConfig.connect+this.timeoutConfig.read,s=setTimeout(()=>r.abort(),a),o={...c,signal:r.signal};try{const e=await globalThis.fetch(i,o);if(clearTimeout(s),!e.ok){let t="";try{const r=e;"function"==typeof r.text?t=await r.text():"function"==typeof r.json&&(t=JSON.stringify(await r.json()))}catch{}throw new w(e.status,e.statusText,t)}let t="";const r=e,a=r&&r.headers;let n;return a&&("function"==typeof a.get?t=a.get("content-type")||a.get("Content-Type")||"":"object"==typeof a&&(t=a["content-type"]||a["Content-Type"]||"")),n=t.includes("application/json")||!t&&"function"==typeof r.json?await e.json():t.includes("text/")||!t&&"function"==typeof r.text?await e.text():"function"==typeof r.arrayBuffer?await e.arrayBuffer():e,n}catch(r){if(clearTimeout(s),r instanceof Error&&"AbortError"===r.name){const e=this.timeoutConfig.connect+this.timeoutConfig.read;l=new k(`Request to ${i} timed out after ${e}ms`)}else if(r instanceof w){if(r.statusCode>=400&&r.statusCode<500)throw r;if(!(r.statusCode>=500&&r.statusCode<600))throw r;{const t=e.toUpperCase();if(!("GET"===t||"HEAD"===t||"OPTIONS"===t))throw r;l=r}}else l=r instanceof Error&&"TypeError"===r.name&&r.message.includes("fetch")?new _(i,r):r instanceof Error?r:new Error(String(r));if(t===this.maxRetries)break;const a=Math.min(1e3*Math.pow(2,t),1e4);await this._sleep(a)}}throw l||(l=new Error(`Request to ${i} failed after ${this.maxRetries+1} attempts with no specific error`)),l}_buildUrl(e,t){if(!t||0===Object.keys(t).length)return e;const r=new URL(e);return Object.entries(t).forEach(([e,t])=>{null!=t&&r.searchParams.append(e,String(t))}),r.toString()}_sleep(e){return new Promise(t=>setTimeout(t,e))}async close(){this.closed=!0}async aclose(){await this.close()}}class T{constructor(e){if(this.id=e.id,this.name=e.name,this.slug=e.slug,this.provider=e.provider??null,this.connection_status=e.connection_status,!(this.id&&this.name&&this.slug&&this.connection_status))throw new Error("ServerSummary missing required fields")}static fromApiResponse(e){return new T(e)}}class R extends T{constructor(e){super(e),this.url=e.url??null}static fromApiResponse(e){return new R(e)}}class ${constructor(e){if(this.agent_token=e.agent_token,this.expires_in=e.expires_in,!this.agent_token||"number"!=typeof this.expires_in)throw new Error("AgentToken missing required fields")}static fromApiResponse(e){return new $(e)}}const C="undefined"!=typeof window&&void 0!==window.document,O="undefined"==typeof window&&"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function I(e,t=""){return O?process.env[e]??t:C&&window.ENV?window.ENV[e]??t:t}class A{constructor(e={}){this.authDomain=e.authDomain??(I("AUTH_DOMAIN")||"auth.barndoor.ai"),this.clientId=e.clientId??(I("AGENT_CLIENT_ID")||""),this.clientSecret=e.clientSecret??(I("AGENT_CLIENT_SECRET")||""),this.apiAudience=e.apiAudience??(I("API_AUDIENCE")||"https://barndoor.ai/"),this.environment=e.environment??(I("MODE")||I("BARNDOOR_ENV")||"production"),this.promptForLogin=e.promptForLogin??!1,this.skipLoginLocal=e.skipLoginLocal??!1,this.apiBaseUrl="",this.mcpBaseUrl="",this._setEnvironmentDefaults(e)}_setEnvironmentDefaults(e){const t=this.environment.toLowerCase();"localdev"===t||"local"===t?(this.authDomain=this.authDomain||"localhost:3001",this.apiBaseUrl=e.apiBaseUrl??(I("BARNDOOR_API")||"http://localhost:8000"),this.mcpBaseUrl=e.mcpBaseUrl??(I("BARNDOOR_MCP")||I("BARNDOOR_URL")||"http://localhost:8000")):"development"===t||"dev"===t?(this.apiBaseUrl=e.apiBaseUrl??(I("BARNDOOR_API")||"https://api.barndoordev.com"),this.mcpBaseUrl=e.mcpBaseUrl??(I("BARNDOOR_MCP")||I("BARNDOOR_URL")||"https://{organization_id}.mcp.barndoordev.com")):(this.apiBaseUrl=e.apiBaseUrl??(I("BARNDOOR_API")||"https://api.barndoor.ai"),this.mcpBaseUrl=e.mcpBaseUrl??(I("BARNDOOR_MCP")||I("BARNDOOR_URL")||"https://{organization_id}.mcp.barndoor.ai"))}static getStaticConfig(){return new A}static getDynamicConfig(e,t={}){const{requireOrganization:r=!0,fallbackOrganizationId:a}=t,s=new A,o=j(e);if(o.hasOrganization){const e=String(o.organizationId??"").trim().toLowerCase();if(!/^[a-z0-9-]+$/.test(e))throw new E("Invalid organization ID format from token");return s.apiBaseUrl=s.apiBaseUrl.replace("{organization_id}",e),s.mcpBaseUrl=s.mcpBaseUrl.replace("{organization_id}",e),s}if(a)return s.apiBaseUrl=s.apiBaseUrl.replace("{organization_id}",a),s.mcpBaseUrl=s.mcpBaseUrl.replace("{organization_id}",a),s;if(r){const e=o.error||"No organization information found in token";throw new E(`Failed to extract organization ID from token: ${e}. This token may be for a personal account or may be missing organization claims. Consider using getStaticConfig() for organization-independent operations or provide a fallbackOrganizationId in the options.`)}return s}validate(){if(!this.authDomain||""===this.authDomain.trim())throw new E("authDomain is required");if(!this.apiAudience||""===this.apiAudience.trim())throw new E("apiAudience is required");if(!this.apiBaseUrl||""===this.apiBaseUrl.trim())throw new E("apiBaseUrl is required");if(!this.mcpBaseUrl||""===this.mcpBaseUrl.trim())throw new E("mcpBaseUrl is required")}}function j(e){try{const t=e.split(".");if(3!==t.length)return{hasOrganization:!1,error:"Invalid JWT format - expected 3 parts separated by dots"};let r,a;try{r=JSON.parse(function(e){if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");throw new Error("No base64 decode function available")}(t[1].replace(/-/g,"+").replace(/_/g,"/")))}catch(e){return{hasOrganization:!1,error:"Failed to parse JWT payload - token may be corrupted"}}if(r.user&&"object"==typeof r.user&&(a=r.user.organization_name??r.user.organization_slug),!a){const e=r["https://barndoor.ai/organization_slug"],t=r["https://barndoor.ai/organization_id"],s=r.organization_slug,o=r.org_slug,n=r.org_id,i=r.organization_id;a=("string"==typeof e?e:void 0)??("string"==typeof t?t:void 0)??("string"==typeof s?s:void 0)??("string"==typeof o?o:void 0)??("string"==typeof n?n:void 0)??("string"==typeof i?i:void 0)}return a&&"string"==typeof a&&""!==a.trim()?{organizationId:a.trim(),hasOrganization:!0}:{hasOrganization:!1,error:"No organization information found in token. This token may be for a personal account or may be missing organization claims."}}catch(e){return{hasOrganization:!1,error:`Failed to decode JWT token: ${e instanceof Error?e.message:String(e)}`}}}function F(){return A.getStaticConfig()}function D(e,t){return A.getDynamicConfig(e,t)}function N(e){return j(e)}function U(e){return j(e).hasOrganization}let L={debug:(e,...t)=>{"undefined"!=typeof console&&console.debug&&console.debug(e,...t)},info:(e,...t)=>{"undefined"!=typeof console&&console.info&&console.info(e,...t)},warn:(e,...t)=>{"undefined"!=typeof console&&console.warn&&console.warn(e,...t)},error:(e,...t)=>{"undefined"!=typeof console&&console.error&&console.error(e,...t)}};function q(e){L=e}function z(){return L}function V(e){return{debug:(t,...r)=>{L.debug(`[${e}] ${t}`,...r)},info:(t,...r)=>{L.info(`[${e}] ${t}`,...r)},warn:(t,...r)=>{L.warn(`[${e}] ${t}`,...r)},error:(t,...r)=>{L.error(`[${e}] ${t}`,...r)}}}function M(e,...t){L.debug(e,...t)}function Z(e,...t){L.info(e,...t)}function H(e,...t){L.warn(e,...t)}function B(e,...t){L.error(e,...t)}class Q{constructor(e,t={}){this._logger=V("client");const{token:r,timeout:a=30,maxRetries:s=3}=t;this.base=this._validateUrl(e,"API base URL").replace(/\/$/,"");const o=Object.prototype.hasOwnProperty.call(t,"token");if(this._token=o?this._validateToken(r):null,"number"!=typeof a||a<=0)throw new E("timeout must be a positive number");if(!Number.isInteger(s)||s<0)throw new E("maxRetries must be a non-negative integer");const n=new x(a,a/3);this._http=new S(n,s),this._tokenValidated=!1,this._closed=!1,this._logger.info(`Initialized BarndoorSDK for ${this.base}`)}get token(){if(!this._token)throw new Error("No token available. Call authenticate() first or provide token in constructor.");return this._token}async authenticate(e){this._token=this._validateToken(e),this._tokenValidated=!1,await this.ensureValidToken(),this._logger.info("Authentication successful")}_validateUrl(e,t){if(!e||"string"!=typeof e)throw new E(`${t} must be a non-empty string`);try{return new URL(e),e}catch(e){throw new E(`${t} must be a valid URL`)}}_validateToken(e){if(!e||"string"!=typeof e)throw new v("Token must be a non-empty string");if(3!==e.split(".").length)throw new v("Token must be a valid JWT");return e}_ensureNotClosed(){if(this._closed)throw new Error("SDK has been closed. Create a new instance or use as context manager.")}async _req(e,t,r={}){this._ensureNotClosed(),await this.ensureValidToken();const a=r.headers??{};a.Authorization=`Bearer ${this.token}`;const s=`${this.base}${t}`;return await this._http.request(e,s,{...r,headers:a})}async validateCachedToken(){if(!this.token)return!1;try{const e=F(),t=(await fetch(`https://${e.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${this.token}`}})).ok;return t&&(this._tokenValidated=!0),t}catch(e){return!1}}async ensureValidToken(){if(this._tokenValidated)return;const e=(O?process.env.BARNDOOR_ENV:"")??"";if(["test","ci"].includes(e.toLowerCase()))return void(this._tokenValidated=!0);if(!await this.validateCachedToken())throw new v("Token validation failed. Please re-authenticate.");this._tokenValidated=!0}async listServers(){this._logger.debug("Fetching server list");try{const e=(await this._req("GET","/servers")).data.map(e=>T.fromApiResponse(e));return this._logger.info(`Retrieved ${e.length} servers`),e}catch(e){throw this._logger.error("Failed to list servers:",e),e}}async getServer(e){const t=this._validateServerId(e);this._logger.info(`Fetching server details for ${t}`);const r=await this._req("GET",`/servers/${t}`);return R.fromApiResponse(r)}async initiateConnection(e,t){const r=this._validateServerId(e);let a;t&&(a=this._validateUrl(t,"Return URL")),this._logger.info(`Initiating connection for server ${r}`);const s=a?{return_url:a}:void 0;try{return await this._req("POST",`/servers/${r}/connect`,{params:s,json:{}})}catch(e){if(e instanceof w&&500===e.statusCode&&e.responseBody?.includes("OAuth server configuration not found"))throw new Error("Server is missing OAuth configuration. Ask an admin to configure credentials before initiating a connection.");throw e}}async getConnectionStatus(e){const t=this._validateServerId(e);this._logger.info(`Checking connection status for server ${t}`);return(await this._req("GET",`/servers/${t}/connection`)).status}async disconnectServer(e){const t=this._validateServerId(e);this._logger.info(`Disconnecting from server ${t}`);try{await this._req("DELETE",`/servers/${t}/connection`),this._logger.info(`Successfully disconnected from server ${t}`)}catch(e){if(e instanceof w&&404===e.statusCode)throw new Error(`Connection not found for server ${t}. Server may not be connected.`);throw e}}_validateServerId(e){if(!e||"string"!=typeof e)throw new Error("Server ID must be a non-empty string");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)&&!/^[a-z0-9-]+$/.test(e))throw new Error("Server ID must be a valid UUID or slug (lowercase letters, numbers, and hyphens only)");return e}async close(){this._closed||(await this._http.close(),this._closed=!0)}async aclose(){await this.close()}async ensureServerConnected(r,a={}){const{pollSeconds:s=60}=a;if(!O)throw new Error("ensureServerConnected requires Node.js environment for browser opening");const o=(await this.listServers()).find(e=>e.slug===r||e.provider&&e.provider.toLowerCase()===r.toLowerCase());if(!o)throw new b(r);if("connected"===o.connection_status)return;const n=(await this.initiateConnection(o.id)).auth_url;if(!n)throw new Error("Registry did not return auth_url");const i=t.platform();let c;try{c=new URL(n)}catch{throw new Error("Invalid auth_url returned by server")}if("https:"!==c.protocol&&("http:"!==c.protocol||"localhost"!==c.hostname&&"127.0.0.1"!==c.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===i?e("open",[n],{detached:!0,stdio:"ignore"}).unref():"win32"===i?e("powershell",["-NoProfile","Start-Process",n],{detached:!0,stdio:"ignore"}).unref():e("xdg-open",[n],{detached:!0,stdio:"ignore"}).unref()}catch(e){this._logger.warn("Failed to open browser",e)}for(let e=0;e<s;e++){if("connected"===await this.getConnectionStatus(o.id))return;await new Promise(e=>setTimeout(e,1e3))}throw new Error("OAuth connection was not completed in time")}}class K{constructor(){this._codeVerifier=null,this._currentState=null,this._logger=V("pkce")}async buildAuthorizationUrl({domain:e,clientId:t,redirectUri:a,audience:s,scope:o="openid profile email"}){this._codeVerifier=J(32);const n=W(await async function(e){const t=(new TextEncoder).encode(e);if(C&&window.crypto&&window.crypto.subtle){const e=await window.crypto.subtle.digest("SHA-256",t);return new Uint8Array(e)}if(O){const t=r.createHash("sha256").update(e).digest();return new Uint8Array(t)}throw new Error("SHA256 not available in this environment")}(this._codeVerifier));this._currentState=J(16);return`https://${e}/authorize?${new URLSearchParams({response_type:"code",client_id:t,redirect_uri:a,scope:o,audience:s,state:this._currentState,code_challenge:n,code_challenge_method:"S256"}).toString()}`}async exchangeCodeForToken({domain:e,clientId:t,code:r,redirectUri:a,clientSecret:s}){const o={grant_type:"authorization_code",client_id:t,code:r,redirect_uri:a};if(s&&(o.client_secret=s),this._codeVerifier&&(o.code_verifier=this._codeVerifier),!s&&!this._codeVerifier)throw new P("Either client_secret or PKCE verifier must be provided");try{const t=await fetch(`https://${e}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){const e=await t.json().catch(()=>({}));throw this._logger.error("Token endpoint response:",e),new P(`Token exchange failed: ${e.error??e.error_description??t.statusText}`)}const r=await t.json();return this.clearState(),r}catch(e){if(e instanceof P)throw e;const t=e instanceof Error?e.message:String(e);throw new P(`Token exchange failed: ${t}`)}}validateState(e){return Boolean(this._currentState&&e===this._currentState)}clearState(){this._codeVerifier=null,this._currentState=null}getState(){return this._codeVerifier&&this._currentState?{codeVerifier:this._codeVerifier,codeChallenge:"",state:this._currentState,timestamp:Date.now()}:null}}function J(e){const t=new Uint8Array(e);if(C&&window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(t);else{if(!O)throw new Error("Secure random generator not available for PKCE.");r.randomFillSync(t)}return W(t)}function W(e){const t=function(e){if("undefined"!=typeof globalThis&&globalThis.btoa)return globalThis.btoa(String.fromCharCode(...e));if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");throw new Error("No base64 encode function available")}(e);return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function G(e=52765){if(!O)throw new Error("Local callback server is only available in Node.js environment");const t=`http://localhost:${e}/cb`,r=new Promise((r,o)=>{const n=a.createServer((e,t)=>{const a=s.parse(e.url??"",!0);if("/cb"===a.pathname){const{code:e,state:s,error:i,error_description:c}=a.query;t.writeHead(200,{"Content-Type":"text/html"}),i?(t.end("\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>Error: Authentication error occurred.</p>\n <p>Description: Please return to the application for details.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n "),n.close(),o(new P(`OAuth error: ${i} - ${c}`))):e?(t.end("\n <html>\n <body>\n <h1>Authentication Successful</h1>\n <p>You can close this window and return to your application.</p>\n </body>\n </html>\n "),n.close(),r([e,s])):(t.end("\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>No authorization code received.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n "),n.close(),o(new P("No authorization code received")))}else t.writeHead(404),t.end("Not found")});n.listen(e,"localhost",()=>{console.log(`OAuth callback server listening on ${t}`)}),n.on("error",e=>{o(new P(`Failed to start callback server: ${e.message}`))})});return[t,r]}const Y=V("token");function X(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")}function ee(e){try{const t=e.split(".");if(3!==t.length)return null;return JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");if(O)return Buffer.from(t,"base64").toString("utf8");if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(t);throw new Error("No base64 decode function available")}(t[1]))}catch(e){return null}}function te(e,t){return"undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?e:Promise.race([e,new Promise((e,r)=>{setTimeout(()=>r(new Error("Request timeout")),t)})])}var re;!function(e){e.VALID="valid",e.EXPIRED="expired",e.INVALID="invalid"}(re||(re={}));const ae=new Map;class se{constructor(e){this.lockAcquired=!1,this.lockFile=`${e}.lock`}async acquire(e=5e3){if(!O)return;const t=Date.now();for(;Date.now()-t<e;)try{return await l.writeFile(this.lockFile,process.pid.toString(),{flag:"wx"}),void(this.lockAcquired=!0)}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw new v(`Failed to acquire file lock: ${e}`);try{const e=await l.readFile(this.lockFile,"utf8"),t=parseInt(e.trim(),10);try{process.kill(t,0),await new Promise(e=>setTimeout(e,100));continue}catch(e){if(e&&"object"==typeof e&&"code"in e){const t=e;if("EPERM"===t.code){await new Promise(e=>setTimeout(e,100));continue}if("ESRCH"===t.code){await l.unlink(this.lockFile).catch(()=>{});continue}}await l.unlink(this.lockFile).catch(()=>{});continue}}catch{await l.unlink(this.lockFile).catch(()=>{});continue}}throw new v("Failed to acquire file lock: timeout")}async release(){if(O&&this.lockAcquired)try{await l.unlink(this.lockFile),this.lockAcquired=!1}catch(e){console.debug("Failed to release file lock:",e)}}}class oe{}class ne extends oe{constructor(){super(),this.storageKey="barndoor_token"}async loadToken(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return Y.warn("Failed to load token from localStorage:",e),null}}async saveToken(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){const t=e instanceof Error?e.message:String(e);throw new v(`Failed to save token: ${t}`)}}async clearToken(){try{localStorage.removeItem(this.storageKey)}catch(e){Y.warn("Failed to clear token from localStorage:",e)}}}class ie extends oe{constructor(){super(),this.tokenFile=this._getTokenFilePath()}_getTokenFilePath(){if(O)return n.join(t.homedir(),".barndoor","token.json");throw new Error("NodeTokenStorage can only be used in Node.js environment")}async loadToken(){if(!O)throw new Error("NodeTokenStorage can only be used in Node.js environment");const e=new se(this.tokenFile);try{await e.acquire();const t=await l.readFile(this.tokenFile,"utf8");return JSON.parse(t)}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||Y.warn("Failed to load token from file:",e),null}finally{await e.release()}}async saveToken(e){if(!O)throw new Error("NodeTokenStorage can only be used in Node.js environment");const t=new se(this.tokenFile);try{await t.acquire(),await l.mkdir(n.dirname(this.tokenFile),{recursive:!0}),await l.writeFile(this.tokenFile,JSON.stringify(e,null,2)),await l.chmod(this.tokenFile,384),Y.debug("Token saved to storage")}catch(e){const t=e instanceof Error?e.message:String(e);throw new v(`Failed to save token: ${t}`)}finally{await t.release()}}async clearToken(){if(!O)throw new Error("NodeTokenStorage can only be used in Node.js environment");try{await l.unlink(this.tokenFile)}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"!==e.code&&Y.warn("Failed to clear token file:",e)}}}function ce(){if(C)return new ne;if(O)return new ie;throw new Error("Unsupported environment for token storage")}async function le(e,t,r){try{const a=function(e){if(!ae.has(e)){const t=u(new URL(`https://${e}/.well-known/jwks.json`));ae.set(e,t)}return ae.get(e)}(t);return await d(e,a,{issuer:`https://${t}/`,audience:r}),Y.debug("Token verified locally using JWKS"),re.VALID}catch(e){return e&&"object"==typeof e&&"code"in e&&"ERR_JWT_EXPIRED"===e.code?(Y.debug("Token expired (verified locally)"),re.EXPIRED):(Y.debug("JWT verification failed:",e),re.INVALID)}}class de{constructor(){this._locked=!1,this._waitQueue=[]}async acquire(){return new Promise(e=>{this._locked?this._waitQueue.push(e):(this._locked=!0,e())})}release(){if(this._waitQueue.length>0){const e=this._waitQueue.shift();e&&e()}else this._locked=!1}async withLock(e){await this.acquire();try{return await e()}finally{this.release()}}}class ue{constructor(e){this._refreshMutex=new de,this.storage=ce()}async getValidToken(){return this._refreshMutex.withLock(async()=>{const e=await this.storage.loadToken();if(!e)throw new v("No token found. Please authenticate.");try{if(this._shouldRefreshToken(e)&&e.refresh_token){Y.debug("Proactively refreshing token before expiration");const t=await this._refreshToken(e),r={...e,...t};return await this.storage.saveToken(r),r.access_token}const t=await this._validateOrRefresh(e);return await this.storage.saveToken(t),t.access_token}catch(e){throw Y.error("Token validation/refresh failed:",e),new g("Token expired and refresh failed. Please re-authenticate.")}})}_shouldRefreshToken(e){const t=ee(e.access_token);if(!t?.exp)return!0;const r=Math.floor(Date.now()/1e3);return t.exp-r<300}async _validateOrRefresh(e){const t=e.access_token,r=F(),a=await le(t,r.authDomain,r.apiAudience);if(a===re.VALID)return Y.debug("Token validated locally"),e;if(a===re.INVALID&&(Y.debug("Local validation failed, trying remote"),await this._isTokenValidRemote(t)))return Y.debug("Token validated remotely"),e;if(Y.info("Token invalid or expired, attempting refresh"),e.refresh_token){const t=await this._refreshToken(e);return{...e,...t}}throw new g("Token expired and no refresh token available")}async _isTokenValidRemote(e){try{const t=F(),r=fetch(`https://${t.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return(await te(r,5e3)).ok}catch(e){return Y.debug("Remote token validation failed:",e),!1}}async _refreshToken(e){const t=e.refresh_token;if(!t)throw new v("No refresh token available");const r=F();if(C&&r.clientSecret)throw new v("Refresh flow requires a confidential client; run interactive login again.");const a={grant_type:"refresh_token",client_id:r.clientId,refresh_token:t};r.clientSecret&&!C&&(a.client_secret=r.clientSecret);try{const e=fetch(`https://${r.authDomain}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(15e3)}:{}}),t=await te(e,15e3);if(400===t.status){let e="Invalid refresh token";try{e=(await t.json()).error_description||e}catch{}throw Y.warn(`Refresh token invalid: ${e}`),new g(`Refresh token expired or invalid: ${e}`)}if(429===t.status)throw Y.warn("Rate limited during token refresh"),new v("Rate limited during token refresh. Please try again later.");if(t.status>=500)throw Y.warn(`Auth server error during refresh: ${t.status}`),new v(`Auth server temporarily unavailable (HTTP ${t.status})`);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);return await t.json()}catch(e){if(e instanceof v||e instanceof g)throw e;if(e&&"object"==typeof e&&"name"in e){if("TimeoutError"===e.name||"AbortError"===e.name)throw Y.warn("Timeout during token refresh"),new v("Token refresh timed out. Please check your connection.");if("TypeError"===e.name&&"message"in e&&"string"==typeof e.message&&e.message.includes("fetch"))throw Y.warn(`Network error during token refresh: ${e.message}`),new v("Network error during token refresh. Please check your connection.")}Y.error("Unexpected error during token refresh:",e);const t=e instanceof Error?e.message:String(e);throw new v(`Token refresh failed: ${t}`)}}}async function he(){try{const e=ce(),t=await e.loadToken();return t?.access_token??null}catch(e){return null}}async function pe(e){const t=ce();let r;r="string"==typeof e?{access_token:e}:e,await t.saveToken(r)}async function fe(){const e=ce();await e.clearToken()}async function me(e){try{const e=ce(),t=await e.loadToken();if(!t?.access_token)return!1;const r=F(),a=fetch(`https://${r.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${t.access_token}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(1e4)}:{}});return(await te(a,1e4)).ok}catch(e){return!1}}async function ve(e){try{const t=new ue(e||"");return await t.getValidToken(),!0}catch(e){return Y.warn("Token validation/refresh failed:",e),!1}}async function ge(e,t){try{const t=F(),r=await le(e,t.authDomain,t.apiAudience);if(r===re.VALID)return{valid:!0};if(r===re.INVALID)try{const r=fetch(`https://${t.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return{valid:(await te(r,5e3)).ok}}catch(e){return Y.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return Y.warn("Token validation failed:",e),{valid:!1}}}var ye,_e;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(ye||(ye={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(_e||(_e={}));const we=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),be=e=>{switch(typeof e){case"undefined":return we.undefined;case"string":return we.string;case"number":return Number.isNaN(e)?we.nan:we.number;case"boolean":return we.boolean;case"function":return we.function;case"bigint":return we.bigint;case"symbol":return we.symbol;case"object":return Array.isArray(e)?we.array:null===e?we.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?we.promise:"undefined"!=typeof Map&&e instanceof Map?we.map:"undefined"!=typeof Set&&e instanceof Set?we.set:"undefined"!=typeof Date&&e instanceof Date?we.date:we.object;default:return we.unknown}},Pe=ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ee extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(a);else if("invalid_return_type"===s.code)a(s.returnTypeError);else if("invalid_arguments"===s.code)a(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,a=0;for(;a<s.path.length;){const r=s.path[a];a===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof Ee))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ye.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Ee.create=e=>new Ee(e);var ke=(e,t)=>{let r;switch(e.code){case Pe.invalid_type:r=e.received===we.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Pe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,ye.jsonStringifyReplacer)}`;break;case Pe.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(e.keys,", ")}`;break;case Pe.invalid_union:r="Invalid input";break;case Pe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(e.options)}`;break;case Pe.invalid_enum_value:r=`Invalid enum value. Expected ${ye.joinValues(e.options)}, received '${e.received}'`;break;case Pe.invalid_arguments:r="Invalid function arguments";break;case Pe.invalid_return_type:r="Invalid function return type";break;case Pe.invalid_date:r="Invalid date";break;case Pe.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:ye.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Pe.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Pe.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Pe.custom:r="Invalid input";break;case Pe.invalid_intersection_types:r="Intersection results could not be merged";break;case Pe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Pe.not_finite:r="Number must be finite";break;default:r=t.defaultError,ye.assertNever(e)}return{message:r}};let xe=ke;function Se(e,t){const r=xe,a=(e=>{const{data:t,path:r,errorMaps:a,issueData:s}=e,o=[...r,...s.path||[]],n={...s,path:o};if(void 0!==s.message)return{...s,path:o,message:s.message};let i="";const c=a.filter(e=>!!e).slice().reverse();for(const e of c)i=e(n,{data:t,defaultError:i}).message;return{...s,path:o,message:i}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ke?void 0:ke].filter(e=>!!e)});e.common.issues.push(a)}class Te{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const a of t){if("aborted"===a.status)return Re;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return Te.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const a of t){const{key:t,value:s}=a;if("aborted"===t.status)return Re;if("aborted"===s.status)return Re;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!a.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const Re=Object.freeze({status:"aborted"}),$e=e=>({status:"dirty",value:e}),Ce=e=>({status:"valid",value:e}),Oe=e=>"aborted"===e.status,Ie=e=>"dirty"===e.status,Ae=e=>"valid"===e.status,je=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Fe;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Fe||(Fe={}));class De{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ne=(e,t)=>{if(Ae(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Ee(e.common.issues);return this._error=t,this._error}}};function Ue(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:s}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??s.defaultError}:void 0===s.data?{message:o??a??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:o??r??s.defaultError}},description:s}}class Le{get description(){return this._def.description}_getType(e){return be(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:be(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:be(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(je(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:be(e)},a=this._parseSync({data:e,path:r.path,parent:r});return Ne(r,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:be(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Ae(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Ae(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:be(e)},a=this._parse({data:e,path:r.path,parent:r}),s=await(je(a)?a:Promise.resolve(a));return Ne(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{const s=e(t),o=()=>a.addIssue({code:Pe.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(o(),!1)):!!s||(o(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new qt({schema:this,typeName:Jt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return zt.create(this,this._def)}nullable(){return Vt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pt.create(this)}promise(){return Lt.create(this,this._def)}or(e){return xt.create([this,e],this._def)}and(e){return $t.create(this,e,this._def)}transform(e){return new qt({...Ue(this._def),schema:this,typeName:Jt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Mt({...Ue(this._def),innerType:this,defaultValue:t,typeName:Jt.ZodDefault})}brand(){return new Bt({typeName:Jt.ZodBranded,type:this,...Ue(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Zt({...Ue(this._def),innerType:this,catchValue:t,typeName:Jt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Qt.create(this,e)}readonly(){return Kt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const qe=/^c[^\s-]{8,}$/i,ze=/^[0-9a-z]+$/,Ve=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Me=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ze=/^[a-z0-9_-]{21}$/i,He=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Be=/^[-+]?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)?)??$/,Qe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Ke;const Je=/^(?:(?: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])$/,We=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ge=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ye=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Xe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,et=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tt="((\\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])))",rt=new RegExp(`^${tt}$`);function at(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function st(e){return new RegExp(`^${at(e)}$`)}function ot(e){let t=`${tt}T${at(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function nt(e,t){return!("v4"!==t&&t||!Je.test(e))||!("v6"!==t&&t||!Ge.test(e))}function it(e,t){if(!He.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(a));return"object"==typeof s&&null!==s&&((!("typ"in s)||"JWT"===s?.typ)&&(!!s.alg&&(!t||s.alg===t)))}catch{return!1}}function ct(e,t){return!("v4"!==t&&t||!We.test(e))||!("v6"!==t&&t||!Ye.test(e))}class lt extends Le{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==we.string){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.string,received:t.parsedType}),Re}const t=new Te;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("max"===a.kind)e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const s=e.data.length>a.value,o=e.data.length<a.value;(s||o)&&(r=this._getOrReturnCtx(e,r),s?Se(r,{code:Pe.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&Se(r,{code:Pe.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if("email"===a.kind)Qe.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"email",code:Pe.invalid_string,message:a.message}),t.dirty());else if("emoji"===a.kind)Ke||(Ke=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ke.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"emoji",code:Pe.invalid_string,message:a.message}),t.dirty());else if("uuid"===a.kind)Me.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"uuid",code:Pe.invalid_string,message:a.message}),t.dirty());else if("nanoid"===a.kind)Ze.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"nanoid",code:Pe.invalid_string,message:a.message}),t.dirty());else if("cuid"===a.kind)qe.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"cuid",code:Pe.invalid_string,message:a.message}),t.dirty());else if("cuid2"===a.kind)ze.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"cuid2",code:Pe.invalid_string,message:a.message}),t.dirty());else if("ulid"===a.kind)Ve.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"ulid",code:Pe.invalid_string,message:a.message}),t.dirty());else if("url"===a.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Se(r,{validation:"url",code:Pe.invalid_string,message:a.message}),t.dirty()}else if("regex"===a.kind){a.regex.lastIndex=0;a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"regex",code:Pe.invalid_string,message:a.message}),t.dirty())}else if("trim"===a.kind)e.data=e.data.trim();else if("includes"===a.kind)e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty());else if("toLowerCase"===a.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===a.kind)e.data=e.data.toUpperCase();else if("startsWith"===a.kind)e.data.startsWith(a.value)||(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty());else if("endsWith"===a.kind)e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty());else if("datetime"===a.kind){ot(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.invalid_string,validation:"datetime",message:a.message}),t.dirty())}else if("date"===a.kind){rt.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.invalid_string,validation:"date",message:a.message}),t.dirty())}else if("time"===a.kind){st(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.invalid_string,validation:"time",message:a.message}),t.dirty())}else"duration"===a.kind?Be.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"duration",code:Pe.invalid_string,message:a.message}),t.dirty()):"ip"===a.kind?nt(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"ip",code:Pe.invalid_string,message:a.message}),t.dirty()):"jwt"===a.kind?it(e.data,a.alg)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"jwt",code:Pe.invalid_string,message:a.message}),t.dirty()):"cidr"===a.kind?ct(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"cidr",code:Pe.invalid_string,message:a.message}),t.dirty()):"base64"===a.kind?Xe.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"base64",code:Pe.invalid_string,message:a.message}),t.dirty()):"base64url"===a.kind?et.test(e.data)||(r=this._getOrReturnCtx(e,r),Se(r,{validation:"base64url",code:Pe.invalid_string,message:a.message}),t.dirty()):ye.assertNever(a);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Pe.invalid_string,...Fe.errToObj(r)})}_addCheck(e){return new lt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Fe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Fe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Fe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Fe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Fe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Fe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Fe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Fe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Fe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Fe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Fe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Fe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Fe.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Fe.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Fe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Fe.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Fe.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Fe.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Fe.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Fe.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Fe.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Fe.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Fe.errToObj(t)})}nonempty(e){return this.min(1,Fe.errToObj(e))}trim(){return new lt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new lt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new lt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function dt(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,s=r>a?r:a;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}lt.create=e=>new lt({checks:[],typeName:Jt.ZodString,coerce:e?.coerce??!1,...Ue(e)});class ut extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==we.number){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.number,received:t.parsedType}),Re}let t;const r=new Te;for(const a of this._def.checks)if("int"===a.kind)ye.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else"multipleOf"===a.kind?0!==dt(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.not_finite,message:a.message}),r.dirty()):ye.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Fe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Fe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Fe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Fe.toString(t))}setLimit(e,t,r,a){return new ut({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Fe.toString(a)}]})}_addCheck(e){return new ut({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Fe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Fe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Fe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Fe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Fe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Fe.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Fe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Fe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Fe.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&ye.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ut.create=e=>new ut({checks:[],typeName:Jt.ZodNumber,coerce:e?.coerce||!1,...Ue(e)});class ht extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==we.bigint)return this._getInvalidInput(e);let t;const r=new Te;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Se(t,{code:Pe.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):ye.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.bigint,received:t.parsedType}),Re}gte(e,t){return this.setLimit("min",e,!0,Fe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Fe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Fe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Fe.toString(t))}setLimit(e,t,r,a){return new ht({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Fe.toString(a)}]})}_addCheck(e){return new ht({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Fe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Fe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Fe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Fe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Fe.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ht.create=e=>new ht({checks:[],typeName:Jt.ZodBigInt,coerce:e?.coerce??!1,...Ue(e)});class pt extends Le{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==we.boolean){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.boolean,received:t.parsedType}),Re}return Ce(e.data)}}pt.create=e=>new pt({typeName:Jt.ZodBoolean,coerce:e?.coerce||!1,...Ue(e)});class ft extends Le{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==we.date){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.date,received:t.parsedType}),Re}if(Number.isNaN(e.data.getTime())){return Se(this._getOrReturnCtx(e),{code:Pe.invalid_date}),Re}const t=new Te;let r;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(r=this._getOrReturnCtx(e,r),Se(r,{code:Pe.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):ye.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ft({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Fe.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Fe.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ft.create=e=>new ft({checks:[],coerce:e?.coerce||!1,typeName:Jt.ZodDate,...Ue(e)});class mt extends Le{_parse(e){if(this._getType(e)!==we.symbol){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.symbol,received:t.parsedType}),Re}return Ce(e.data)}}mt.create=e=>new mt({typeName:Jt.ZodSymbol,...Ue(e)});class vt extends Le{_parse(e){if(this._getType(e)!==we.undefined){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.undefined,received:t.parsedType}),Re}return Ce(e.data)}}vt.create=e=>new vt({typeName:Jt.ZodUndefined,...Ue(e)});class gt extends Le{_parse(e){if(this._getType(e)!==we.null){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.null,received:t.parsedType}),Re}return Ce(e.data)}}gt.create=e=>new gt({typeName:Jt.ZodNull,...Ue(e)});class yt extends Le{constructor(){super(...arguments),this._any=!0}_parse(e){return Ce(e.data)}}yt.create=e=>new yt({typeName:Jt.ZodAny,...Ue(e)});class _t extends Le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ce(e.data)}}_t.create=e=>new _t({typeName:Jt.ZodUnknown,...Ue(e)});class wt extends Le{_parse(e){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.never,received:t.parsedType}),Re}}wt.create=e=>new wt({typeName:Jt.ZodNever,...Ue(e)});class bt extends Le{_parse(e){if(this._getType(e)!==we.undefined){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.void,received:t.parsedType}),Re}return Ce(e.data)}}bt.create=e=>new bt({typeName:Jt.ZodVoid,...Ue(e)});class Pt extends Le{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==we.array)return Se(t,{code:Pe.invalid_type,expected:we.array,received:t.parsedType}),Re;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,s=t.data.length<a.exactLength.value;(e||s)&&(Se(t,{code:e?Pe.too_big:Pe.too_small,minimum:s?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(Se(t,{code:Pe.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(Se(t,{code:Pe.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new De(t,e,t.path,r)))).then(e=>Te.mergeArray(r,e));const s=[...t.data].map((e,r)=>a.type._parseSync(new De(t,e,t.path,r)));return Te.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new Pt({...this._def,minLength:{value:e,message:Fe.toString(t)}})}max(e,t){return new Pt({...this._def,maxLength:{value:e,message:Fe.toString(t)}})}length(e,t){return new Pt({...this._def,exactLength:{value:e,message:Fe.toString(t)}})}nonempty(e){return this.min(1,e)}}function Et(e){if(e instanceof kt){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=zt.create(Et(a))}return new kt({...e._def,shape:()=>t})}return e instanceof Pt?new Pt({...e._def,type:Et(e.element)}):e instanceof zt?zt.create(Et(e.unwrap())):e instanceof Vt?Vt.create(Et(e.unwrap())):e instanceof Ct?Ct.create(e.items.map(e=>Et(e))):e}Pt.create=(e,t)=>new Pt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Jt.ZodArray,...Ue(t)});class kt extends Le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=ye.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==we.object){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.object,received:t.parsedType}),Re}const{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof wt&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||o.push(e);const n=[];for(const e of s){const t=a[e],s=r.data[e];n.push({key:{status:"valid",value:e},value:t._parse(new De(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof wt){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)n.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(Se(r,{code:Pe.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const a=r.data[t];n.push({key:{status:"valid",value:t},value:e._parse(new De(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of n){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>Te.mergeObjectSync(t,e)):Te.mergeObjectSync(t,n)}get shape(){return this._def.shape()}strict(e){return Fe.errToObj,new kt({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:Fe.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new kt({...this._def,unknownKeys:"strip"})}passthrough(){return new kt({...this._def,unknownKeys:"passthrough"})}extend(e){return new kt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new kt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Jt.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new kt({...this._def,catchall:e})}pick(e){const t={};for(const r of ye.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new kt({...this._def,shape:()=>t})}omit(e){const t={};for(const r of ye.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new kt({...this._def,shape:()=>t})}deepPartial(){return Et(this)}partial(e){const t={};for(const r of ye.objectKeys(this.shape)){const a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new kt({...this._def,shape:()=>t})}required(e){const t={};for(const r of ye.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof zt;)e=e._def.innerType;t[r]=e}return new kt({...this._def,shape:()=>t})}keyof(){return Dt(ye.objectKeys(this.shape))}}kt.create=(e,t)=>new kt({shape:()=>e,unknownKeys:"strip",catchall:wt.create(),typeName:Jt.ZodObject,...Ue(t)}),kt.strictCreate=(e,t)=>new kt({shape:()=>e,unknownKeys:"strict",catchall:wt.create(),typeName:Jt.ZodObject,...Ue(t)}),kt.lazycreate=(e,t)=>new kt({shape:e,unknownKeys:"strip",catchall:wt.create(),typeName:Jt.ZodObject,...Ue(t)});class xt extends Le{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new Ee(e.ctx.common.issues));return Se(t,{code:Pe.invalid_union,unionErrors:r}),Re});{let e;const a=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=a.map(e=>new Ee(e));return Se(t,{code:Pe.invalid_union,unionErrors:s}),Re}}get options(){return this._def.options}}xt.create=(e,t)=>new xt({options:e,typeName:Jt.ZodUnion,...Ue(t)});const St=e=>e instanceof jt?St(e.schema):e instanceof qt?St(e.innerType()):e instanceof Ft?[e.value]:e instanceof Nt?e.options:e instanceof Ut?ye.objectValues(e.enum):e instanceof Mt?St(e._def.innerType):e instanceof vt?[void 0]:e instanceof gt?[null]:e instanceof zt?[void 0,...St(e.unwrap())]:e instanceof Vt?[null,...St(e.unwrap())]:e instanceof Bt||e instanceof Kt?St(e.unwrap()):e instanceof Zt?St(e._def.innerType):[];class Tt extends Le{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==we.object)return Se(t,{code:Pe.invalid_type,expected:we.object,received:t.parsedType}),Re;const r=this.discriminator,a=t.data[r],s=this.optionsMap.get(a);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(Se(t,{code:Pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Re)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=St(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(a.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);a.set(s,r)}}return new Tt({typeName:Jt.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...Ue(r)})}}function Rt(e,t){const r=be(e),a=be(t);if(e===t)return{valid:!0,data:e};if(r===we.object&&a===we.object){const r=ye.objectKeys(t),a=ye.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of a){const a=Rt(e[r],t[r]);if(!a.valid)return{valid:!1};s[r]=a.data}return{valid:!0,data:s}}if(r===we.array&&a===we.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let a=0;a<e.length;a++){const s=Rt(e[a],t[a]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===we.date&&a===we.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class $t extends Le{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(Oe(e)||Oe(a))return Re;const s=Rt(e.value,a.value);return s.valid?((Ie(e)||Ie(a))&&t.dirty(),{status:t.value,value:s.data}):(Se(r,{code:Pe.invalid_intersection_types}),Re)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}$t.create=(e,t,r)=>new $t({left:e,right:t,typeName:Jt.ZodIntersection,...Ue(r)});class Ct extends Le{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==we.array)return Se(r,{code:Pe.invalid_type,expected:we.array,received:r.parsedType}),Re;if(r.data.length<this._def.items.length)return Se(r,{code:Pe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Re;!this._def.rest&&r.data.length>this._def.items.length&&(Se(r,{code:Pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new De(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>Te.mergeArray(t,e)):Te.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new Ct({...this._def,rest:e})}}Ct.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:e,typeName:Jt.ZodTuple,rest:null,...Ue(t)})};class Ot extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==we.object)return Se(r,{code:Pe.invalid_type,expected:we.object,received:r.parsedType}),Re;const a=[],s=this._def.keyType,o=this._def.valueType;for(const e in r.data)a.push({key:s._parse(new De(r,e,r.path,e)),value:o._parse(new De(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?Te.mergeObjectAsync(t,a):Te.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new Ot(t instanceof Le?{keyType:e,valueType:t,typeName:Jt.ZodRecord,...Ue(r)}:{keyType:lt.create(),valueType:e,typeName:Jt.ZodRecord,...Ue(t)})}}class It extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==we.map)return Se(r,{code:Pe.invalid_type,expected:we.map,received:r.parsedType}),Re;const a=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:a._parse(new De(r,e,r.path,[o,"key"])),value:s._parse(new De(r,t,r.path,[o,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of o){const a=await r.key,s=await r.value;if("aborted"===a.status||"aborted"===s.status)return Re;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of o){const a=r.key,s=r.value;if("aborted"===a.status||"aborted"===s.status)return Re;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}}}}It.create=(e,t,r)=>new It({valueType:t,keyType:e,typeName:Jt.ZodMap,...Ue(r)});class At extends Le{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==we.set)return Se(r,{code:Pe.invalid_type,expected:we.set,received:r.parsedType}),Re;const a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(Se(r,{code:Pe.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(Se(r,{code:Pe.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const s=this._def.valueType;function o(e){const r=new Set;for(const a of e){if("aborted"===a.status)return Re;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const n=[...r.data.values()].map((e,t)=>s._parse(new De(r,e,r.path,t)));return r.common.async?Promise.all(n).then(e=>o(e)):o(n)}min(e,t){return new At({...this._def,minSize:{value:e,message:Fe.toString(t)}})}max(e,t){return new At({...this._def,maxSize:{value:e,message:Fe.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}At.create=(e,t)=>new At({valueType:e,minSize:null,maxSize:null,typeName:Jt.ZodSet,...Ue(t)});class jt extends Le{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}jt.create=(e,t)=>new jt({getter:e,typeName:Jt.ZodLazy,...Ue(t)});class Ft extends Le{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Se(t,{received:t.data,code:Pe.invalid_literal,expected:this._def.value}),Re}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Dt(e,t){return new Nt({values:e,typeName:Jt.ZodEnum,...Ue(t)})}Ft.create=(e,t)=>new Ft({value:e,typeName:Jt.ZodLiteral,...Ue(t)});class Nt extends Le{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Se(t,{expected:ye.joinValues(r),received:t.parsedType,code:Pe.invalid_type}),Re}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return Se(t,{received:t.data,code:Pe.invalid_enum_value,options:r}),Re}return Ce(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Nt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Nt.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Nt.create=Dt;class Ut extends Le{_parse(e){const t=ye.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==we.string&&r.parsedType!==we.number){const e=ye.objectValues(t);return Se(r,{expected:ye.joinValues(e),received:r.parsedType,code:Pe.invalid_type}),Re}if(this._cache||(this._cache=new Set(ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=ye.objectValues(t);return Se(r,{received:r.data,code:Pe.invalid_enum_value,options:e}),Re}return Ce(e.data)}get enum(){return this._def.values}}Ut.create=(e,t)=>new Ut({values:e,typeName:Jt.ZodNativeEnum,...Ue(t)});class Lt extends Le{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==we.promise&&!1===t.common.async)return Se(t,{code:Pe.invalid_type,expected:we.promise,received:t.parsedType}),Re;const r=t.parsedType===we.promise?t.data:Promise.resolve(t.data);return Ce(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Lt.create=(e,t)=>new Lt({type:e,typeName:Jt.ZodPromise,...Ue(t)});class qt extends Le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Jt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:e=>{Se(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===a.type){const e=a.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Re;const a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?Re:"dirty"===a.status||"dirty"===t.value?$e(a.value):a});{if("aborted"===t.value)return Re;const a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?Re:"dirty"===a.status||"dirty"===t.value?$e(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?Re:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?Re:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===a.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ae(e))return Re;const o=a.transform(e.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>Ae(e)?Promise.resolve(a.transform(e.value,s)).then(e=>({status:t.value,value:e})):Re)}ye.assertNever(a)}}qt.create=(e,t,r)=>new qt({schema:e,typeName:Jt.ZodEffects,effect:t,...Ue(r)}),qt.createWithPreprocess=(e,t,r)=>new qt({schema:t,effect:{type:"preprocess",transform:e},typeName:Jt.ZodEffects,...Ue(r)});class zt extends Le{_parse(e){return this._getType(e)===we.undefined?Ce(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}zt.create=(e,t)=>new zt({innerType:e,typeName:Jt.ZodOptional,...Ue(t)});class Vt extends Le{_parse(e){return this._getType(e)===we.null?Ce(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Vt.create=(e,t)=>new Vt({innerType:e,typeName:Jt.ZodNullable,...Ue(t)});class Mt extends Le{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===we.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Mt.create=(e,t)=>new Mt({innerType:e,typeName:Jt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Ue(t)});class Zt extends Le{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return je(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Ee(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new Ee(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Zt.create=(e,t)=>new Zt({innerType:e,typeName:Jt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Ue(t)});class Ht extends Le{_parse(e){if(this._getType(e)!==we.nan){const t=this._getOrReturnCtx(e);return Se(t,{code:Pe.invalid_type,expected:we.nan,received:t.parsedType}),Re}return{status:"valid",value:e.data}}}Ht.create=e=>new Ht({typeName:Jt.ZodNaN,...Ue(e)});class Bt extends Le{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Qt extends Le{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?Re:"dirty"===e.status?(t.dirty(),$e(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?Re:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Qt({in:e,out:t,typeName:Jt.ZodPipeline})}}class Kt extends Le{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Ae(e)&&(e.value=Object.freeze(e.value)),e);return je(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var Jt;Kt.create=(e,t)=>new Kt({innerType:e,typeName:Jt.ZodReadonly,...Ue(t)}),kt.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Jt||(Jt={}));const Wt=lt.create,Gt=ut.create;Ht.create,ht.create;const Yt=pt.create;ft.create,mt.create,vt.create,gt.create;const Xt=yt.create,er=_t.create;wt.create,bt.create;const tr=Pt.create,rr=kt.create;kt.strictCreate;const ar=xt.create,sr=Tt.create;$t.create,Ct.create;const or=Ot.create;It.create,At.create,jt.create;const nr=Ft.create,ir=Nt.create;Ut.create,Lt.create,qt.create;const cr=zt.create;Vt.create,qt.createWithPreprocess;const lr="2025-06-18",dr=[lr,"2025-03-26","2024-11-05","2024-10-07"],ur="2.0",hr=ar([Wt(),Gt().int()]),pr=Wt(),fr=rr({progressToken:cr(hr)}).passthrough(),mr=rr({_meta:cr(fr)}).passthrough(),vr=rr({method:Wt(),params:cr(mr)}),gr=rr({_meta:cr(rr({}).passthrough())}).passthrough(),yr=rr({method:Wt(),params:cr(gr)}),_r=rr({_meta:cr(rr({}).passthrough())}).passthrough(),wr=ar([Wt(),Gt().int()]),br=rr({jsonrpc:nr(ur),id:wr}).merge(vr).strict(),Pr=e=>br.safeParse(e).success,Er=rr({jsonrpc:nr(ur)}).merge(yr).strict(),kr=rr({jsonrpc:nr(ur),id:wr,result:_r}).strict(),xr=e=>kr.safeParse(e).success;var Sr;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(Sr||(Sr={}));const Tr=rr({jsonrpc:nr(ur),id:wr,error:rr({code:Gt().int(),message:Wt(),data:cr(er())})}).strict(),Rr=ar([br,Er,kr,Tr]),$r=_r.strict(),Cr=yr.extend({method:nr("notifications/cancelled"),params:gr.extend({requestId:wr,reason:Wt().optional()})}),Or=rr({name:Wt(),title:cr(Wt())}).passthrough(),Ir=Or.extend({version:Wt()}),Ar=rr({experimental:cr(rr({}).passthrough()),sampling:cr(rr({}).passthrough()),elicitation:cr(rr({}).passthrough()),roots:cr(rr({listChanged:cr(Yt())}).passthrough())}).passthrough(),jr=vr.extend({method:nr("initialize"),params:mr.extend({protocolVersion:Wt(),capabilities:Ar,clientInfo:Ir})}),Fr=rr({experimental:cr(rr({}).passthrough()),logging:cr(rr({}).passthrough()),completions:cr(rr({}).passthrough()),prompts:cr(rr({listChanged:cr(Yt())}).passthrough()),resources:cr(rr({subscribe:cr(Yt()),listChanged:cr(Yt())}).passthrough()),tools:cr(rr({listChanged:cr(Yt())}).passthrough())}).passthrough(),Dr=_r.extend({protocolVersion:Wt(),capabilities:Fr,serverInfo:Ir,instructions:cr(Wt())}),Nr=yr.extend({method:nr("notifications/initialized")}),Ur=vr.extend({method:nr("ping")}),Lr=rr({progress:Gt(),total:cr(Gt()),message:cr(Wt())}).passthrough(),qr=yr.extend({method:nr("notifications/progress"),params:gr.merge(Lr).extend({progressToken:hr})}),zr=vr.extend({params:mr.extend({cursor:cr(pr)}).optional()}),Vr=_r.extend({nextCursor:cr(pr)}),Mr=rr({uri:Wt(),mimeType:cr(Wt()),_meta:cr(rr({}).passthrough())}).passthrough(),Zr=Mr.extend({text:Wt()}),Hr=Wt().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Br=Mr.extend({blob:Hr}),Qr=Or.extend({uri:Wt(),description:cr(Wt()),mimeType:cr(Wt()),_meta:cr(rr({}).passthrough())}),Kr=Or.extend({uriTemplate:Wt(),description:cr(Wt()),mimeType:cr(Wt()),_meta:cr(rr({}).passthrough())}),Jr=zr.extend({method:nr("resources/list")}),Wr=Vr.extend({resources:tr(Qr)}),Gr=zr.extend({method:nr("resources/templates/list")}),Yr=Vr.extend({resourceTemplates:tr(Kr)}),Xr=vr.extend({method:nr("resources/read"),params:mr.extend({uri:Wt()})}),ea=_r.extend({contents:tr(ar([Zr,Br]))}),ta=yr.extend({method:nr("notifications/resources/list_changed")}),ra=vr.extend({method:nr("resources/subscribe"),params:mr.extend({uri:Wt()})}),aa=vr.extend({method:nr("resources/unsubscribe"),params:mr.extend({uri:Wt()})}),sa=yr.extend({method:nr("notifications/resources/updated"),params:gr.extend({uri:Wt()})}),oa=rr({name:Wt(),description:cr(Wt()),required:cr(Yt())}).passthrough(),na=Or.extend({description:cr(Wt()),arguments:cr(tr(oa)),_meta:cr(rr({}).passthrough())}),ia=zr.extend({method:nr("prompts/list")}),ca=Vr.extend({prompts:tr(na)}),la=vr.extend({method:nr("prompts/get"),params:mr.extend({name:Wt(),arguments:cr(or(Wt()))})}),da=rr({type:nr("text"),text:Wt(),_meta:cr(rr({}).passthrough())}).passthrough(),ua=rr({type:nr("image"),data:Hr,mimeType:Wt(),_meta:cr(rr({}).passthrough())}).passthrough(),ha=rr({type:nr("audio"),data:Hr,mimeType:Wt(),_meta:cr(rr({}).passthrough())}).passthrough(),pa=rr({type:nr("resource"),resource:ar([Zr,Br]),_meta:cr(rr({}).passthrough())}).passthrough(),fa=ar([da,ua,ha,Qr.extend({type:nr("resource_link")}),pa]),ma=rr({role:ir(["user","assistant"]),content:fa}).passthrough(),va=_r.extend({description:cr(Wt()),messages:tr(ma)}),ga=yr.extend({method:nr("notifications/prompts/list_changed")}),ya=rr({title:cr(Wt()),readOnlyHint:cr(Yt()),destructiveHint:cr(Yt()),idempotentHint:cr(Yt()),openWorldHint:cr(Yt())}).passthrough(),_a=Or.extend({description:cr(Wt()),inputSchema:rr({type:nr("object"),properties:cr(rr({}).passthrough()),required:cr(tr(Wt()))}).passthrough(),outputSchema:cr(rr({type:nr("object"),properties:cr(rr({}).passthrough()),required:cr(tr(Wt()))}).passthrough()),annotations:cr(ya),_meta:cr(rr({}).passthrough())}),wa=zr.extend({method:nr("tools/list")}),ba=Vr.extend({tools:tr(_a)}),Pa=_r.extend({content:tr(fa).default([]),structuredContent:rr({}).passthrough().optional(),isError:cr(Yt())});Pa.or(_r.extend({toolResult:er()}));const Ea=vr.extend({method:nr("tools/call"),params:mr.extend({name:Wt(),arguments:cr(or(er()))})}),ka=yr.extend({method:nr("notifications/tools/list_changed")}),xa=ir(["debug","info","notice","warning","error","critical","alert","emergency"]),Sa=vr.extend({method:nr("logging/setLevel"),params:mr.extend({level:xa})}),Ta=yr.extend({method:nr("notifications/message"),params:gr.extend({level:xa,logger:cr(Wt()),data:er()})}),Ra=rr({name:Wt().optional()}).passthrough(),$a=rr({hints:cr(tr(Ra)),costPriority:cr(Gt().min(0).max(1)),speedPriority:cr(Gt().min(0).max(1)),intelligencePriority:cr(Gt().min(0).max(1))}).passthrough(),Ca=rr({role:ir(["user","assistant"]),content:ar([da,ua,ha])}).passthrough(),Oa=vr.extend({method:nr("sampling/createMessage"),params:mr.extend({messages:tr(Ca),systemPrompt:cr(Wt()),includeContext:cr(ir(["none","thisServer","allServers"])),temperature:cr(Gt()),maxTokens:Gt().int(),stopSequences:cr(tr(Wt())),metadata:cr(rr({}).passthrough()),modelPreferences:cr($a)})}),Ia=_r.extend({model:Wt(),stopReason:cr(ir(["endTurn","stopSequence","maxTokens"]).or(Wt())),role:ir(["user","assistant"]),content:sr("type",[da,ua,ha])}),Aa=ar([rr({type:nr("boolean"),title:cr(Wt()),description:cr(Wt()),default:cr(Yt())}).passthrough(),rr({type:nr("string"),title:cr(Wt()),description:cr(Wt()),minLength:cr(Gt()),maxLength:cr(Gt()),format:cr(ir(["email","uri","date","date-time"]))}).passthrough(),rr({type:ir(["number","integer"]),title:cr(Wt()),description:cr(Wt()),minimum:cr(Gt()),maximum:cr(Gt())}).passthrough(),rr({type:nr("string"),title:cr(Wt()),description:cr(Wt()),enum:tr(Wt()),enumNames:cr(tr(Wt()))}).passthrough()]),ja=vr.extend({method:nr("elicitation/create"),params:mr.extend({message:Wt(),requestedSchema:rr({type:nr("object"),properties:or(Wt(),Aa),required:cr(tr(Wt()))}).passthrough()})}),Fa=_r.extend({action:ir(["accept","decline","cancel"]),content:cr(or(Wt(),er()))}),Da=rr({type:nr("ref/resource"),uri:Wt()}).passthrough(),Na=rr({type:nr("ref/prompt"),name:Wt()}).passthrough(),Ua=vr.extend({method:nr("completion/complete"),params:mr.extend({ref:ar([Na,Da]),argument:rr({name:Wt(),value:Wt()}).passthrough(),context:cr(rr({arguments:cr(or(Wt(),Wt()))}))})}),La=_r.extend({completion:rr({values:tr(Wt()).max(100),total:cr(Gt().int()),hasMore:cr(Yt())}).passthrough()}),qa=rr({uri:Wt().startsWith("file://"),name:cr(Wt()),_meta:cr(rr({}).passthrough())}).passthrough(),za=vr.extend({method:nr("roots/list")}),Va=_r.extend({roots:tr(qa)}),Ma=yr.extend({method:nr("notifications/roots/list_changed")});ar([Ur,jr,Ua,Sa,la,ia,Jr,Gr,Xr,ra,aa,Ea,wa]),ar([Cr,qr,Nr,Ma]),ar([$r,Ia,Fa,Va]),ar([Ur,Oa,ja,za]),ar([Cr,qr,Ta,sa,ta,ka,ga]),ar([$r,Dr,La,va,ca,Wr,Yr,ea,Pa,ba]);class Za extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class Ha{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Cr,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(qr,e=>{this._onprogress(e)}),this.setRequestHandler(Ur,e=>({}))}_setupTimeout(e,t,r,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:a})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Za(Sr.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,a;this._transport=e;const s=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==s||s(),this._onclose()};const o=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==o||o(e),this._onerror(e)};const n=null===(a=this._transport)||void 0===a?void 0:a.onmessage;this._transport.onmessage=(e,t)=>{var r;null==n||n(e,t),xr(e)||(r=e,Tr.safeParse(r).success)?this._onresponse(e):Pr(e)?this._onrequest(e,t):(e=>Er.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new Za(Sr.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,a,s,o;const n=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler;if(void 0===n)return void(null===(a=this._transport)||void 0===a||a.send({jsonrpc:"2.0",id:e.id,error:{code:Sr.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const c={signal:i.signal,sessionId:null===(s=this._transport)||void 0===s?void 0:s.sessionId,_meta:null===(o=e.params)||void 0===o?void 0:o._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,a)=>this.request(t,r,{...a,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>n(e,c)).then(t=>{var r;if(!i.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r,a;if(!i.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Sr.InternalError,message:null!==(a=t.message)&&void 0!==a?a:"Internal error"}})}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,a=Number(t),s=this._progressHandlers.get(a);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(a),n=this._timeoutInfo.get(a);if(n&&o&&n.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){return void o(e)}s(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);if(void 0!==r)if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),xr(e))r(e);else{r(new Za(e.error.code,e.error.message,e.error.data))}else this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}=null!=r?r:{};return new Promise((n,i)=>{var c,l,d,u,h,p;if(!this._transport)return void i(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(l=null==r?void 0:r.signal)||void 0===l||l.throwIfAborted();const f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(f,r.onprogress),m.params={...e.params,_meta:{...(null===(d=e.params)||void 0===d?void 0:d._meta)||{},progressToken:f}});const v=e=>{var t;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),i(e)};this._responseHandlers.set(f,e=>{var a;if(!(null===(a=null==r?void 0:r.signal)||void 0===a?void 0:a.aborted)){if(e instanceof Error)return i(e);try{const r=t.parse(e.result);n(r)}catch(e){i(e)}}}),null===(u=null==r?void 0:r.signal)||void 0===u||u.addEventListener("abort",()=>{var e;v(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const g=null!==(h=null==r?void 0:r.timeout)&&void 0!==h?h:6e4;this._setupTimeout(f,g,null==r?void 0:r.maxTotalTimeout,()=>v(new Za(Sr.RequestTimeout,"Request timed out",{timeout:g})),null!==(p=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==p&&p),this._transport.send(m,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(f),i(e)})})}async notification(e,t){var r,a;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);if((null!==(a=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==a?a:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const a={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(a,t).catch(e=>this._onerror(e))})}const s={...e,jsonrpc:"2.0"};await this._transport.send(s,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,a)=>Promise.resolve(t(e.parse(r),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Ba(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Qa={exports:{}};
2
- /** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */!function(e){function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var a=t.length-1,s=1;s<a;++s)t[s]=t[s].slice(1,-1);return t[a]=t[a].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function a(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function s(e){return e.toUpperCase()}function o(e){return null!=e?e instanceof Array?e:"number"!=typeof e.length||e.split||e.setInterval||e.call?[e]:Array.prototype.slice.call(e):[]}function n(e,t){var r=e;if(t)for(var a in t)r[a]=t[a];return r}function i(e){var a="[A-Za-z]",s="[0-9]",o=t(s,"[A-Fa-f]"),n=r(r("%[EFef]"+o+"%"+o+o+"%"+o+o)+"|"+r("%[89A-Fa-f]"+o+"%"+o+o)+"|"+r("%"+o+o)),i="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",i),l=e?"[\\uE000-\\uF8FF]":"[]",d=t(a,s,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]");r(a+t(a,s,"[\\+\\-\\.]")+"*"),r(r(n+"|"+t(d,i,"[\\:]"))+"*");var u=r(r("25[0-5]")+"|"+r("2[0-4]"+s)+"|"+r("1"+s+s)+"|"+r("0?[1-9]"+s)+"|0?0?"+s),h=r(u+"\\."+u+"\\."+u+"\\."+u),p=r(o+"{1,4}"),f=r(r(p+"\\:"+p)+"|"+h),m=r(r(p+"\\:")+"{6}"+f),v=r("\\:\\:"+r(p+"\\:")+"{5}"+f),g=r(r(p)+"?\\:\\:"+r(p+"\\:")+"{4}"+f),y=r(r(r(p+"\\:")+"{0,1}"+p)+"?\\:\\:"+r(p+"\\:")+"{3}"+f),_=r(r(r(p+"\\:")+"{0,2}"+p)+"?\\:\\:"+r(p+"\\:")+"{2}"+f),w=r(r(r(p+"\\:")+"{0,3}"+p)+"?\\:\\:"+p+"\\:"+f),b=r(r(r(p+"\\:")+"{0,4}"+p)+"?\\:\\:"+f),P=r(r(r(p+"\\:")+"{0,5}"+p)+"?\\:\\:"+p),E=r(r(r(p+"\\:")+"{0,6}"+p)+"?\\:\\:"),k=r([m,v,g,y,_,w,b,P,E].join("|")),x=r(r(d+"|"+n)+"+");r("[vV]"+o+"+\\."+t(d,i,"[\\:]")+"+"),r(r(n+"|"+t(d,i))+"*");var S=r(n+"|"+t(d,i,"[\\:\\@]"));return r(r(n+"|"+t(d,i,"[\\@]"))+"+"),r(r(S+"|"+t("[\\/\\?]",l))+"*"),{NOT_SCHEME:new RegExp(t("[^]",a,s,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",d,i),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",d,i),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",d,i),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",d,i),"g"),NOT_QUERY:new RegExp(t("[^\\%]",d,i,"[\\:\\@\\/\\?]",l),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",d,i,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",d,i),"g"),UNRESERVED:new RegExp(d,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",d,c),"g"),PCT_ENCODED:new RegExp(n,"g"),IPV4ADDRESS:new RegExp("^("+h+")$"),IPV6ADDRESS:new RegExp("^\\[?("+k+")"+r(r("\\%25|\\%(?!"+o+"{2})")+"("+x+")")+"?\\]?$")}}var c=i(!1),l=i(!0),d=function(){function e(e,t){var r=[],a=!0,s=!1,o=void 0;try{for(var n,i=e[Symbol.iterator]();!(a=(n=i.next()).done)&&(r.push(n.value),!t||r.length!==t);a=!0);}catch(e){s=!0,o=e}finally{try{!a&&i.return&&i.return()}finally{if(s)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},h=2147483647,p=36,f=1,m=26,v=38,g=700,y=72,_=128,w="-",b=/^xn--/,P=/[^\0-\x7E]/,E=/[\x2E\u3002\uFF0E\uFF61]/g,k={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},x=p-f,S=Math.floor,T=String.fromCharCode;function R(e){throw new RangeError(k[e])}function $(e,t){for(var r=[],a=e.length;a--;)r[a]=t(e[a]);return r}function C(e,t){var r=e.split("@"),a="";return r.length>1&&(a=r[0]+"@",e=r[1]),a+$((e=e.replace(E,".")).split("."),t).join(".")}function O(e){for(var t=[],r=0,a=e.length;r<a;){var s=e.charCodeAt(r++);if(s>=55296&&s<=56319&&r<a){var o=e.charCodeAt(r++);56320==(64512&o)?t.push(((1023&s)<<10)+(1023&o)+65536):(t.push(s),r--)}else t.push(s)}return t}var I=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:p},A=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},j=function(e,t,r){var a=0;for(e=r?S(e/g):e>>1,e+=S(e/t);e>x*m>>1;a+=p)e=S(e/x);return S(a+(x+1)*e/(e+v))},F=function(e){var t=[],r=e.length,a=0,s=_,o=y,n=e.lastIndexOf(w);n<0&&(n=0);for(var i=0;i<n;++i)e.charCodeAt(i)>=128&&R("not-basic"),t.push(e.charCodeAt(i));for(var c=n>0?n+1:0;c<r;){for(var l=a,d=1,u=p;;u+=p){c>=r&&R("invalid-input");var v=I(e.charCodeAt(c++));(v>=p||v>S((h-a)/d))&&R("overflow"),a+=v*d;var g=u<=o?f:u>=o+m?m:u-o;if(v<g)break;var b=p-g;d>S(h/b)&&R("overflow"),d*=b}var P=t.length+1;o=j(a-l,P,0==l),S(a/P)>h-s&&R("overflow"),s+=S(a/P),a%=P,t.splice(a++,0,s)}return String.fromCodePoint.apply(String,t)},D=function(e){var t=[],r=(e=O(e)).length,a=_,s=0,o=y,n=!0,i=!1,c=void 0;try{for(var l,d=e[Symbol.iterator]();!(n=(l=d.next()).done);n=!0){var u=l.value;u<128&&t.push(T(u))}}catch(e){i=!0,c=e}finally{try{!n&&d.return&&d.return()}finally{if(i)throw c}}var v=t.length,g=v;for(v&&t.push(w);g<r;){var b=h,P=!0,E=!1,k=void 0;try{for(var x,$=e[Symbol.iterator]();!(P=(x=$.next()).done);P=!0){var C=x.value;C>=a&&C<b&&(b=C)}}catch(e){E=!0,k=e}finally{try{!P&&$.return&&$.return()}finally{if(E)throw k}}var I=g+1;b-a>S((h-s)/I)&&R("overflow"),s+=(b-a)*I,a=b;var F=!0,D=!1,N=void 0;try{for(var U,L=e[Symbol.iterator]();!(F=(U=L.next()).done);F=!0){var q=U.value;if(q<a&&++s>h&&R("overflow"),q==a){for(var z=s,V=p;;V+=p){var M=V<=o?f:V>=o+m?m:V-o;if(z<M)break;var Z=z-M,H=p-M;t.push(T(A(M+Z%H,0))),z=S(Z/H)}t.push(T(A(z,0))),o=j(s,I,g==v),s=0,++g}}}catch(e){D=!0,N=e}finally{try{!F&&L.return&&L.return()}finally{if(D)throw N}}++s,++a}return t.join("")},N=function(e){return C(e,function(e){return b.test(e)?F(e.slice(4).toLowerCase()):e})},U=function(e){return C(e,function(e){return P.test(e)?"xn--"+D(e):e})},L={version:"2.1.0",ucs2:{decode:O,encode:function(e){return String.fromCodePoint.apply(String,u(e))}},decode:F,encode:D,toASCII:U,toUnicode:N},q={};function z(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function V(e){for(var t="",r=0,a=e.length;r<a;){var s=parseInt(e.substr(r+1,2),16);if(s<128)t+=String.fromCharCode(s),r+=3;else if(s>=194&&s<224){if(a-r>=6){var o=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&s)<<6|63&o)}else t+=e.substr(r,6);r+=6}else if(s>=224){if(a-r>=9){var n=parseInt(e.substr(r+4,2),16),i=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function M(e,t){function r(e){var r=V(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,z).replace(t.PCT_ENCODED,s)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,z).replace(t.PCT_ENCODED,s)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,z).replace(t.PCT_ENCODED,s)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,z).replace(t.PCT_ENCODED,s)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,z).replace(t.PCT_ENCODED,s)),e}function Z(e){return e.replace(/^0*(.*)/,"$1")||"0"}function H(e,t){var r=e.match(t.IPV4ADDRESS)||[],a=d(r,2)[1];return a?a.split(".").map(Z).join("."):e}function B(e,t){var r=e.match(t.IPV6ADDRESS)||[],a=d(r,3),s=a[1],o=a[2];if(s){for(var n=s.toLowerCase().split("::").reverse(),i=d(n,2),c=i[0],l=i[1],u=l?l.split(":").map(Z):[],h=c.split(":").map(Z),p=t.IPV4ADDRESS.test(h[h.length-1]),f=p?7:8,m=h.length-f,v=Array(f),g=0;g<f;++g)v[g]=u[g]||h[m+g]||"";p&&(v[f-1]=H(v[f-1],t));var y=v.reduce(function(e,t,r){if(!t||"0"===t){var a=e[e.length-1];a&&a.index+a.length===r?a.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],_=void 0;if(y&&y.length>1){var w=v.slice(0,y.index),b=v.slice(y.index+y.length);_=w.join(":")+"::"+b.join(":")}else _=v.join(":");return o&&(_+="%"+o),_}return e}var Q=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,K=void 0==="".match(/(){0}/)[1];function J(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},a=!1!==t.iri?l:c;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var s=e.match(Q);if(s){K?(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5])):(r.scheme=s[1]||void 0,r.userinfo=-1!==e.indexOf("@")?s[3]:void 0,r.host=-1!==e.indexOf("//")?s[4]:void 0,r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=-1!==e.indexOf("?")?s[7]:void 0,r.fragment=-1!==e.indexOf("#")?s[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?s[4]:void 0)),r.host&&(r.host=B(H(r.host,a),a)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var o=q[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||o&&o.unicodeSupport)M(r,a);else{if(r.host&&(t.domainHost||o&&o.domainHost))try{r.host=L.toASCII(r.host.replace(a.PCT_ENCODED,V).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}M(r,c)}o&&o.parse&&o.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}function W(e,t){var r=!1!==t.iri?l:c,a=[];return void 0!==e.userinfo&&(a.push(e.userinfo),a.push("@")),void 0!==e.host&&a.push(B(H(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(a.push(":"),a.push(String(e.port))),a.length?a.join(""):void 0}var G=/^\.\.?\//,Y=/^\/\.(\/|$)/,X=/^\/\.\.(\/|$)/,ee=/^\/?(?:.|\n)*?(?=\/|$)/;function te(e){for(var t=[];e.length;)if(e.match(G))e=e.replace(G,"");else if(e.match(Y))e=e.replace(Y,"/");else if(e.match(X))e=e.replace(X,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(ee);if(!r)throw new Error("Unexpected dot segment condition");var a=r[0];e=e.slice(a.length),t.push(a)}return t.join("")}function re(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?l:c,a=[],s=q[(t.scheme||e.scheme||"").toLowerCase()];if(s&&s.serialize&&s.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||s&&s.domainHost)try{e.host=t.iri?L.toUnicode(e.host):L.toASCII(e.host.replace(r.PCT_ENCODED,V).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}M(e,r),"suffix"!==t.reference&&e.scheme&&(a.push(e.scheme),a.push(":"));var o=W(e,t);if(void 0!==o&&("suffix"!==t.reference&&a.push("//"),a.push(o),e.path&&"/"!==e.path.charAt(0)&&a.push("/")),void 0!==e.path){var n=e.path;t.absolutePath||s&&s.absolutePath||(n=te(n)),void 0===o&&(n=n.replace(/^\/\//,"/%2F")),a.push(n)}return void 0!==e.query&&(a.push("?"),a.push(e.query)),void 0!==e.fragment&&(a.push("#"),a.push(e.fragment)),a.join("")}function ae(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a={};return arguments[3]||(e=J(re(e,r),r),t=J(re(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=te(t.path||""),a.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=te(t.path||""),a.query=t.query):(t.path?("/"===t.path.charAt(0)?a.path=te(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path:a.path="/"+t.path,a.path=te(a.path)),a.query=t.query):(a.path=e.path,void 0!==t.query?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function se(e,t,r){var a=n({scheme:"null"},r);return re(ae(J(e,a),J(t,a),a,!0),a)}function oe(e,t){return"string"==typeof e?e=re(J(e,t),t):"object"===a(e)&&(e=J(re(e,t),t)),e}function ne(e,t,r){return"string"==typeof e?e=re(J(e,r),r):"object"===a(e)&&(e=re(e,r)),"string"==typeof t?t=re(J(t,r),r):"object"===a(t)&&(t=re(t,r)),e===t}function ie(e,t){return e&&e.toString().replace(t&&t.iri?l.ESCAPE:c.ESCAPE,z)}function ce(e,t){return e&&e.toString().replace(t&&t.iri?l.PCT_ENCODED:c.PCT_ENCODED,V)}var le={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},de={scheme:"https",domainHost:le.domainHost,parse:le.parse,serialize:le.serialize};function ue(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var he={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=ue(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(ue(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),a=d(r,2),s=a[0],o=a[1];e.path=s&&"/"!==s?s:void 0,e.query=o,e.resourceName=void 0}return e.fragment=void 0,e}},pe={scheme:"wss",domainHost:he.domainHost,parse:he.parse,serialize:he.serialize},fe={},me="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",ve="[0-9A-Fa-f]",ge=r(r("%[EFef]"+ve+"%"+ve+ve+"%"+ve+ve)+"|"+r("%[89A-Fa-f]"+ve+"%"+ve+ve)+"|"+r("%"+ve+ve)),ye="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",_e=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),we="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",be=new RegExp(me,"g"),Pe=new RegExp(ge,"g"),Ee=new RegExp(t("[^]",ye,"[\\.]",'[\\"]',_e),"g"),ke=new RegExp(t("[^]",me,we),"g"),xe=ke;function Se(e){var t=V(e);return t.match(be)?t:e}var Te={scheme:"mailto",parse:function(e,t){var r=e,a=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var s=!1,o={},n=r.query.split("&"),i=0,c=n.length;i<c;++i){var l=n[i].split("=");switch(l[0]){case"to":for(var d=l[1].split(","),u=0,h=d.length;u<h;++u)a.push(d[u]);break;case"subject":r.subject=ce(l[1],t);break;case"body":r.body=ce(l[1],t);break;default:s=!0,o[ce(l[0],t)]=ce(l[1],t)}}s&&(r.headers=o)}r.query=void 0;for(var p=0,f=a.length;p<f;++p){var m=a[p].split("@");if(m[0]=ce(m[0]),t.unicodeSupport)m[1]=ce(m[1],t).toLowerCase();else try{m[1]=L.toASCII(ce(m[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}a[p]=m.join("@")}return r},serialize:function(e,t){var r=e,a=o(e.to);if(a){for(var n=0,i=a.length;n<i;++n){var c=String(a[n]),l=c.lastIndexOf("@"),d=c.slice(0,l).replace(Pe,Se).replace(Pe,s).replace(Ee,z),u=c.slice(l+1);try{u=t.iri?L.toUnicode(u):L.toASCII(ce(u,t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}a[n]=d+"@"+u}r.path=a.join(",")}var h=e.headers=e.headers||{};e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body);var p=[];for(var f in h)h[f]!==fe[f]&&p.push(f.replace(Pe,Se).replace(Pe,s).replace(ke,z)+"="+h[f].replace(Pe,Se).replace(Pe,s).replace(xe,z));return p.length&&(r.query=p.join("&")),r}},Re=/^([^\:]+)\:(.*)/,$e={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(Re),a=e;if(r){var s=t.scheme||a.scheme||"urn",o=r[1].toLowerCase(),n=r[2],i=s+":"+(t.nid||o),c=q[i];a.nid=o,a.nss=n,a.path=void 0,c&&(a=c.parse(a,t))}else a.error=a.error||"URN can not be parsed.";return a},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",a=e.nid,s=r+":"+(t.nid||a),o=q[s];o&&(e=o.serialize(e,t));var n=e,i=e.nss;return n.path=(a||t.nid)+":"+i,n}},Ce=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Oe={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(Ce)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};q[le.scheme]=le,q[de.scheme]=de,q[he.scheme]=he,q[pe.scheme]=pe,q[Te.scheme]=Te,q[$e.scheme]=$e,q[Oe.scheme]=Oe,e.SCHEMES=q,e.pctEncChar=z,e.pctDecChars=V,e.parse=J,e.removeDotSegments=te,e.serialize=re,e.resolveComponents=ae,e.resolve=se,e.normalize=oe,e.equal=ne,e.escapeComponent=ie,e.unescapeComponent=ce,Object.defineProperty(e,"__esModule",{value:!0})}(Qa.exports);var Ka=Qa.exports,Ja=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var a,s,o;if(Array.isArray(t)){if((a=t.length)!=r.length)return!1;for(s=a;0!==s--;)if(!e(t[s],r[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((a=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=a;0!==s--;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=a;0!==s--;){var n=o[s];if(!e(t[n],r[n]))return!1}return!0}return t!=t&&r!=r},Wa={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:Ga,checkDataTypes:function(e,t,r){if(1===e.length)return Ga(e[0],t,r,!0);var a="",s=Xa(e);for(var o in s.array&&s.object&&(a=s.null?"(":"(!"+t+" || ",a+="typeof "+t+' !== "object")',delete s.null,delete s.array,delete s.object),s.number&&delete s.integer,s)a+=(a?" && ":"")+Ga(o,t,r,!0);return a},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],a=0;a<t.length;a++){var s=t[a];(Ya[s]||"array"===e&&"array"===s)&&(r[r.length]=s)}if(r.length)return r}else{if(Ya[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:Xa,getProperty:rs,escapeQuotes:as,equal:Ja,ucs2length:function(e){for(var t,r=0,a=e.length,s=0;s<a;)r++,(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<a&&56320==(64512&(t=e.charCodeAt(s)))&&s++;return r},varOccurences:function(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var a in e)if(a!=r&&t[a])return!0},schemaUnknownRules:function(e,t){if("boolean"==typeof e)return;for(var r in e)if(!t[r])return r},toQuotedString:ss,getPathExpr:function(e,t,r,a){var s=r?"'/' + "+t+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'";return is(e,s)},getPath:function(e,t,r){var a=ss(r?"/"+cs(t):rs(t));return is(e,a)},getData:function(e,t,r){var a,s,o,n;if(""===e)return"rootData";if("/"==e[0]){if(!os.test(e))throw new Error("Invalid JSON-pointer: "+e);s=e,o="rootData"}else{if(!(n=e.match(ns)))throw new Error("Invalid JSON-pointer: "+e);if(a=+n[1],"#"==(s=n[2])){if(a>=t)throw new Error("Cannot access property/index "+a+" levels up, current level is "+t);return r[t-a]}if(a>t)throw new Error("Cannot access data "+a+" levels up, current level is "+t);if(o="data"+(t-a||""),!s)return o}for(var i=o,c=s.split("/"),l=0;l<c.length;l++){var d=c[l];d&&(i+=" && "+(o+=rs(ls(d))))}return i},unescapeFragment:function(e){return ls(decodeURIComponent(e))},unescapeJsonPointer:ls,escapeFragment:function(e){return encodeURIComponent(cs(e))},escapeJsonPointer:cs};function Ga(e,t,r,a){var s=a?" !== ":" === ",o=a?" || ":" && ",n=a?"!":"",i=a?"":"!";switch(e){case"null":return t+s+"null";case"array":return n+"Array.isArray("+t+")";case"object":return"("+n+t+o+"typeof "+t+s+'"object"'+o+i+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+s+'"number"'+o+i+"("+t+" % 1)"+o+t+s+t+(r?o+n+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+s+'"'+e+'"'+(r?o+n+"isFinite("+t+")":"")+")";default:return"typeof "+t+s+'"'+e+'"'}}var Ya=Xa(["string","number","integer","boolean","null"]);function Xa(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var es=/^[a-z$_][a-z$_0-9]*$/i,ts=/'|\\/g;function rs(e){return"number"==typeof e?"["+e+"]":es.test(e)?"."+e:"['"+as(e)+"']"}function as(e){return e.replace(ts,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function ss(e){return"'"+as(e)+"'"}var os=/^\/(?:[^~]|~0|~1)*$/,ns=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function is(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function cs(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ls(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var ds=Wa,us=function(e){ds.copy(e,this)};var hs={exports:{}},ps=hs.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),fs(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function fs(e,t,r,a,s,o,n,i,c,l){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var d in t(a,s,o,n,i,c,l),a){var u=a[d];if(Array.isArray(u)){if(d in ps.arrayKeywords)for(var h=0;h<u.length;h++)fs(e,t,r,u[h],s+"/"+d+"/"+h,o,s,d,a,h)}else if(d in ps.propsKeywords){if(u&&"object"==typeof u)for(var p in u)fs(e,t,r,u[p],s+"/"+d+"/"+ms(p),o,s,d,a,p)}else(d in ps.keywords||e.allKeys&&!(d in ps.skipKeywords))&&fs(e,t,r,u,s+"/"+d,o,s,d,a)}r(a,s,o,n,i,c,l)}}function ms(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}ps.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},ps.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},ps.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},ps.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};var vs=hs.exports,gs=Ka,ys=Ja,_s=Wa,ws=us,bs=vs,Ps=Es;function Es(e,t,r){var a=this._refs[r];if("string"==typeof a){if(!this._refs[a])return Es.call(this,e,t,a);a=this._refs[a]}if((a=a||this._schemas[r])instanceof ws)return $s(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var s,o,n,i=ks.call(this,t,r);return i&&(s=i.schema,t=i.root,n=i.baseId),s instanceof ws?o=s.validate||e.call(this,s.schema,t,void 0,n):void 0!==s&&(o=$s(s,this._opts.inlineRefs)?s:e.call(this,s,t,void 0,n)),o}function ks(e,t){var r=gs.parse(t),a=As(r),s=Is(this._getId(e.schema));if(0===Object.keys(e.schema).length||a!==s){var o=Fs(a),n=this._refs[o];if("string"==typeof n)return xs.call(this,e,n,r);if(n instanceof ws)n.validate||this._compile(n),e=n;else{if(!((n=this._schemas[o])instanceof ws))return;if(n.validate||this._compile(n),o==Fs(t))return{schema:n,root:e,baseId:s};e=n}if(!e.schema)return;s=Is(this._getId(e.schema))}return Ts.call(this,r,s,e.schema,e)}function xs(e,t,r){var a=ks.call(this,e,t);if(a){var s=a.schema,o=a.baseId;e=a.root;var n=this._getId(s);return n&&(o=Ds(o,n)),Ts.call(this,r,o,s,e)}}Es.normalizeId=Fs,Es.fullPath=Is,Es.url=Ds,Es.ids=function(e){var t=Fs(this._getId(e)),r={"":t},a={"":Is(t,!1)},s={},o=this;return bs(e,{allKeys:!0},function(e,t,n,i,c,l,d){if(""!==t){var u=o._getId(e),h=r[i],p=a[i]+"/"+c;if(void 0!==d&&(p+="/"+("number"==typeof d?d:_s.escapeFragment(d))),"string"==typeof u){u=h=Fs(h?gs.resolve(h,u):u);var f=o._refs[u];if("string"==typeof f&&(f=o._refs[f]),f&&f.schema){if(!ys(e,f.schema))throw new Error('id "'+u+'" resolves to more than one schema')}else if(u!=Fs(p))if("#"==u[0]){if(s[u]&&!ys(e,s[u]))throw new Error('id "'+u+'" resolves to more than one schema');s[u]=e}else o._refs[u]=p}r[t]=h,a[t]=p}}),s},Es.inlineRef=$s,Es.schema=ks;var Ss=_s.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Ts(e,t,r,a){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var s=e.fragment.split("/"),o=1;o<s.length;o++){var n=s[o];if(n){if(void 0===(r=r[n=_s.unescapeFragment(n)]))break;var i;if(!Ss[n]&&((i=this._getId(r))&&(t=Ds(t,i)),r.$ref)){var c=Ds(t,r.$ref),l=ks.call(this,a,c);l&&(r=l.schema,a=l.root,t=l.baseId)}}}return void 0!==r&&r!==a.schema?{schema:r,root:a,baseId:t}:void 0}}var Rs=_s.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function $s(e,t){return!1!==t&&(void 0===t||!0===t?Cs(e):t?Os(e)<=t:void 0)}function Cs(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!Cs(t))return!1}else for(var a in e){if("$ref"==a)return!1;if("object"==typeof(t=e[a])&&!Cs(t))return!1}return!0}function Os(e){var t,r=0;if(Array.isArray(e)){for(var a=0;a<e.length;a++)if("object"==typeof(t=e[a])&&(r+=Os(t)),r==1/0)return 1/0}else for(var s in e){if("$ref"==s)return 1/0;if(Rs[s])r++;else if("object"==typeof(t=e[s])&&(r+=Os(t)+1),r==1/0)return 1/0}return r}function Is(e,t){return!1!==t&&(e=Fs(e)),As(gs.parse(e))}function As(e){return gs.serialize(e).split("#")[0]+"#"}var js=/#\/?$/;function Fs(e){return e?e.replace(js,""):""}function Ds(e,t){return t=Fs(t),gs.resolve(e,t)}var Ns=Ps,Us={Validation:qs(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:qs(Ls)};function Ls(e,t,r){this.message=r||Ls.message(e,t),this.missingRef=Ns.url(e,t),this.missingSchema=Ns.normalizeId(Ns.fullPath(this.missingRef))}function qs(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}Ls.message=function(e,t){return"can't resolve reference "+t+" from id "+e};var zs=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,a="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(r=t.cmp,function(e){return function(t,a){var s={key:t,value:e[t]},o={key:a,value:e[a]};return r(s,o)}}),o=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,n;if(Array.isArray(t)){for(n="[",r=0;r<t.length;r++)r&&(n+=","),n+=e(t[r])||"null";return n+"]"}if(null===t)return"null";if(-1!==o.indexOf(t)){if(a)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var i=o.push(t)-1,c=Object.keys(t).sort(s&&s(t));for(n="",r=0;r<c.length;r++){var l=c[r],d=e(t[l]);d&&(n&&(n+=","),n+=JSON.stringify(l)+":"+d)}return o.splice(i,1),"{"+n+"}"}}(e)},Vs=function(e,t,r){var a="",s=!0===e.schema.$async,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords){var i=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(i){var c="unknown keyword: "+i;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(a+=" var validate = ",s&&(e.async=!0,a+="async "),a+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n&&(e.opts.sourceCode||e.opts.processCode)&&(a+=" /*# sourceURL="+n+" */ ")),"boolean"==typeof e.schema||!o&&!e.schema.$ref){t="false schema";var l=e.level,d=e.dataLevel,u=e.schema[t],h=e.schemaPath+e.util.getProperty(t),p=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,m="data"+(d||""),v="valid"+l;if(!1===e.schema){e.isTop?f=!0:a+=" var "+v+" = false; ",(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'boolean schema is false' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?a+=s?" return data; ":" validate.errors = null; return true; ":a+=" var "+v+" = true; ";return e.isTop&&(a+=" }; return validate; "),a}if(e.isTop){var y=e.isTop;l=e.level=0,d=e.dataLevel=0,m="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}a+=" var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data; "}else{l=e.level,m="data"+((d=e.dataLevel)||"");if(n&&(e.baseId=e.resolve.url(e.baseId,n)),s&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+l+" = errors;"}v="valid"+l,f=!e.opts.allErrors;var w="",b="",P=e.schema.type,E=Array.isArray(P);if(P&&e.opts.nullable&&!0===e.schema.nullable&&(E?-1==P.indexOf("null")&&(P=P.concat("null")):"null"!=P&&(P=[P,"null"],E=!0)),E&&1==P.length&&(P=P[0],E=!1),e.schema.$ref&&o){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(a+=" "+e.RULES.all.$comment.code(e,"$comment")),P){if(e.opts.coerceTypes)var k=e.util.coerceToTypes(e.opts.coerceTypes,P);var x=e.RULES.types[P];if(k||E||!0===x||x&&!G(x)){h=e.schemaPath+".type",p=e.errSchemaPath+"/type",h=e.schemaPath+".type",p=e.errSchemaPath+"/type";var S=E?"checkDataTypes":"checkDataType";if(a+=" if ("+e.util[S](P,m,e.opts.strictNumbers,!0)+") { ",k){var T="dataType"+l,R="coerced"+l;a+=" var "+T+" = typeof "+m+"; var "+R+" = undefined; ","array"==e.opts.coerceTypes&&(a+=" if ("+T+" == 'object' && Array.isArray("+m+") && "+m+".length == 1) { "+m+" = "+m+"[0]; "+T+" = typeof "+m+"; if ("+e.util.checkDataType(e.schema.type,m,e.opts.strictNumbers)+") "+R+" = "+m+"; } "),a+=" if ("+R+" !== undefined) ; ";var $=k;if($)for(var C,O=-1,I=$.length-1;O<I;)"string"==(C=$[O+=1])?a+=" else if ("+T+" == 'number' || "+T+" == 'boolean') "+R+" = '' + "+m+"; else if ("+m+" === null) "+R+" = ''; ":"number"==C||"integer"==C?(a+=" else if ("+T+" == 'boolean' || "+m+" === null || ("+T+" == 'string' && "+m+" && "+m+" == +"+m+" ","integer"==C&&(a+=" && !("+m+" % 1)"),a+=")) "+R+" = +"+m+"; "):"boolean"==C?a+=" else if ("+m+" === 'false' || "+m+" === 0 || "+m+" === null) "+R+" = false; else if ("+m+" === 'true' || "+m+" === 1) "+R+" = true; ":"null"==C?a+=" else if ("+m+" === '' || "+m+" === 0 || "+m+" === false) "+R+" = null; ":"array"==e.opts.coerceTypes&&"array"==C&&(a+=" else if ("+T+" == 'string' || "+T+" == 'number' || "+T+" == 'boolean' || "+m+" == null) "+R+" = ["+m+"]; ");a+=" else { ",(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } if ("+R+" !== undefined) { ";var A=d?"data"+(d-1||""):"parentData";a+=" "+m+" = "+R+"; ",d||(a+="if ("+A+" !== undefined)"),a+=" "+A+"["+(d?e.dataPathArr[d]:"parentDataProperty")+"] = "+R+"; } "}else{(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}a+=" } "}}if(e.schema.$ref&&!o)a+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",f&&(a+=" } if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",b+="}");else{var j=e.RULES;if(j)for(var F=-1,D=j.length-1;F<D;)if(G(x=j[F+=1])){if(x.type&&(a+=" if ("+e.util.checkDataType(x.type,m,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==x.type&&e.schema.properties){u=e.schema.properties;var N=Object.keys(u);if(N)for(var U,L=-1,q=N.length-1;L<q;){if(void 0!==(M=u[U=N[L+=1]]).default){var z=m+e.util.getProperty(U);if(e.compositeRule){if(e.opts.strictDefaults){_="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}}else if("array"==x.type&&Array.isArray(e.schema.items)){var V=e.schema.items;if(V){O=-1;for(var M,Z=V.length-1;O<Z;)if(void 0!==(M=V[O+=1]).default){z=m+"["+O+"]";if(e.compositeRule){if(e.opts.strictDefaults){_="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}}var H=x.rules;if(H)for(var B,Q=-1,K=H.length-1;Q<K;)if(Y(B=H[Q+=1])){var J=B.code(e,B.keyword,x.type);J&&(a+=" "+J+" ",f&&(w+="}"))}if(f&&(a+=" "+w+" ",w=""),x.type&&(a+=" } ",P&&P===x.type&&!k)){a+=" else { ";var W;h=e.schemaPath+".type",p=e.errSchemaPath+"/type";(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } "}f&&(a+=" if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",b+="}")}}function G(e){for(var t=e.rules,r=0;r<t.length;r++)if(Y(t[r]))return!0}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,a=0;a<r.length;a++)if(void 0!==e.schema[r[a]])return!0}(t)}return f&&(a+=" "+b+" "),y?(s?(a+=" if (errors === 0) return data; ",a+=" else throw new ValidationError(vErrors); "):(a+=" validate.errors = vErrors; ",a+=" return errors === 0; "),a+=" }; return validate;"):a+=" var "+v+" = errors === errs_"+l+";",a},Ms=Ps,Zs=Wa,Hs=Us,Bs=zs,Qs=Vs,Ks=Zs.ucs2length,Js=Ja,Ws=Hs.Validation,Gs=function e(t,r,a,s){var o=this,n=this._opts,i=[void 0],c={},l=[],d={},u=[],h={},p=[];r=r||{schema:t,refVal:i,refs:c};var f=Ys.call(this,t,r,s),m=this._compilations[f.index];if(f.compiling)return m.callValidate=function e(){var t=m.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var v=this._formats,g=this.RULES;try{var y=w(t,r,a,s);m.validate=y;var _=m.callValidate;return _&&(_.schema=y.schema,_.errors=null,_.refs=y.refs,_.refVal=y.refVal,_.root=y.root,_.$async=y.$async,n.sourceCode&&(_.source=y.source)),y}finally{Xs.call(this,t,r,s)}function w(t,a,s,d){var h=!a||a&&a.schema==t;if(a.schema!=r.schema)return e.call(o,t,a,s,d);var f,m=!0===t.$async,y=Qs({isTop:!0,schema:t,isRoot:h,baseId:d,root:a,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Hs.MissingRef,RULES:g,validate:Qs,util:Zs,resolve:Ms,resolveRef:b,usePattern:k,useDefault:x,useCustomRule:S,opts:n,formats:v,logger:o.logger,self:o});y=oo(i,ao)+oo(l,to)+oo(u,ro)+oo(p,so)+y,n.processCode&&(y=n.processCode(y,t));try{f=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",y)(o,g,v,r,i,u,p,Js,Ks,Ws),i[0]=f}catch(e){throw o.logger.error("Error compiling schema, function code:",y),e}return f.schema=t,f.errors=null,f.refs=c,f.refVal=i,f.root=h?f:a,m&&(f.$async=!0),!0===n.sourceCode&&(f.source={code:y,patterns:l,defaults:u}),f}function b(t,s,l){s=Ms.url(t,s);var d,u,h=c[s];if(void 0!==h)return E(d=i[h],u="refVal["+h+"]");if(!l&&r.refs){var p=r.refs[s];if(void 0!==p)return E(d=r.refVal[p],u=P(s,d))}u=P(s);var f=Ms.call(o,w,r,s);if(void 0===f){var m=a&&a[s];m&&(f=Ms.inlineRef(m,n.inlineRefs)?m:e.call(o,m,r,a,t))}if(void 0!==f)return function(e,t){var r=c[e];i[r]=t}(s,f),E(f,u);!function(e){delete c[e]}(s)}function P(e,t){var r=i.length;return i[r]=t,c[e]=r,"refVal"+r}function E(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function k(e){var t=d[e];return void 0===t&&(t=d[e]=l.length,l[t]=e),"pattern"+t}function x(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return Zs.toQuotedString(e);case"object":if(null===e)return"null";var t=Bs(e),r=h[t];return void 0===r&&(r=h[t]=u.length,u[r]=e),"default"+r}}function S(e,t,r,a){if(!1!==o._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));var i=e.definition.validateSchema;if(i)if(!i(t)){var c="keyword schema is invalid: "+o.errorsText(i.errors);if("log"!=o._opts.validateSchema)throw new Error(c);o.logger.error(c)}}var l,d=e.definition.compile,u=e.definition.inline,h=e.definition.macro;if(d)l=d.call(o,t,r,a);else if(h)l=h.call(o,t,r,a),!1!==n.validateSchema&&o.validateSchema(l,!0);else if(u)l=u.call(o,a,e.keyword,t,r);else if(!(l=e.definition.validate))return;if(void 0===l)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var f=p.length;return p[f]=l,{code:"customRule"+f,validate:l}}};function Ys(e,t,r){var a=eo.call(this,e,t,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:t,baseId:r},{index:a,compiling:!1})}function Xs(e,t,r){var a=eo.call(this,e,t,r);a>=0&&this._compilations.splice(a,1)}function eo(e,t,r){for(var a=0;a<this._compilations.length;a++){var s=this._compilations[a];if(s.schema==e&&s.root==t&&s.baseId==r)return a}return-1}function to(e,t){return"var pattern"+e+" = new RegExp("+Zs.toQuotedString(t[e])+");"}function ro(e){return"var default"+e+" = defaults["+e+"];"}function ao(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function so(e){return"var customRule"+e+" = customRules["+e+"];"}function oo(e,t){if(!e.length)return"";for(var r="",a=0;a<e.length;a++)r+=t(a,e);return r}var no={exports:{}},io=no.exports=function(){this._cache={}};io.prototype.put=function(e,t){this._cache[e]=t},io.prototype.get=function(e){return this._cache[e]},io.prototype.del=function(e){delete this._cache[e]},io.prototype.clear=function(){this._cache={}};var co=no.exports,lo=Wa,uo=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ho=[0,31,28,31,30,31,30,31,31,30,31,30,31],po=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,fo=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,mo=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,vo=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,go=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,yo=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,_o=/^(?:\/(?:[^~/]|~0|~1)*)*$/,wo=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,bo=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Po=Eo;function Eo(e){return e="full"==e?"full":"fast",lo.copy(Eo[e])}function ko(e){var t=e.match(uo);if(!t)return!1;var r=+t[1],a=+t[2],s=+t[3];return a>=1&&a<=12&&s>=1&&s<=(2==a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:ho[a])}function xo(e,t){var r=e.match(po);if(!r)return!1;var a=r[1],s=r[2],o=r[3],n=r[5];return(a<=23&&s<=59&&o<=59||23==a&&59==s&&60==o)&&(!t||n)}Eo.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":vo,url:go,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:fo,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:$o,uuid:yo,"json-pointer":_o,"json-pointer-uri-fragment":wo,"relative-json-pointer":bo},Eo.full={date:ko,time:xo,"date-time":function(e){var t=e.split(So);return 2==t.length&&ko(t[0])&&xo(t[1],!0)},uri:function(e){return To.test(e)&&mo.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":vo,url:go,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:fo,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:$o,uuid:yo,"json-pointer":_o,"json-pointer-uri-fragment":wo,"relative-json-pointer":bo};var So=/t|\s/i;var To=/\/|:/;var Ro=/[^\\]\\Z/;function $o(e){if(Ro.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}var Co=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i;var p="maximum"==t,f=p?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[f],v=e.opts.$data&&m&&m.$data,g=p?"<":">",y=p?">":"<",_=void 0;if(!h&&"number"!=typeof i&&void 0!==i)throw new Error(t+" must be number");if(!v&&void 0!==m&&"number"!=typeof m&&"boolean"!=typeof m)throw new Error(f+" must be number or boolean");if(v){var w=e.util.getData(m.$data,n,e.dataPathArr),b="exclusive"+o,P="exclType"+o,E="exclIsNumber"+o,k="' + "+(T="op"+o)+" + '";s+=" var schemaExcl"+o+" = "+w+"; ",s+=" var "+b+"; var "+P+" = typeof "+(w="schemaExcl"+o)+"; if ("+P+" != 'boolean' && "+P+" != 'undefined' && "+P+" != 'number') { ";var x;_=f;(x=x||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var S=s;s=x.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+S+"]); ":s+=" validate.errors = ["+S+"]; return false; ":s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+P+" == 'number' ? ( ("+b+" = "+a+" === undefined || "+w+" "+g+"= "+a+") ? "+u+" "+y+"= "+w+" : "+u+" "+y+" "+a+" ) : ( ("+b+" = "+w+" === true) ? "+u+" "+y+"= "+a+" : "+u+" "+y+" "+a+" ) || "+u+" !== "+u+") { var op"+o+" = "+b+" ? '"+g+"' : '"+g+"='; ",void 0===i&&(_=f,l=e.errSchemaPath+"/"+f,a=w,h=v)}else{k=g;if((E="number"==typeof m)&&h){var T="'"+k+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+m+" "+g+"= "+a+" ? "+u+" "+y+"= "+m+" : "+u+" "+y+" "+a+" ) || "+u+" !== "+u+") { "}else{E&&void 0===i?(b=!0,_=f,l=e.errSchemaPath+"/"+f,a=m,y+="="):(E&&(a=Math[p?"min":"max"](m,i)),m===(!E||a)?(b=!0,_=f,l=e.errSchemaPath+"/"+f,y+="="):(b=!1,k+="="));T="'"+k+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+" "+y+" "+a+" || "+u+" !== "+u+") { "}}_=_||t,(x=x||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { comparison: "+T+", limit: "+a+", exclusive: "+b+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+k+" ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";S=s;return s=x.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+S+"]); ":s+=" validate.errors = ["+S+"]; return false; ":s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { "),s},Oo=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+".length "+("maxItems"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},Io=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");var p="maxLength"==t?">":"<";s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),!1===e.opts.unicode?s+=" "+u+".length ":s+=" ucs2length("+u+") ",s+=" "+p+" "+a+") { ";var f=t,m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==t?"longer":"shorter",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var v=s;return s=m.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},Ao=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+u+").length "+("maxProperties"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},jo={$ref:function(e,t,r){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[t],l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),h="valid"+n;if("#"==c||"#/"==c)e.isRoot?(a=e.async,s="validate"):(a=!0===e.root.schema.$async,s="root.refVal[0]");else{var p=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===p){var f=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(f),(y=y||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(o+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(o+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),o+=" } "):o+=" {} ";var m=o;o=y.pop(),!e.compositeRule&&d?e.async?o+=" throw new ValidationError(["+m+"]); ":o+=" validate.errors = ["+m+"]; return false; ":o+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(o+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,f);e.logger.warn(f),d&&(o+=" if (true) { ")}}else if(p.inline){var v=e.util.copy(e);v.level++;var g="valid"+v.level;v.schema=p.schema,v.schemaPath="",v.errSchemaPath=c,o+=" "+e.validate(v).replace(/validate\.schema/g,p.code)+" ",d&&(o+=" if ("+g+") { ")}else a=!0===p.$async||e.async&&!1!==p.$async,s=p.code}if(s){var y;(y=y||[]).push(o),o="",e.opts.passContext?o+=" "+s+".call(this, ":o+=" "+s+"( ",o+=" "+u+", (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var _=o+=" , "+(i?"data"+(i-1||""):"parentData")+" , "+(i?e.dataPathArr[i]:"parentDataProperty")+", rootData) ";if(o=y.pop(),a){if(!e.async)throw new Error("async schema referenced by sync schema");d&&(o+=" var "+h+"; "),o+=" try { await "+_+"; ",d&&(o+=" "+h+" = true; "),o+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",d&&(o+=" "+h+" = false; "),o+=" } ",d&&(o+=" if ("+h+") { ")}else o+=" if (!"+_+") { if (vErrors === null) vErrors = "+s+".errors; else vErrors = vErrors.concat("+s+".errors); errors = vErrors.length; } ",d&&(o+=" else { ")}return o},allOf:function(e,t,r){var a=" ",s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),n=e.errSchemaPath+"/"+t,i=!e.opts.allErrors,c=e.util.copy(e),l="";c.level++;var d="valid"+c.level,u=c.baseId,h=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m<v;)f=p[m+=1],(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(h=!1,c.schema=f,c.schemaPath=o+"["+m+"]",c.errSchemaPath=n+"/"+m,a+=" "+e.validate(c)+" ",c.baseId=u,i&&(a+=" if ("+d+") { ",l+="}"));return i&&(a+=h?" if (true) { ":" "+l.slice(0,-1)+" "),a},anyOf:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=n.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(v){var g=p.baseId;a+=" var "+h+" = errors; var "+u+" = false; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=n;if(_)for(var w,b=-1,P=_.length-1;b<P;)w=_[b+=1],p.schema=w,p.schemaPath=i+"["+b+"]",p.errSchemaPath=c+"/"+b,a+=" "+e.validate(p)+" ",p.baseId=g,a+=" "+u+" = "+u+" || "+m+"; if (!"+u+") { ",f+="}";e.compositeRule=p.compositeRule=y,a+=" "+f+" if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else l&&(a+=" if (true) { ");return a},$comment:function(e,t,r){var a=" ",s=e.schema[t],o=e.errSchemaPath+"/"+t;e.opts.allErrors;var n=e.util.toQuotedString(s);return!0===e.opts.$comment?a+=" console.log("+n+");":"function"==typeof e.opts.$comment&&(a+=" self._opts.$comment("+n+", "+e.util.toQuotedString(o)+", validate.root.schema);"),a},const:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; "),h||(a+=" var schema"+s+" = validate.schema"+i+";"),a+="var "+u+" = equal("+d+", schema"+s+"); if (!"+u+") { ";var p=p||[];p.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var f=a;return a=p.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+f+"]); ":a+=" validate.errors = ["+f+"]; return false; ":a+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a},contains:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m="i"+s,v=p.dataLevel=e.dataLevel+1,g="data"+v,y=e.baseId,_=e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all);if(a+="var "+h+" = errors;var "+u+";",_){var w=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" var "+f+" = false; for (var "+m+" = 0; "+m+" < "+d+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var b=d+"["+m+"]";p.dataPathArr[v]=m;var P=e.validate(p);p.baseId=y,e.util.varOccurences(P,g)<2?a+=" "+e.util.varReplace(P,g,b)+" ":a+=" var "+g+" = "+b+"; "+P+" ",a+=" if ("+f+") break; } ",e.compositeRule=p.compositeRule=w,a+=" if (!"+f+") {"}else a+=" if ("+d+".length == 0) {";var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var k=a;return a=E.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { ",_&&(a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a},dependencies:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m={},v={},g=e.opts.ownProperties;for(b in n)if("__proto__"!=b){var y=n[b],_=Array.isArray(y)?v:m;_[b]=y}a+="var "+u+" = errors;";var w=e.errorPath;for(var b in a+="var missing"+s+";",v)if((_=v[b]).length){if(a+=" if ( "+d+e.util.getProperty(b)+" !== undefined ",g&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(b)+"') "),l){a+=" && ( ";var P=_;if(P)for(var E=-1,k=P.length-1;E<k;){C=P[E+=1],E&&(a+=" || "),a+=" ( ( "+(j=d+(A=e.util.getProperty(C)))+" === undefined ",g&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(C)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?C:A)+") ) "}a+=")) { ";var x="missing"+s,S="' + "+x+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,x,!0):w+" + "+x);var T=T||[];T.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+S+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var R=a;a=T.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+R+"]); ":a+=" validate.errors = ["+R+"]; return false; ":a+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{a+=" ) { ";var $=_;if($)for(var C,O=-1,I=$.length-1;O<I;){C=$[O+=1];var A=e.util.getProperty(C),j=(S=e.util.escapeQuotes(C),d+A);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,C,e.opts.jsonPointers)),a+=" if ( "+j+" === undefined ",g&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(C)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+S+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}a+=" } ",l&&(p+="}",a+=" else { ")}e.errorPath=w;var F=h.baseId;for(var b in m){y=m[b];(e.opts.strictKeywords?"object"==typeof y&&Object.keys(y).length>0||!1===y:e.util.schemaHasRules(y,e.RULES.all))&&(a+=" "+f+" = true; if ( "+d+e.util.getProperty(b)+" !== undefined ",g&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(b)+"') "),a+=") { ",h.schema=y,h.schemaPath=i+e.util.getProperty(b),h.errSchemaPath=c+"/"+e.util.escapeFragment(b),a+=" "+e.validate(h)+" ",h.baseId=F,a+=" } ",l&&(a+=" if ("+f+") { ",p+="}"))}return l&&(a+=" "+p+" if ("+u+" == errors) {"),a},enum:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var p="i"+s,f="schema"+s;h||(a+=" var "+f+" = validate.schema"+i+";"),a+="var "+u+";",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=u+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+d+", "+f+"["+p+"])) { "+u+" = true; break; }",h&&(a+=" } "),a+=" if (!"+u+") { ";var m=m||[];m.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var v=a;return a=m.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a},format:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||"");if(!1===e.opts.format)return l&&(a+=" if (true) { "),a;var u,h=e.opts.$data&&n&&n.$data;h?(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",u="schema"+s):u=n;var p=e.opts.unknownFormats,f=Array.isArray(p);if(h){a+=" var "+(m="format"+s)+" = formats["+u+"]; var "+(v="isObject"+s)+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+(g="formatType"+s)+" = "+v+" && "+m+".type || 'string'; if ("+v+") { ",e.async&&(a+=" var async"+s+" = "+m+".async; "),a+=" "+m+" = "+m+".validate; } if ( ",h&&(a+=" ("+u+" !== undefined && typeof "+u+" != 'string') || "),a+=" (","ignore"!=p&&(a+=" ("+u+" && !"+m+" ",f&&(a+=" && self._opts.unknownFormats.indexOf("+u+") == -1 "),a+=") || "),a+=" ("+m+" && "+g+" == '"+r+"' && !(typeof "+m+" == 'function' ? ",e.async?a+=" (async"+s+" ? await "+m+"("+d+") : "+m+"("+d+")) ":a+=" "+m+"("+d+") ",a+=" : "+m+".test("+d+"))))) {"}else{var m;if(!(m=e.formats[n])){if("ignore"==p)return e.logger.warn('unknown format "'+n+'" ignored in schema at path "'+e.errSchemaPath+'"'),l&&(a+=" if (true) { "),a;if(f&&p.indexOf(n)>=0)return l&&(a+=" if (true) { "),a;throw new Error('unknown format "'+n+'" is used in schema at path "'+e.errSchemaPath+'"')}var v,g=(v="object"==typeof m&&!(m instanceof RegExp)&&m.validate)&&m.type||"string";if(v){var y=!0===m.async;m=m.validate}if(g!=r)return l&&(a+=" if (true) { "),a;if(y){if(!e.async)throw new Error("async format in sync schema");a+=" if (!(await "+(_="formats"+e.util.getProperty(n)+".validate")+"("+d+"))) { "}else{a+=" if (! ";var _="formats"+e.util.getProperty(n);v&&(_+=".validate"),a+="function"==typeof m?" "+_+"("+d+") ":" "+_+".test("+d+") ",a+=") { "}}var w=w||[];w.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",a+=h?""+u:""+e.util.toQuotedString(n),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=h?"' + "+u+" + '":""+e.util.escapeQuotes(n),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=h?"validate.schema"+i:""+e.util.toQuotedString(n),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var b=a;return a=w.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+b+"]); ":a+=" validate.errors = ["+b+"]; return false; ":a+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",l&&(a+=" else { "),a},if:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m=e.schema.then,v=e.schema.else,g=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),y=void 0!==v&&(e.opts.strictKeywords?"object"==typeof v&&Object.keys(v).length>0||!1===v:e.util.schemaHasRules(v,e.RULES.all)),_=p.baseId;if(g||y){var w;p.createErrors=!1,p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" var "+h+" = errors; var "+u+" = true; ";var b=e.compositeRule;e.compositeRule=p.compositeRule=!0,a+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=b,g?(a+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+u+" = "+f+"; ",g&&y?a+=" var "+(w="ifClause"+s)+" = 'then'; ":w="'then'",a+=" } ",y&&(a+=" else { ")):a+=" if (!"+f+") { ",y&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+u+" = "+f+"; ",g&&y?a+=" var "+(w="ifClause"+s)+" = 'else'; ":w="'else'",a+=" } "),a+=" if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+w+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match \"' + "+w+" + '\" schema' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } ",l&&(a+=" else { ")}else l&&(a+=" if (true) { ");return a},items:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,g=p.dataLevel=e.dataLevel+1,y="data"+g,_=e.baseId;if(a+="var "+h+" = errors;var "+u+";",Array.isArray(n)){var w=e.schema.additionalItems;if(!1===w){a+=" "+u+" = "+d+".length <= "+n.length+"; ";var b=c;c=e.errSchemaPath+"/additionalItems",a+=" if (!"+u+") { ";var P=P||[];P.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+n.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+n.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var E=a;a=P.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+E+"]); ":a+=" validate.errors = ["+E+"]; return false; ":a+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c=b,l&&(f+="}",a+=" else { ")}var k=n;if(k)for(var x,S=-1,T=k.length-1;S<T;)if(x=k[S+=1],e.opts.strictKeywords?"object"==typeof x&&Object.keys(x).length>0||!1===x:e.util.schemaHasRules(x,e.RULES.all)){a+=" "+m+" = true; if ("+d+".length > "+S+") { ";var R=d+"["+S+"]";p.schema=x,p.schemaPath=i+"["+S+"]",p.errSchemaPath=c+"/"+S,p.errorPath=e.util.getPathExpr(e.errorPath,S,e.opts.jsonPointers,!0),p.dataPathArr[g]=S;var $=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,R)+" ":a+=" var "+y+" = "+R+"; "+$+" ",a+=" } ",l&&(a+=" if ("+m+") { ",f+="}")}if("object"==typeof w&&(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))){p.schema=w,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+m+" = true; if ("+d+".length > "+n.length+") { for (var "+v+" = "+n.length+"; "+v+" < "+d+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);R=d+"["+v+"]";p.dataPathArr[g]=v;$=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,R)+" ":a+=" var "+y+" = "+R+"; "+$+" ",l&&(a+=" if (!"+m+") break; "),a+=" } } ",l&&(a+=" if ("+m+") { ",f+="}")}}else if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" for (var "+v+" = 0; "+v+" < "+d+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);R=d+"["+v+"]";p.dataPathArr[g]=v;$=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,R)+" ":a+=" var "+y+" = "+R+"; "+$+" ",l&&(a+=" if (!"+m+") break; "),a+=" }"}return l&&(a+=" "+f+" if ("+h+" == errors) {"),a},maximum:Co,minimum:Co,maxItems:Oo,minItems:Oo,maxLength:Io,minLength:Io,maxProperties:Ao,minProperties:Ao,multipleOf:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="var division"+o+";if (",h&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+o+" = "+u+" / "+a+", ",e.opts.multipleOfPrecision?s+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":s+=" division"+o+" !== parseInt(division"+o+") ",s+=" ) ",h&&(s+=" ) "),s+=" ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},not:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=i,h.errSchemaPath=c,a+=" var "+u+" = errors; ";var f,m=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(f=h.opts.allErrors,h.opts.allErrors=!1),a+=" "+e.validate(h)+" ",h.createErrors=!0,f&&(h.opts.allErrors=f),e.compositeRule=h.compositeRule=m,a+=" if ("+p+") { ";var v=v||[];v.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var g=a;a=v.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(a+=" if (false) { ");return a},oneOf:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=p.baseId,g="prevValid"+s,y="passingSchemas"+s;a+="var "+h+" = errors , "+g+" = false , "+u+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var w=n;if(w)for(var b,P=-1,E=w.length-1;P<E;)b=w[P+=1],(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))?(p.schema=b,p.schemaPath=i+"["+P+"]",p.errSchemaPath=c+"/"+P,a+=" "+e.validate(p)+" ",p.baseId=v):a+=" var "+m+" = true; ",P&&(a+=" if ("+m+" && "+g+") { "+u+" = false; "+y+" = ["+y+", "+P+"]; } else { ",f+="}"),a+=" if ("+m+") { "+u+" = "+g+" = true; "+y+" = "+P+"; }";return e.compositeRule=p.compositeRule=_,a+=f+"if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+y+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a},pattern:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'string') || "),s+=" !"+(h?"(new RegExp("+a+"))":e.usePattern(i))+".test("+u+") ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { pattern: ",s+=h?""+a:""+e.util.toQuotedString(i),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match pattern \"",s+=h?"' + "+a+" + '":""+e.util.escapeQuotes(i),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+e.util.toQuotedString(i),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},properties:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m="key"+s,v="idx"+s,g=h.dataLevel=e.dataLevel+1,y="data"+g,_="dataProperties"+s,w=Object.keys(n||{}).filter(A),b=e.schema.patternProperties||{},P=Object.keys(b).filter(A),E=e.schema.additionalProperties,k=w.length||P.length,x=!1===E,S="object"==typeof E&&Object.keys(E).length,T=e.opts.removeAdditional,R=x||S||T,$=e.opts.ownProperties,C=e.baseId,O=e.schema.required;if(O&&(!e.opts.$data||!O.$data)&&O.length<e.opts.loopRequired)var I=e.util.toHash(O);function A(e){return"__proto__"!==e}if(a+="var "+u+" = errors;var "+f+" = true;",$&&(a+=" var "+_+" = undefined;"),R){if(a+=$?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+d+") { ",k){if(a+=" var isAdditional"+s+" = !(false ",w.length)if(w.length>8)a+=" || validate.schema"+i+".hasOwnProperty("+m+") ";else{var j=w;if(j)for(var F=-1,D=j.length-1;F<D;)J=j[F+=1],a+=" || "+m+" == "+e.util.toQuotedString(J)+" "}if(P.length){var N=P;if(N)for(var U=-1,L=N.length-1;U<L;)oe=N[U+=1],a+=" || "+e.usePattern(oe)+".test("+m+") "}a+=" ); if (isAdditional"+s+") { "}if("all"==T)a+=" delete "+d+"["+m+"]; ";else{var q=e.errorPath,z="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),x)if(T)a+=" delete "+d+"["+m+"]; ";else{a+=" "+f+" = false; ";var V=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+z+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is an invalid additional property":a+="should NOT have additional properties",a+="' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var M=a;a=re.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,l&&(a+=" break; ")}else if(S)if("failing"==T){a+=" var "+u+" = errors; ";var Z=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var H=d+"["+m+"]";h.dataPathArr[g]=m;var B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",a+=" if (!"+f+") { errors = "+u+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+d+"["+m+"]; } ",e.compositeRule=h.compositeRule=Z}else{h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);H=d+"["+m+"]";h.dataPathArr[g]=m;B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",l&&(a+=" if (!"+f+") break; ")}e.errorPath=q}k&&(a+=" } "),a+=" } ",l&&(a+=" if ("+f+") { ",p+="}")}var Q=e.opts.useDefaults&&!e.compositeRule;if(w.length){var K=w;if(K)for(var J,W=-1,G=K.length-1;W<G;){var Y=n[J=K[W+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){var X=e.util.getProperty(J),ee=(H=d+X,Q&&void 0!==Y.default);h.schema=Y,h.schemaPath=i+X,h.errSchemaPath=c+"/"+e.util.escapeFragment(J),h.errorPath=e.util.getPath(e.errorPath,J,e.opts.jsonPointers),h.dataPathArr[g]=e.util.toQuotedString(J);B=e.validate(h);if(h.baseId=C,e.util.varOccurences(B,y)<2){B=e.util.varReplace(B,y,H);var te=H}else{te=y;a+=" var "+y+" = "+H+"; "}if(ee)a+=" "+B+" ";else{if(I&&I[J]){a+=" if ( "+te+" === undefined ",$&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = false; ";q=e.errorPath,V=c;var re,ae=e.util.escapeQuotes(J);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(q,J,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+ae+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+ae+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";M=a;a=re.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,e.errorPath=q,a+=" } else { "}else l?(a+=" if ( "+te+" === undefined ",$&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = true; } else { "):(a+=" if ("+te+" !== undefined ",$&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=" ) { ");a+=" "+B+" } "}}l&&(a+=" if ("+f+") { ",p+="}")}}if(P.length){var se=P;if(se)for(var oe,ne=-1,ie=se.length-1;ne<ie;){Y=b[oe=se[ne+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){h.schema=Y,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(oe),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(oe),a+=$?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+d+") { ",a+=" if ("+e.usePattern(oe)+".test("+m+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);H=d+"["+m+"]";h.dataPathArr[g]=m;B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",l&&(a+=" if (!"+f+") break; "),a+=" } ",l&&(a+=" else "+f+" = true; "),a+=" } ",l&&(a+=" if ("+f+") { ",p+="}")}}}return l&&(a+=" "+p+" if ("+u+" == errors) {"),a},propertyNames:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(a+="var "+u+" = errors;",e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=i,h.errSchemaPath=c;var f="key"+s,m="idx"+s,v="i"+s,g="' + "+f+" + '",y="data"+(h.dataLevel=e.dataLevel+1),_="dataProperties"+s,w=e.opts.ownProperties,b=e.baseId;w&&(a+=" var "+_+" = undefined; "),a+=w?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+f+" = "+_+"["+m+"]; ":" for (var "+f+" in "+d+") { ",a+=" var startErrs"+s+" = errors; ";var P=f,E=e.compositeRule;e.compositeRule=h.compositeRule=!0;var k=e.validate(h);h.baseId=b,e.util.varOccurences(k,y)<2?a+=" "+e.util.varReplace(k,y,P)+" ":a+=" var "+y+" = "+P+"; "+k+" ",e.compositeRule=h.compositeRule=E,a+=" if (!"+p+") { for (var "+v+"=startErrs"+s+"; "+v+"<errors; "+v+"++) { vErrors["+v+"].propertyName = "+f+"; } var err = ",!1!==e.createErrors?(a+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+g+"' } ",!1!==e.opts.messages&&(a+=" , message: 'property name \\'"+g+"\\' is invalid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),l&&(a+=" break; "),a+=" } }"}return l&&(a+=" if ("+u+" == errors) {"),a},required:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var p="schema"+s;if(!h)if(n.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],m=n;if(m)for(var v,g=-1,y=m.length-1;g<y;){v=m[g+=1];var _=e.schema.properties[v];_&&(e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=v)}}else f=n;if(h||f.length){var w=e.errorPath,b=h||f.length>=e.opts.loopRequired,P=e.opts.ownProperties;if(l)if(a+=" var missing"+s+"; ",b){h||(a+=" var "+p+" = validate.schema"+i+"; ");var E="' + "+($="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,$,e.opts.jsonPointers)),a+=" var "+u+" = true; ",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=" for (var "+S+" = 0; "+S+" < "+p+".length; "+S+"++) { "+u+" = "+d+"["+p+"["+S+"]] !== undefined ",P&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", "+p+"["+S+"]) "),a+="; if (!"+u+") break; } ",h&&(a+=" } "),a+=" if (!"+u+") { ",(R=R||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var k=a;a=R.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var x=f;if(x)for(var S=-1,T=x.length-1;S<T;){O=x[S+=1],S&&(a+=" || "),a+=" ( ( "+(F=d+(j=e.util.getProperty(O)))+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:j)+") ) "}a+=") { ";var R;E="' + "+($="missing"+s)+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,$,!0):w+" + "+$),(R=R||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";k=a;a=R.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(b){h||(a+=" var "+p+" = validate.schema"+i+"; ");var $;E="' + "+($="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,$,e.opts.jsonPointers)),h&&(a+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),a+=" for (var "+S+" = 0; "+S+" < "+p+".length; "+S+"++) { if ("+d+"["+p+"["+S+"]] === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", "+p+"["+S+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(a+=" } ")}else{var C=f;if(C)for(var O,I=-1,A=C.length-1;I<A;){O=C[I+=1];var j=e.util.getProperty(O),F=(E=e.util.escapeQuotes(O),d+j);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,O,e.opts.jsonPointers)),a+=" if ( "+F+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=w}else l&&(a+=" if (true) {");return a},uniqueItems:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h="valid"+o,p=e.opts.$data&&i&&i.$data;if(p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,(i||p)&&!1!==e.opts.uniqueItems){p&&(s+=" var "+h+"; if ("+a+" === false || "+a+" === undefined) "+h+" = true; else if (typeof "+a+" != 'boolean') "+h+" = false; else { "),s+=" var i = "+u+".length , "+h+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,m=Array.isArray(f);if(!f||"object"==f||"array"==f||m&&(f.indexOf("object")>=0||f.indexOf("array")>=0))s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+h+" = false; break outer; } } } ";else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ";var v="checkDataType"+(m?"s":"");s+=" if ("+e.util[v](f,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ",p&&(s+=" } "),s+=" if (!"+h+") { ";var g=g||[];g.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var y=s;s=g.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+y+"]); ":s+=" validate.errors = ["+y+"]; return false; ":s+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { ")}else d&&(s+=" if (true) { ");return s},validate:Vs},Fo=jo,Do=Wa.toHash,No=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],Uo=Us.MissingRef,Lo=function e(t,r,a){var s=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(a=r,r=void 0);var o=n(t).then(function(){var e=s._addSchema(t,void 0,r);return e.validate||i(e)});a&&o.then(function(e){a(null,e)},a);return o;function n(t){var r=t.$schema;return r&&!s.getSchema(r)?e.call(s,{$ref:r},!0):Promise.resolve()}function i(e){try{return s._compile(e)}catch(t){if(t instanceof Uo)return function(t){var a=t.missingSchema;if(l(a))throw new Error("Schema "+a+" is loaded but "+t.missingRef+" cannot be resolved");var o=s._loadingSchemas[a];o||(o=s._loadingSchemas[a]=s._opts.loadSchema(a)).then(c,c);return o.then(function(e){if(!l(a))return n(e).then(function(){l(a)||s.addSchema(e,a,void 0,r)})}).then(function(){return i(e)});function c(){delete s._loadingSchemas[a]}function l(e){return s._refs[e]||s._schemas[e]}}(t);throw t}}};var qo={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0},zo=qo,Vo={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:zo.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:zo.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},Mo=/^[a-z_$][a-z0-9_$-]*$/i,Zo=function(e,t,r){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[t],l=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,h="data"+(i||""),p="valid"+n,f="errs__"+n,m=e.opts.$data&&c&&c.$data;m?(o+=" var schema"+n+" = "+e.util.getData(c.$data,i,e.dataPathArr)+"; ",s="schema"+n):s=c;var v,g,y,_,w,b=this,P="definition"+n,E=b.definition,k="";if(m&&E.$data){w="keywordValidate"+n;var x=E.validateSchema;o+=" var "+P+" = RULES.custom['"+t+"'].definition; var "+w+" = "+P+".validate;"}else{if(!(_=e.useCustomRule(b,c,e.schema,e)))return;s="validate.schema"+l,w=_.code,v=E.compile,g=E.inline,y=E.macro}var S=w+".errors",T="i"+n,R="ruleErr"+n,$=E.async;if($&&!e.async)throw new Error("async keyword in sync schema");if(g||y||(o+=S+" = null;"),o+="var "+f+" = errors;var "+p+";",m&&E.$data&&(k+="}",o+=" if ("+s+" === undefined) { "+p+" = true; } else { ",x&&(k+="}",o+=" "+p+" = "+P+".validateSchema("+s+"); if ("+p+") { ")),g)E.statements?o+=" "+_.validate+" ":o+=" "+p+" = "+_.validate+"; ";else if(y){var C=e.util.copy(e);k="";C.level++;var O="valid"+C.level;C.schema=_.validate,C.schemaPath="";var I=e.compositeRule;e.compositeRule=C.compositeRule=!0;var A=e.validate(C).replace(/validate\.schema/g,w);e.compositeRule=C.compositeRule=I,o+=" "+A}else{(N=N||[]).push(o),o="",o+=" "+w+".call( ",e.opts.passContext?o+="this":o+="self",v||!1===E.schema?o+=" , "+h+" ":o+=" , "+s+" , "+h+" , validate.schema"+e.schemaPath+" ",o+=" , (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var j=i?"data"+(i-1||""):"parentData",F=i?e.dataPathArr[i]:"parentDataProperty",D=o+=" , "+j+" , "+F+" , rootData ) ";o=N.pop(),!1===E.errors?(o+=" "+p+" = ",$&&(o+="await "),o+=D+"; "):o+=$?" var "+(S="customErrors"+n)+" = null; try { "+p+" = await "+D+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+S+" = e.errors; else throw e; } ":" "+S+" = null; "+p+" = "+D+"; "}if(E.modifying&&(o+=" if ("+j+") "+h+" = "+j+"["+F+"];"),o+=""+k,E.valid)u&&(o+=" if (true) { ");else{var N;o+=" if ( ",void 0===E.valid?(o+=" !",o+=y?""+O:""+p):o+=" "+!E.valid+" ",o+=") { ",a=b.keyword,(N=N||[]).push(o),o="",(N=N||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),o+=" } "):o+=" {} ";var U=o;o=N.pop(),!e.compositeRule&&u?e.async?o+=" throw new ValidationError(["+U+"]); ":o+=" validate.errors = ["+U+"]; return false; ":o+=" var err = "+U+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var L=o;o=N.pop(),g?E.errors?"full"!=E.errors&&(o+=" for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+R+" = vErrors["+T+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+R+".schemaPath === undefined) { "+R+'.schemaPath = "'+d+'"; } ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+h+"; "),o+=" } "):!1===E.errors?o+=" "+L+" ":(o+=" if ("+f+" == errors) { "+L+" } else { for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+R+" = vErrors["+T+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+R+".schemaPath === undefined) { "+R+'.schemaPath = "'+d+'"; } ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+h+"; "),o+=" } } "):y?(o+=" var err = ",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),o+=" } "):o+=" {} ",o+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?o+=" throw new ValidationError(vErrors); ":o+=" validate.errors = vErrors; return false; ")):!1===E.errors?o+=" "+L+" ":(o+=" if (Array.isArray("+S+")) { if (vErrors === null) vErrors = "+S+"; else vErrors = vErrors.concat("+S+"); errors = vErrors.length; for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+R+" = vErrors["+T+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; "+R+'.schemaPath = "'+d+'"; ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+h+"; "),o+=" } } else { "+L+" } "),o+=" } ",u&&(o+=" else { ")}return o},Ho=Vo,Bo={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!Mo.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var a=t.type;if(Array.isArray(a))for(var s=0;s<a.length;s++)n(e,a[s],t);else n(e,a,t);var o=t.metaSchema;o&&(t.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(o,!0))}function n(e,t,a){for(var s,o=0;o<r.length;o++){var n=r[o];if(n.type==t){s=n;break}}s||(s={type:t,rules:[]},r.push(s));var i={keyword:e,definition:a,custom:!0,code:Zo,implements:a.implements};s.rules.push(i),r.custom[e]=i}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var a=t[r].rules,s=0;s<a.length;s++)if(a[s].keyword==e){a.splice(s,1);break}return this},validate:function e(t,r){e.errors=null;var a=this._validateKeyword=this._validateKeyword||this.compile(Ho,!0);if(a(t))return!0;if(e.errors=a.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(a.errors));return!1}};var Qo={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},Ko=Gs,Jo=Ps,Wo=co,Go=us,Yo=zs,Xo=Po,en=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=Do(t),e.types=Do(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var a;if("object"==typeof r){var s=Object.keys(r)[0];a=r[s],r=s,a.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:Fo[r],implements:a}}),e.all.$comment={keyword:"$comment",code:Fo.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=Do(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e},tn=function(e,t){for(var r=0;r<t.length;r++){e=JSON.parse(JSON.stringify(e));var a,s=t[r].split("/"),o=e;for(a=1;a<s.length;a++)o=o[s[a]];for(a=0;a<No.length;a++){var n=No[a],i=o[n];i&&(o[n]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e},rn=Wa,an=dn;dn.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);r=a.validate||this._compile(a)}var s=r(t);!0!==r.$async&&(this.errors=r.errors);return s},dn.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},dn.prototype.addSchema=function(e,t,r,a){if(Array.isArray(e)){for(var s=0;s<e.length;s++)this.addSchema(e[s],void 0,r,a);return this}var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");return vn(this,t=Jo.normalizeId(t||o)),this._schemas[t]=this._addSchema(e,r,a,!0),this},dn.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},dn.prototype.validateSchema=function(e,t){var r=e.$schema;if(void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||function(e){var t=e._opts.meta;return e._opts.defaultMeta="object"==typeof t?e._getId(t)||t:e.getSchema(nn)?nn:void 0,e._opts.defaultMeta}(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,e);if(!a&&t){var s="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(s);this.logger.error(s)}return a},dn.prototype.getSchema=function(e){var t=un(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=Jo.schema.call(e,{schema:{}},t);if(r){var a=r.schema,s=r.root,o=r.baseId,n=Ko.call(e,a,s,void 0,o);return e._fragments[t]=new Go({ref:t,fragment:!0,schema:a,root:s,baseId:o,validate:n}),n}}(this,e)}},dn.prototype.removeSchema=function(e){if(e instanceof RegExp)return hn(this,this._schemas,e),hn(this,this._refs,e),this;switch(typeof e){case"undefined":return hn(this,this._schemas),hn(this,this._refs),this._cache.clear(),this;case"string":var t=un(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,a=r?r(e):e;this._cache.del(a);var s=this._getId(e);s&&(s=Jo.normalizeId(s),delete this._schemas[s],delete this._refs[s])}return this},dn.prototype.addFormat=function(e,t){"string"==typeof t&&(t=new RegExp(t));return this._formats[e]=t,this},dn.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,a=void 0===t.dataVar?"data":t.dataVar,s="",o=0;o<e.length;o++){var n=e[o];n&&(s+=a+n.dataPath+" "+n.message+r)}return s.slice(0,-r.length)},dn.prototype._addSchema=function(e,t,r,a){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var s=this._opts.serialize,o=s?s(e):e,n=this._cache.get(o);if(n)return n;a=a||!1!==this._opts.addUsedSchema;var i=Jo.normalizeId(this._getId(e));i&&a&&vn(this,i);var c,l=!1!==this._opts.validateSchema&&!t;l&&!(c=i&&i==Jo.normalizeId(e.$schema))&&this.validateSchema(e,!0);var d=Jo.ids.call(this,e),u=new Go({id:i,schema:e,localRefs:d,cacheKey:o,meta:r});"#"!=i[0]&&a&&(this._refs[i]=u);this._cache.put(o,u),l&&c&&this.validateSchema(e,!0);return u},dn.prototype._compile=function(e,t){if(e.compiling)return e.validate=s,s.schema=e.schema,s.errors=null,s.root=t||s,!0===e.schema.$async&&(s.$async=!0),s;var r,a;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{a=Ko.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=a,e.refs=a.refs,e.refVal=a.refVal,e.root=a.root,a;function s(){var t=e.validate,r=t.apply(this,arguments);return s.errors=t.errors,r}},dn.prototype.compileAsync=Lo;var sn=Bo;dn.prototype.addKeyword=sn.add,dn.prototype.getKeyword=sn.get,dn.prototype.removeKeyword=sn.remove,dn.prototype.validateKeyword=sn.validate;var on=Us;dn.ValidationError=on.Validation,dn.MissingRefError=on.MissingRef,dn.$dataMetaSchema=tn;var nn="http://json-schema.org/draft-07/schema",cn=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],ln=["/properties"];function dn(e){if(!(this instanceof dn))return new dn(e);e=this._opts=rn.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:gn,warn:gn,error:gn};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=Xo(e.format),this._cache=e.cache||new Wo,this._loadingSchemas={},this._compilations=[],this.RULES=en(),this._getId=function(e){switch(e.schemaId){case"auto":return mn;case"id":return pn;default:return fn}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=Yo),this._metaOpts=function(e){for(var t=rn.copy(e._opts),r=0;r<cn.length;r++)delete t[cn[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;e._opts.$data&&(t=Qo,e.addMetaSchema(t,t.$id,!0));if(!1===e._opts.meta)return;var r=qo;e._opts.$data&&(r=tn(r,ln));e.addMetaSchema(r,nn,!0),e._refs["http://json-schema.org/schema"]=nn}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(!t)return;if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function un(e,t){return t=Jo.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function hn(e,t,r){for(var a in t){var s=t[a];s.meta||r&&!r.test(a)||(e._cache.del(s.cacheKey),delete t[a])}}function pn(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function fn(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function mn(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function vn(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function gn(){}var yn=Ba(an);class _n extends Ha{constructor(e,t){var r;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._ajv=new yn}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapability(e,t){var r;if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:lr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Dr,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!dr.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,r,a,s,o;switch(e){case"logging/setLevel":if(!(null===(t=this._serverCapabilities)||void 0===t?void 0:t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null===(a=this._serverCapabilities)||void 0===a?void 0:a.resources))throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(null===(s=this._serverCapabilities)||void 0===s?void 0:s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null===(o=this._serverCapabilities)||void 0===o?void 0:o.completions))throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var t;if("notifications/roots/list_changed"===e)if(!(null===(t=this._capabilities.roots)||void 0===t?void 0:t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:"ping"},$r,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},La,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},$r,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},va,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ca,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Wr,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Yr,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ea,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},$r,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},$r,t)}async callTool(e,t=Pa,r){const a=await this.request({method:"tools/call",params:e},t,r),s=this.getToolOutputValidator(e.name);if(s){if(!a.structuredContent&&!a.isError)throw new Za(Sr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent)try{if(!s(a.structuredContent))throw new Za(Sr.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(e){if(e instanceof Za)throw e;throw new Za(Sr.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return a}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const t of e)if(t.outputSchema)try{const e=this._ajv.compile(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},ba,t);return this.cacheToolOutputSchemas(r.tools),r}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}const wn=rr({resource:Wt().url(),authorization_servers:tr(Wt().url()).optional(),jwks_uri:Wt().url().optional(),scopes_supported:tr(Wt()).optional(),bearer_methods_supported:tr(Wt()).optional(),resource_signing_alg_values_supported:tr(Wt()).optional(),resource_name:Wt().optional(),resource_documentation:Wt().optional(),resource_policy_uri:Wt().url().optional(),resource_tos_uri:Wt().url().optional(),tls_client_certificate_bound_access_tokens:Yt().optional(),authorization_details_types_supported:tr(Wt()).optional(),dpop_signing_alg_values_supported:tr(Wt()).optional(),dpop_bound_access_tokens_required:Yt().optional()}).passthrough(),bn=rr({issuer:Wt(),authorization_endpoint:Wt(),token_endpoint:Wt(),registration_endpoint:Wt().optional(),scopes_supported:tr(Wt()).optional(),response_types_supported:tr(Wt()),response_modes_supported:tr(Wt()).optional(),grant_types_supported:tr(Wt()).optional(),token_endpoint_auth_methods_supported:tr(Wt()).optional(),token_endpoint_auth_signing_alg_values_supported:tr(Wt()).optional(),service_documentation:Wt().optional(),revocation_endpoint:Wt().optional(),revocation_endpoint_auth_methods_supported:tr(Wt()).optional(),revocation_endpoint_auth_signing_alg_values_supported:tr(Wt()).optional(),introspection_endpoint:Wt().optional(),introspection_endpoint_auth_methods_supported:tr(Wt()).optional(),introspection_endpoint_auth_signing_alg_values_supported:tr(Wt()).optional(),code_challenge_methods_supported:tr(Wt()).optional()}).passthrough(),Pn=rr({issuer:Wt(),authorization_endpoint:Wt(),token_endpoint:Wt(),userinfo_endpoint:Wt().optional(),jwks_uri:Wt(),registration_endpoint:Wt().optional(),scopes_supported:tr(Wt()).optional(),response_types_supported:tr(Wt()),response_modes_supported:tr(Wt()).optional(),grant_types_supported:tr(Wt()).optional(),acr_values_supported:tr(Wt()).optional(),subject_types_supported:tr(Wt()),id_token_signing_alg_values_supported:tr(Wt()),id_token_encryption_alg_values_supported:tr(Wt()).optional(),id_token_encryption_enc_values_supported:tr(Wt()).optional(),userinfo_signing_alg_values_supported:tr(Wt()).optional(),userinfo_encryption_alg_values_supported:tr(Wt()).optional(),userinfo_encryption_enc_values_supported:tr(Wt()).optional(),request_object_signing_alg_values_supported:tr(Wt()).optional(),request_object_encryption_alg_values_supported:tr(Wt()).optional(),request_object_encryption_enc_values_supported:tr(Wt()).optional(),token_endpoint_auth_methods_supported:tr(Wt()).optional(),token_endpoint_auth_signing_alg_values_supported:tr(Wt()).optional(),display_values_supported:tr(Wt()).optional(),claim_types_supported:tr(Wt()).optional(),claims_supported:tr(Wt()).optional(),service_documentation:Wt().optional(),claims_locales_supported:tr(Wt()).optional(),ui_locales_supported:tr(Wt()).optional(),claims_parameter_supported:Yt().optional(),request_parameter_supported:Yt().optional(),request_uri_parameter_supported:Yt().optional(),require_request_uri_registration:Yt().optional(),op_policy_uri:Wt().optional(),op_tos_uri:Wt().optional()}).passthrough().merge(bn.pick({code_challenge_methods_supported:!0})),En=rr({access_token:Wt(),id_token:Wt().optional(),token_type:Wt(),expires_in:Gt().optional(),scope:Wt().optional(),refresh_token:Wt().optional()}).strip(),kn=rr({error:Wt(),error_description:Wt().optional(),error_uri:Wt().optional()}),xn=rr({redirect_uris:tr(Wt()).refine(e=>e.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:Wt().optional(),grant_types:tr(Wt()).optional(),response_types:tr(Wt()).optional(),client_name:Wt().optional(),client_uri:Wt().optional(),logo_uri:Wt().optional(),scope:Wt().optional(),contacts:tr(Wt()).optional(),tos_uri:Wt().optional(),policy_uri:Wt().optional(),jwks_uri:Wt().optional(),jwks:Xt().optional(),software_id:Wt().optional(),software_version:Wt().optional(),software_statement:Wt().optional()}).strip(),Sn=rr({client_id:Wt(),client_secret:Wt().optional(),client_id_issued_at:Gt().optional(),client_secret_expires_at:Gt().optional()}).strip(),Tn=xn.merge(Sn);rr({error:Wt(),error_description:Wt().optional()}).strip(),rr({token:Wt(),token_type_hint:Wt().optional()}).strip();class Rn extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class $n extends Rn{}$n.errorCode="invalid_request";class Cn extends Rn{}Cn.errorCode="invalid_client";class On extends Rn{}On.errorCode="invalid_grant";class In extends Rn{}In.errorCode="unauthorized_client";class An extends Rn{}An.errorCode="unsupported_grant_type";class jn extends Rn{}jn.errorCode="invalid_scope";class Fn extends Rn{}Fn.errorCode="access_denied";class Dn extends Rn{}Dn.errorCode="server_error";class Nn extends Rn{}Nn.errorCode="temporarily_unavailable";class Un extends Rn{}Un.errorCode="unsupported_response_type";class Ln extends Rn{}Ln.errorCode="unsupported_token_type";class qn extends Rn{}qn.errorCode="invalid_token";class zn extends Rn{}zn.errorCode="method_not_allowed";class Vn extends Rn{}Vn.errorCode="too_many_requests";class Mn extends Rn{}Mn.errorCode="invalid_client_metadata";class Zn extends Rn{}Zn.errorCode="insufficient_scope";const Hn={[$n.errorCode]:$n,[Cn.errorCode]:Cn,[On.errorCode]:On,[In.errorCode]:In,[An.errorCode]:An,[jn.errorCode]:jn,[Fn.errorCode]:Fn,[Dn.errorCode]:Dn,[Nn.errorCode]:Nn,[Un.errorCode]:Un,[Ln.errorCode]:Ln,[qn.errorCode]:qn,[zn.errorCode]:zn,[Vn.errorCode]:Vn,[Mn.errorCode]:Mn,[Zn.errorCode]:Zn};class Bn extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function Qn(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Kn(e,t,r,a){const{client_id:s,client_secret:o}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${a}`)}(s,o,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(s,o,a);case"none":return void function(e,t){t.set("client_id",e)}(s,a);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function Jn(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=kn.parse(JSON.parse(r)),{error:t,error_description:a,error_uri:s}=e;return new(Hn[t]||Dn)(a||"",s)}catch(e){return new Dn(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function Wn(e,t){var r,a;try{return await Gn(e,t)}catch(s){if(s instanceof Cn||s instanceof In)return await(null===(r=e.invalidateCredentials)||void 0===r?void 0:r.call(e,"all")),await Gn(e,t);if(s instanceof On)return await(null===(a=e.invalidateCredentials)||void 0===a?void 0:a.call(e,"tokens")),await Gn(e,t);throw s}}async function Gn(e,{serverUrl:t,authorizationCode:r,scope:a,resourceMetadataUrl:s,fetchFn:o}){let n,i;try{n=await async function(e,t,r=fetch){const a=await async function(e,t,r,a){var s,o;const n=new URL(e),i=null!==(s=null==a?void 0:a.protocolVersion)&&void 0!==s?s:lr;let c;if(null==a?void 0:a.metadataUrl)c=new URL(a.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,n.pathname);c=new URL(e,null!==(o=null==a?void 0:a.metadataServerUrl)&&void 0!==o?o:n),c.search=n.search}let l=await Xn(c,i,r);if(!(null==a?void 0:a.metadataUrl)&&function(e,t){return!e||404===e.status&&"/"!==t}(l,n.pathname)){const e=new URL(`/.well-known/${t}`,n);l=await Xn(e,i,r)}return l}(e,"oauth-protected-resource",r,{protocolVersion:null==t?void 0:t.protocolVersion,metadataUrl:null==t?void 0:t.resourceMetadataUrl});if(!a||404===a.status)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return wn.parse(await a.json())}(t,{resourceMetadataUrl:s},o),n.authorization_servers&&n.authorization_servers.length>0&&(i=n.authorization_servers[0])}catch(e){}i||(i=t);const c=await async function(e,t,r){const a=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(a,null==r?void 0:r.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),a="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==a.origin)return!1;if(r.pathname.length<a.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return s.startsWith(o)}({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}(t,e,n),l=await async function(e,{fetchFn:t=fetch,protocolVersion:r=lr}={}){var a;const s={"MCP-Protocol-Version":r},o=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),a;let s=t.pathname;s.endsWith("/")&&(s=s.slice(0,-1));return a.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"}),a.push({url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),a}(e);for(const{url:e,type:r}of o){const o=await Yn(e,s,t);if(!o)throw new Error(`CORS error trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`);if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}if("oauth"===r)return bn.parse(await o.json());{const t=Pn.parse(await o.json());if(!(null===(a=t.code_challenge_methods_supported)||void 0===a?void 0:a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}return}(i,{fetchFn:o});let d=await Promise.resolve(e.clientInformation());if(!d){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:a}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const o=await(null!=a?a:fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Jn(o);return Tn.parse(await o.json())}(i,{metadata:l,clientMetadata:e.clientMetadata});await e.saveClientInformation(t),d=t}if(void 0!==r){const t=await e.codeVerifier(),a=await async function(e,{metadata:t,clientInformation:r,authorizationCode:a,codeVerifier:s,redirectUri:o,resource:n,addClientAuthentication:i,fetchFn:c}){var l;const d="authorization_code",u=(null==t?void 0:t.token_endpoint)?new URL(t.token_endpoint):new URL("/token",e);if((null==t?void 0:t.grant_types_supported)&&!t.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:d,code:a,code_verifier:s,redirect_uri:String(o)});if(i)i(h,p,e,t);else{Kn(Qn(r,null!==(l=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==l?l:[]),r,h,p)}n&&p.set("resource",n.href);const f=await(null!=c?c:fetch)(u,{method:"POST",headers:h,body:p});if(!f.ok)throw await Jn(f);return En.parse(await f.json())}(i,{metadata:l,clientInformation:d,authorizationCode:r,codeVerifier:t,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(a),"AUTHORIZED"}const u=await e.tokens();if(null==u?void 0:u.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:a,resource:s,addClientAuthentication:o,fetchFn:n}){var i;const c="refresh_token";let l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),u=new URLSearchParams({grant_type:c,refresh_token:a});if(o)o(d,u,e,t);else{Kn(Qn(r,null!==(i=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==i?i:[]),r,d,u)}s&&u.set("resource",s.href);const h=await(null!=n?n:fetch)(l,{method:"POST",headers:d,body:u});if(!h.ok)throw await Jn(h);return En.parse({refresh_token:a,...await h.json()})}(i,{metadata:l,clientInformation:d,refreshToken:u.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof Rn&&!(e instanceof Dn))throw e}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:m}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:a,scope:s,state:o,resource:n}){const i="code",c="S256";let l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL("/authorize",e);const d=await h(),u=d.code_verifier,p=d.code_challenge;l.searchParams.set("response_type",i),l.searchParams.set("client_id",r.client_id),l.searchParams.set("code_challenge",p),l.searchParams.set("code_challenge_method",c),l.searchParams.set("redirect_uri",String(a)),o&&l.searchParams.set("state",o);s&&l.searchParams.set("scope",s);(null==s?void 0:s.includes("offline_access"))&&l.searchParams.append("prompt","consent");n&&l.searchParams.set("resource",n.href);return{authorizationUrl:l,codeVerifier:u}}(i,{metadata:l,clientInformation:d,state:p,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(f),"REDIRECT"}async function Yn(e,t,r=fetch){try{return await r(e,{headers:t})}catch(a){if(a instanceof TypeError)return t?Yn(e,void 0,r):void 0;throw a}}async function Xn(e,t,r=fetch){const a={"MCP-Protocol-Version":t};return await Yn(e,a,r)}class ei extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function ti(e){}function ri(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ti,onError:r=ti,onRetry:a=ti,onComment:s}=e;let o,n="",i=!0,c="",l="";function d(e){if(""===e)return c.length>0&&t({id:o,event:l||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),o=void 0,c="",void(l="");if(e.startsWith(":"))return void(s&&s(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),a=" "===e[r+1]?2:1;return void u(t,e.slice(r+a),e)}u(e,"",e)}function u(e,t,s){switch(e){case"event":l=t;break;case"data":c=`${c}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?a(parseInt(t,10)):r(new ei(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:s}));break;default:r(new ei(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:s}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,a]=function(e){const t=[];let r="",a=0;for(;a<e.length;){const s=e.indexOf("\r",a),o=e.indexOf("\n",a);let n=-1;if(-1!==s&&-1!==o?n=Math.min(s,o):-1!==s?n=s:-1!==o&&(n=o),-1===n){r=e.slice(a);break}{const r=e.slice(a,n);t.push(r),a=n+1,"\r"===e[a-1]&&"\n"===e[a]&&a++}}return[t,r]}(`${n}${t}`);for(const e of r)d(e);n=a,i=!1},reset:function(e={}){n&&e.consume&&d(n),i=!0,o=void 0,c="",l="",n=""}}}class ai extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let a;super({start(s){a=ri({onEvent:e=>{s.enqueue(e)},onError(t){"terminate"===e?s.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){a.feed(e)}})}}const si={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class oi extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class ni{constructor(e,t){var r;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==t?void 0:t.requestInit,this._authProvider=null==t?void 0:t.authProvider,this._fetch=null==t?void 0:t.fetch,this._sessionId=null==t?void 0:t.sessionId,this._reconnectionOptions=null!==(r=null==t?void 0:t.reconnectionOptions)&&void 0!==r?r:si}async _authThenStart(){var e;if(!this._authProvider)throw new Bn("No auth provider");let t;try{t=await Wn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw null===(e=this.onerror)||void 0===e||e.call(this,t),t}if("AUTHORIZED"!==t)throw new Bn;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const t={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(t.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders(null===(e=this._requestInit)||void 0===e?void 0:e.headers);return new Headers({...t,...r})}async _startOrAuthSse(e){var t,r,a;const{resumptionToken:s}=e;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);const o=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,{method:"GET",headers:a,signal:null===(r=this._abortController)||void 0===r?void 0:r.signal});if(!o.ok){if(401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new oi(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw null===(a=this.onerror)||void 0===a||a.call(this,e),e}}_getNextReconnectionDelay(e){const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),a)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var r;const a=this._reconnectionOptions.maxRetries;if(a>0&&t>=a)return void(null===(r=this.onerror)||void 0===r||r.call(this,new Error(`Maximum reconnection attempts (${a}) exceeded.`)));const s=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var a;null===(a=this.onerror)||void 0===a||a.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},s)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:a,replayMessageId:s}=t;let o;(async()=>{var t,n,i,c;try{const r=e.pipeThrough(new TextDecoderStream).pipeThrough(new ai).getReader();for(;;){const{value:e,done:i}=await r.read();if(i)break;if(e.id&&(o=e.id,null==a||a(e.id)),!e.event||"message"===e.event)try{const r=Rr.parse(JSON.parse(e.data));void 0!==s&&xr(r)&&(r.id=s),null===(t=this.onmessage)||void 0===t||t.call(this,r)}catch(e){null===(n=this.onerror)||void 0===n||n.call(this,e)}}}catch(e){if(null===(i=this.onerror)||void 0===i||i.call(this,new Error(`SSE stream disconnected: ${e}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:a,replayMessageId:s},0)}catch(e){null===(c=this.onerror)||void 0===c||c.call(this,new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Bn("No auth provider");if("AUTHORIZED"!==await Wn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new Bn("Failed to authorize")}async close(){var e,t;null===(e=this._abortController)||void 0===e||e.abort(),null===(t=this.onclose)||void 0===t||t.call(this)}async send(e,t){var r,a,s,o,n;try{const{resumptionToken:o,onresumptiontoken:i}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:Pr(e)?e.id:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)});const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const l={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:null===(r=this._abortController)||void 0===r?void 0:r.signal},d=await(null!==(a=this._fetch)&&void 0!==a?a:fetch)(this._url,l),u=d.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!d.ok){if(401===d.status&&this._authProvider){this._resourceMetadataUrl=function(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[r,a]=t.split(" ");if("bearer"!==r.toLowerCase()||!a)return;const s=/resource_metadata="([^"]*)"/.exec(t);if(s)try{return new URL(s[1])}catch(e){return}}(d);if("AUTHORIZED"!==await Wn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new Bn;return this.send(e)}const t=await d.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${t}`)}if(202===d.status)return n=e,void(Nr.safeParse(n).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)}));const h=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,p=d.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:i},!1);else{if(!(null==p?void 0:p.includes("application/json")))throw new oi(-1,`Unexpected content type: ${p}`);{const e=await d.json(),t=Array.isArray(e)?e.map(e=>Rr.parse(e)):[Rr.parse(e)];for(const e of t)null===(s=this.onmessage)||void 0===s||s.call(this,e)}}}catch(e){throw null===(o=this.onerror)||void 0===o||o.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,r;if(this._sessionId)try{const r=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:r,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal},s=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,a);if(!s.ok&&405!==s.status)throw new oi(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(e){throw null===(r=this.onerror)||void 0===r||r.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}const ii=V("quickstart");async function ci(r={}){if(!O)throw new Error("Interactive login is only available in Node.js environment");ii.info("Starting interactive login flow");const a=F(),{authDomain:s=a.authDomain,clientId:o=a.clientId,clientSecret:n=a.clientSecret,audience:i=a.apiAudience,apiBaseUrl:c=a.apiBaseUrl,port:l=52765}=r;if(!o||!n)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const d=await he();if(d)try{let e;U(d)?e=D(d):(ii.warn("Cached token has no organization information, using static config"),e=F());const t=new Q(e.apiBaseUrl,{token:d});return await t.validateCachedToken(),ii.info("Using cached valid token"),t}catch(e){ii.info("Cached token invalid, starting OAuth flow")}else ii.info("No cached token, starting OAuth flow");const[u,h]=G(l),p=new K,f=await p.buildAuthorizationUrl({domain:s,clientId:o,redirectUri:u,audience:i}),m=t.platform();let v;try{v=new URL(f)}catch{throw new Error("Invalid auth URL")}if("https:"!==v.protocol&&("http:"!==v.protocol||"localhost"!==v.hostname&&"127.0.0.1"!==v.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===m?e("open",[f],{detached:!0,stdio:"ignore"}).unref():"win32"===m?e("powershell",["-NoProfile","Start-Process",f],{detached:!0,stdio:"ignore"}).unref():e("xdg-open",[f],{detached:!0,stdio:"ignore"}).unref(),ii.info("Please complete login in your browser…")}catch(e){ii.warn("Failed to open browser automatically. Please visit:",f)}const[g,y]=await h,_=await p.exchangeCodeForToken({domain:s,clientId:o,clientSecret:n,code:g,redirectUri:u});let w;return await pe(_),U(_.access_token)?w=D(_.access_token):(ii.warn("New token has no organization information, using static config"),w=F()),new Q(w.apiBaseUrl,{token:_.access_token})}async function li(e,t,r={}){const{timeout:a=90}=r;ii.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:a}),ii.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof b?ii.error(`Server '${t}' not found`):ii.error(`Failed to connect to ${t}:`,e),e}}async function di(e,t,r={}){const{proxyBaseUrl:a="http://proxy-ingress:8080",transport:s="streamable-http"}=r,o=await e.listServers(),n=new Set(o.map(e=>e.slug));if(!n.has(t))throw new b(t,Array.from(n));const i=(O?process.env.BARNDOOR_ENV||process.env.MODE:"")||"localdev";let c;if(["localdev","local","development","dev"].includes(i.toLowerCase()))if(U(e.token)){c=`${D(e.token).mcpBaseUrl}/mcp/${t}`}else{ii.warn("Token has no organization information, using static config for MCP connection");c=`${F().mcpBaseUrl}/mcp/${t}`}else if(U(e.token)){c=`${D(e.token).mcpBaseUrl}/mcp/${t}`}else{ii.warn("Token has no organization information, using static config for MCP connection");c=`${F().mcpBaseUrl}/mcp/${t}`}return[{url:c,transport:s,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":hi()}},c]}async function ui(e,t,r={}){const[a]=await di(e,t,r),s=a,o=new _n({name:"barndoor-js-sdk",version:"0.1.0"}),n=new ni(new URL(s.url),{requestInit:{headers:s.headers}});return await o.connect(n),o}function hi(){if(O&&"function"==typeof r.randomUUID)return r.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(O&&"function"==typeof r.randomBytes)e=r.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const a=t[6],s=t[8];t[6]=15&a|64,t[8]=63&s|128;const o=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${o.substring(0,8)}-${o.substring(8,12)}-${o.substring(12,16)}-${o.substring(16,20)}-${o.substring(20)}`}const pi=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=o(import.meta.url),t=i(e),r=c(t,"..","package.json");return JSON.parse(p(r,"utf8")).version}return'"0.2.2"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();export{$ as AgentToken,m as AuthenticationError,A as BarndoorConfig,f as BarndoorError,Q as BarndoorSDK,E as ConfigurationError,_ as ConnectionError,w as HTTPError,re as JWTVerificationResult,P as OAuthError,K as PKCEManager,R as ServerDetail,b as ServerNotFoundError,T as ServerSummary,k as TimeoutError,v as TokenError,g as TokenExpiredError,ue as TokenManager,y as TokenValidationError,N as checkTokenOrganization,fe as clearCachedToken,V as createScopedLogger,M as debug,li as ensureServerConnected,B as error,D as getDynamicConfig,z as getLogger,F as getStaticConfig,U as hasOrganizationInfo,Z as info,C as isBrowser,O as isNode,me as isTokenActive,ve as isTokenActiveWithRefresh,he as loadUserToken,ci as loginInteractive,ui as makeMcpClient,di as makeMcpConnectionParams,pe as saveUserToken,q as setLogger,X as setTokenLogger,G as startLocalCallbackServer,ge as validateToken,le as verifyJWTLocal,pi as version,H as warn};
1
+ import{spawn as e}from"child_process";import t from"os";import r from"crypto";import a from"http";import s,{fileURLToPath as o}from"url";import n,{dirname as i,join as c}from"path";import l from"fs/promises";import{jwtVerify as d,createRemoteJWKSet as u}from"jose";import h from"readline";import p from"pkce-challenge";import{readFileSync as f}from"fs";class m extends Error{constructor(e){super(e),this.name="BarndoorError"}}class v extends m{constructor(e,t=null){super(e),this.name="AuthenticationError",this.errorCode=t}}class g extends v{constructor(e,t=null){let r=e;r+=t?` ${t}`:" Run 'barndoor-login' to authenticate.",super(r),this.name="TokenError",this.helpText=t}}class y extends g{}class _ extends g{}class w extends m{constructor(e,t){let r;const a=t.toString().toLowerCase();r=a.includes("timeout")?`Connection to ${e} timed out. Please check your internet connection and try again.`:a.includes("connection refused")?`Could not connect to ${e}. The service may be unavailable.`:a.includes("name resolution")||a.includes("getaddrinfo")?`Could not resolve hostname for ${e}. Please check the URL and your DNS settings.`:`Failed to connect to ${e}. Please check your internet connection.`,super(r),this.url=e,this.originalError=t}}class b extends m{constructor(e,t,r=null){super(b._createUserFriendlyMessage(e,t,r)),this.name="HTTPError",this.statusCode=e,this.responseBody=r}static _createUserFriendlyMessage(e,t,r){const a=`Request failed (HTTP ${e})`;return 400===e?`${a}: Invalid request. Please check your input parameters.`:401===e?`${a}: Authentication failed. Please check your token or re-authenticate.`:403===e?`${a}: Access denied. You don't have permission for this operation.`:404===e?`${a}: Resource not found. Please check the server ID or URL.`:429===e?`${a}: Rate limit exceeded. Please wait before making more requests.`:e>=500&&e<600?`${a}: Server error. Please try again later or contact support.`:`${a}: ${t}`}}class P extends m{constructor(e,t=null){let r=`Server '${e}' not found`;r+=t?`. Available servers: ${t.join(", ")}`:". Use listServers() to see available servers.",super(r),this.serverIdentifier=e,this.availableServers=t}}let E=class extends v{};class k extends m{}class x extends m{}class S{constructor(e=30,t=10){this.read=1e3*e,this.connect=1e3*t}}class R{constructor(e=new S,t=3){this.timeoutConfig=e,this.maxRetries=t,this.closed=!1}async request(e,t,r={}){if(this.closed)throw new Error("HTTP client has been closed");const{headers:a={},json:s,params:o,...n}=r,i=this._buildUrl(t,o),c={method:e.toUpperCase(),headers:{"Content-Type":"application/json","User-Agent":"barndoor-js-sdk/0.1.0",...a},...n};let l;s&&(c.body=JSON.stringify(s));for(let t=0;t<=this.maxRetries;t++){const r=new AbortController,a=this.timeoutConfig.connect+this.timeoutConfig.read,s=setTimeout(()=>r.abort(),a),o={...c,signal:r.signal};try{const e=await globalThis.fetch(i,o);if(clearTimeout(s),!e.ok){let t="";try{const r=e;"function"==typeof r.text?t=await r.text():"function"==typeof r.json&&(t=JSON.stringify(await r.json()))}catch{}throw new b(e.status,e.statusText,t)}let t="";const r=e,a=r&&r.headers;let n;return a&&("function"==typeof a.get?t=a.get("content-type")||a.get("Content-Type")||"":"object"==typeof a&&(t=a["content-type"]||a["Content-Type"]||"")),n=t.includes("application/json")||!t&&"function"==typeof r.json?await e.json():t.includes("text/")||!t&&"function"==typeof r.text?await e.text():"function"==typeof r.arrayBuffer?await e.arrayBuffer():e,n}catch(r){if(clearTimeout(s),r instanceof Error&&"AbortError"===r.name){const e=this.timeoutConfig.connect+this.timeoutConfig.read;l=new x(`Request to ${i} timed out after ${e}ms`)}else if(r instanceof b){if(r.statusCode>=400&&r.statusCode<500)throw r;if(!(r.statusCode>=500&&r.statusCode<600))throw r;{const t=e.toUpperCase();if(!("GET"===t||"HEAD"===t||"OPTIONS"===t))throw r;l=r}}else l=r instanceof Error&&"TypeError"===r.name&&r.message.includes("fetch")?new w(i,r):r instanceof Error?r:new Error(String(r));if(t===this.maxRetries)break;const a=Math.min(1e3*Math.pow(2,t),1e4);await this._sleep(a)}}throw l||(l=new Error(`Request to ${i} failed after ${this.maxRetries+1} attempts with no specific error`)),l}_buildUrl(e,t){if(!t||0===Object.keys(t).length)return e;const r=new URL(e);return Object.entries(t).forEach(([e,t])=>{null!=t&&r.searchParams.append(e,String(t))}),r.toString()}_sleep(e){return new Promise(t=>setTimeout(t,e))}async close(){this.closed=!0}async aclose(){await this.close()}}class T{constructor(e){if(this.id=e.id,this.name=e.name,this.slug=e.slug,this.provider=e.provider??null,this.connection_status=e.connection_status,!(this.id&&this.name&&this.slug&&this.connection_status))throw new Error("ServerSummary missing required fields")}static fromApiResponse(e){return new T(e)}}class $ extends T{constructor(e){super(e),this.url=e.url??null}static fromApiResponse(e){return new $(e)}}class C{constructor(e){if(this.agent_token=e.agent_token,this.expires_in=e.expires_in,!this.agent_token||"number"!=typeof this.expires_in)throw new Error("AgentToken missing required fields")}static fromApiResponse(e){return new C(e)}}const O="undefined"!=typeof window&&void 0!==window.document,A="undefined"==typeof window&&"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function I(e,t=""){return A?process.env[e]??t:O&&window.ENV?window.ENV[e]??t:t}class j{constructor(e={}){this.authDomain=e.authDomain??(I("AUTH_DOMAIN")||"auth.barndoor.ai"),this.clientId=e.clientId??(I("AGENT_CLIENT_ID")||""),this.clientSecret=e.clientSecret??(I("AGENT_CLIENT_SECRET")||""),this.apiAudience=e.apiAudience??(I("API_AUDIENCE")||"https://barndoor.ai/"),this.environment=e.environment??(I("MODE")||I("BARNDOOR_ENV")||"production"),this.promptForLogin=e.promptForLogin??!1,this.skipLoginLocal=e.skipLoginLocal??!1,this.apiBaseUrl="",this.mcpBaseUrl="",this._setEnvironmentDefaults(e)}_setEnvironmentDefaults(e){const t=this.environment.toLowerCase();"localdev"===t||"local"===t?(this.authDomain=this.authDomain||"localhost:3001",this.apiBaseUrl=e.apiBaseUrl??(I("BARNDOOR_API")||"http://localhost:8000"),this.mcpBaseUrl=e.mcpBaseUrl??(I("BARNDOOR_MCP")||I("BARNDOOR_URL")||"http://localhost:8000"),e.apiAudience||I("API_AUDIENCE")||(this.apiAudience="https://barndoor.api/")):"development"===t||"dev"===t?(this.apiBaseUrl=e.apiBaseUrl??(I("BARNDOOR_API")||"https://{organization_id}.mcp.barndoordev.com"),this.mcpBaseUrl=e.mcpBaseUrl??(I("BARNDOOR_MCP")||I("BARNDOOR_URL")||"https://{organization_id}.mcp.barndoordev.com"),e.apiAudience||I("API_AUDIENCE")||(this.apiAudience="https://barndoor.api/")):(this.apiBaseUrl=e.apiBaseUrl??(I("BARNDOOR_API")||"https://{organization_id}.mcp.barndoor.ai"),this.mcpBaseUrl=e.mcpBaseUrl??(I("BARNDOOR_MCP")||I("BARNDOOR_URL")||"https://{organization_id}.mcp.barndoor.ai"))}static getStaticConfig(){return new j}static getDynamicConfig(e,t={}){const{requireOrganization:r=!0,fallbackOrganizationId:a}=t,s=new j,o=F(e);if(o.hasOrganization){const e=String(o.organizationId??"").trim().toLowerCase();if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e))throw new k("Invalid organization subdomain format from token");return s.apiBaseUrl=s.apiBaseUrl.replace("{organization_id}",e),s.mcpBaseUrl=s.mcpBaseUrl.replace("{organization_id}",e),s}if(a)return s.apiBaseUrl=s.apiBaseUrl.replace("{organization_id}",a),s.mcpBaseUrl=s.mcpBaseUrl.replace("{organization_id}",a),s;if(r){const e=o.error||"No organization information found in token";throw new k(`Failed to extract organization ID from token: ${e}. This token may be for a personal account or may be missing organization claims. Consider using getStaticConfig() for organization-independent operations or provide a fallbackOrganizationId in the options.`)}return s}validate(){if(!this.authDomain||""===this.authDomain.trim())throw new k("authDomain is required");if(!this.apiAudience||""===this.apiAudience.trim())throw new k("apiAudience is required");if(!this.apiBaseUrl||""===this.apiBaseUrl.trim())throw new k("apiBaseUrl is required");if(!this.mcpBaseUrl||""===this.mcpBaseUrl.trim())throw new k("mcpBaseUrl is required")}}function F(e){try{const t=e.split(".");if(3!==t.length)return{hasOrganization:!1,error:"Invalid JWT format - expected 3 parts separated by dots"};let r,a;try{r=JSON.parse(function(e){if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");throw new Error("No base64 decode function available")}(t[1].replace(/-/g,"+").replace(/_/g,"/")))}catch(e){return{hasOrganization:!1,error:"Failed to parse JWT payload - token may be corrupted"}}if(r.user&&"object"==typeof r.user&&(a=r.user.organization_name??r.user.organization_slug),!a){const e=r["https://barndoor.ai/organization_slug"],t=r.organization_slug,s=r.organization_name,o=r.org_slug;a=("string"==typeof s?s:void 0)??("string"==typeof e?e:void 0)??("string"==typeof t?t:void 0)??("string"==typeof o?o:void 0)}return a&&"string"==typeof a&&""!==a.trim()?{organizationId:a.trim(),hasOrganization:!0}:{hasOrganization:!1,error:"No organization information found in token. This token may be for a personal account or may be missing organization claims."}}catch(e){return{hasOrganization:!1,error:`Failed to decode JWT token: ${e instanceof Error?e.message:String(e)}`}}}function D(){return j.getStaticConfig()}function N(e,t){return j.getDynamicConfig(e,t)}function U(e){return F(e)}function L(e){return F(e).hasOrganization}let q={debug:(e,...t)=>{"undefined"!=typeof console&&console.debug&&console.debug(e,...t)},info:(e,...t)=>{"undefined"!=typeof console&&console.info&&console.info(e,...t)},warn:(e,...t)=>{"undefined"!=typeof console&&console.warn&&console.warn(e,...t)},error:(e,...t)=>{"undefined"!=typeof console&&console.error&&console.error(e,...t)}};function z(e){q=e}function V(){return q}function M(e){return{debug:(t,...r)=>{q.debug(`[${e}] ${t}`,...r)},info:(t,...r)=>{q.info(`[${e}] ${t}`,...r)},warn:(t,...r)=>{q.warn(`[${e}] ${t}`,...r)},error:(t,...r)=>{q.error(`[${e}] ${t}`,...r)}}}function Z(e,...t){q.debug(e,...t)}function H(e,...t){q.info(e,...t)}function B(e,...t){q.warn(e,...t)}function Q(e,...t){q.error(e,...t)}class K{constructor(e,t={}){this._logger=M("client");const{token:r,timeout:a=30,maxRetries:s=3}=t;this.base=this._validateUrl(e,"API base URL").replace(/\/$/,"");const o=Object.prototype.hasOwnProperty.call(t,"token");if(this._token=o?this._validateToken(r):null,"number"!=typeof a||a<=0)throw new k("timeout must be a positive number");if(!Number.isInteger(s)||s<0)throw new k("maxRetries must be a non-negative integer");const n=new S(a,a/3);this._http=new R(n,s),this._tokenValidated=!1,this._closed=!1,this._logger.info(`Initialized BarndoorSDK for ${this.base}`)}get token(){if(!this._token)throw new Error("No token available. Call authenticate() first or provide token in constructor.");return this._token}async authenticate(e){this._token=this._validateToken(e),this._tokenValidated=!1,await this.ensureValidToken(),this._logger.info("Authentication successful")}_validateUrl(e,t){if(!e||"string"!=typeof e)throw new k(`${t} must be a non-empty string`);try{return new URL(e),e}catch(e){throw new k(`${t} must be a valid URL`)}}_validateToken(e){if(!e||"string"!=typeof e)throw new g("Token must be a non-empty string");if(3!==e.split(".").length)throw new g("Token must be a valid JWT");return e}_ensureNotClosed(){if(this._closed)throw new Error("SDK has been closed. Create a new instance or use as context manager.")}async _req(e,t,r={}){this._ensureNotClosed(),await this.ensureValidToken();const a=r.headers??{};a.Authorization=`Bearer ${this.token}`;const s=`${this.base}${t}`;return await this._http.request(e,s,{...r,headers:a})}async validateCachedToken(){if(!this.token)return!1;try{const e=D(),t=new AbortController,r=setTimeout(()=>t.abort(),1e4);try{const r=(await fetch(`https://${e.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${this.token}`},signal:t.signal})).ok;return r&&(this._tokenValidated=!0),r}finally{clearTimeout(r)}}catch(e){return!1}}async ensureValidToken(){if(!this._token)throw new Error("No token available. Call authenticate() first or provide token in constructor.");if(this._tokenValidated)return;const e=(A?process.env.BARNDOOR_ENV:"")??"";if(["test","ci"].includes(e.toLowerCase()))return void(this._tokenValidated=!0);if(!await this.validateCachedToken())throw new g("Token validation failed. Please re-authenticate.");this._tokenValidated=!0}async listServers(){this._logger.debug("Fetching server list");try{const e=[];let t=1;for(;null!==t;){const r=1===t?"/servers":`/servers?page=${t}`,a=await this._req("GET",r),s=a.data.map(e=>T.fromApiResponse(e));e.push(...s),t=a.pagination.next_page}return this._logger.info(`Retrieved ${e.length} servers total`),e}catch(e){throw this._logger.error("Failed to list servers:",e),e}}async getServer(e){const t=this._validateServerId(e);this._logger.info(`Fetching server details for ${t}`);const r=await this._req("GET",`/servers/${t}`);return $.fromApiResponse(r)}async initiateConnection(e,t){const r=this._validateServerId(e);let a;t&&(a=this._validateUrl(t,"Return URL")),this._logger.info(`Initiating connection for server ${r}`);const s=a?{return_url:a}:void 0;try{return await this._req("POST",`/servers/${r}/connect`,{params:s,json:{}})}catch(e){if(e instanceof b&&500===e.statusCode&&e.responseBody?.includes("OAuth server configuration not found"))throw new Error("Server is missing OAuth configuration. Ask an admin to configure credentials before initiating a connection.");throw e}}async getConnectionStatus(e){const t=this._validateServerId(e);this._logger.info(`Checking connection status for server ${t}`);return(await this._req("GET",`/servers/${t}/connection`)).status}async disconnectServer(e){const t=this._validateServerId(e);this._logger.info(`Disconnecting from server ${t}`);try{await this._req("DELETE",`/servers/${t}/connection`),this._logger.info(`Successfully disconnected from server ${t}`)}catch(e){if(e instanceof b&&404===e.statusCode)throw new Error(`Connection not found for server ${t}. Server may not be connected.`);throw e}}_validateServerId(e){if(!e||"string"!=typeof e)throw new Error("Server ID must be a non-empty string");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)&&!/^[a-z0-9-]+$/.test(e))throw new Error("Server ID must be a valid UUID or slug (lowercase letters, numbers, and hyphens only)");return e}async close(){this._closed||(await this._http.close(),this._closed=!0)}async aclose(){await this.close()}async ensureServerConnected(r,a={}){const{pollSeconds:s=60}=a;if(!A)throw new Error("ensureServerConnected requires Node.js environment for browser opening");const o=(await this.listServers()).find(e=>e.slug===r||e.provider&&e.provider.toLowerCase()===r.toLowerCase());if(!o)throw new P(r);if("connected"===o.connection_status)return;const n=(await this.initiateConnection(o.id)).auth_url;if(!n)throw new Error("Registry did not return auth_url");const i=t.platform();let c;try{c=new URL(n)}catch{throw new Error("Invalid auth_url returned by server")}if("https:"!==c.protocol&&("http:"!==c.protocol||"localhost"!==c.hostname&&"127.0.0.1"!==c.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===i?e("open",[n],{detached:!0,stdio:"ignore"}).unref():"win32"===i?e("powershell",["-NoProfile","Start-Process",n],{detached:!0,stdio:"ignore"}).unref():e("xdg-open",[n],{detached:!0,stdio:"ignore"}).unref()}catch(e){this._logger.warn("Failed to open browser",e)}for(let e=0;e<s;e++){if("connected"===await this.getConnectionStatus(o.id))return;await new Promise(e=>setTimeout(e,1e3))}throw new Error("OAuth connection was not completed in time")}}class J{constructor(){this._codeVerifier=null,this._currentState=null,this._logger=M("pkce")}async buildAuthorizationUrl({domain:e,clientId:t,redirectUri:a,audience:s,scope:o="openid profile email"}){this._codeVerifier=W(32);const n=G(await async function(e){const t=(new TextEncoder).encode(e);if(O&&window.crypto&&window.crypto.subtle){const e=await window.crypto.subtle.digest("SHA-256",t);return new Uint8Array(e)}if(A){const t=r.createHash("sha256").update(e).digest();return new Uint8Array(t)}throw new Error("SHA256 not available in this environment")}(this._codeVerifier));this._currentState=W(16);return`https://${e}/authorize?${new URLSearchParams({response_type:"code",client_id:t,redirect_uri:a,scope:o,audience:s,state:this._currentState,code_challenge:n,code_challenge_method:"S256"}).toString()}`}async exchangeCodeForToken({domain:e,clientId:t,code:r,redirectUri:a,clientSecret:s}){const o={grant_type:"authorization_code",client_id:t,code:r,redirect_uri:a};if(s&&(o.client_secret=s),this._codeVerifier&&(o.code_verifier=this._codeVerifier),!s&&!this._codeVerifier)throw new E("Either client_secret or PKCE verifier must be provided");try{const t=await fetch(`https://${e}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){const e=await t.json().catch(()=>({}));throw this._logger.error("Token endpoint response:",e),new E(`Token exchange failed: ${e.error??e.error_description??t.statusText}`)}const r=await t.json();return this.clearState(),r}catch(e){if(e instanceof E)throw e;const t=e instanceof Error?e.message:String(e);throw new E(`Token exchange failed: ${t}`)}}validateState(e){return Boolean(this._currentState&&e===this._currentState)}clearState(){this._codeVerifier=null,this._currentState=null}getState(){return this._codeVerifier&&this._currentState?{codeVerifier:this._codeVerifier,codeChallenge:"",state:this._currentState,timestamp:Date.now()}:null}}function W(e){const t=new Uint8Array(e);if(O&&window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(t);else{if(!A)throw new Error("Secure random generator not available for PKCE.");r.randomFillSync(t)}return G(t)}function G(e){const t=function(e){if("undefined"!=typeof globalThis&&globalThis.btoa)return globalThis.btoa(String.fromCharCode(...e));if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");throw new Error("No base64 encode function available")}(e);return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Y(e=52765){if(!A)throw new Error("Local callback server is only available in Node.js environment");const t=`http://${"undefined"!=typeof process&&process.env&&process.env.BARNDOOR_REDIRECT_HOST||"localhost"}:${e}/cb`,r=new Promise((r,o)=>{const n=a.createServer((e,t)=>{const a=s.parse(e.url??"",!0);if("/cb"===a.pathname){const{code:e,state:s,error:i,error_description:c}=a.query;t.writeHead(200,{"Content-Type":"text/html"}),i?(t.end("\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>Error: Authentication error occurred.</p>\n <p>Description: Please return to the application for details.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n "),n.close(),o(new E(`OAuth error: ${i} - ${c}`))):e?(t.end("\n <html>\n <body>\n <h1>Authentication Successful</h1>\n <p>You can close this window and return to your application.</p>\n </body>\n </html>\n "),n.close(),r([e,s])):(t.end("\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>No authorization code received.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n "),n.close(),o(new E("No authorization code received")))}else t.writeHead(404),t.end("Not found")});n.listen(e,()=>{console.log(`OAuth callback server listening on ${t}`)}),n.on("error",e=>{o(new E(`Failed to start callback server: ${e.message}`))})});return[t,r]}const X=M("token");function ee(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")}function te(e){try{const t=e.split(".");if(3!==t.length)return null;return JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");if(A)return Buffer.from(t,"base64").toString("utf8");if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(t);throw new Error("No base64 decode function available")}(t[1]))}catch(e){return null}}function re(e,t){return"undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?e:Promise.race([e,new Promise((e,r)=>{setTimeout(()=>r(new Error("Request timeout")),t)})])}var ae;!function(e){e.VALID="valid",e.EXPIRED="expired",e.INVALID="invalid"}(ae||(ae={}));const se=new Map;class oe{constructor(e){this.lockAcquired=!1,this.lockFile=`${e}.lock`}async acquire(e=5e3){if(!A)return;const t=Date.now();for(;Date.now()-t<e;)try{return await l.writeFile(this.lockFile,process.pid.toString(),{flag:"wx"}),void(this.lockAcquired=!0)}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw new g(`Failed to acquire file lock: ${e}`);try{const e=await l.readFile(this.lockFile,"utf8"),t=parseInt(e.trim(),10);try{process.kill(t,0),await new Promise(e=>setTimeout(e,100));continue}catch(e){if(e&&"object"==typeof e&&"code"in e){const t=e;if("EPERM"===t.code){await new Promise(e=>setTimeout(e,100));continue}if("ESRCH"===t.code){await l.unlink(this.lockFile).catch(()=>{});continue}}await l.unlink(this.lockFile).catch(()=>{});continue}}catch{await l.unlink(this.lockFile).catch(()=>{});continue}}throw new g("Failed to acquire file lock: timeout")}async release(){if(A&&this.lockAcquired)try{await l.unlink(this.lockFile),this.lockAcquired=!1}catch(e){console.debug("Failed to release file lock:",e)}}}class ne{}class ie extends ne{constructor(){super(),this.storageKey="barndoor_token"}async loadToken(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return X.warn("Failed to load token from localStorage:",e),null}}async saveToken(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){const t=e instanceof Error?e.message:String(e);throw new g(`Failed to save token: ${t}`)}}async clearToken(){try{localStorage.removeItem(this.storageKey)}catch(e){X.warn("Failed to clear token from localStorage:",e)}}}class ce extends ne{constructor(){super(),this.tokenFile=this._getTokenFilePath()}_getTokenFilePath(){if(A)return n.join(t.homedir(),".barndoor","token.json");throw new Error("NodeTokenStorage can only be used in Node.js environment")}async loadToken(){if(!A)throw new Error("NodeTokenStorage can only be used in Node.js environment");const e=new oe(this.tokenFile);try{await e.acquire();const t=await l.readFile(this.tokenFile,"utf8");return JSON.parse(t)}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||X.warn("Failed to load token from file:",e),null}finally{await e.release()}}async saveToken(e){if(!A)throw new Error("NodeTokenStorage can only be used in Node.js environment");const t=new oe(this.tokenFile);try{await t.acquire(),await l.mkdir(n.dirname(this.tokenFile),{recursive:!0}),await l.writeFile(this.tokenFile,JSON.stringify(e,null,2)),await l.chmod(this.tokenFile,384),X.debug("Token saved to storage")}catch(e){const t=e instanceof Error?e.message:String(e);throw new g(`Failed to save token: ${t}`)}finally{await t.release()}}async clearToken(){if(!A)throw new Error("NodeTokenStorage can only be used in Node.js environment");try{await l.unlink(this.tokenFile)}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"!==e.code&&X.warn("Failed to clear token file:",e)}}}function le(){if(O)return new ie;if(A)return new ce;throw new Error("Unsupported environment for token storage")}async function de(e,t,r){try{const a=function(e){if(!se.has(e)){const t=u(new URL(`https://${e}/.well-known/jwks.json`));se.set(e,t)}return se.get(e)}(t);return await d(e,a,{issuer:`https://${t}/`,audience:r}),X.debug("Token verified locally using JWKS"),ae.VALID}catch(e){return e&&"object"==typeof e&&"code"in e&&"ERR_JWT_EXPIRED"===e.code?(X.debug("Token expired (verified locally)"),ae.EXPIRED):(X.debug("JWT verification failed:",e),ae.INVALID)}}class ue{constructor(){this._locked=!1,this._waitQueue=[]}async acquire(){return new Promise(e=>{this._locked?this._waitQueue.push(e):(this._locked=!0,e())})}release(){if(this._waitQueue.length>0){const e=this._waitQueue.shift();e&&e()}else this._locked=!1}async withLock(e){await this.acquire();try{return await e()}finally{this.release()}}}class he{constructor(e){this._refreshMutex=new ue,this.storage=le()}async getValidToken(){return this._refreshMutex.withLock(async()=>{const e=await this.storage.loadToken();if(!e)throw new g("No token found. Please authenticate.");try{if(this._shouldRefreshToken(e)&&e.refresh_token){X.debug("Proactively refreshing token before expiration");const t=await this._refreshToken(e),r={...e,...t};return await this.storage.saveToken(r),r.access_token}const t=await this._validateOrRefresh(e);return await this.storage.saveToken(t),t.access_token}catch(e){throw X.error("Token validation/refresh failed:",e),new y("Token expired and refresh failed. Please re-authenticate.")}})}_shouldRefreshToken(e){const t=te(e.access_token);if(!t?.exp)return!0;const r=Math.floor(Date.now()/1e3);return t.exp-r<300}async _validateOrRefresh(e){const t=e.access_token,r=D(),a=await de(t,r.authDomain,r.apiAudience);if(a===ae.VALID)return X.debug("Token validated locally"),e;if(a===ae.INVALID&&(X.debug("Local validation failed, trying remote"),await this._isTokenValidRemote(t)))return X.debug("Token validated remotely"),e;if(X.info("Token invalid or expired, attempting refresh"),e.refresh_token){const t=await this._refreshToken(e);return{...e,...t}}throw new y("Token expired and no refresh token available")}async _isTokenValidRemote(e){try{const t=D(),r=fetch(`https://${t.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return(await re(r,5e3)).ok}catch(e){return X.debug("Remote token validation failed:",e),!1}}async _refreshToken(e){const t=e.refresh_token;if(!t)throw new g("No refresh token available");const r=D();if(O&&r.clientSecret)throw new g("Refresh flow requires a confidential client; run interactive login again.");const a={grant_type:"refresh_token",client_id:r.clientId,refresh_token:t};r.clientSecret&&!O&&(a.client_secret=r.clientSecret);try{const e=fetch(`https://${r.authDomain}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(15e3)}:{}}),t=await re(e,15e3);if(400===t.status){let e="Invalid refresh token";try{e=(await t.json()).error_description||e}catch{}throw X.warn(`Refresh token invalid: ${e}`),new y(`Refresh token expired or invalid: ${e}`)}if(429===t.status)throw X.warn("Rate limited during token refresh"),new g("Rate limited during token refresh. Please try again later.");if(t.status>=500)throw X.warn(`Auth server error during refresh: ${t.status}`),new g(`Auth server temporarily unavailable (HTTP ${t.status})`);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);return await t.json()}catch(e){if(e instanceof g||e instanceof y)throw e;if(e&&"object"==typeof e&&"name"in e){if("TimeoutError"===e.name||"AbortError"===e.name)throw X.warn("Timeout during token refresh"),new g("Token refresh timed out. Please check your connection.");if("TypeError"===e.name&&"message"in e&&"string"==typeof e.message&&e.message.includes("fetch"))throw X.warn(`Network error during token refresh: ${e.message}`),new g("Network error during token refresh. Please check your connection.")}X.error("Unexpected error during token refresh:",e);const t=e instanceof Error?e.message:String(e);throw new g(`Token refresh failed: ${t}`)}}}async function pe(){try{const e=le(),t=await e.loadToken();return t?.access_token??null}catch(e){return null}}async function fe(e){const t=le();let r;r="string"==typeof e?{access_token:e}:e,await t.saveToken(r)}async function me(){const e=le();await e.clearToken()}async function ve(e){try{const e=le(),t=await e.loadToken();if(!t?.access_token)return!1;const r=D(),a=fetch(`https://${r.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${t.access_token}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(1e4)}:{}});return(await re(a,1e4)).ok}catch(e){return!1}}async function ge(e){try{const t=new he(e||"");return await t.getValidToken(),!0}catch(e){return X.warn("Token validation/refresh failed:",e),!1}}async function ye(e,t){try{const t=D(),r=await de(e,t.authDomain,t.apiAudience);if(r===ae.VALID)return{valid:!0};if(r===ae.INVALID)try{const r=fetch(`https://${t.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return{valid:(await re(r,5e3)).ok}}catch(e){return X.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return X.warn("Token validation failed:",e),{valid:!1}}}var _e,we;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(_e||(_e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(we||(we={}));const be=_e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pe=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return Number.isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:null===e?be.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?be.promise:"undefined"!=typeof Map&&e instanceof Map?be.map:"undefined"!=typeof Set&&e instanceof Set?be.set:"undefined"!=typeof Date&&e instanceof Date?be.date:be.object;default:return be.unknown}},Ee=_e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ke extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(a);else if("invalid_return_type"===s.code)a(s.returnTypeError);else if("invalid_arguments"===s.code)a(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,a=0;for(;a<s.path.length;){const r=s.path[a];a===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof ke))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_e.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}ke.create=e=>new ke(e);var xe=(e,t)=>{let r;switch(e.code){case Ee.invalid_type:r=e.received===be.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Ee.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,_e.jsonStringifyReplacer)}`;break;case Ee.unrecognized_keys:r=`Unrecognized key(s) in object: ${_e.joinValues(e.keys,", ")}`;break;case Ee.invalid_union:r="Invalid input";break;case Ee.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${_e.joinValues(e.options)}`;break;case Ee.invalid_enum_value:r=`Invalid enum value. Expected ${_e.joinValues(e.options)}, received '${e.received}'`;break;case Ee.invalid_arguments:r="Invalid function arguments";break;case Ee.invalid_return_type:r="Invalid function return type";break;case Ee.invalid_date:r="Invalid date";break;case Ee.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:_e.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Ee.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Ee.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Ee.custom:r="Invalid input";break;case Ee.invalid_intersection_types:r="Intersection results could not be merged";break;case Ee.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Ee.not_finite:r="Number must be finite";break;default:r=t.defaultError,_e.assertNever(e)}return{message:r}};let Se=xe;function Re(e,t){const r=Se,a=(e=>{const{data:t,path:r,errorMaps:a,issueData:s}=e,o=[...r,...s.path||[]],n={...s,path:o};if(void 0!==s.message)return{...s,path:o,message:s.message};let i="";const c=a.filter(e=>!!e).slice().reverse();for(const e of c)i=e(n,{data:t,defaultError:i}).message;return{...s,path:o,message:i}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===xe?void 0:xe].filter(e=>!!e)});e.common.issues.push(a)}class Te{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const a of t){if("aborted"===a.status)return $e;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return Te.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const a of t){const{key:t,value:s}=a;if("aborted"===t.status)return $e;if("aborted"===s.status)return $e;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!a.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const $e=Object.freeze({status:"aborted"}),Ce=e=>({status:"dirty",value:e}),Oe=e=>({status:"valid",value:e}),Ae=e=>"aborted"===e.status,Ie=e=>"dirty"===e.status,je=e=>"valid"===e.status,Fe=e=>"undefined"!=typeof Promise&&e instanceof Promise;var De;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(De||(De={}));class Ne{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ue=(e,t)=>{if(je(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ke(e.common.issues);return this._error=t,this._error}}};function Le(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:s}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??s.defaultError}:void 0===s.data?{message:o??a??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:o??r??s.defaultError}},description:s}}class qe{get description(){return this._def.description}_getType(e){return Pe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Fe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)},a=this._parseSync({data:e,path:r.path,parent:r});return Ue(r,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return je(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>je(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)},a=this._parse({data:e,path:r.path,parent:r}),s=await(Fe(a)?a:Promise.resolve(a));return Ue(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{const s=e(t),o=()=>a.addIssue({code:Ee.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(o(),!1)):!!s||(o(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new zt({schema:this,typeName:Wt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Vt.create(this,this._def)}nullable(){return Mt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Et.create(this)}promise(){return qt.create(this,this._def)}or(e){return St.create([this,e],this._def)}and(e){return Ct.create(this,e,this._def)}transform(e){return new zt({...Le(this._def),schema:this,typeName:Wt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Zt({...Le(this._def),innerType:this,defaultValue:t,typeName:Wt.ZodDefault})}brand(){return new Qt({typeName:Wt.ZodBranded,type:this,...Le(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ht({...Le(this._def),innerType:this,catchValue:t,typeName:Wt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Kt.create(this,e)}readonly(){return Jt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ze=/^c[^\s-]{8,}$/i,Ve=/^[0-9a-z]+$/,Me=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ze=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,He=/^[a-z0-9_-]{21}$/i,Be=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qe=/^[-+]?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)?)??$/,Ke=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Je;const We=/^(?:(?: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])$/,Ge=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ye=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Xe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,et=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rt="((\\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])))",at=new RegExp(`^${rt}$`);function st(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function ot(e){return new RegExp(`^${st(e)}$`)}function nt(e){let t=`${rt}T${st(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function it(e,t){return!("v4"!==t&&t||!We.test(e))||!("v6"!==t&&t||!Ye.test(e))}function ct(e,t){if(!Be.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(a));return"object"==typeof s&&null!==s&&((!("typ"in s)||"JWT"===s?.typ)&&(!!s.alg&&(!t||s.alg===t)))}catch{return!1}}function lt(e,t){return!("v4"!==t&&t||!Ge.test(e))||!("v6"!==t&&t||!Xe.test(e))}class dt extends qe{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==be.string){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.string,received:t.parsedType}),$e}const t=new Te;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("max"===a.kind)e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const s=e.data.length>a.value,o=e.data.length<a.value;(s||o)&&(r=this._getOrReturnCtx(e,r),s?Re(r,{code:Ee.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&Re(r,{code:Ee.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if("email"===a.kind)Ke.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"email",code:Ee.invalid_string,message:a.message}),t.dirty());else if("emoji"===a.kind)Je||(Je=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Je.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"emoji",code:Ee.invalid_string,message:a.message}),t.dirty());else if("uuid"===a.kind)Ze.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"uuid",code:Ee.invalid_string,message:a.message}),t.dirty());else if("nanoid"===a.kind)He.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"nanoid",code:Ee.invalid_string,message:a.message}),t.dirty());else if("cuid"===a.kind)ze.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"cuid",code:Ee.invalid_string,message:a.message}),t.dirty());else if("cuid2"===a.kind)Ve.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"cuid2",code:Ee.invalid_string,message:a.message}),t.dirty());else if("ulid"===a.kind)Me.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"ulid",code:Ee.invalid_string,message:a.message}),t.dirty());else if("url"===a.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Re(r,{validation:"url",code:Ee.invalid_string,message:a.message}),t.dirty()}else if("regex"===a.kind){a.regex.lastIndex=0;a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"regex",code:Ee.invalid_string,message:a.message}),t.dirty())}else if("trim"===a.kind)e.data=e.data.trim();else if("includes"===a.kind)e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty());else if("toLowerCase"===a.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===a.kind)e.data=e.data.toUpperCase();else if("startsWith"===a.kind)e.data.startsWith(a.value)||(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty());else if("endsWith"===a.kind)e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty());else if("datetime"===a.kind){nt(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.invalid_string,validation:"datetime",message:a.message}),t.dirty())}else if("date"===a.kind){at.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.invalid_string,validation:"date",message:a.message}),t.dirty())}else if("time"===a.kind){ot(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.invalid_string,validation:"time",message:a.message}),t.dirty())}else"duration"===a.kind?Qe.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"duration",code:Ee.invalid_string,message:a.message}),t.dirty()):"ip"===a.kind?it(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"ip",code:Ee.invalid_string,message:a.message}),t.dirty()):"jwt"===a.kind?ct(e.data,a.alg)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"jwt",code:Ee.invalid_string,message:a.message}),t.dirty()):"cidr"===a.kind?lt(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"cidr",code:Ee.invalid_string,message:a.message}),t.dirty()):"base64"===a.kind?et.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"base64",code:Ee.invalid_string,message:a.message}),t.dirty()):"base64url"===a.kind?tt.test(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{validation:"base64url",code:Ee.invalid_string,message:a.message}),t.dirty()):_e.assertNever(a);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Ee.invalid_string,...De.errToObj(r)})}_addCheck(e){return new dt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...De.errToObj(e)})}url(e){return this._addCheck({kind:"url",...De.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...De.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...De.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...De.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...De.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...De.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...De.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...De.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...De.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...De.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...De.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...De.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...De.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...De.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...De.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...De.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...De.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...De.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...De.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...De.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...De.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...De.errToObj(t)})}nonempty(e){return this.min(1,De.errToObj(e))}trim(){return new dt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new dt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new dt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function ut(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,s=r>a?r:a;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}dt.create=e=>new dt({checks:[],typeName:Wt.ZodString,coerce:e?.coerce??!1,...Le(e)});class ht extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==be.number){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.number,received:t.parsedType}),$e}let t;const r=new Te;for(const a of this._def.checks)if("int"===a.kind)_e.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else"multipleOf"===a.kind?0!==ut(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.not_finite,message:a.message}),r.dirty()):_e.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,De.toString(t))}gt(e,t){return this.setLimit("min",e,!1,De.toString(t))}lte(e,t){return this.setLimit("max",e,!0,De.toString(t))}lt(e,t){return this.setLimit("max",e,!1,De.toString(t))}setLimit(e,t,r,a){return new ht({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:De.toString(a)}]})}_addCheck(e){return new ht({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:De.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:De.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:De.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:De.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:De.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:De.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:De.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:De.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:De.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&_e.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ht.create=e=>new ht({checks:[],typeName:Wt.ZodNumber,coerce:e?.coerce||!1,...Le(e)});class pt extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==be.bigint)return this._getInvalidInput(e);let t;const r=new Te;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Re(t,{code:Ee.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):_e.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.bigint,received:t.parsedType}),$e}gte(e,t){return this.setLimit("min",e,!0,De.toString(t))}gt(e,t){return this.setLimit("min",e,!1,De.toString(t))}lte(e,t){return this.setLimit("max",e,!0,De.toString(t))}lt(e,t){return this.setLimit("max",e,!1,De.toString(t))}setLimit(e,t,r,a){return new pt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:De.toString(a)}]})}_addCheck(e){return new pt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:De.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:De.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:De.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:De.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:De.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}pt.create=e=>new pt({checks:[],typeName:Wt.ZodBigInt,coerce:e?.coerce??!1,...Le(e)});class ft extends qe{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==be.boolean){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.boolean,received:t.parsedType}),$e}return Oe(e.data)}}ft.create=e=>new ft({typeName:Wt.ZodBoolean,coerce:e?.coerce||!1,...Le(e)});class mt extends qe{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==be.date){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.date,received:t.parsedType}),$e}if(Number.isNaN(e.data.getTime())){return Re(this._getOrReturnCtx(e),{code:Ee.invalid_date}),$e}const t=new Te;let r;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(r=this._getOrReturnCtx(e,r),Re(r,{code:Ee.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):_e.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new mt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:De.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:De.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}mt.create=e=>new mt({checks:[],coerce:e?.coerce||!1,typeName:Wt.ZodDate,...Le(e)});class vt extends qe{_parse(e){if(this._getType(e)!==be.symbol){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.symbol,received:t.parsedType}),$e}return Oe(e.data)}}vt.create=e=>new vt({typeName:Wt.ZodSymbol,...Le(e)});class gt extends qe{_parse(e){if(this._getType(e)!==be.undefined){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.undefined,received:t.parsedType}),$e}return Oe(e.data)}}gt.create=e=>new gt({typeName:Wt.ZodUndefined,...Le(e)});class yt extends qe{_parse(e){if(this._getType(e)!==be.null){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.null,received:t.parsedType}),$e}return Oe(e.data)}}yt.create=e=>new yt({typeName:Wt.ZodNull,...Le(e)});class _t extends qe{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}}_t.create=e=>new _t({typeName:Wt.ZodAny,...Le(e)});class wt extends qe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oe(e.data)}}wt.create=e=>new wt({typeName:Wt.ZodUnknown,...Le(e)});class bt extends qe{_parse(e){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.never,received:t.parsedType}),$e}}bt.create=e=>new bt({typeName:Wt.ZodNever,...Le(e)});class Pt extends qe{_parse(e){if(this._getType(e)!==be.undefined){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.void,received:t.parsedType}),$e}return Oe(e.data)}}Pt.create=e=>new Pt({typeName:Wt.ZodVoid,...Le(e)});class Et extends qe{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==be.array)return Re(t,{code:Ee.invalid_type,expected:be.array,received:t.parsedType}),$e;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,s=t.data.length<a.exactLength.value;(e||s)&&(Re(t,{code:e?Ee.too_big:Ee.too_small,minimum:s?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(Re(t,{code:Ee.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(Re(t,{code:Ee.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new Ne(t,e,t.path,r)))).then(e=>Te.mergeArray(r,e));const s=[...t.data].map((e,r)=>a.type._parseSync(new Ne(t,e,t.path,r)));return Te.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new Et({...this._def,minLength:{value:e,message:De.toString(t)}})}max(e,t){return new Et({...this._def,maxLength:{value:e,message:De.toString(t)}})}length(e,t){return new Et({...this._def,exactLength:{value:e,message:De.toString(t)}})}nonempty(e){return this.min(1,e)}}function kt(e){if(e instanceof xt){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=Vt.create(kt(a))}return new xt({...e._def,shape:()=>t})}return e instanceof Et?new Et({...e._def,type:kt(e.element)}):e instanceof Vt?Vt.create(kt(e.unwrap())):e instanceof Mt?Mt.create(kt(e.unwrap())):e instanceof Ot?Ot.create(e.items.map(e=>kt(e))):e}Et.create=(e,t)=>new Et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Wt.ZodArray,...Le(t)});class xt extends qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=_e.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==be.object){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.object,received:t.parsedType}),$e}const{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof bt&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||o.push(e);const n=[];for(const e of s){const t=a[e],s=r.data[e];n.push({key:{status:"valid",value:e},value:t._parse(new Ne(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof bt){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)n.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(Re(r,{code:Ee.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const a=r.data[t];n.push({key:{status:"valid",value:t},value:e._parse(new Ne(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of n){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>Te.mergeObjectSync(t,e)):Te.mergeObjectSync(t,n)}get shape(){return this._def.shape()}strict(e){return De.errToObj,new xt({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:De.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new xt({...this._def,unknownKeys:"strip"})}passthrough(){return new xt({...this._def,unknownKeys:"passthrough"})}extend(e){return new xt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new xt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Wt.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new xt({...this._def,catchall:e})}pick(e){const t={};for(const r of _e.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new xt({...this._def,shape:()=>t})}omit(e){const t={};for(const r of _e.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new xt({...this._def,shape:()=>t})}deepPartial(){return kt(this)}partial(e){const t={};for(const r of _e.objectKeys(this.shape)){const a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new xt({...this._def,shape:()=>t})}required(e){const t={};for(const r of _e.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Vt;)e=e._def.innerType;t[r]=e}return new xt({...this._def,shape:()=>t})}keyof(){return Nt(_e.objectKeys(this.shape))}}xt.create=(e,t)=>new xt({shape:()=>e,unknownKeys:"strip",catchall:bt.create(),typeName:Wt.ZodObject,...Le(t)}),xt.strictCreate=(e,t)=>new xt({shape:()=>e,unknownKeys:"strict",catchall:bt.create(),typeName:Wt.ZodObject,...Le(t)}),xt.lazycreate=(e,t)=>new xt({shape:e,unknownKeys:"strip",catchall:bt.create(),typeName:Wt.ZodObject,...Le(t)});class St extends qe{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new ke(e.ctx.common.issues));return Re(t,{code:Ee.invalid_union,unionErrors:r}),$e});{let e;const a=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=a.map(e=>new ke(e));return Re(t,{code:Ee.invalid_union,unionErrors:s}),$e}}get options(){return this._def.options}}St.create=(e,t)=>new St({options:e,typeName:Wt.ZodUnion,...Le(t)});const Rt=e=>e instanceof Ft?Rt(e.schema):e instanceof zt?Rt(e.innerType()):e instanceof Dt?[e.value]:e instanceof Ut?e.options:e instanceof Lt?_e.objectValues(e.enum):e instanceof Zt?Rt(e._def.innerType):e instanceof gt?[void 0]:e instanceof yt?[null]:e instanceof Vt?[void 0,...Rt(e.unwrap())]:e instanceof Mt?[null,...Rt(e.unwrap())]:e instanceof Qt||e instanceof Jt?Rt(e.unwrap()):e instanceof Ht?Rt(e._def.innerType):[];class Tt extends qe{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==be.object)return Re(t,{code:Ee.invalid_type,expected:be.object,received:t.parsedType}),$e;const r=this.discriminator,a=t.data[r],s=this.optionsMap.get(a);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(Re(t,{code:Ee.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),$e)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=Rt(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(a.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);a.set(s,r)}}return new Tt({typeName:Wt.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...Le(r)})}}function $t(e,t){const r=Pe(e),a=Pe(t);if(e===t)return{valid:!0,data:e};if(r===be.object&&a===be.object){const r=_e.objectKeys(t),a=_e.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of a){const a=$t(e[r],t[r]);if(!a.valid)return{valid:!1};s[r]=a.data}return{valid:!0,data:s}}if(r===be.array&&a===be.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let a=0;a<e.length;a++){const s=$t(e[a],t[a]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===be.date&&a===be.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class Ct extends qe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(Ae(e)||Ae(a))return $e;const s=$t(e.value,a.value);return s.valid?((Ie(e)||Ie(a))&&t.dirty(),{status:t.value,value:s.data}):(Re(r,{code:Ee.invalid_intersection_types}),$e)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ct.create=(e,t,r)=>new Ct({left:e,right:t,typeName:Wt.ZodIntersection,...Le(r)});class Ot extends qe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==be.array)return Re(r,{code:Ee.invalid_type,expected:be.array,received:r.parsedType}),$e;if(r.data.length<this._def.items.length)return Re(r,{code:Ee.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$e;!this._def.rest&&r.data.length>this._def.items.length&&(Re(r,{code:Ee.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new Ne(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>Te.mergeArray(t,e)):Te.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new Ot({...this._def,rest:e})}}Ot.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ot({items:e,typeName:Wt.ZodTuple,rest:null,...Le(t)})};class At extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==be.object)return Re(r,{code:Ee.invalid_type,expected:be.object,received:r.parsedType}),$e;const a=[],s=this._def.keyType,o=this._def.valueType;for(const e in r.data)a.push({key:s._parse(new Ne(r,e,r.path,e)),value:o._parse(new Ne(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?Te.mergeObjectAsync(t,a):Te.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new At(t instanceof qe?{keyType:e,valueType:t,typeName:Wt.ZodRecord,...Le(r)}:{keyType:dt.create(),valueType:e,typeName:Wt.ZodRecord,...Le(t)})}}class It extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==be.map)return Re(r,{code:Ee.invalid_type,expected:be.map,received:r.parsedType}),$e;const a=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:a._parse(new Ne(r,e,r.path,[o,"key"])),value:s._parse(new Ne(r,t,r.path,[o,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of o){const a=await r.key,s=await r.value;if("aborted"===a.status||"aborted"===s.status)return $e;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of o){const a=r.key,s=r.value;if("aborted"===a.status||"aborted"===s.status)return $e;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}}}}It.create=(e,t,r)=>new It({valueType:t,keyType:e,typeName:Wt.ZodMap,...Le(r)});class jt extends qe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==be.set)return Re(r,{code:Ee.invalid_type,expected:be.set,received:r.parsedType}),$e;const a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(Re(r,{code:Ee.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(Re(r,{code:Ee.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const s=this._def.valueType;function o(e){const r=new Set;for(const a of e){if("aborted"===a.status)return $e;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const n=[...r.data.values()].map((e,t)=>s._parse(new Ne(r,e,r.path,t)));return r.common.async?Promise.all(n).then(e=>o(e)):o(n)}min(e,t){return new jt({...this._def,minSize:{value:e,message:De.toString(t)}})}max(e,t){return new jt({...this._def,maxSize:{value:e,message:De.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}jt.create=(e,t)=>new jt({valueType:e,minSize:null,maxSize:null,typeName:Wt.ZodSet,...Le(t)});class Ft extends qe{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ft.create=(e,t)=>new Ft({getter:e,typeName:Wt.ZodLazy,...Le(t)});class Dt extends qe{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Re(t,{received:t.data,code:Ee.invalid_literal,expected:this._def.value}),$e}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Nt(e,t){return new Ut({values:e,typeName:Wt.ZodEnum,...Le(t)})}Dt.create=(e,t)=>new Dt({value:e,typeName:Wt.ZodLiteral,...Le(t)});class Ut extends qe{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Re(t,{expected:_e.joinValues(r),received:t.parsedType,code:Ee.invalid_type}),$e}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return Re(t,{received:t.data,code:Ee.invalid_enum_value,options:r}),$e}return Oe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ut.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ut.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ut.create=Nt;class Lt extends qe{_parse(e){const t=_e.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==be.string&&r.parsedType!==be.number){const e=_e.objectValues(t);return Re(r,{expected:_e.joinValues(e),received:r.parsedType,code:Ee.invalid_type}),$e}if(this._cache||(this._cache=new Set(_e.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=_e.objectValues(t);return Re(r,{received:r.data,code:Ee.invalid_enum_value,options:e}),$e}return Oe(e.data)}get enum(){return this._def.values}}Lt.create=(e,t)=>new Lt({values:e,typeName:Wt.ZodNativeEnum,...Le(t)});class qt extends qe{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==be.promise&&!1===t.common.async)return Re(t,{code:Ee.invalid_type,expected:be.promise,received:t.parsedType}),$e;const r=t.parsedType===be.promise?t.data:Promise.resolve(t.data);return Oe(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}qt.create=(e,t)=>new qt({type:e,typeName:Wt.ZodPromise,...Le(t)});class zt extends qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Wt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:e=>{Re(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===a.type){const e=a.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return $e;const a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?$e:"dirty"===a.status||"dirty"===t.value?Ce(a.value):a});{if("aborted"===t.value)return $e;const a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?$e:"dirty"===a.status||"dirty"===t.value?Ce(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?$e:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?$e:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===a.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!je(e))return $e;const o=a.transform(e.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>je(e)?Promise.resolve(a.transform(e.value,s)).then(e=>({status:t.value,value:e})):$e)}_e.assertNever(a)}}zt.create=(e,t,r)=>new zt({schema:e,typeName:Wt.ZodEffects,effect:t,...Le(r)}),zt.createWithPreprocess=(e,t,r)=>new zt({schema:t,effect:{type:"preprocess",transform:e},typeName:Wt.ZodEffects,...Le(r)});class Vt extends qe{_parse(e){return this._getType(e)===be.undefined?Oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Vt.create=(e,t)=>new Vt({innerType:e,typeName:Wt.ZodOptional,...Le(t)});class Mt extends qe{_parse(e){return this._getType(e)===be.null?Oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Mt.create=(e,t)=>new Mt({innerType:e,typeName:Wt.ZodNullable,...Le(t)});class Zt extends qe{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Zt.create=(e,t)=>new Zt({innerType:e,typeName:Wt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Le(t)});class Ht extends qe{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Fe(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ht.create=(e,t)=>new Ht({innerType:e,typeName:Wt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Le(t)});class Bt extends qe{_parse(e){if(this._getType(e)!==be.nan){const t=this._getOrReturnCtx(e);return Re(t,{code:Ee.invalid_type,expected:be.nan,received:t.parsedType}),$e}return{status:"valid",value:e.data}}}Bt.create=e=>new Bt({typeName:Wt.ZodNaN,...Le(e)});class Qt extends qe{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Kt extends qe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?$e:"dirty"===e.status?(t.dirty(),Ce(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?$e:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Kt({in:e,out:t,typeName:Wt.ZodPipeline})}}class Jt extends qe{_parse(e){const t=this._def.innerType._parse(e),r=e=>(je(e)&&(e.value=Object.freeze(e.value)),e);return Fe(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var Wt;Jt.create=(e,t)=>new Jt({innerType:e,typeName:Wt.ZodReadonly,...Le(t)}),xt.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Wt||(Wt={}));const Gt=dt.create,Yt=ht.create;Bt.create,pt.create;const Xt=ft.create;mt.create,vt.create,gt.create,yt.create;const er=_t.create,tr=wt.create;bt.create,Pt.create;const rr=Et.create,ar=xt.create;xt.strictCreate;const sr=St.create,or=Tt.create;Ct.create,Ot.create;const nr=At.create;It.create,jt.create,Ft.create;const ir=Dt.create,cr=Ut.create;Lt.create,qt.create,zt.create;const lr=Vt.create;Mt.create,zt.createWithPreprocess;const dr="2025-06-18",ur=[dr,"2025-03-26","2024-11-05","2024-10-07"],hr="2.0",pr=sr([Gt(),Yt().int()]),fr=Gt(),mr=ar({progressToken:lr(pr)}).passthrough(),vr=ar({_meta:lr(mr)}).passthrough(),gr=ar({method:Gt(),params:lr(vr)}),yr=ar({_meta:lr(ar({}).passthrough())}).passthrough(),_r=ar({method:Gt(),params:lr(yr)}),wr=ar({_meta:lr(ar({}).passthrough())}).passthrough(),br=sr([Gt(),Yt().int()]),Pr=ar({jsonrpc:ir(hr),id:br}).merge(gr).strict(),Er=e=>Pr.safeParse(e).success,kr=ar({jsonrpc:ir(hr)}).merge(_r).strict(),xr=ar({jsonrpc:ir(hr),id:br,result:wr}).strict(),Sr=e=>xr.safeParse(e).success;var Rr;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(Rr||(Rr={}));const Tr=ar({jsonrpc:ir(hr),id:br,error:ar({code:Yt().int(),message:Gt(),data:lr(tr())})}).strict(),$r=sr([Pr,kr,xr,Tr]),Cr=wr.strict(),Or=_r.extend({method:ir("notifications/cancelled"),params:yr.extend({requestId:br,reason:Gt().optional()})}),Ar=ar({name:Gt(),title:lr(Gt())}).passthrough(),Ir=Ar.extend({version:Gt()}),jr=ar({experimental:lr(ar({}).passthrough()),sampling:lr(ar({}).passthrough()),elicitation:lr(ar({}).passthrough()),roots:lr(ar({listChanged:lr(Xt())}).passthrough())}).passthrough(),Fr=gr.extend({method:ir("initialize"),params:vr.extend({protocolVersion:Gt(),capabilities:jr,clientInfo:Ir})}),Dr=ar({experimental:lr(ar({}).passthrough()),logging:lr(ar({}).passthrough()),completions:lr(ar({}).passthrough()),prompts:lr(ar({listChanged:lr(Xt())}).passthrough()),resources:lr(ar({subscribe:lr(Xt()),listChanged:lr(Xt())}).passthrough()),tools:lr(ar({listChanged:lr(Xt())}).passthrough())}).passthrough(),Nr=wr.extend({protocolVersion:Gt(),capabilities:Dr,serverInfo:Ir,instructions:lr(Gt())}),Ur=_r.extend({method:ir("notifications/initialized")}),Lr=gr.extend({method:ir("ping")}),qr=ar({progress:Yt(),total:lr(Yt()),message:lr(Gt())}).passthrough(),zr=_r.extend({method:ir("notifications/progress"),params:yr.merge(qr).extend({progressToken:pr})}),Vr=gr.extend({params:vr.extend({cursor:lr(fr)}).optional()}),Mr=wr.extend({nextCursor:lr(fr)}),Zr=ar({uri:Gt(),mimeType:lr(Gt()),_meta:lr(ar({}).passthrough())}).passthrough(),Hr=Zr.extend({text:Gt()}),Br=Gt().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Qr=Zr.extend({blob:Br}),Kr=Ar.extend({uri:Gt(),description:lr(Gt()),mimeType:lr(Gt()),_meta:lr(ar({}).passthrough())}),Jr=Ar.extend({uriTemplate:Gt(),description:lr(Gt()),mimeType:lr(Gt()),_meta:lr(ar({}).passthrough())}),Wr=Vr.extend({method:ir("resources/list")}),Gr=Mr.extend({resources:rr(Kr)}),Yr=Vr.extend({method:ir("resources/templates/list")}),Xr=Mr.extend({resourceTemplates:rr(Jr)}),ea=gr.extend({method:ir("resources/read"),params:vr.extend({uri:Gt()})}),ta=wr.extend({contents:rr(sr([Hr,Qr]))}),ra=_r.extend({method:ir("notifications/resources/list_changed")}),aa=gr.extend({method:ir("resources/subscribe"),params:vr.extend({uri:Gt()})}),sa=gr.extend({method:ir("resources/unsubscribe"),params:vr.extend({uri:Gt()})}),oa=_r.extend({method:ir("notifications/resources/updated"),params:yr.extend({uri:Gt()})}),na=ar({name:Gt(),description:lr(Gt()),required:lr(Xt())}).passthrough(),ia=Ar.extend({description:lr(Gt()),arguments:lr(rr(na)),_meta:lr(ar({}).passthrough())}),ca=Vr.extend({method:ir("prompts/list")}),la=Mr.extend({prompts:rr(ia)}),da=gr.extend({method:ir("prompts/get"),params:vr.extend({name:Gt(),arguments:lr(nr(Gt()))})}),ua=ar({type:ir("text"),text:Gt(),_meta:lr(ar({}).passthrough())}).passthrough(),ha=ar({type:ir("image"),data:Br,mimeType:Gt(),_meta:lr(ar({}).passthrough())}).passthrough(),pa=ar({type:ir("audio"),data:Br,mimeType:Gt(),_meta:lr(ar({}).passthrough())}).passthrough(),fa=ar({type:ir("resource"),resource:sr([Hr,Qr]),_meta:lr(ar({}).passthrough())}).passthrough(),ma=sr([ua,ha,pa,Kr.extend({type:ir("resource_link")}),fa]),va=ar({role:cr(["user","assistant"]),content:ma}).passthrough(),ga=wr.extend({description:lr(Gt()),messages:rr(va)}),ya=_r.extend({method:ir("notifications/prompts/list_changed")}),_a=ar({title:lr(Gt()),readOnlyHint:lr(Xt()),destructiveHint:lr(Xt()),idempotentHint:lr(Xt()),openWorldHint:lr(Xt())}).passthrough(),wa=Ar.extend({description:lr(Gt()),inputSchema:ar({type:ir("object"),properties:lr(ar({}).passthrough()),required:lr(rr(Gt()))}).passthrough(),outputSchema:lr(ar({type:ir("object"),properties:lr(ar({}).passthrough()),required:lr(rr(Gt()))}).passthrough()),annotations:lr(_a),_meta:lr(ar({}).passthrough())}),ba=Vr.extend({method:ir("tools/list")}),Pa=Mr.extend({tools:rr(wa)}),Ea=wr.extend({content:rr(ma).default([]),structuredContent:ar({}).passthrough().optional(),isError:lr(Xt())});Ea.or(wr.extend({toolResult:tr()}));const ka=gr.extend({method:ir("tools/call"),params:vr.extend({name:Gt(),arguments:lr(nr(tr()))})}),xa=_r.extend({method:ir("notifications/tools/list_changed")}),Sa=cr(["debug","info","notice","warning","error","critical","alert","emergency"]),Ra=gr.extend({method:ir("logging/setLevel"),params:vr.extend({level:Sa})}),Ta=_r.extend({method:ir("notifications/message"),params:yr.extend({level:Sa,logger:lr(Gt()),data:tr()})}),$a=ar({name:Gt().optional()}).passthrough(),Ca=ar({hints:lr(rr($a)),costPriority:lr(Yt().min(0).max(1)),speedPriority:lr(Yt().min(0).max(1)),intelligencePriority:lr(Yt().min(0).max(1))}).passthrough(),Oa=ar({role:cr(["user","assistant"]),content:sr([ua,ha,pa])}).passthrough(),Aa=gr.extend({method:ir("sampling/createMessage"),params:vr.extend({messages:rr(Oa),systemPrompt:lr(Gt()),includeContext:lr(cr(["none","thisServer","allServers"])),temperature:lr(Yt()),maxTokens:Yt().int(),stopSequences:lr(rr(Gt())),metadata:lr(ar({}).passthrough()),modelPreferences:lr(Ca)})}),Ia=wr.extend({model:Gt(),stopReason:lr(cr(["endTurn","stopSequence","maxTokens"]).or(Gt())),role:cr(["user","assistant"]),content:or("type",[ua,ha,pa])}),ja=sr([ar({type:ir("boolean"),title:lr(Gt()),description:lr(Gt()),default:lr(Xt())}).passthrough(),ar({type:ir("string"),title:lr(Gt()),description:lr(Gt()),minLength:lr(Yt()),maxLength:lr(Yt()),format:lr(cr(["email","uri","date","date-time"]))}).passthrough(),ar({type:cr(["number","integer"]),title:lr(Gt()),description:lr(Gt()),minimum:lr(Yt()),maximum:lr(Yt())}).passthrough(),ar({type:ir("string"),title:lr(Gt()),description:lr(Gt()),enum:rr(Gt()),enumNames:lr(rr(Gt()))}).passthrough()]),Fa=gr.extend({method:ir("elicitation/create"),params:vr.extend({message:Gt(),requestedSchema:ar({type:ir("object"),properties:nr(Gt(),ja),required:lr(rr(Gt()))}).passthrough()})}),Da=wr.extend({action:cr(["accept","decline","cancel"]),content:lr(nr(Gt(),tr()))}),Na=ar({type:ir("ref/resource"),uri:Gt()}).passthrough(),Ua=ar({type:ir("ref/prompt"),name:Gt()}).passthrough(),La=gr.extend({method:ir("completion/complete"),params:vr.extend({ref:sr([Ua,Na]),argument:ar({name:Gt(),value:Gt()}).passthrough(),context:lr(ar({arguments:lr(nr(Gt(),Gt()))}))})}),qa=wr.extend({completion:ar({values:rr(Gt()).max(100),total:lr(Yt().int()),hasMore:lr(Xt())}).passthrough()}),za=ar({uri:Gt().startsWith("file://"),name:lr(Gt()),_meta:lr(ar({}).passthrough())}).passthrough(),Va=gr.extend({method:ir("roots/list")}),Ma=wr.extend({roots:rr(za)}),Za=_r.extend({method:ir("notifications/roots/list_changed")});sr([Lr,Fr,La,Ra,da,ca,Wr,Yr,ea,aa,sa,ka,ba]),sr([Or,zr,Ur,Za]),sr([Cr,Ia,Da,Ma]),sr([Lr,Aa,Fa,Va]),sr([Or,zr,Ta,oa,ra,xa,ya]),sr([Cr,Nr,qa,ga,la,Gr,Xr,ta,Ea,Pa]);class Ha extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class Ba{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Or,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(zr,e=>{this._onprogress(e)}),this.setRequestHandler(Lr,e=>({}))}_setupTimeout(e,t,r,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:a})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Ha(Rr.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,a;this._transport=e;const s=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==s||s(),this._onclose()};const o=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==o||o(e),this._onerror(e)};const n=null===(a=this._transport)||void 0===a?void 0:a.onmessage;this._transport.onmessage=(e,t)=>{var r;null==n||n(e,t),Sr(e)||(r=e,Tr.safeParse(r).success)?this._onresponse(e):Er(e)?this._onrequest(e,t):(e=>kr.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new Ha(Rr.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,a,s,o;const n=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler;if(void 0===n)return void(null===(a=this._transport)||void 0===a||a.send({jsonrpc:"2.0",id:e.id,error:{code:Rr.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const c={signal:i.signal,sessionId:null===(s=this._transport)||void 0===s?void 0:s.sessionId,_meta:null===(o=e.params)||void 0===o?void 0:o._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,a)=>this.request(t,r,{...a,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>n(e,c)).then(t=>{var r;if(!i.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r,a;if(!i.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Rr.InternalError,message:null!==(a=t.message)&&void 0!==a?a:"Internal error"}})}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,a=Number(t),s=this._progressHandlers.get(a);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(a),n=this._timeoutInfo.get(a);if(n&&o&&n.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){return void o(e)}s(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);if(void 0!==r)if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),Sr(e))r(e);else{r(new Ha(e.error.code,e.error.message,e.error.data))}else this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}=null!=r?r:{};return new Promise((n,i)=>{var c,l,d,u,h,p;if(!this._transport)return void i(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(l=null==r?void 0:r.signal)||void 0===l||l.throwIfAborted();const f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(f,r.onprogress),m.params={...e.params,_meta:{...(null===(d=e.params)||void 0===d?void 0:d._meta)||{},progressToken:f}});const v=e=>{var t;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),i(e)};this._responseHandlers.set(f,e=>{var a;if(!(null===(a=null==r?void 0:r.signal)||void 0===a?void 0:a.aborted)){if(e instanceof Error)return i(e);try{const r=t.parse(e.result);n(r)}catch(e){i(e)}}}),null===(u=null==r?void 0:r.signal)||void 0===u||u.addEventListener("abort",()=>{var e;v(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const g=null!==(h=null==r?void 0:r.timeout)&&void 0!==h?h:6e4;this._setupTimeout(f,g,null==r?void 0:r.maxTotalTimeout,()=>v(new Ha(Rr.RequestTimeout,"Request timed out",{timeout:g})),null!==(p=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==p&&p),this._transport.send(m,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(f),i(e)})})}async notification(e,t){var r,a;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);if((null!==(a=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==a?a:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const a={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(a,t).catch(e=>this._onerror(e))})}const s={...e,jsonrpc:"2.0"};await this._transport.send(s,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,a)=>Promise.resolve(t(e.parse(r),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Qa(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ka={exports:{}};
2
+ /** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */!function(e){function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var a=t.length-1,s=1;s<a;++s)t[s]=t[s].slice(1,-1);return t[a]=t[a].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function a(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function s(e){return e.toUpperCase()}function o(e){return null!=e?e instanceof Array?e:"number"!=typeof e.length||e.split||e.setInterval||e.call?[e]:Array.prototype.slice.call(e):[]}function n(e,t){var r=e;if(t)for(var a in t)r[a]=t[a];return r}function i(e){var a="[A-Za-z]",s="[0-9]",o=t(s,"[A-Fa-f]"),n=r(r("%[EFef]"+o+"%"+o+o+"%"+o+o)+"|"+r("%[89A-Fa-f]"+o+"%"+o+o)+"|"+r("%"+o+o)),i="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",i),l=e?"[\\uE000-\\uF8FF]":"[]",d=t(a,s,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]");r(a+t(a,s,"[\\+\\-\\.]")+"*"),r(r(n+"|"+t(d,i,"[\\:]"))+"*");var u=r(r("25[0-5]")+"|"+r("2[0-4]"+s)+"|"+r("1"+s+s)+"|"+r("0?[1-9]"+s)+"|0?0?"+s),h=r(u+"\\."+u+"\\."+u+"\\."+u),p=r(o+"{1,4}"),f=r(r(p+"\\:"+p)+"|"+h),m=r(r(p+"\\:")+"{6}"+f),v=r("\\:\\:"+r(p+"\\:")+"{5}"+f),g=r(r(p)+"?\\:\\:"+r(p+"\\:")+"{4}"+f),y=r(r(r(p+"\\:")+"{0,1}"+p)+"?\\:\\:"+r(p+"\\:")+"{3}"+f),_=r(r(r(p+"\\:")+"{0,2}"+p)+"?\\:\\:"+r(p+"\\:")+"{2}"+f),w=r(r(r(p+"\\:")+"{0,3}"+p)+"?\\:\\:"+p+"\\:"+f),b=r(r(r(p+"\\:")+"{0,4}"+p)+"?\\:\\:"+f),P=r(r(r(p+"\\:")+"{0,5}"+p)+"?\\:\\:"+p),E=r(r(r(p+"\\:")+"{0,6}"+p)+"?\\:\\:"),k=r([m,v,g,y,_,w,b,P,E].join("|")),x=r(r(d+"|"+n)+"+");r("[vV]"+o+"+\\."+t(d,i,"[\\:]")+"+"),r(r(n+"|"+t(d,i))+"*");var S=r(n+"|"+t(d,i,"[\\:\\@]"));return r(r(n+"|"+t(d,i,"[\\@]"))+"+"),r(r(S+"|"+t("[\\/\\?]",l))+"*"),{NOT_SCHEME:new RegExp(t("[^]",a,s,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",d,i),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",d,i),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",d,i),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",d,i),"g"),NOT_QUERY:new RegExp(t("[^\\%]",d,i,"[\\:\\@\\/\\?]",l),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",d,i,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",d,i),"g"),UNRESERVED:new RegExp(d,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",d,c),"g"),PCT_ENCODED:new RegExp(n,"g"),IPV4ADDRESS:new RegExp("^("+h+")$"),IPV6ADDRESS:new RegExp("^\\[?("+k+")"+r(r("\\%25|\\%(?!"+o+"{2})")+"("+x+")")+"?\\]?$")}}var c=i(!1),l=i(!0),d=function(){function e(e,t){var r=[],a=!0,s=!1,o=void 0;try{for(var n,i=e[Symbol.iterator]();!(a=(n=i.next()).done)&&(r.push(n.value),!t||r.length!==t);a=!0);}catch(e){s=!0,o=e}finally{try{!a&&i.return&&i.return()}finally{if(s)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},h=2147483647,p=36,f=1,m=26,v=38,g=700,y=72,_=128,w="-",b=/^xn--/,P=/[^\0-\x7E]/,E=/[\x2E\u3002\uFF0E\uFF61]/g,k={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},x=p-f,S=Math.floor,R=String.fromCharCode;function T(e){throw new RangeError(k[e])}function $(e,t){for(var r=[],a=e.length;a--;)r[a]=t(e[a]);return r}function C(e,t){var r=e.split("@"),a="";return r.length>1&&(a=r[0]+"@",e=r[1]),a+$((e=e.replace(E,".")).split("."),t).join(".")}function O(e){for(var t=[],r=0,a=e.length;r<a;){var s=e.charCodeAt(r++);if(s>=55296&&s<=56319&&r<a){var o=e.charCodeAt(r++);56320==(64512&o)?t.push(((1023&s)<<10)+(1023&o)+65536):(t.push(s),r--)}else t.push(s)}return t}var A=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:p},I=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},j=function(e,t,r){var a=0;for(e=r?S(e/g):e>>1,e+=S(e/t);e>x*m>>1;a+=p)e=S(e/x);return S(a+(x+1)*e/(e+v))},F=function(e){var t=[],r=e.length,a=0,s=_,o=y,n=e.lastIndexOf(w);n<0&&(n=0);for(var i=0;i<n;++i)e.charCodeAt(i)>=128&&T("not-basic"),t.push(e.charCodeAt(i));for(var c=n>0?n+1:0;c<r;){for(var l=a,d=1,u=p;;u+=p){c>=r&&T("invalid-input");var v=A(e.charCodeAt(c++));(v>=p||v>S((h-a)/d))&&T("overflow"),a+=v*d;var g=u<=o?f:u>=o+m?m:u-o;if(v<g)break;var b=p-g;d>S(h/b)&&T("overflow"),d*=b}var P=t.length+1;o=j(a-l,P,0==l),S(a/P)>h-s&&T("overflow"),s+=S(a/P),a%=P,t.splice(a++,0,s)}return String.fromCodePoint.apply(String,t)},D=function(e){var t=[],r=(e=O(e)).length,a=_,s=0,o=y,n=!0,i=!1,c=void 0;try{for(var l,d=e[Symbol.iterator]();!(n=(l=d.next()).done);n=!0){var u=l.value;u<128&&t.push(R(u))}}catch(e){i=!0,c=e}finally{try{!n&&d.return&&d.return()}finally{if(i)throw c}}var v=t.length,g=v;for(v&&t.push(w);g<r;){var b=h,P=!0,E=!1,k=void 0;try{for(var x,$=e[Symbol.iterator]();!(P=(x=$.next()).done);P=!0){var C=x.value;C>=a&&C<b&&(b=C)}}catch(e){E=!0,k=e}finally{try{!P&&$.return&&$.return()}finally{if(E)throw k}}var A=g+1;b-a>S((h-s)/A)&&T("overflow"),s+=(b-a)*A,a=b;var F=!0,D=!1,N=void 0;try{for(var U,L=e[Symbol.iterator]();!(F=(U=L.next()).done);F=!0){var q=U.value;if(q<a&&++s>h&&T("overflow"),q==a){for(var z=s,V=p;;V+=p){var M=V<=o?f:V>=o+m?m:V-o;if(z<M)break;var Z=z-M,H=p-M;t.push(R(I(M+Z%H,0))),z=S(Z/H)}t.push(R(I(z,0))),o=j(s,A,g==v),s=0,++g}}}catch(e){D=!0,N=e}finally{try{!F&&L.return&&L.return()}finally{if(D)throw N}}++s,++a}return t.join("")},N=function(e){return C(e,function(e){return b.test(e)?F(e.slice(4).toLowerCase()):e})},U=function(e){return C(e,function(e){return P.test(e)?"xn--"+D(e):e})},L={version:"2.1.0",ucs2:{decode:O,encode:function(e){return String.fromCodePoint.apply(String,u(e))}},decode:F,encode:D,toASCII:U,toUnicode:N},q={};function z(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function V(e){for(var t="",r=0,a=e.length;r<a;){var s=parseInt(e.substr(r+1,2),16);if(s<128)t+=String.fromCharCode(s),r+=3;else if(s>=194&&s<224){if(a-r>=6){var o=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&s)<<6|63&o)}else t+=e.substr(r,6);r+=6}else if(s>=224){if(a-r>=9){var n=parseInt(e.substr(r+4,2),16),i=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function M(e,t){function r(e){var r=V(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,z).replace(t.PCT_ENCODED,s)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,z).replace(t.PCT_ENCODED,s)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,z).replace(t.PCT_ENCODED,s)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,z).replace(t.PCT_ENCODED,s)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,z).replace(t.PCT_ENCODED,s)),e}function Z(e){return e.replace(/^0*(.*)/,"$1")||"0"}function H(e,t){var r=e.match(t.IPV4ADDRESS)||[],a=d(r,2)[1];return a?a.split(".").map(Z).join("."):e}function B(e,t){var r=e.match(t.IPV6ADDRESS)||[],a=d(r,3),s=a[1],o=a[2];if(s){for(var n=s.toLowerCase().split("::").reverse(),i=d(n,2),c=i[0],l=i[1],u=l?l.split(":").map(Z):[],h=c.split(":").map(Z),p=t.IPV4ADDRESS.test(h[h.length-1]),f=p?7:8,m=h.length-f,v=Array(f),g=0;g<f;++g)v[g]=u[g]||h[m+g]||"";p&&(v[f-1]=H(v[f-1],t));var y=v.reduce(function(e,t,r){if(!t||"0"===t){var a=e[e.length-1];a&&a.index+a.length===r?a.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],_=void 0;if(y&&y.length>1){var w=v.slice(0,y.index),b=v.slice(y.index+y.length);_=w.join(":")+"::"+b.join(":")}else _=v.join(":");return o&&(_+="%"+o),_}return e}var Q=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,K=void 0==="".match(/(){0}/)[1];function J(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},a=!1!==t.iri?l:c;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var s=e.match(Q);if(s){K?(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5])):(r.scheme=s[1]||void 0,r.userinfo=-1!==e.indexOf("@")?s[3]:void 0,r.host=-1!==e.indexOf("//")?s[4]:void 0,r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=-1!==e.indexOf("?")?s[7]:void 0,r.fragment=-1!==e.indexOf("#")?s[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?s[4]:void 0)),r.host&&(r.host=B(H(r.host,a),a)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var o=q[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||o&&o.unicodeSupport)M(r,a);else{if(r.host&&(t.domainHost||o&&o.domainHost))try{r.host=L.toASCII(r.host.replace(a.PCT_ENCODED,V).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}M(r,c)}o&&o.parse&&o.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}function W(e,t){var r=!1!==t.iri?l:c,a=[];return void 0!==e.userinfo&&(a.push(e.userinfo),a.push("@")),void 0!==e.host&&a.push(B(H(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(a.push(":"),a.push(String(e.port))),a.length?a.join(""):void 0}var G=/^\.\.?\//,Y=/^\/\.(\/|$)/,X=/^\/\.\.(\/|$)/,ee=/^\/?(?:.|\n)*?(?=\/|$)/;function te(e){for(var t=[];e.length;)if(e.match(G))e=e.replace(G,"");else if(e.match(Y))e=e.replace(Y,"/");else if(e.match(X))e=e.replace(X,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(ee);if(!r)throw new Error("Unexpected dot segment condition");var a=r[0];e=e.slice(a.length),t.push(a)}return t.join("")}function re(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?l:c,a=[],s=q[(t.scheme||e.scheme||"").toLowerCase()];if(s&&s.serialize&&s.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||s&&s.domainHost)try{e.host=t.iri?L.toUnicode(e.host):L.toASCII(e.host.replace(r.PCT_ENCODED,V).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}M(e,r),"suffix"!==t.reference&&e.scheme&&(a.push(e.scheme),a.push(":"));var o=W(e,t);if(void 0!==o&&("suffix"!==t.reference&&a.push("//"),a.push(o),e.path&&"/"!==e.path.charAt(0)&&a.push("/")),void 0!==e.path){var n=e.path;t.absolutePath||s&&s.absolutePath||(n=te(n)),void 0===o&&(n=n.replace(/^\/\//,"/%2F")),a.push(n)}return void 0!==e.query&&(a.push("?"),a.push(e.query)),void 0!==e.fragment&&(a.push("#"),a.push(e.fragment)),a.join("")}function ae(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a={};return arguments[3]||(e=J(re(e,r),r),t=J(re(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=te(t.path||""),a.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=te(t.path||""),a.query=t.query):(t.path?("/"===t.path.charAt(0)?a.path=te(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path:a.path="/"+t.path,a.path=te(a.path)),a.query=t.query):(a.path=e.path,void 0!==t.query?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function se(e,t,r){var a=n({scheme:"null"},r);return re(ae(J(e,a),J(t,a),a,!0),a)}function oe(e,t){return"string"==typeof e?e=re(J(e,t),t):"object"===a(e)&&(e=J(re(e,t),t)),e}function ne(e,t,r){return"string"==typeof e?e=re(J(e,r),r):"object"===a(e)&&(e=re(e,r)),"string"==typeof t?t=re(J(t,r),r):"object"===a(t)&&(t=re(t,r)),e===t}function ie(e,t){return e&&e.toString().replace(t&&t.iri?l.ESCAPE:c.ESCAPE,z)}function ce(e,t){return e&&e.toString().replace(t&&t.iri?l.PCT_ENCODED:c.PCT_ENCODED,V)}var le={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},de={scheme:"https",domainHost:le.domainHost,parse:le.parse,serialize:le.serialize};function ue(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var he={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=ue(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(ue(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),a=d(r,2),s=a[0],o=a[1];e.path=s&&"/"!==s?s:void 0,e.query=o,e.resourceName=void 0}return e.fragment=void 0,e}},pe={scheme:"wss",domainHost:he.domainHost,parse:he.parse,serialize:he.serialize},fe={},me="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",ve="[0-9A-Fa-f]",ge=r(r("%[EFef]"+ve+"%"+ve+ve+"%"+ve+ve)+"|"+r("%[89A-Fa-f]"+ve+"%"+ve+ve)+"|"+r("%"+ve+ve)),ye="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",_e=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),we="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",be=new RegExp(me,"g"),Pe=new RegExp(ge,"g"),Ee=new RegExp(t("[^]",ye,"[\\.]",'[\\"]',_e),"g"),ke=new RegExp(t("[^]",me,we),"g"),xe=ke;function Se(e){var t=V(e);return t.match(be)?t:e}var Re={scheme:"mailto",parse:function(e,t){var r=e,a=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var s=!1,o={},n=r.query.split("&"),i=0,c=n.length;i<c;++i){var l=n[i].split("=");switch(l[0]){case"to":for(var d=l[1].split(","),u=0,h=d.length;u<h;++u)a.push(d[u]);break;case"subject":r.subject=ce(l[1],t);break;case"body":r.body=ce(l[1],t);break;default:s=!0,o[ce(l[0],t)]=ce(l[1],t)}}s&&(r.headers=o)}r.query=void 0;for(var p=0,f=a.length;p<f;++p){var m=a[p].split("@");if(m[0]=ce(m[0]),t.unicodeSupport)m[1]=ce(m[1],t).toLowerCase();else try{m[1]=L.toASCII(ce(m[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}a[p]=m.join("@")}return r},serialize:function(e,t){var r=e,a=o(e.to);if(a){for(var n=0,i=a.length;n<i;++n){var c=String(a[n]),l=c.lastIndexOf("@"),d=c.slice(0,l).replace(Pe,Se).replace(Pe,s).replace(Ee,z),u=c.slice(l+1);try{u=t.iri?L.toUnicode(u):L.toASCII(ce(u,t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}a[n]=d+"@"+u}r.path=a.join(",")}var h=e.headers=e.headers||{};e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body);var p=[];for(var f in h)h[f]!==fe[f]&&p.push(f.replace(Pe,Se).replace(Pe,s).replace(ke,z)+"="+h[f].replace(Pe,Se).replace(Pe,s).replace(xe,z));return p.length&&(r.query=p.join("&")),r}},Te=/^([^\:]+)\:(.*)/,$e={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(Te),a=e;if(r){var s=t.scheme||a.scheme||"urn",o=r[1].toLowerCase(),n=r[2],i=s+":"+(t.nid||o),c=q[i];a.nid=o,a.nss=n,a.path=void 0,c&&(a=c.parse(a,t))}else a.error=a.error||"URN can not be parsed.";return a},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",a=e.nid,s=r+":"+(t.nid||a),o=q[s];o&&(e=o.serialize(e,t));var n=e,i=e.nss;return n.path=(a||t.nid)+":"+i,n}},Ce=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Oe={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(Ce)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};q[le.scheme]=le,q[de.scheme]=de,q[he.scheme]=he,q[pe.scheme]=pe,q[Re.scheme]=Re,q[$e.scheme]=$e,q[Oe.scheme]=Oe,e.SCHEMES=q,e.pctEncChar=z,e.pctDecChars=V,e.parse=J,e.removeDotSegments=te,e.serialize=re,e.resolveComponents=ae,e.resolve=se,e.normalize=oe,e.equal=ne,e.escapeComponent=ie,e.unescapeComponent=ce,Object.defineProperty(e,"__esModule",{value:!0})}(Ka.exports);var Ja=Ka.exports,Wa=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var a,s,o;if(Array.isArray(t)){if((a=t.length)!=r.length)return!1;for(s=a;0!==s--;)if(!e(t[s],r[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((a=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=a;0!==s--;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=a;0!==s--;){var n=o[s];if(!e(t[n],r[n]))return!1}return!0}return t!=t&&r!=r},Ga={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:Ya,checkDataTypes:function(e,t,r){if(1===e.length)return Ya(e[0],t,r,!0);var a="",s=es(e);for(var o in s.array&&s.object&&(a=s.null?"(":"(!"+t+" || ",a+="typeof "+t+' !== "object")',delete s.null,delete s.array,delete s.object),s.number&&delete s.integer,s)a+=(a?" && ":"")+Ya(o,t,r,!0);return a},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],a=0;a<t.length;a++){var s=t[a];(Xa[s]||"array"===e&&"array"===s)&&(r[r.length]=s)}if(r.length)return r}else{if(Xa[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:es,getProperty:as,escapeQuotes:ss,equal:Wa,ucs2length:function(e){for(var t,r=0,a=e.length,s=0;s<a;)r++,(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<a&&56320==(64512&(t=e.charCodeAt(s)))&&s++;return r},varOccurences:function(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var a in e)if(a!=r&&t[a])return!0},schemaUnknownRules:function(e,t){if("boolean"==typeof e)return;for(var r in e)if(!t[r])return r},toQuotedString:os,getPathExpr:function(e,t,r,a){var s=r?"'/' + "+t+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'";return cs(e,s)},getPath:function(e,t,r){var a=os(r?"/"+ls(t):as(t));return cs(e,a)},getData:function(e,t,r){var a,s,o,n;if(""===e)return"rootData";if("/"==e[0]){if(!ns.test(e))throw new Error("Invalid JSON-pointer: "+e);s=e,o="rootData"}else{if(!(n=e.match(is)))throw new Error("Invalid JSON-pointer: "+e);if(a=+n[1],"#"==(s=n[2])){if(a>=t)throw new Error("Cannot access property/index "+a+" levels up, current level is "+t);return r[t-a]}if(a>t)throw new Error("Cannot access data "+a+" levels up, current level is "+t);if(o="data"+(t-a||""),!s)return o}for(var i=o,c=s.split("/"),l=0;l<c.length;l++){var d=c[l];d&&(i+=" && "+(o+=as(ds(d))))}return i},unescapeFragment:function(e){return ds(decodeURIComponent(e))},unescapeJsonPointer:ds,escapeFragment:function(e){return encodeURIComponent(ls(e))},escapeJsonPointer:ls};function Ya(e,t,r,a){var s=a?" !== ":" === ",o=a?" || ":" && ",n=a?"!":"",i=a?"":"!";switch(e){case"null":return t+s+"null";case"array":return n+"Array.isArray("+t+")";case"object":return"("+n+t+o+"typeof "+t+s+'"object"'+o+i+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+s+'"number"'+o+i+"("+t+" % 1)"+o+t+s+t+(r?o+n+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+s+'"'+e+'"'+(r?o+n+"isFinite("+t+")":"")+")";default:return"typeof "+t+s+'"'+e+'"'}}var Xa=es(["string","number","integer","boolean","null"]);function es(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var ts=/^[a-z$_][a-z$_0-9]*$/i,rs=/'|\\/g;function as(e){return"number"==typeof e?"["+e+"]":ts.test(e)?"."+e:"['"+ss(e)+"']"}function ss(e){return e.replace(rs,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function os(e){return"'"+ss(e)+"'"}var ns=/^\/(?:[^~]|~0|~1)*$/,is=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cs(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function ls(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ds(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var us=Ga,hs=function(e){us.copy(e,this)};var ps={exports:{}},fs=ps.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),ms(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function ms(e,t,r,a,s,o,n,i,c,l){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var d in t(a,s,o,n,i,c,l),a){var u=a[d];if(Array.isArray(u)){if(d in fs.arrayKeywords)for(var h=0;h<u.length;h++)ms(e,t,r,u[h],s+"/"+d+"/"+h,o,s,d,a,h)}else if(d in fs.propsKeywords){if(u&&"object"==typeof u)for(var p in u)ms(e,t,r,u[p],s+"/"+d+"/"+vs(p),o,s,d,a,p)}else(d in fs.keywords||e.allKeys&&!(d in fs.skipKeywords))&&ms(e,t,r,u,s+"/"+d,o,s,d,a)}r(a,s,o,n,i,c,l)}}function vs(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}fs.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},fs.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},fs.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},fs.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};var gs=ps.exports,ys=Ja,_s=Wa,ws=Ga,bs=hs,Ps=gs,Es=ks;function ks(e,t,r){var a=this._refs[r];if("string"==typeof a){if(!this._refs[a])return ks.call(this,e,t,a);a=this._refs[a]}if((a=a||this._schemas[r])instanceof bs)return Cs(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var s,o,n,i=xs.call(this,t,r);return i&&(s=i.schema,t=i.root,n=i.baseId),s instanceof bs?o=s.validate||e.call(this,s.schema,t,void 0,n):void 0!==s&&(o=Cs(s,this._opts.inlineRefs)?s:e.call(this,s,t,void 0,n)),o}function xs(e,t){var r=ys.parse(t),a=js(r),s=Is(this._getId(e.schema));if(0===Object.keys(e.schema).length||a!==s){var o=Ds(a),n=this._refs[o];if("string"==typeof n)return Ss.call(this,e,n,r);if(n instanceof bs)n.validate||this._compile(n),e=n;else{if(!((n=this._schemas[o])instanceof bs))return;if(n.validate||this._compile(n),o==Ds(t))return{schema:n,root:e,baseId:s};e=n}if(!e.schema)return;s=Is(this._getId(e.schema))}return Ts.call(this,r,s,e.schema,e)}function Ss(e,t,r){var a=xs.call(this,e,t);if(a){var s=a.schema,o=a.baseId;e=a.root;var n=this._getId(s);return n&&(o=Ns(o,n)),Ts.call(this,r,o,s,e)}}ks.normalizeId=Ds,ks.fullPath=Is,ks.url=Ns,ks.ids=function(e){var t=Ds(this._getId(e)),r={"":t},a={"":Is(t,!1)},s={},o=this;return Ps(e,{allKeys:!0},function(e,t,n,i,c,l,d){if(""!==t){var u=o._getId(e),h=r[i],p=a[i]+"/"+c;if(void 0!==d&&(p+="/"+("number"==typeof d?d:ws.escapeFragment(d))),"string"==typeof u){u=h=Ds(h?ys.resolve(h,u):u);var f=o._refs[u];if("string"==typeof f&&(f=o._refs[f]),f&&f.schema){if(!_s(e,f.schema))throw new Error('id "'+u+'" resolves to more than one schema')}else if(u!=Ds(p))if("#"==u[0]){if(s[u]&&!_s(e,s[u]))throw new Error('id "'+u+'" resolves to more than one schema');s[u]=e}else o._refs[u]=p}r[t]=h,a[t]=p}}),s},ks.inlineRef=Cs,ks.schema=xs;var Rs=ws.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Ts(e,t,r,a){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var s=e.fragment.split("/"),o=1;o<s.length;o++){var n=s[o];if(n){if(void 0===(r=r[n=ws.unescapeFragment(n)]))break;var i;if(!Rs[n]&&((i=this._getId(r))&&(t=Ns(t,i)),r.$ref)){var c=Ns(t,r.$ref),l=xs.call(this,a,c);l&&(r=l.schema,a=l.root,t=l.baseId)}}}return void 0!==r&&r!==a.schema?{schema:r,root:a,baseId:t}:void 0}}var $s=ws.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function Cs(e,t){return!1!==t&&(void 0===t||!0===t?Os(e):t?As(e)<=t:void 0)}function Os(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!Os(t))return!1}else for(var a in e){if("$ref"==a)return!1;if("object"==typeof(t=e[a])&&!Os(t))return!1}return!0}function As(e){var t,r=0;if(Array.isArray(e)){for(var a=0;a<e.length;a++)if("object"==typeof(t=e[a])&&(r+=As(t)),r==1/0)return 1/0}else for(var s in e){if("$ref"==s)return 1/0;if($s[s])r++;else if("object"==typeof(t=e[s])&&(r+=As(t)+1),r==1/0)return 1/0}return r}function Is(e,t){return!1!==t&&(e=Ds(e)),js(ys.parse(e))}function js(e){return ys.serialize(e).split("#")[0]+"#"}var Fs=/#\/?$/;function Ds(e){return e?e.replace(Fs,""):""}function Ns(e,t){return t=Ds(t),ys.resolve(e,t)}var Us=Es,Ls={Validation:zs(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:zs(qs)};function qs(e,t,r){this.message=r||qs.message(e,t),this.missingRef=Us.url(e,t),this.missingSchema=Us.normalizeId(Us.fullPath(this.missingRef))}function zs(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}qs.message=function(e,t){return"can't resolve reference "+t+" from id "+e};var Vs=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,a="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(r=t.cmp,function(e){return function(t,a){var s={key:t,value:e[t]},o={key:a,value:e[a]};return r(s,o)}}),o=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,n;if(Array.isArray(t)){for(n="[",r=0;r<t.length;r++)r&&(n+=","),n+=e(t[r])||"null";return n+"]"}if(null===t)return"null";if(-1!==o.indexOf(t)){if(a)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var i=o.push(t)-1,c=Object.keys(t).sort(s&&s(t));for(n="",r=0;r<c.length;r++){var l=c[r],d=e(t[l]);d&&(n&&(n+=","),n+=JSON.stringify(l)+":"+d)}return o.splice(i,1),"{"+n+"}"}}(e)},Ms=function(e,t,r){var a="",s=!0===e.schema.$async,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords){var i=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(i){var c="unknown keyword: "+i;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(a+=" var validate = ",s&&(e.async=!0,a+="async "),a+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n&&(e.opts.sourceCode||e.opts.processCode)&&(a+=" /*# sourceURL="+n+" */ ")),"boolean"==typeof e.schema||!o&&!e.schema.$ref){t="false schema";var l=e.level,d=e.dataLevel,u=e.schema[t],h=e.schemaPath+e.util.getProperty(t),p=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,m="data"+(d||""),v="valid"+l;if(!1===e.schema){e.isTop?f=!0:a+=" var "+v+" = false; ",(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'boolean schema is false' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?a+=s?" return data; ":" validate.errors = null; return true; ":a+=" var "+v+" = true; ";return e.isTop&&(a+=" }; return validate; "),a}if(e.isTop){var y=e.isTop;l=e.level=0,d=e.dataLevel=0,m="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}a+=" var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data; "}else{l=e.level,m="data"+((d=e.dataLevel)||"");if(n&&(e.baseId=e.resolve.url(e.baseId,n)),s&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+l+" = errors;"}v="valid"+l,f=!e.opts.allErrors;var w="",b="",P=e.schema.type,E=Array.isArray(P);if(P&&e.opts.nullable&&!0===e.schema.nullable&&(E?-1==P.indexOf("null")&&(P=P.concat("null")):"null"!=P&&(P=[P,"null"],E=!0)),E&&1==P.length&&(P=P[0],E=!1),e.schema.$ref&&o){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(a+=" "+e.RULES.all.$comment.code(e,"$comment")),P){if(e.opts.coerceTypes)var k=e.util.coerceToTypes(e.opts.coerceTypes,P);var x=e.RULES.types[P];if(k||E||!0===x||x&&!G(x)){h=e.schemaPath+".type",p=e.errSchemaPath+"/type",h=e.schemaPath+".type",p=e.errSchemaPath+"/type";var S=E?"checkDataTypes":"checkDataType";if(a+=" if ("+e.util[S](P,m,e.opts.strictNumbers,!0)+") { ",k){var R="dataType"+l,T="coerced"+l;a+=" var "+R+" = typeof "+m+"; var "+T+" = undefined; ","array"==e.opts.coerceTypes&&(a+=" if ("+R+" == 'object' && Array.isArray("+m+") && "+m+".length == 1) { "+m+" = "+m+"[0]; "+R+" = typeof "+m+"; if ("+e.util.checkDataType(e.schema.type,m,e.opts.strictNumbers)+") "+T+" = "+m+"; } "),a+=" if ("+T+" !== undefined) ; ";var $=k;if($)for(var C,O=-1,A=$.length-1;O<A;)"string"==(C=$[O+=1])?a+=" else if ("+R+" == 'number' || "+R+" == 'boolean') "+T+" = '' + "+m+"; else if ("+m+" === null) "+T+" = ''; ":"number"==C||"integer"==C?(a+=" else if ("+R+" == 'boolean' || "+m+" === null || ("+R+" == 'string' && "+m+" && "+m+" == +"+m+" ","integer"==C&&(a+=" && !("+m+" % 1)"),a+=")) "+T+" = +"+m+"; "):"boolean"==C?a+=" else if ("+m+" === 'false' || "+m+" === 0 || "+m+" === null) "+T+" = false; else if ("+m+" === 'true' || "+m+" === 1) "+T+" = true; ":"null"==C?a+=" else if ("+m+" === '' || "+m+" === 0 || "+m+" === false) "+T+" = null; ":"array"==e.opts.coerceTypes&&"array"==C&&(a+=" else if ("+R+" == 'string' || "+R+" == 'number' || "+R+" == 'boolean' || "+m+" == null) "+T+" = ["+m+"]; ");a+=" else { ",(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } if ("+T+" !== undefined) { ";var I=d?"data"+(d-1||""):"parentData";a+=" "+m+" = "+T+"; ",d||(a+="if ("+I+" !== undefined)"),a+=" "+I+"["+(d?e.dataPathArr[d]:"parentDataProperty")+"] = "+T+"; } "}else{(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}a+=" } "}}if(e.schema.$ref&&!o)a+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",f&&(a+=" } if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",b+="}");else{var j=e.RULES;if(j)for(var F=-1,D=j.length-1;F<D;)if(G(x=j[F+=1])){if(x.type&&(a+=" if ("+e.util.checkDataType(x.type,m,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==x.type&&e.schema.properties){u=e.schema.properties;var N=Object.keys(u);if(N)for(var U,L=-1,q=N.length-1;L<q;){if(void 0!==(M=u[U=N[L+=1]]).default){var z=m+e.util.getProperty(U);if(e.compositeRule){if(e.opts.strictDefaults){_="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}}else if("array"==x.type&&Array.isArray(e.schema.items)){var V=e.schema.items;if(V){O=-1;for(var M,Z=V.length-1;O<Z;)if(void 0!==(M=V[O+=1]).default){z=m+"["+O+"]";if(e.compositeRule){if(e.opts.strictDefaults){_="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}}var H=x.rules;if(H)for(var B,Q=-1,K=H.length-1;Q<K;)if(Y(B=H[Q+=1])){var J=B.code(e,B.keyword,x.type);J&&(a+=" "+J+" ",f&&(w+="}"))}if(f&&(a+=" "+w+" ",w=""),x.type&&(a+=" } ",P&&P===x.type&&!k)){a+=" else { ";var W;h=e.schemaPath+".type",p=e.errSchemaPath+"/type";(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } "}f&&(a+=" if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",b+="}")}}function G(e){for(var t=e.rules,r=0;r<t.length;r++)if(Y(t[r]))return!0}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,a=0;a<r.length;a++)if(void 0!==e.schema[r[a]])return!0}(t)}return f&&(a+=" "+b+" "),y?(s?(a+=" if (errors === 0) return data; ",a+=" else throw new ValidationError(vErrors); "):(a+=" validate.errors = vErrors; ",a+=" return errors === 0; "),a+=" }; return validate;"):a+=" var "+v+" = errors === errs_"+l+";",a},Zs=Es,Hs=Ga,Bs=Ls,Qs=Vs,Ks=Ms,Js=Hs.ucs2length,Ws=Wa,Gs=Bs.Validation,Ys=function e(t,r,a,s){var o=this,n=this._opts,i=[void 0],c={},l=[],d={},u=[],h={},p=[];r=r||{schema:t,refVal:i,refs:c};var f=Xs.call(this,t,r,s),m=this._compilations[f.index];if(f.compiling)return m.callValidate=function e(){var t=m.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var v=this._formats,g=this.RULES;try{var y=w(t,r,a,s);m.validate=y;var _=m.callValidate;return _&&(_.schema=y.schema,_.errors=null,_.refs=y.refs,_.refVal=y.refVal,_.root=y.root,_.$async=y.$async,n.sourceCode&&(_.source=y.source)),y}finally{eo.call(this,t,r,s)}function w(t,a,s,d){var h=!a||a&&a.schema==t;if(a.schema!=r.schema)return e.call(o,t,a,s,d);var f,m=!0===t.$async,y=Ks({isTop:!0,schema:t,isRoot:h,baseId:d,root:a,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Bs.MissingRef,RULES:g,validate:Ks,util:Hs,resolve:Zs,resolveRef:b,usePattern:k,useDefault:x,useCustomRule:S,opts:n,formats:v,logger:o.logger,self:o});y=no(i,so)+no(l,ro)+no(u,ao)+no(p,oo)+y,n.processCode&&(y=n.processCode(y,t));try{f=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",y)(o,g,v,r,i,u,p,Ws,Js,Gs),i[0]=f}catch(e){throw o.logger.error("Error compiling schema, function code:",y),e}return f.schema=t,f.errors=null,f.refs=c,f.refVal=i,f.root=h?f:a,m&&(f.$async=!0),!0===n.sourceCode&&(f.source={code:y,patterns:l,defaults:u}),f}function b(t,s,l){s=Zs.url(t,s);var d,u,h=c[s];if(void 0!==h)return E(d=i[h],u="refVal["+h+"]");if(!l&&r.refs){var p=r.refs[s];if(void 0!==p)return E(d=r.refVal[p],u=P(s,d))}u=P(s);var f=Zs.call(o,w,r,s);if(void 0===f){var m=a&&a[s];m&&(f=Zs.inlineRef(m,n.inlineRefs)?m:e.call(o,m,r,a,t))}if(void 0!==f)return function(e,t){var r=c[e];i[r]=t}(s,f),E(f,u);!function(e){delete c[e]}(s)}function P(e,t){var r=i.length;return i[r]=t,c[e]=r,"refVal"+r}function E(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function k(e){var t=d[e];return void 0===t&&(t=d[e]=l.length,l[t]=e),"pattern"+t}function x(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return Hs.toQuotedString(e);case"object":if(null===e)return"null";var t=Qs(e),r=h[t];return void 0===r&&(r=h[t]=u.length,u[r]=e),"default"+r}}function S(e,t,r,a){if(!1!==o._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));var i=e.definition.validateSchema;if(i)if(!i(t)){var c="keyword schema is invalid: "+o.errorsText(i.errors);if("log"!=o._opts.validateSchema)throw new Error(c);o.logger.error(c)}}var l,d=e.definition.compile,u=e.definition.inline,h=e.definition.macro;if(d)l=d.call(o,t,r,a);else if(h)l=h.call(o,t,r,a),!1!==n.validateSchema&&o.validateSchema(l,!0);else if(u)l=u.call(o,a,e.keyword,t,r);else if(!(l=e.definition.validate))return;if(void 0===l)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var f=p.length;return p[f]=l,{code:"customRule"+f,validate:l}}};function Xs(e,t,r){var a=to.call(this,e,t,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:t,baseId:r},{index:a,compiling:!1})}function eo(e,t,r){var a=to.call(this,e,t,r);a>=0&&this._compilations.splice(a,1)}function to(e,t,r){for(var a=0;a<this._compilations.length;a++){var s=this._compilations[a];if(s.schema==e&&s.root==t&&s.baseId==r)return a}return-1}function ro(e,t){return"var pattern"+e+" = new RegExp("+Hs.toQuotedString(t[e])+");"}function ao(e){return"var default"+e+" = defaults["+e+"];"}function so(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function oo(e){return"var customRule"+e+" = customRules["+e+"];"}function no(e,t){if(!e.length)return"";for(var r="",a=0;a<e.length;a++)r+=t(a,e);return r}var io={exports:{}},co=io.exports=function(){this._cache={}};co.prototype.put=function(e,t){this._cache[e]=t},co.prototype.get=function(e){return this._cache[e]},co.prototype.del=function(e){delete this._cache[e]},co.prototype.clear=function(){this._cache={}};var lo=io.exports,uo=Ga,ho=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,po=[0,31,28,31,30,31,30,31,31,30,31,30,31],fo=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,mo=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,vo=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,go=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,yo=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,_o=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,wo=/^(?:\/(?:[^~/]|~0|~1)*)*$/,bo=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Po=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Eo=ko;function ko(e){return e="full"==e?"full":"fast",uo.copy(ko[e])}function xo(e){var t=e.match(ho);if(!t)return!1;var r=+t[1],a=+t[2],s=+t[3];return a>=1&&a<=12&&s>=1&&s<=(2==a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:po[a])}function So(e,t){var r=e.match(fo);if(!r)return!1;var a=r[1],s=r[2],o=r[3],n=r[5];return(a<=23&&s<=59&&o<=59||23==a&&59==s&&60==o)&&(!t||n)}ko.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":go,url:yo,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:mo,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:Co,uuid:_o,"json-pointer":wo,"json-pointer-uri-fragment":bo,"relative-json-pointer":Po},ko.full={date:xo,time:So,"date-time":function(e){var t=e.split(Ro);return 2==t.length&&xo(t[0])&&So(t[1],!0)},uri:function(e){return To.test(e)&&vo.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":go,url:yo,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:mo,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:Co,uuid:_o,"json-pointer":wo,"json-pointer-uri-fragment":bo,"relative-json-pointer":Po};var Ro=/t|\s/i;var To=/\/|:/;var $o=/[^\\]\\Z/;function Co(e){if($o.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}var Oo=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i;var p="maximum"==t,f=p?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[f],v=e.opts.$data&&m&&m.$data,g=p?"<":">",y=p?">":"<",_=void 0;if(!h&&"number"!=typeof i&&void 0!==i)throw new Error(t+" must be number");if(!v&&void 0!==m&&"number"!=typeof m&&"boolean"!=typeof m)throw new Error(f+" must be number or boolean");if(v){var w=e.util.getData(m.$data,n,e.dataPathArr),b="exclusive"+o,P="exclType"+o,E="exclIsNumber"+o,k="' + "+(R="op"+o)+" + '";s+=" var schemaExcl"+o+" = "+w+"; ",s+=" var "+b+"; var "+P+" = typeof "+(w="schemaExcl"+o)+"; if ("+P+" != 'boolean' && "+P+" != 'undefined' && "+P+" != 'number') { ";var x;_=f;(x=x||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var S=s;s=x.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+S+"]); ":s+=" validate.errors = ["+S+"]; return false; ":s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+P+" == 'number' ? ( ("+b+" = "+a+" === undefined || "+w+" "+g+"= "+a+") ? "+u+" "+y+"= "+w+" : "+u+" "+y+" "+a+" ) : ( ("+b+" = "+w+" === true) ? "+u+" "+y+"= "+a+" : "+u+" "+y+" "+a+" ) || "+u+" !== "+u+") { var op"+o+" = "+b+" ? '"+g+"' : '"+g+"='; ",void 0===i&&(_=f,l=e.errSchemaPath+"/"+f,a=w,h=v)}else{k=g;if((E="number"==typeof m)&&h){var R="'"+k+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+m+" "+g+"= "+a+" ? "+u+" "+y+"= "+m+" : "+u+" "+y+" "+a+" ) || "+u+" !== "+u+") { "}else{E&&void 0===i?(b=!0,_=f,l=e.errSchemaPath+"/"+f,a=m,y+="="):(E&&(a=Math[p?"min":"max"](m,i)),m===(!E||a)?(b=!0,_=f,l=e.errSchemaPath+"/"+f,y+="="):(b=!1,k+="="));R="'"+k+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+" "+y+" "+a+" || "+u+" !== "+u+") { "}}_=_||t,(x=x||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { comparison: "+R+", limit: "+a+", exclusive: "+b+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+k+" ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";S=s;return s=x.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+S+"]); ":s+=" validate.errors = ["+S+"]; return false; ":s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { "),s},Ao=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+".length "+("maxItems"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},Io=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");var p="maxLength"==t?">":"<";s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),!1===e.opts.unicode?s+=" "+u+".length ":s+=" ucs2length("+u+") ",s+=" "+p+" "+a+") { ";var f=t,m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==t?"longer":"shorter",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var v=s;return s=m.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},jo=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+u+").length "+("maxProperties"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},Fo={$ref:function(e,t,r){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[t],l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),h="valid"+n;if("#"==c||"#/"==c)e.isRoot?(a=e.async,s="validate"):(a=!0===e.root.schema.$async,s="root.refVal[0]");else{var p=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===p){var f=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(f),(y=y||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(o+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(o+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),o+=" } "):o+=" {} ";var m=o;o=y.pop(),!e.compositeRule&&d?e.async?o+=" throw new ValidationError(["+m+"]); ":o+=" validate.errors = ["+m+"]; return false; ":o+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(o+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,f);e.logger.warn(f),d&&(o+=" if (true) { ")}}else if(p.inline){var v=e.util.copy(e);v.level++;var g="valid"+v.level;v.schema=p.schema,v.schemaPath="",v.errSchemaPath=c,o+=" "+e.validate(v).replace(/validate\.schema/g,p.code)+" ",d&&(o+=" if ("+g+") { ")}else a=!0===p.$async||e.async&&!1!==p.$async,s=p.code}if(s){var y;(y=y||[]).push(o),o="",e.opts.passContext?o+=" "+s+".call(this, ":o+=" "+s+"( ",o+=" "+u+", (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var _=o+=" , "+(i?"data"+(i-1||""):"parentData")+" , "+(i?e.dataPathArr[i]:"parentDataProperty")+", rootData) ";if(o=y.pop(),a){if(!e.async)throw new Error("async schema referenced by sync schema");d&&(o+=" var "+h+"; "),o+=" try { await "+_+"; ",d&&(o+=" "+h+" = true; "),o+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",d&&(o+=" "+h+" = false; "),o+=" } ",d&&(o+=" if ("+h+") { ")}else o+=" if (!"+_+") { if (vErrors === null) vErrors = "+s+".errors; else vErrors = vErrors.concat("+s+".errors); errors = vErrors.length; } ",d&&(o+=" else { ")}return o},allOf:function(e,t,r){var a=" ",s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),n=e.errSchemaPath+"/"+t,i=!e.opts.allErrors,c=e.util.copy(e),l="";c.level++;var d="valid"+c.level,u=c.baseId,h=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m<v;)f=p[m+=1],(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(h=!1,c.schema=f,c.schemaPath=o+"["+m+"]",c.errSchemaPath=n+"/"+m,a+=" "+e.validate(c)+" ",c.baseId=u,i&&(a+=" if ("+d+") { ",l+="}"));return i&&(a+=h?" if (true) { ":" "+l.slice(0,-1)+" "),a},anyOf:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=n.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(v){var g=p.baseId;a+=" var "+h+" = errors; var "+u+" = false; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=n;if(_)for(var w,b=-1,P=_.length-1;b<P;)w=_[b+=1],p.schema=w,p.schemaPath=i+"["+b+"]",p.errSchemaPath=c+"/"+b,a+=" "+e.validate(p)+" ",p.baseId=g,a+=" "+u+" = "+u+" || "+m+"; if (!"+u+") { ",f+="}";e.compositeRule=p.compositeRule=y,a+=" "+f+" if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else l&&(a+=" if (true) { ");return a},$comment:function(e,t,r){var a=" ",s=e.schema[t],o=e.errSchemaPath+"/"+t;e.opts.allErrors;var n=e.util.toQuotedString(s);return!0===e.opts.$comment?a+=" console.log("+n+");":"function"==typeof e.opts.$comment&&(a+=" self._opts.$comment("+n+", "+e.util.toQuotedString(o)+", validate.root.schema);"),a},const:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; "),h||(a+=" var schema"+s+" = validate.schema"+i+";"),a+="var "+u+" = equal("+d+", schema"+s+"); if (!"+u+") { ";var p=p||[];p.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var f=a;return a=p.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+f+"]); ":a+=" validate.errors = ["+f+"]; return false; ":a+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a},contains:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m="i"+s,v=p.dataLevel=e.dataLevel+1,g="data"+v,y=e.baseId,_=e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all);if(a+="var "+h+" = errors;var "+u+";",_){var w=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" var "+f+" = false; for (var "+m+" = 0; "+m+" < "+d+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var b=d+"["+m+"]";p.dataPathArr[v]=m;var P=e.validate(p);p.baseId=y,e.util.varOccurences(P,g)<2?a+=" "+e.util.varReplace(P,g,b)+" ":a+=" var "+g+" = "+b+"; "+P+" ",a+=" if ("+f+") break; } ",e.compositeRule=p.compositeRule=w,a+=" if (!"+f+") {"}else a+=" if ("+d+".length == 0) {";var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var k=a;return a=E.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { ",_&&(a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a},dependencies:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m={},v={},g=e.opts.ownProperties;for(b in n)if("__proto__"!=b){var y=n[b],_=Array.isArray(y)?v:m;_[b]=y}a+="var "+u+" = errors;";var w=e.errorPath;for(var b in a+="var missing"+s+";",v)if((_=v[b]).length){if(a+=" if ( "+d+e.util.getProperty(b)+" !== undefined ",g&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(b)+"') "),l){a+=" && ( ";var P=_;if(P)for(var E=-1,k=P.length-1;E<k;){C=P[E+=1],E&&(a+=" || "),a+=" ( ( "+(j=d+(I=e.util.getProperty(C)))+" === undefined ",g&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(C)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?C:I)+") ) "}a+=")) { ";var x="missing"+s,S="' + "+x+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,x,!0):w+" + "+x);var R=R||[];R.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+S+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var T=a;a=R.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+T+"]); ":a+=" validate.errors = ["+T+"]; return false; ":a+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{a+=" ) { ";var $=_;if($)for(var C,O=-1,A=$.length-1;O<A;){C=$[O+=1];var I=e.util.getProperty(C),j=(S=e.util.escapeQuotes(C),d+I);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,C,e.opts.jsonPointers)),a+=" if ( "+j+" === undefined ",g&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(C)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+S+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}a+=" } ",l&&(p+="}",a+=" else { ")}e.errorPath=w;var F=h.baseId;for(var b in m){y=m[b];(e.opts.strictKeywords?"object"==typeof y&&Object.keys(y).length>0||!1===y:e.util.schemaHasRules(y,e.RULES.all))&&(a+=" "+f+" = true; if ( "+d+e.util.getProperty(b)+" !== undefined ",g&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(b)+"') "),a+=") { ",h.schema=y,h.schemaPath=i+e.util.getProperty(b),h.errSchemaPath=c+"/"+e.util.escapeFragment(b),a+=" "+e.validate(h)+" ",h.baseId=F,a+=" } ",l&&(a+=" if ("+f+") { ",p+="}"))}return l&&(a+=" "+p+" if ("+u+" == errors) {"),a},enum:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var p="i"+s,f="schema"+s;h||(a+=" var "+f+" = validate.schema"+i+";"),a+="var "+u+";",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=u+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+d+", "+f+"["+p+"])) { "+u+" = true; break; }",h&&(a+=" } "),a+=" if (!"+u+") { ";var m=m||[];m.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var v=a;return a=m.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a},format:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||"");if(!1===e.opts.format)return l&&(a+=" if (true) { "),a;var u,h=e.opts.$data&&n&&n.$data;h?(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",u="schema"+s):u=n;var p=e.opts.unknownFormats,f=Array.isArray(p);if(h){a+=" var "+(m="format"+s)+" = formats["+u+"]; var "+(v="isObject"+s)+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+(g="formatType"+s)+" = "+v+" && "+m+".type || 'string'; if ("+v+") { ",e.async&&(a+=" var async"+s+" = "+m+".async; "),a+=" "+m+" = "+m+".validate; } if ( ",h&&(a+=" ("+u+" !== undefined && typeof "+u+" != 'string') || "),a+=" (","ignore"!=p&&(a+=" ("+u+" && !"+m+" ",f&&(a+=" && self._opts.unknownFormats.indexOf("+u+") == -1 "),a+=") || "),a+=" ("+m+" && "+g+" == '"+r+"' && !(typeof "+m+" == 'function' ? ",e.async?a+=" (async"+s+" ? await "+m+"("+d+") : "+m+"("+d+")) ":a+=" "+m+"("+d+") ",a+=" : "+m+".test("+d+"))))) {"}else{var m;if(!(m=e.formats[n])){if("ignore"==p)return e.logger.warn('unknown format "'+n+'" ignored in schema at path "'+e.errSchemaPath+'"'),l&&(a+=" if (true) { "),a;if(f&&p.indexOf(n)>=0)return l&&(a+=" if (true) { "),a;throw new Error('unknown format "'+n+'" is used in schema at path "'+e.errSchemaPath+'"')}var v,g=(v="object"==typeof m&&!(m instanceof RegExp)&&m.validate)&&m.type||"string";if(v){var y=!0===m.async;m=m.validate}if(g!=r)return l&&(a+=" if (true) { "),a;if(y){if(!e.async)throw new Error("async format in sync schema");a+=" if (!(await "+(_="formats"+e.util.getProperty(n)+".validate")+"("+d+"))) { "}else{a+=" if (! ";var _="formats"+e.util.getProperty(n);v&&(_+=".validate"),a+="function"==typeof m?" "+_+"("+d+") ":" "+_+".test("+d+") ",a+=") { "}}var w=w||[];w.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",a+=h?""+u:""+e.util.toQuotedString(n),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=h?"' + "+u+" + '":""+e.util.escapeQuotes(n),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=h?"validate.schema"+i:""+e.util.toQuotedString(n),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var b=a;return a=w.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+b+"]); ":a+=" validate.errors = ["+b+"]; return false; ":a+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",l&&(a+=" else { "),a},if:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m=e.schema.then,v=e.schema.else,g=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),y=void 0!==v&&(e.opts.strictKeywords?"object"==typeof v&&Object.keys(v).length>0||!1===v:e.util.schemaHasRules(v,e.RULES.all)),_=p.baseId;if(g||y){var w;p.createErrors=!1,p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" var "+h+" = errors; var "+u+" = true; ";var b=e.compositeRule;e.compositeRule=p.compositeRule=!0,a+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=b,g?(a+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+u+" = "+f+"; ",g&&y?a+=" var "+(w="ifClause"+s)+" = 'then'; ":w="'then'",a+=" } ",y&&(a+=" else { ")):a+=" if (!"+f+") { ",y&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+u+" = "+f+"; ",g&&y?a+=" var "+(w="ifClause"+s)+" = 'else'; ":w="'else'",a+=" } "),a+=" if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+w+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match \"' + "+w+" + '\" schema' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } ",l&&(a+=" else { ")}else l&&(a+=" if (true) { ");return a},items:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,g=p.dataLevel=e.dataLevel+1,y="data"+g,_=e.baseId;if(a+="var "+h+" = errors;var "+u+";",Array.isArray(n)){var w=e.schema.additionalItems;if(!1===w){a+=" "+u+" = "+d+".length <= "+n.length+"; ";var b=c;c=e.errSchemaPath+"/additionalItems",a+=" if (!"+u+") { ";var P=P||[];P.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+n.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+n.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var E=a;a=P.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+E+"]); ":a+=" validate.errors = ["+E+"]; return false; ":a+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c=b,l&&(f+="}",a+=" else { ")}var k=n;if(k)for(var x,S=-1,R=k.length-1;S<R;)if(x=k[S+=1],e.opts.strictKeywords?"object"==typeof x&&Object.keys(x).length>0||!1===x:e.util.schemaHasRules(x,e.RULES.all)){a+=" "+m+" = true; if ("+d+".length > "+S+") { ";var T=d+"["+S+"]";p.schema=x,p.schemaPath=i+"["+S+"]",p.errSchemaPath=c+"/"+S,p.errorPath=e.util.getPathExpr(e.errorPath,S,e.opts.jsonPointers,!0),p.dataPathArr[g]=S;var $=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,T)+" ":a+=" var "+y+" = "+T+"; "+$+" ",a+=" } ",l&&(a+=" if ("+m+") { ",f+="}")}if("object"==typeof w&&(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))){p.schema=w,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+m+" = true; if ("+d+".length > "+n.length+") { for (var "+v+" = "+n.length+"; "+v+" < "+d+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);T=d+"["+v+"]";p.dataPathArr[g]=v;$=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,T)+" ":a+=" var "+y+" = "+T+"; "+$+" ",l&&(a+=" if (!"+m+") break; "),a+=" } } ",l&&(a+=" if ("+m+") { ",f+="}")}}else if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" for (var "+v+" = 0; "+v+" < "+d+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);T=d+"["+v+"]";p.dataPathArr[g]=v;$=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,T)+" ":a+=" var "+y+" = "+T+"; "+$+" ",l&&(a+=" if (!"+m+") break; "),a+=" }"}return l&&(a+=" "+f+" if ("+h+" == errors) {"),a},maximum:Oo,minimum:Oo,maxItems:Ao,minItems:Ao,maxLength:Io,minLength:Io,maxProperties:jo,minProperties:jo,multipleOf:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="var division"+o+";if (",h&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+o+" = "+u+" / "+a+", ",e.opts.multipleOfPrecision?s+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":s+=" division"+o+" !== parseInt(division"+o+") ",s+=" ) ",h&&(s+=" ) "),s+=" ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},not:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=i,h.errSchemaPath=c,a+=" var "+u+" = errors; ";var f,m=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(f=h.opts.allErrors,h.opts.allErrors=!1),a+=" "+e.validate(h)+" ",h.createErrors=!0,f&&(h.opts.allErrors=f),e.compositeRule=h.compositeRule=m,a+=" if ("+p+") { ";var v=v||[];v.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var g=a;a=v.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(a+=" if (false) { ");return a},oneOf:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=p.baseId,g="prevValid"+s,y="passingSchemas"+s;a+="var "+h+" = errors , "+g+" = false , "+u+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var w=n;if(w)for(var b,P=-1,E=w.length-1;P<E;)b=w[P+=1],(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))?(p.schema=b,p.schemaPath=i+"["+P+"]",p.errSchemaPath=c+"/"+P,a+=" "+e.validate(p)+" ",p.baseId=v):a+=" var "+m+" = true; ",P&&(a+=" if ("+m+" && "+g+") { "+u+" = false; "+y+" = ["+y+", "+P+"]; } else { ",f+="}"),a+=" if ("+m+") { "+u+" = "+g+" = true; "+y+" = "+P+"; }";return e.compositeRule=p.compositeRule=_,a+=f+"if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+y+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a},pattern:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'string') || "),s+=" !"+(h?"(new RegExp("+a+"))":e.usePattern(i))+".test("+u+") ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { pattern: ",s+=h?""+a:""+e.util.toQuotedString(i),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match pattern \"",s+=h?"' + "+a+" + '":""+e.util.escapeQuotes(i),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+e.util.toQuotedString(i),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},properties:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m="key"+s,v="idx"+s,g=h.dataLevel=e.dataLevel+1,y="data"+g,_="dataProperties"+s,w=Object.keys(n||{}).filter(I),b=e.schema.patternProperties||{},P=Object.keys(b).filter(I),E=e.schema.additionalProperties,k=w.length||P.length,x=!1===E,S="object"==typeof E&&Object.keys(E).length,R=e.opts.removeAdditional,T=x||S||R,$=e.opts.ownProperties,C=e.baseId,O=e.schema.required;if(O&&(!e.opts.$data||!O.$data)&&O.length<e.opts.loopRequired)var A=e.util.toHash(O);function I(e){return"__proto__"!==e}if(a+="var "+u+" = errors;var "+f+" = true;",$&&(a+=" var "+_+" = undefined;"),T){if(a+=$?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+d+") { ",k){if(a+=" var isAdditional"+s+" = !(false ",w.length)if(w.length>8)a+=" || validate.schema"+i+".hasOwnProperty("+m+") ";else{var j=w;if(j)for(var F=-1,D=j.length-1;F<D;)J=j[F+=1],a+=" || "+m+" == "+e.util.toQuotedString(J)+" "}if(P.length){var N=P;if(N)for(var U=-1,L=N.length-1;U<L;)oe=N[U+=1],a+=" || "+e.usePattern(oe)+".test("+m+") "}a+=" ); if (isAdditional"+s+") { "}if("all"==R)a+=" delete "+d+"["+m+"]; ";else{var q=e.errorPath,z="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),x)if(R)a+=" delete "+d+"["+m+"]; ";else{a+=" "+f+" = false; ";var V=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+z+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is an invalid additional property":a+="should NOT have additional properties",a+="' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var M=a;a=re.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,l&&(a+=" break; ")}else if(S)if("failing"==R){a+=" var "+u+" = errors; ";var Z=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var H=d+"["+m+"]";h.dataPathArr[g]=m;var B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",a+=" if (!"+f+") { errors = "+u+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+d+"["+m+"]; } ",e.compositeRule=h.compositeRule=Z}else{h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);H=d+"["+m+"]";h.dataPathArr[g]=m;B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",l&&(a+=" if (!"+f+") break; ")}e.errorPath=q}k&&(a+=" } "),a+=" } ",l&&(a+=" if ("+f+") { ",p+="}")}var Q=e.opts.useDefaults&&!e.compositeRule;if(w.length){var K=w;if(K)for(var J,W=-1,G=K.length-1;W<G;){var Y=n[J=K[W+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){var X=e.util.getProperty(J),ee=(H=d+X,Q&&void 0!==Y.default);h.schema=Y,h.schemaPath=i+X,h.errSchemaPath=c+"/"+e.util.escapeFragment(J),h.errorPath=e.util.getPath(e.errorPath,J,e.opts.jsonPointers),h.dataPathArr[g]=e.util.toQuotedString(J);B=e.validate(h);if(h.baseId=C,e.util.varOccurences(B,y)<2){B=e.util.varReplace(B,y,H);var te=H}else{te=y;a+=" var "+y+" = "+H+"; "}if(ee)a+=" "+B+" ";else{if(A&&A[J]){a+=" if ( "+te+" === undefined ",$&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = false; ";q=e.errorPath,V=c;var re,ae=e.util.escapeQuotes(J);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(q,J,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+ae+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+ae+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";M=a;a=re.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,e.errorPath=q,a+=" } else { "}else l?(a+=" if ( "+te+" === undefined ",$&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = true; } else { "):(a+=" if ("+te+" !== undefined ",$&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=" ) { ");a+=" "+B+" } "}}l&&(a+=" if ("+f+") { ",p+="}")}}if(P.length){var se=P;if(se)for(var oe,ne=-1,ie=se.length-1;ne<ie;){Y=b[oe=se[ne+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){h.schema=Y,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(oe),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(oe),a+=$?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+d+") { ",a+=" if ("+e.usePattern(oe)+".test("+m+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);H=d+"["+m+"]";h.dataPathArr[g]=m;B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",l&&(a+=" if (!"+f+") break; "),a+=" } ",l&&(a+=" else "+f+" = true; "),a+=" } ",l&&(a+=" if ("+f+") { ",p+="}")}}}return l&&(a+=" "+p+" if ("+u+" == errors) {"),a},propertyNames:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(a+="var "+u+" = errors;",e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=i,h.errSchemaPath=c;var f="key"+s,m="idx"+s,v="i"+s,g="' + "+f+" + '",y="data"+(h.dataLevel=e.dataLevel+1),_="dataProperties"+s,w=e.opts.ownProperties,b=e.baseId;w&&(a+=" var "+_+" = undefined; "),a+=w?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+f+" = "+_+"["+m+"]; ":" for (var "+f+" in "+d+") { ",a+=" var startErrs"+s+" = errors; ";var P=f,E=e.compositeRule;e.compositeRule=h.compositeRule=!0;var k=e.validate(h);h.baseId=b,e.util.varOccurences(k,y)<2?a+=" "+e.util.varReplace(k,y,P)+" ":a+=" var "+y+" = "+P+"; "+k+" ",e.compositeRule=h.compositeRule=E,a+=" if (!"+p+") { for (var "+v+"=startErrs"+s+"; "+v+"<errors; "+v+"++) { vErrors["+v+"].propertyName = "+f+"; } var err = ",!1!==e.createErrors?(a+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+g+"' } ",!1!==e.opts.messages&&(a+=" , message: 'property name \\'"+g+"\\' is invalid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),l&&(a+=" break; "),a+=" } }"}return l&&(a+=" if ("+u+" == errors) {"),a},required:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var p="schema"+s;if(!h)if(n.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],m=n;if(m)for(var v,g=-1,y=m.length-1;g<y;){v=m[g+=1];var _=e.schema.properties[v];_&&(e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=v)}}else f=n;if(h||f.length){var w=e.errorPath,b=h||f.length>=e.opts.loopRequired,P=e.opts.ownProperties;if(l)if(a+=" var missing"+s+"; ",b){h||(a+=" var "+p+" = validate.schema"+i+"; ");var E="' + "+($="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,$,e.opts.jsonPointers)),a+=" var "+u+" = true; ",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=" for (var "+S+" = 0; "+S+" < "+p+".length; "+S+"++) { "+u+" = "+d+"["+p+"["+S+"]] !== undefined ",P&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", "+p+"["+S+"]) "),a+="; if (!"+u+") break; } ",h&&(a+=" } "),a+=" if (!"+u+") { ",(T=T||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var k=a;a=T.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var x=f;if(x)for(var S=-1,R=x.length-1;S<R;){O=x[S+=1],S&&(a+=" || "),a+=" ( ( "+(F=d+(j=e.util.getProperty(O)))+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:j)+") ) "}a+=") { ";var T;E="' + "+($="missing"+s)+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,$,!0):w+" + "+$),(T=T||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";k=a;a=T.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(b){h||(a+=" var "+p+" = validate.schema"+i+"; ");var $;E="' + "+($="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,$,e.opts.jsonPointers)),h&&(a+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),a+=" for (var "+S+" = 0; "+S+" < "+p+".length; "+S+"++) { if ("+d+"["+p+"["+S+"]] === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", "+p+"["+S+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(a+=" } ")}else{var C=f;if(C)for(var O,A=-1,I=C.length-1;A<I;){O=C[A+=1];var j=e.util.getProperty(O),F=(E=e.util.escapeQuotes(O),d+j);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,O,e.opts.jsonPointers)),a+=" if ( "+F+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=w}else l&&(a+=" if (true) {");return a},uniqueItems:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h="valid"+o,p=e.opts.$data&&i&&i.$data;if(p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,(i||p)&&!1!==e.opts.uniqueItems){p&&(s+=" var "+h+"; if ("+a+" === false || "+a+" === undefined) "+h+" = true; else if (typeof "+a+" != 'boolean') "+h+" = false; else { "),s+=" var i = "+u+".length , "+h+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,m=Array.isArray(f);if(!f||"object"==f||"array"==f||m&&(f.indexOf("object")>=0||f.indexOf("array")>=0))s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+h+" = false; break outer; } } } ";else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ";var v="checkDataType"+(m?"s":"");s+=" if ("+e.util[v](f,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ",p&&(s+=" } "),s+=" if (!"+h+") { ";var g=g||[];g.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var y=s;s=g.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+y+"]); ":s+=" validate.errors = ["+y+"]; return false; ":s+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { ")}else d&&(s+=" if (true) { ");return s},validate:Ms},Do=Fo,No=Ga.toHash,Uo=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],Lo=Ls.MissingRef,qo=function e(t,r,a){var s=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(a=r,r=void 0);var o=n(t).then(function(){var e=s._addSchema(t,void 0,r);return e.validate||i(e)});a&&o.then(function(e){a(null,e)},a);return o;function n(t){var r=t.$schema;return r&&!s.getSchema(r)?e.call(s,{$ref:r},!0):Promise.resolve()}function i(e){try{return s._compile(e)}catch(t){if(t instanceof Lo)return function(t){var a=t.missingSchema;if(l(a))throw new Error("Schema "+a+" is loaded but "+t.missingRef+" cannot be resolved");var o=s._loadingSchemas[a];o||(o=s._loadingSchemas[a]=s._opts.loadSchema(a)).then(c,c);return o.then(function(e){if(!l(a))return n(e).then(function(){l(a)||s.addSchema(e,a,void 0,r)})}).then(function(){return i(e)});function c(){delete s._loadingSchemas[a]}function l(e){return s._refs[e]||s._schemas[e]}}(t);throw t}}};var zo={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0},Vo=zo,Mo={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:Vo.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:Vo.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},Zo=/^[a-z_$][a-z0-9_$-]*$/i,Ho=function(e,t,r){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[t],l=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,h="data"+(i||""),p="valid"+n,f="errs__"+n,m=e.opts.$data&&c&&c.$data;m?(o+=" var schema"+n+" = "+e.util.getData(c.$data,i,e.dataPathArr)+"; ",s="schema"+n):s=c;var v,g,y,_,w,b=this,P="definition"+n,E=b.definition,k="";if(m&&E.$data){w="keywordValidate"+n;var x=E.validateSchema;o+=" var "+P+" = RULES.custom['"+t+"'].definition; var "+w+" = "+P+".validate;"}else{if(!(_=e.useCustomRule(b,c,e.schema,e)))return;s="validate.schema"+l,w=_.code,v=E.compile,g=E.inline,y=E.macro}var S=w+".errors",R="i"+n,T="ruleErr"+n,$=E.async;if($&&!e.async)throw new Error("async keyword in sync schema");if(g||y||(o+=S+" = null;"),o+="var "+f+" = errors;var "+p+";",m&&E.$data&&(k+="}",o+=" if ("+s+" === undefined) { "+p+" = true; } else { ",x&&(k+="}",o+=" "+p+" = "+P+".validateSchema("+s+"); if ("+p+") { ")),g)E.statements?o+=" "+_.validate+" ":o+=" "+p+" = "+_.validate+"; ";else if(y){var C=e.util.copy(e);k="";C.level++;var O="valid"+C.level;C.schema=_.validate,C.schemaPath="";var A=e.compositeRule;e.compositeRule=C.compositeRule=!0;var I=e.validate(C).replace(/validate\.schema/g,w);e.compositeRule=C.compositeRule=A,o+=" "+I}else{(N=N||[]).push(o),o="",o+=" "+w+".call( ",e.opts.passContext?o+="this":o+="self",v||!1===E.schema?o+=" , "+h+" ":o+=" , "+s+" , "+h+" , validate.schema"+e.schemaPath+" ",o+=" , (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var j=i?"data"+(i-1||""):"parentData",F=i?e.dataPathArr[i]:"parentDataProperty",D=o+=" , "+j+" , "+F+" , rootData ) ";o=N.pop(),!1===E.errors?(o+=" "+p+" = ",$&&(o+="await "),o+=D+"; "):o+=$?" var "+(S="customErrors"+n)+" = null; try { "+p+" = await "+D+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+S+" = e.errors; else throw e; } ":" "+S+" = null; "+p+" = "+D+"; "}if(E.modifying&&(o+=" if ("+j+") "+h+" = "+j+"["+F+"];"),o+=""+k,E.valid)u&&(o+=" if (true) { ");else{var N;o+=" if ( ",void 0===E.valid?(o+=" !",o+=y?""+O:""+p):o+=" "+!E.valid+" ",o+=") { ",a=b.keyword,(N=N||[]).push(o),o="",(N=N||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),o+=" } "):o+=" {} ";var U=o;o=N.pop(),!e.compositeRule&&u?e.async?o+=" throw new ValidationError(["+U+"]); ":o+=" validate.errors = ["+U+"]; return false; ":o+=" var err = "+U+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var L=o;o=N.pop(),g?E.errors?"full"!=E.errors&&(o+=" for (var "+R+"="+f+"; "+R+"<errors; "+R+"++) { var "+T+" = vErrors["+R+"]; if ("+T+".dataPath === undefined) "+T+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+T+".schemaPath === undefined) { "+T+'.schemaPath = "'+d+'"; } ',e.opts.verbose&&(o+=" "+T+".schema = "+s+"; "+T+".data = "+h+"; "),o+=" } "):!1===E.errors?o+=" "+L+" ":(o+=" if ("+f+" == errors) { "+L+" } else { for (var "+R+"="+f+"; "+R+"<errors; "+R+"++) { var "+T+" = vErrors["+R+"]; if ("+T+".dataPath === undefined) "+T+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+T+".schemaPath === undefined) { "+T+'.schemaPath = "'+d+'"; } ',e.opts.verbose&&(o+=" "+T+".schema = "+s+"; "+T+".data = "+h+"; "),o+=" } } "):y?(o+=" var err = ",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),o+=" } "):o+=" {} ",o+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?o+=" throw new ValidationError(vErrors); ":o+=" validate.errors = vErrors; return false; ")):!1===E.errors?o+=" "+L+" ":(o+=" if (Array.isArray("+S+")) { if (vErrors === null) vErrors = "+S+"; else vErrors = vErrors.concat("+S+"); errors = vErrors.length; for (var "+R+"="+f+"; "+R+"<errors; "+R+"++) { var "+T+" = vErrors["+R+"]; if ("+T+".dataPath === undefined) "+T+".dataPath = (dataPath || '') + "+e.errorPath+"; "+T+'.schemaPath = "'+d+'"; ',e.opts.verbose&&(o+=" "+T+".schema = "+s+"; "+T+".data = "+h+"; "),o+=" } } else { "+L+" } "),o+=" } ",u&&(o+=" else { ")}return o},Bo=Mo,Qo={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!Zo.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var a=t.type;if(Array.isArray(a))for(var s=0;s<a.length;s++)n(e,a[s],t);else n(e,a,t);var o=t.metaSchema;o&&(t.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(o,!0))}function n(e,t,a){for(var s,o=0;o<r.length;o++){var n=r[o];if(n.type==t){s=n;break}}s||(s={type:t,rules:[]},r.push(s));var i={keyword:e,definition:a,custom:!0,code:Ho,implements:a.implements};s.rules.push(i),r.custom[e]=i}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var a=t[r].rules,s=0;s<a.length;s++)if(a[s].keyword==e){a.splice(s,1);break}return this},validate:function e(t,r){e.errors=null;var a=this._validateKeyword=this._validateKeyword||this.compile(Bo,!0);if(a(t))return!0;if(e.errors=a.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(a.errors));return!1}};var Ko={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},Jo=Ys,Wo=Es,Go=lo,Yo=hs,Xo=Vs,en=Eo,tn=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=No(t),e.types=No(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var a;if("object"==typeof r){var s=Object.keys(r)[0];a=r[s],r=s,a.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:Do[r],implements:a}}),e.all.$comment={keyword:"$comment",code:Do.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=No(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e},rn=function(e,t){for(var r=0;r<t.length;r++){e=JSON.parse(JSON.stringify(e));var a,s=t[r].split("/"),o=e;for(a=1;a<s.length;a++)o=o[s[a]];for(a=0;a<Uo.length;a++){var n=Uo[a],i=o[n];i&&(o[n]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e},an=Ga,sn=un;un.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);r=a.validate||this._compile(a)}var s=r(t);!0!==r.$async&&(this.errors=r.errors);return s},un.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},un.prototype.addSchema=function(e,t,r,a){if(Array.isArray(e)){for(var s=0;s<e.length;s++)this.addSchema(e[s],void 0,r,a);return this}var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");return gn(this,t=Wo.normalizeId(t||o)),this._schemas[t]=this._addSchema(e,r,a,!0),this},un.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},un.prototype.validateSchema=function(e,t){var r=e.$schema;if(void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||function(e){var t=e._opts.meta;return e._opts.defaultMeta="object"==typeof t?e._getId(t)||t:e.getSchema(cn)?cn:void 0,e._opts.defaultMeta}(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,e);if(!a&&t){var s="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(s);this.logger.error(s)}return a},un.prototype.getSchema=function(e){var t=hn(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=Wo.schema.call(e,{schema:{}},t);if(r){var a=r.schema,s=r.root,o=r.baseId,n=Jo.call(e,a,s,void 0,o);return e._fragments[t]=new Yo({ref:t,fragment:!0,schema:a,root:s,baseId:o,validate:n}),n}}(this,e)}},un.prototype.removeSchema=function(e){if(e instanceof RegExp)return pn(this,this._schemas,e),pn(this,this._refs,e),this;switch(typeof e){case"undefined":return pn(this,this._schemas),pn(this,this._refs),this._cache.clear(),this;case"string":var t=hn(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,a=r?r(e):e;this._cache.del(a);var s=this._getId(e);s&&(s=Wo.normalizeId(s),delete this._schemas[s],delete this._refs[s])}return this},un.prototype.addFormat=function(e,t){"string"==typeof t&&(t=new RegExp(t));return this._formats[e]=t,this},un.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,a=void 0===t.dataVar?"data":t.dataVar,s="",o=0;o<e.length;o++){var n=e[o];n&&(s+=a+n.dataPath+" "+n.message+r)}return s.slice(0,-r.length)},un.prototype._addSchema=function(e,t,r,a){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var s=this._opts.serialize,o=s?s(e):e,n=this._cache.get(o);if(n)return n;a=a||!1!==this._opts.addUsedSchema;var i=Wo.normalizeId(this._getId(e));i&&a&&gn(this,i);var c,l=!1!==this._opts.validateSchema&&!t;l&&!(c=i&&i==Wo.normalizeId(e.$schema))&&this.validateSchema(e,!0);var d=Wo.ids.call(this,e),u=new Yo({id:i,schema:e,localRefs:d,cacheKey:o,meta:r});"#"!=i[0]&&a&&(this._refs[i]=u);this._cache.put(o,u),l&&c&&this.validateSchema(e,!0);return u},un.prototype._compile=function(e,t){if(e.compiling)return e.validate=s,s.schema=e.schema,s.errors=null,s.root=t||s,!0===e.schema.$async&&(s.$async=!0),s;var r,a;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{a=Jo.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=a,e.refs=a.refs,e.refVal=a.refVal,e.root=a.root,a;function s(){var t=e.validate,r=t.apply(this,arguments);return s.errors=t.errors,r}},un.prototype.compileAsync=qo;var on=Qo;un.prototype.addKeyword=on.add,un.prototype.getKeyword=on.get,un.prototype.removeKeyword=on.remove,un.prototype.validateKeyword=on.validate;var nn=Ls;un.ValidationError=nn.Validation,un.MissingRefError=nn.MissingRef,un.$dataMetaSchema=rn;var cn="http://json-schema.org/draft-07/schema",ln=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],dn=["/properties"];function un(e){if(!(this instanceof un))return new un(e);e=this._opts=an.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:yn,warn:yn,error:yn};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=en(e.format),this._cache=e.cache||new Go,this._loadingSchemas={},this._compilations=[],this.RULES=tn(),this._getId=function(e){switch(e.schemaId){case"auto":return vn;case"id":return fn;default:return mn}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=Xo),this._metaOpts=function(e){for(var t=an.copy(e._opts),r=0;r<ln.length;r++)delete t[ln[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;e._opts.$data&&(t=Ko,e.addMetaSchema(t,t.$id,!0));if(!1===e._opts.meta)return;var r=zo;e._opts.$data&&(r=rn(r,dn));e.addMetaSchema(r,cn,!0),e._refs["http://json-schema.org/schema"]=cn}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(!t)return;if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function hn(e,t){return t=Wo.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function pn(e,t,r){for(var a in t){var s=t[a];s.meta||r&&!r.test(a)||(e._cache.del(s.cacheKey),delete t[a])}}function fn(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function mn(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function vn(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function gn(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function yn(){}var _n=Qa(sn);class wn extends Ba{constructor(e,t){var r;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._ajv=new _n}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapability(e,t){var r;if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:dr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Nr,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!ur.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,r,a,s,o;switch(e){case"logging/setLevel":if(!(null===(t=this._serverCapabilities)||void 0===t?void 0:t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null===(a=this._serverCapabilities)||void 0===a?void 0:a.resources))throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(null===(s=this._serverCapabilities)||void 0===s?void 0:s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null===(o=this._serverCapabilities)||void 0===o?void 0:o.completions))throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var t;if("notifications/roots/list_changed"===e)if(!(null===(t=this._capabilities.roots)||void 0===t?void 0:t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:"ping"},Cr,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},qa,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Cr,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},ga,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},la,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Gr,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Xr,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ta,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Cr,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Cr,t)}async callTool(e,t=Ea,r){const a=await this.request({method:"tools/call",params:e},t,r),s=this.getToolOutputValidator(e.name);if(s){if(!a.structuredContent&&!a.isError)throw new Ha(Rr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent)try{if(!s(a.structuredContent))throw new Ha(Rr.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(e){if(e instanceof Ha)throw e;throw new Ha(Rr.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return a}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const t of e)if(t.outputSchema)try{const e=this._ajv.compile(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Pa,t);return this.cacheToolOutputSchemas(r.tools),r}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}const bn=ar({resource:Gt().url(),authorization_servers:rr(Gt().url()).optional(),jwks_uri:Gt().url().optional(),scopes_supported:rr(Gt()).optional(),bearer_methods_supported:rr(Gt()).optional(),resource_signing_alg_values_supported:rr(Gt()).optional(),resource_name:Gt().optional(),resource_documentation:Gt().optional(),resource_policy_uri:Gt().url().optional(),resource_tos_uri:Gt().url().optional(),tls_client_certificate_bound_access_tokens:Xt().optional(),authorization_details_types_supported:rr(Gt()).optional(),dpop_signing_alg_values_supported:rr(Gt()).optional(),dpop_bound_access_tokens_required:Xt().optional()}).passthrough(),Pn=ar({issuer:Gt(),authorization_endpoint:Gt(),token_endpoint:Gt(),registration_endpoint:Gt().optional(),scopes_supported:rr(Gt()).optional(),response_types_supported:rr(Gt()),response_modes_supported:rr(Gt()).optional(),grant_types_supported:rr(Gt()).optional(),token_endpoint_auth_methods_supported:rr(Gt()).optional(),token_endpoint_auth_signing_alg_values_supported:rr(Gt()).optional(),service_documentation:Gt().optional(),revocation_endpoint:Gt().optional(),revocation_endpoint_auth_methods_supported:rr(Gt()).optional(),revocation_endpoint_auth_signing_alg_values_supported:rr(Gt()).optional(),introspection_endpoint:Gt().optional(),introspection_endpoint_auth_methods_supported:rr(Gt()).optional(),introspection_endpoint_auth_signing_alg_values_supported:rr(Gt()).optional(),code_challenge_methods_supported:rr(Gt()).optional()}).passthrough(),En=ar({issuer:Gt(),authorization_endpoint:Gt(),token_endpoint:Gt(),userinfo_endpoint:Gt().optional(),jwks_uri:Gt(),registration_endpoint:Gt().optional(),scopes_supported:rr(Gt()).optional(),response_types_supported:rr(Gt()),response_modes_supported:rr(Gt()).optional(),grant_types_supported:rr(Gt()).optional(),acr_values_supported:rr(Gt()).optional(),subject_types_supported:rr(Gt()),id_token_signing_alg_values_supported:rr(Gt()),id_token_encryption_alg_values_supported:rr(Gt()).optional(),id_token_encryption_enc_values_supported:rr(Gt()).optional(),userinfo_signing_alg_values_supported:rr(Gt()).optional(),userinfo_encryption_alg_values_supported:rr(Gt()).optional(),userinfo_encryption_enc_values_supported:rr(Gt()).optional(),request_object_signing_alg_values_supported:rr(Gt()).optional(),request_object_encryption_alg_values_supported:rr(Gt()).optional(),request_object_encryption_enc_values_supported:rr(Gt()).optional(),token_endpoint_auth_methods_supported:rr(Gt()).optional(),token_endpoint_auth_signing_alg_values_supported:rr(Gt()).optional(),display_values_supported:rr(Gt()).optional(),claim_types_supported:rr(Gt()).optional(),claims_supported:rr(Gt()).optional(),service_documentation:Gt().optional(),claims_locales_supported:rr(Gt()).optional(),ui_locales_supported:rr(Gt()).optional(),claims_parameter_supported:Xt().optional(),request_parameter_supported:Xt().optional(),request_uri_parameter_supported:Xt().optional(),require_request_uri_registration:Xt().optional(),op_policy_uri:Gt().optional(),op_tos_uri:Gt().optional()}).passthrough().merge(Pn.pick({code_challenge_methods_supported:!0})),kn=ar({access_token:Gt(),id_token:Gt().optional(),token_type:Gt(),expires_in:Yt().optional(),scope:Gt().optional(),refresh_token:Gt().optional()}).strip(),xn=ar({error:Gt(),error_description:Gt().optional(),error_uri:Gt().optional()}),Sn=ar({redirect_uris:rr(Gt()).refine(e=>e.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:Gt().optional(),grant_types:rr(Gt()).optional(),response_types:rr(Gt()).optional(),client_name:Gt().optional(),client_uri:Gt().optional(),logo_uri:Gt().optional(),scope:Gt().optional(),contacts:rr(Gt()).optional(),tos_uri:Gt().optional(),policy_uri:Gt().optional(),jwks_uri:Gt().optional(),jwks:er().optional(),software_id:Gt().optional(),software_version:Gt().optional(),software_statement:Gt().optional()}).strip(),Rn=ar({client_id:Gt(),client_secret:Gt().optional(),client_id_issued_at:Yt().optional(),client_secret_expires_at:Yt().optional()}).strip(),Tn=Sn.merge(Rn);ar({error:Gt(),error_description:Gt().optional()}).strip(),ar({token:Gt(),token_type_hint:Gt().optional()}).strip();class $n extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Cn extends $n{}Cn.errorCode="invalid_request";class On extends $n{}On.errorCode="invalid_client";class An extends $n{}An.errorCode="invalid_grant";class In extends $n{}In.errorCode="unauthorized_client";class jn extends $n{}jn.errorCode="unsupported_grant_type";class Fn extends $n{}Fn.errorCode="invalid_scope";class Dn extends $n{}Dn.errorCode="access_denied";class Nn extends $n{}Nn.errorCode="server_error";class Un extends $n{}Un.errorCode="temporarily_unavailable";class Ln extends $n{}Ln.errorCode="unsupported_response_type";class qn extends $n{}qn.errorCode="unsupported_token_type";class zn extends $n{}zn.errorCode="invalid_token";class Vn extends $n{}Vn.errorCode="method_not_allowed";class Mn extends $n{}Mn.errorCode="too_many_requests";class Zn extends $n{}Zn.errorCode="invalid_client_metadata";class Hn extends $n{}Hn.errorCode="insufficient_scope";const Bn={[Cn.errorCode]:Cn,[On.errorCode]:On,[An.errorCode]:An,[In.errorCode]:In,[jn.errorCode]:jn,[Fn.errorCode]:Fn,[Dn.errorCode]:Dn,[Nn.errorCode]:Nn,[Un.errorCode]:Un,[Ln.errorCode]:Ln,[qn.errorCode]:qn,[zn.errorCode]:zn,[Vn.errorCode]:Vn,[Mn.errorCode]:Mn,[Zn.errorCode]:Zn,[Hn.errorCode]:Hn};class Qn extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function Kn(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Jn(e,t,r,a){const{client_id:s,client_secret:o}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${a}`)}(s,o,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(s,o,a);case"none":return void function(e,t){t.set("client_id",e)}(s,a);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function Wn(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=xn.parse(JSON.parse(r)),{error:t,error_description:a,error_uri:s}=e;return new(Bn[t]||Nn)(a||"",s)}catch(e){return new Nn(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function Gn(e,t){var r,a;try{return await Yn(e,t)}catch(s){if(s instanceof On||s instanceof In)return await(null===(r=e.invalidateCredentials)||void 0===r?void 0:r.call(e,"all")),await Yn(e,t);if(s instanceof An)return await(null===(a=e.invalidateCredentials)||void 0===a?void 0:a.call(e,"tokens")),await Yn(e,t);throw s}}async function Yn(e,{serverUrl:t,authorizationCode:r,scope:a,resourceMetadataUrl:s,fetchFn:o}){let n,i;try{n=await async function(e,t,r=fetch){const a=await async function(e,t,r,a){var s,o;const n=new URL(e),i=null!==(s=null==a?void 0:a.protocolVersion)&&void 0!==s?s:dr;let c;if(null==a?void 0:a.metadataUrl)c=new URL(a.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,n.pathname);c=new URL(e,null!==(o=null==a?void 0:a.metadataServerUrl)&&void 0!==o?o:n),c.search=n.search}let l=await ei(c,i,r);if(!(null==a?void 0:a.metadataUrl)&&function(e,t){return!e||404===e.status&&"/"!==t}(l,n.pathname)){const e=new URL(`/.well-known/${t}`,n);l=await ei(e,i,r)}return l}(e,"oauth-protected-resource",r,{protocolVersion:null==t?void 0:t.protocolVersion,metadataUrl:null==t?void 0:t.resourceMetadataUrl});if(!a||404===a.status)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return bn.parse(await a.json())}(t,{resourceMetadataUrl:s},o),n.authorization_servers&&n.authorization_servers.length>0&&(i=n.authorization_servers[0])}catch(e){}i||(i=t);const c=await async function(e,t,r){const a=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(a,null==r?void 0:r.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),a="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==a.origin)return!1;if(r.pathname.length<a.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return s.startsWith(o)}({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}(t,e,n),l=await async function(e,{fetchFn:t=fetch,protocolVersion:r=dr}={}){var a;const s={"MCP-Protocol-Version":r},o=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),a;let s=t.pathname;s.endsWith("/")&&(s=s.slice(0,-1));return a.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"}),a.push({url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),a}(e);for(const{url:e,type:r}of o){const o=await Xn(e,s,t);if(!o)throw new Error(`CORS error trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`);if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}if("oauth"===r)return Pn.parse(await o.json());{const t=En.parse(await o.json());if(!(null===(a=t.code_challenge_methods_supported)||void 0===a?void 0:a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}return}(i,{fetchFn:o});let d=await Promise.resolve(e.clientInformation());if(!d){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:a}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const o=await(null!=a?a:fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Wn(o);return Tn.parse(await o.json())}(i,{metadata:l,clientMetadata:e.clientMetadata});await e.saveClientInformation(t),d=t}if(void 0!==r){const t=await e.codeVerifier(),a=await async function(e,{metadata:t,clientInformation:r,authorizationCode:a,codeVerifier:s,redirectUri:o,resource:n,addClientAuthentication:i,fetchFn:c}){var l;const d="authorization_code",u=(null==t?void 0:t.token_endpoint)?new URL(t.token_endpoint):new URL("/token",e);if((null==t?void 0:t.grant_types_supported)&&!t.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:d,code:a,code_verifier:s,redirect_uri:String(o)});if(i)i(h,p,e,t);else{Jn(Kn(r,null!==(l=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==l?l:[]),r,h,p)}n&&p.set("resource",n.href);const f=await(null!=c?c:fetch)(u,{method:"POST",headers:h,body:p});if(!f.ok)throw await Wn(f);return kn.parse(await f.json())}(i,{metadata:l,clientInformation:d,authorizationCode:r,codeVerifier:t,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(a),"AUTHORIZED"}const u=await e.tokens();if(null==u?void 0:u.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:a,resource:s,addClientAuthentication:o,fetchFn:n}){var i;const c="refresh_token";let l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),u=new URLSearchParams({grant_type:c,refresh_token:a});if(o)o(d,u,e,t);else{Jn(Kn(r,null!==(i=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==i?i:[]),r,d,u)}s&&u.set("resource",s.href);const h=await(null!=n?n:fetch)(l,{method:"POST",headers:d,body:u});if(!h.ok)throw await Wn(h);return kn.parse({refresh_token:a,...await h.json()})}(i,{metadata:l,clientInformation:d,refreshToken:u.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof $n&&!(e instanceof Nn))throw e}const h=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:m}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:a,scope:s,state:o,resource:n}){const i="code",c="S256";let l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL("/authorize",e);const d=await p(),u=d.code_verifier,h=d.code_challenge;l.searchParams.set("response_type",i),l.searchParams.set("client_id",r.client_id),l.searchParams.set("code_challenge",h),l.searchParams.set("code_challenge_method",c),l.searchParams.set("redirect_uri",String(a)),o&&l.searchParams.set("state",o);s&&l.searchParams.set("scope",s);(null==s?void 0:s.includes("offline_access"))&&l.searchParams.append("prompt","consent");n&&l.searchParams.set("resource",n.href);return{authorizationUrl:l,codeVerifier:u}}(i,{metadata:l,clientInformation:d,state:h,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(f),"REDIRECT"}async function Xn(e,t,r=fetch){try{return await r(e,{headers:t})}catch(a){if(a instanceof TypeError)return t?Xn(e,void 0,r):void 0;throw a}}async function ei(e,t,r=fetch){const a={"MCP-Protocol-Version":t};return await Xn(e,a,r)}class ti extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function ri(e){}function ai(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ri,onError:r=ri,onRetry:a=ri,onComment:s}=e;let o,n="",i=!0,c="",l="";function d(e){if(""===e)return c.length>0&&t({id:o,event:l||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),o=void 0,c="",void(l="");if(e.startsWith(":"))return void(s&&s(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),a=" "===e[r+1]?2:1;return void u(t,e.slice(r+a),e)}u(e,"",e)}function u(e,t,s){switch(e){case"event":l=t;break;case"data":c=`${c}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?a(parseInt(t,10)):r(new ti(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:s}));break;default:r(new ti(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:s}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,a]=function(e){const t=[];let r="",a=0;for(;a<e.length;){const s=e.indexOf("\r",a),o=e.indexOf("\n",a);let n=-1;if(-1!==s&&-1!==o?n=Math.min(s,o):-1!==s?n=s:-1!==o&&(n=o),-1===n){r=e.slice(a);break}{const r=e.slice(a,n);t.push(r),a=n+1,"\r"===e[a-1]&&"\n"===e[a]&&a++}}return[t,r]}(`${n}${t}`);for(const e of r)d(e);n=a,i=!1},reset:function(e={}){n&&e.consume&&d(n),i=!0,o=void 0,c="",l="",n=""}}}class si extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let a;super({start(s){a=ai({onEvent:e=>{s.enqueue(e)},onError(t){"terminate"===e?s.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){a.feed(e)}})}}const oi={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class ni extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class ii{constructor(e,t){var r;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==t?void 0:t.requestInit,this._authProvider=null==t?void 0:t.authProvider,this._fetch=null==t?void 0:t.fetch,this._sessionId=null==t?void 0:t.sessionId,this._reconnectionOptions=null!==(r=null==t?void 0:t.reconnectionOptions)&&void 0!==r?r:oi}async _authThenStart(){var e;if(!this._authProvider)throw new Qn("No auth provider");let t;try{t=await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw null===(e=this.onerror)||void 0===e||e.call(this,t),t}if("AUTHORIZED"!==t)throw new Qn;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const t={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(t.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders(null===(e=this._requestInit)||void 0===e?void 0:e.headers);return new Headers({...t,...r})}async _startOrAuthSse(e){var t,r,a;const{resumptionToken:s}=e;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);const o=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,{method:"GET",headers:a,signal:null===(r=this._abortController)||void 0===r?void 0:r.signal});if(!o.ok){if(401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new ni(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw null===(a=this.onerror)||void 0===a||a.call(this,e),e}}_getNextReconnectionDelay(e){const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),a)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var r;const a=this._reconnectionOptions.maxRetries;if(a>0&&t>=a)return void(null===(r=this.onerror)||void 0===r||r.call(this,new Error(`Maximum reconnection attempts (${a}) exceeded.`)));const s=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var a;null===(a=this.onerror)||void 0===a||a.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},s)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:a,replayMessageId:s}=t;let o;(async()=>{var t,n,i,c;try{const r=e.pipeThrough(new TextDecoderStream).pipeThrough(new si).getReader();for(;;){const{value:e,done:i}=await r.read();if(i)break;if(e.id&&(o=e.id,null==a||a(e.id)),!e.event||"message"===e.event)try{const r=$r.parse(JSON.parse(e.data));void 0!==s&&Sr(r)&&(r.id=s),null===(t=this.onmessage)||void 0===t||t.call(this,r)}catch(e){null===(n=this.onerror)||void 0===n||n.call(this,e)}}}catch(e){if(null===(i=this.onerror)||void 0===i||i.call(this,new Error(`SSE stream disconnected: ${e}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:a,replayMessageId:s},0)}catch(e){null===(c=this.onerror)||void 0===c||c.call(this,new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Qn("No auth provider");if("AUTHORIZED"!==await Gn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new Qn("Failed to authorize")}async close(){var e,t;null===(e=this._abortController)||void 0===e||e.abort(),null===(t=this.onclose)||void 0===t||t.call(this)}async send(e,t){var r,a,s,o,n;try{const{resumptionToken:o,onresumptiontoken:i}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:Er(e)?e.id:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)});const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const l={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:null===(r=this._abortController)||void 0===r?void 0:r.signal},d=await(null!==(a=this._fetch)&&void 0!==a?a:fetch)(this._url,l),u=d.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!d.ok){if(401===d.status&&this._authProvider){this._resourceMetadataUrl=function(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[r,a]=t.split(" ");if("bearer"!==r.toLowerCase()||!a)return;const s=/resource_metadata="([^"]*)"/.exec(t);if(s)try{return new URL(s[1])}catch(e){return}}(d);if("AUTHORIZED"!==await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new Qn;return this.send(e)}const t=await d.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${t}`)}if(202===d.status)return n=e,void(Ur.safeParse(n).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)}));const h=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,p=d.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:i},!1);else{if(!(null==p?void 0:p.includes("application/json")))throw new ni(-1,`Unexpected content type: ${p}`);{const e=await d.json(),t=Array.isArray(e)?e.map(e=>$r.parse(e)):[$r.parse(e)];for(const e of t)null===(s=this.onmessage)||void 0===s||s.call(this,e)}}}catch(e){throw null===(o=this.onerror)||void 0===o||o.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,r;if(this._sessionId)try{const r=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:r,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal},s=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,a);if(!s.ok&&405!==s.status)throw new ni(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(e){throw null===(r=this.onerror)||void 0===r||r.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}const ci=M("quickstart");async function li(r={}){if(!A)throw new Error("Interactive login is only available in Node.js environment");ci.info("Starting interactive login flow");const a=D(),{authDomain:s=a.authDomain,clientId:o=a.clientId,clientSecret:n=a.clientSecret,audience:i=a.apiAudience,apiBaseUrl:c=a.apiBaseUrl,port:l=52765}=r;if(!o||!n)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const d=await pe();if(d)try{let e;L(d)?e=N(d):(ci.warn("Cached token has no organization information, using static config"),e=D());const t=new K(e.apiBaseUrl,{token:d});return await t.validateCachedToken(),ci.info("Using cached valid token"),t}catch(e){ci.info("Cached token invalid, starting OAuth flow")}else ci.info("No cached token, starting OAuth flow");const u="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let p,f=null;if(u){p=`http://${process.env&&process.env.BARNDOOR_REDIRECT_HOST||"localhost"}:${l}/cb`}else{const e=Y(l);p=e[0],f=e[1]}const m=new J,v=await m.buildAuthorizationUrl({domain:s,clientId:o,redirectUri:p,audience:i});ci.info(`Auth URL: ${v}`);const g=t.platform();let y,_;try{y=new URL(v)}catch{throw new Error("Invalid auth URL")}if("https:"!==y.protocol&&("http:"!==y.protocol||"localhost"!==y.hostname&&"127.0.0.1"!==y.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===g?e("open",[v],{detached:!0,stdio:"ignore"}).unref():"win32"===g?e("powershell",["-NoProfile","Start-Process",v],{detached:!0,stdio:"ignore"}).unref():e("xdg-open",[v],{detached:!0,stdio:"ignore"}).unref(),ci.info("Please complete login in your browser…")}catch(e){ci.warn("Failed to open browser automatically. Please visit:",v)}if(u){const e=await new Promise(e=>{const t=h.createInterface({input:process.stdin,output:process.stdout});t.question("Paste the full redirected URL (or just the code= value): ",r=>{t.close(),e(r.trim())})});try{const t=new URL(e);_=t.searchParams.get("code")||e}catch{_=e}}else{_=(await f)[0]}const w=await m.exchangeCodeForToken({domain:s,clientId:o,clientSecret:n,code:_,redirectUri:p});let b;return await fe(w),L(w.access_token)?b=N(w.access_token):(ci.warn("New token has no organization information, using static config"),b=D()),new K(b.apiBaseUrl,{token:w.access_token})}async function di(e,t,r={}){const{timeout:a=90}=r;ci.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:a}),ci.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof P?ci.error(`Server '${t}' not found`):ci.error(`Failed to connect to ${t}:`,e),e}}async function ui(e,t,r={}){const{serverId:a,serverSlug:s,proxyBaseUrl:o="http://proxy-ingress:8080",transport:n="streamable-http"}=r,i=a||s||t;try{await e.getServer(i)}catch(e){if(e instanceof b&&404===e.statusCode)throw new P(i);throw e}const c=(A?process.env.BARNDOOR_ENV||process.env.MODE:"")||"localdev";let l;if(["localdev","local","development","dev"].includes(c.toLowerCase()))if(L(e.token)){l=`${N(e.token).mcpBaseUrl}/mcp/${i}`}else{ci.warn("Token has no organization information, using static config for MCP connection");l=`${D().mcpBaseUrl}/mcp/${i}`}else if(L(e.token)){l=`${N(e.token).mcpBaseUrl}/mcp/${i}`}else{ci.warn("Token has no organization information, using static config for MCP connection");l=`${D().mcpBaseUrl}/mcp/${i}`}return[{url:l,transport:n,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":pi()}},l]}async function hi(e,t,r={}){const[a]=await ui(e,t,r),s=a,o=new wn({name:"barndoor-js-sdk",version:"0.1.0"}),n=new ii(new URL(s.url),{requestInit:{headers:s.headers}});return await o.connect(n),o}function pi(){if(A&&"function"==typeof r.randomUUID)return r.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(A&&"function"==typeof r.randomBytes)e=r.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const a=t[6],s=t[8];t[6]=15&a|64,t[8]=63&s|128;const o=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${o.substring(0,8)}-${o.substring(8,12)}-${o.substring(12,16)}-${o.substring(16,20)}-${o.substring(20)}`}const fi=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=o(import.meta.url),t=i(e),r=c(t,"..","package.json");return JSON.parse(f(r,"utf8")).version}return'"0.3.0"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();export{C as AgentToken,v as AuthenticationError,j as BarndoorConfig,m as BarndoorError,K as BarndoorSDK,k as ConfigurationError,w as ConnectionError,b as HTTPError,ae as JWTVerificationResult,E as OAuthError,J as PKCEManager,$ as ServerDetail,P as ServerNotFoundError,T as ServerSummary,x as TimeoutError,g as TokenError,y as TokenExpiredError,he as TokenManager,_ as TokenValidationError,U as checkTokenOrganization,me as clearCachedToken,M as createScopedLogger,Z as debug,di as ensureServerConnected,Q as error,N as getDynamicConfig,V as getLogger,D as getStaticConfig,L as hasOrganizationInfo,H as info,O as isBrowser,A as isNode,ve as isTokenActive,ge as isTokenActiveWithRefresh,pe as loadUserToken,li as loginInteractive,hi as makeMcpClient,ui as makeMcpConnectionParams,fe as saveUserToken,z as setLogger,ee as setTokenLogger,Y as startLocalCallbackServer,ye as validateToken,de as verifyJWTLocal,fi as version,B as warn};