@merit-systems/echo-react-sdk 1.0.18 → 1.0.19

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.
@@ -1,3 +1,3 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).EchoReactSDK={},e.jsxRuntime,e.React)}(this,(function(e,t,n){"use strict";var r,o=Object.defineProperty,i=(e,t,n)=>((e,t,n)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class s extends Error{}function a(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(n){return atob(t)}}s.prototype.name="InvalidTokenError";var u,l,c,d={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},p=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(p||{});(c=p||(p={})).reset=function(){u=3,l=d},c.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");u=e},c.setLogger=function(e){l=e};var m=class e{constructor(e){this._name=e}debug(...t){u>=4&&l.debug(e._format(this._name,this._method),...t)}info(...t){u>=3&&l.info(e._format(this._name,this._method),...t)}warn(...t){u>=2&&l.warn(e._format(this._name,this._method),...t)}error(...t){u>=1&&l.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,n){const r=new e(`${t}.${n}`);return r.debug("begin"),r}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){u>=4&&l.debug(e._format(t),...n)}static info(t,...n){u>=3&&l.info(e._format(t),...n)}static warn(t,...n){u>=2&&l.warn(e._format(t),...n)}static error(t,...n){u>=1&&l.error(e._format(t),...n)}};p.reset();var _=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new s("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,r=e.split(".")[n];if("string"!=typeof r)throw new s(`Invalid token specified: missing part #${n+1}`);let o;try{o=a(r)}catch(i){throw new s(`Invalid token specified: invalid base64 for part #${n+1} (${i.message})`)}try{return JSON.parse(o)}catch(i){throw new s(`Invalid token specified: invalid json for part #${n+1} (${i.message})`)}}(e)}catch(t){throw m.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,n){const r=`${f.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${f.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,(new TextEncoder).encode(r));return`${r}.${f.encodeBase64Url(new Uint8Array(o))}`}},h=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),g=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return h(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw m.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const n=(new TextEncoder).encode([e,t].join(":"));return h(n)}static async hash(e,t){const n=(new TextEncoder).encode(t),r=await crypto.subtle.digest(e,n);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":n={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const r=await e.hash("SHA-256",JSON.stringify(n));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:r,keyPair:o,nonce:i}){let s,a;const u={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};n&&(s=await e.hash("SHA-256",n),a=e.encodeBase64Url(s),u.ath=a),i&&(u.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",o.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await _.generateSignedJwt(t,u,o.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const n=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(n)}catch(n){throw n instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${n.message}`):n}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};g.encodeBase64Url=e=>h(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var f=g,v=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new m(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},y=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},b=class e extends v{constructor(){super(...arguments),this._logger=new m(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const n=this._logger.create("init");t=Math.max(Math.floor(t),1);const r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle)return void n.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),n.debug("using duration",t),this._expiration=r;const o=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*o)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},k=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},w=";",x=class extends Error{constructor(e,t){var n,r,o;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw m.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(r=e.error_uri)?r:null,this.state=e.userState,this.session_state=null!=(o=e.session_state)?o:null,this.url_state=e.url_state}},I=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},S=class{constructor(e){this._logger=new m("AccessTokenEvents"),this._expiringTimer=new b("Access token expiring"),this._expiredTimer=new b("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const r=n+1;t.debug("registering expired timer, raising in",r,"seconds"),this._expiredTimer.init(r)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},$=class{constructor(e,t,n,r,o){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=o,this._logger=new m("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const i=new URL(n);this._frame_origin=i.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=i.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},O=class{constructor(){this._logger=new m("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},E=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},T=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new m("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...r}=t;if(!n)return await fetch(e,r);const o=new AbortController,i=setTimeout((()=>o.abort()),1e3*n);try{return await fetch(e,{...t,signal:o.signal})}catch(s){if(s instanceof DOMException&&"AbortError"===s.name)throw new I("Network timed out");throw s}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){const o=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let s;t&&(o.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{o.debug("url:",e),s=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:r,credentials:n})}catch(l){throw o.error("Network Error"),l}o.debug("HTTP response received, status",s.status);const a=s.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&o.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),s.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let u;try{u=await s.json()}catch(l){if(o.error("Error parsing JSON response",l),s.ok)throw l;throw new Error(`${s.statusText} (${s.status})`)}if(!s.ok){if(o.error("Error from server:",u),u.error)throw new x(u);throw new Error(`${s.statusText} (${s.status}): ${JSON.stringify(u)}`)}return u}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:o,extraHeaders:i}){const s=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let u;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{s.debug("url:",e),u=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:r,credentials:o})}catch(p){throw s.error("Network error"),p}s.debug("HTTP response received, status",u.status);const l=u.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const c=await u.text();let d={};if(c)try{d=JSON.parse(c)}catch(p){if(s.error("Error parsing JSON response",p),u.ok)throw p;throw new Error(`${u.statusText} (${u.status})`)}if(!u.ok){if(s.error("Error from server:",d),u.headers.has("dpop-nonce")){const e=u.headers.get("dpop-nonce");throw new E(e,`${JSON.stringify(d)}`)}if(d.error)throw new x(d,t);throw new Error(`${u.statusText} (${u.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["accept","content-type"],o=["authorization"];0!==n.length&&n.forEach((n=>{if(r.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be set",n,r);if(o.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n))return void t.warn("Header could not be overridden",n,o);const i="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];i&&""!==i&&(e[n]=i)}))}},R=class{constructor(e){this._settings=e,this._logger=new m("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new T(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const n=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(n.debug("resolved"),void 0===r[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return r[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},N=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new m("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let n=0;n<e;n++){const e=await this._store.key(n);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},A=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:o,client_id:i,client_secret:s,response_type:a="code",scope:u="openid",redirect_uri:l,post_logout_redirect_uri:c,client_authentication:d="client_secret_post",prompt:p,display:m,max_age:_,ui_locales:h,acr_values:g,resource:f,response_mode:v,filterProtocolClaims:y=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:k,staleStateAgeInSeconds:w=900,mergeClaimsStrategy:x={array:"replace"},disablePKCE:I=!1,stateStore:S,revokeTokenAdditionalContentTypes:$,fetchRequestCredentials:E,refreshTokenAllowedScope:T,extraQueryParams:R={},extraTokenParams:A={},extraHeaders:C={},dpop:P,omitScopeWhenRequesting:U=!1}){var j;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=n,this.metadataSeed=o,this.signingKeys=r,this.client_id=i,this.client_secret=s,this.response_type=a,this.scope=u,this.redirect_uri=l,this.post_logout_redirect_uri=c,this.client_authentication=d,this.prompt=p,this.display=m,this.max_age=_,this.ui_locales=h,this.acr_values=g,this.resource=f,this.response_mode=v,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=w,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=U,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=$,this.fetchRequestCredentials=E||"same-origin",this.requestTimeoutInSeconds=k,S)this.stateStore=S;else{const e="undefined"!=typeof window?window.localStorage:new O;this.stateStore=new N({store:e})}if(this.refreshTokenAllowedScope=T,this.extraQueryParams=R,this.extraTokenParams=A,this.extraHeaders=C,this.dpop=P,this.dpop&&!(null==(j=this.dpop)?void 0:j.store))throw new Error("A DPoPStore is required when dpop is enabled")}},C=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new m("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const n=_.decode(e);return t.debug("JWT decoding successful"),n}catch(n){throw t.error("Error parsing JWT response"),n}},this._jsonService=new T(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const r=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",r),r}},P=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new m("TokenClient"),this._jsonService=new T(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:o,...i}){const s=this._logger.create("exchangeCode");n||s.throw(new Error("A client_id is required")),t||s.throw(new Error("A redirect_uri is required")),i.code||s.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,p]of Object.entries(i))null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw s.throw(new Error("A client_secret is required")),null;u=f.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:o});return s.debug("got response"),c}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:r=this._settings.scope,...o}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||s.set("scope",r);for(const[c,d]of Object.entries(o))null!=d&&s.set(c,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw i.throw(new Error("A client_secret is required")),null;a=f.generateBasicAuth(t,n);break;case"client_secret_post":s.append("client_id",t),n&&s.append("client_secret",n)}const u=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:o,...i}){const s=this._logger.create("exchangeRefreshToken");t||s.throw(new Error("A client_id is required")),i.refresh_token||s.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[d,p]of Object.entries(i))Array.isArray(p)?p.forEach((e=>a.append(d,e))):null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw s.throw(new Error("A client_secret is required")),null;u=f.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:o});return s.debug("got response"),c}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const o=new URLSearchParams;for(const[i,s]of Object.entries(e))null!=s&&o.set(i,s);o.set("client_id",this._settings.client_id),this._settings.client_secret&&o.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:o,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),n.debug("got response")}},U=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new m("ResponseValidator"),this._userInfoService=new C(this._settings,this._metadataService),this._tokenClient=new P(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){const r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t,n),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){const n=this._logger.create("validateCredentialsResponse"),r=e.isOpenId&&!!e.id_token;r&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,r),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new x(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new x(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const r=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void r.debug("not loading user info");r.debug("loading user info");const o=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),n&&o.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(o)),r.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,n){const r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");const o=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:n,...t.extraTokenParams});Object.assign(e,o)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const o=_.decode(null!=(n=e.id_token)?n:"");if(o.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=_.decode(t);o.sub!==e.sub&&r.throw(new Error("sub in id_token does not match current sub")),o.auth_time&&o.auth_time!==e.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),o.azp&&o.azp!==e.azp&&r.throw(new Error("azp in id_token does not match original azp")),!o.azp&&e.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=o}},j=class e{constructor(e){this.id=e.id||f.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=b.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new m("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return m.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){const r=m.createStatic("State","clearStaleState"),o=b.getEpochTime()-n,i=await t.getAllKeys();r.debug("got keys",i);for(let a=0;a<i.length;a++){const n=i[a],u=await t.get(n);let l=!1;if(u)try{const t=await e.fromStorageString(u);r.debug("got item from key:",n,t.created),t.created<=o&&(l=!0)}catch(s){r.error("Error parsing state for key:",n,s),l=!0}else r.debug("no item in storage for key:",n),l=!0;l&&(r.debug("removed item for key:",n),t.remove(n))}}},z=class e extends j{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const n=!0===t.code_verifier?f.generateCodeVerifier():t.code_verifier||void 0,r=n?await f.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:r})}toStorageString(){return new m("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){m.createStatic("SigninState","fromStorageString");const n=JSON.parse(t);return e.create(n)}},D=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:r,redirect_uri:o,response_type:i,scope:s,state_data:a,response_mode:u,request_type:l,client_secret:c,nonce:d,url_state:p,resource:m,skipUserInfo:_,extraQueryParams:h,extraTokenParams:g,disablePKCE:f,dpopJkt:v,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!o)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!s)throw this._logger.error("create: No scope passed"),new Error("scope");if(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const k=await z.create({data:a,request_type:l,url_state:p,code_verifier:!f,client_id:r,authority:n,redirect_uri:o,response_mode:u,client_secret:c,scope:s,extraTokenParams:g,skipUserInfo:_}),x=new URL(t);x.searchParams.append("client_id",r),x.searchParams.append("redirect_uri",o),x.searchParams.append("response_type",i),y||x.searchParams.append("scope",s),d&&x.searchParams.append("nonce",d),v&&x.searchParams.append("dpop_jkt",v);let I=k.id;if(p&&(I=`${I}${w}${p}`),x.searchParams.append("state",I),k.code_challenge&&(x.searchParams.append("code_challenge",k.code_challenge),x.searchParams.append("code_challenge_method","S256")),m){(Array.isArray(m)?m:[m]).forEach((e=>x.searchParams.append("resource",e)))}for(const[e,w]of Object.entries({response_mode:u,...b,...h}))null!=w&&x.searchParams.append(e,w.toString());return new e({url:x.href,state:k})}};D._logger=new m("SigninRequest");var M=D,L=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(w);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(w))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},q=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:o,request_type:i,client_id:s,url_state:a}){if(this._logger=new m("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const u=new URL(e);if(n&&u.searchParams.append("id_token_hint",n),s&&u.searchParams.append("client_id",s),r&&(u.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new j({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${w}${a}`),u.searchParams.append("state",e)}for(const[l,c]of Object.entries({...o}))null!=c&&u.searchParams.append(l,c.toString());this.url=u.href}},Z=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(w);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(w))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},F=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],W=["sub","iss","aud","exp","iat"],H=class{constructor(e){this._settings=e,this._logger=new m("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:F;for(const n of e)W.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[r,o]of Object.entries(t))if(n[r]!==o)if(Array.isArray(n[r])||Array.isArray(o))if("replace"==this._settings.mergeClaimsStrategy.array)n[r]=o;else{const e=Array.isArray(n[r])?n[r]:[n[r]];for(const t of Array.isArray(o)?o:[o])e.includes(t)||e.push(t);n[r]=e}else"object"==typeof n[r]&&"object"==typeof o?n[r]=this.mergeClaims(n[r],o):n[r]=o;return n}},B=class{constructor(e,t){this.keys=e,this.nonce=t}},J=class{constructor(e,t){this._logger=new m("OidcClient"),this.settings=e instanceof A?e:new A(e),this.metadataService=null!=t?t:new R(this.settings),this._claimsService=new H(this.settings),this._validator=new U(this.settings,this.metadataService,this._claimsService),this._tokenClient=new P(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:o,login_hint:i,skipUserInfo:s,nonce:a,url_state:u,response_type:l=this.settings.response_type,scope:c=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:m=this.settings.display,max_age:_=this.settings.max_age,ui_locales:h=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:f=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:k,omitScopeWhenRequesting:w=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",I);const S=await M.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:c,state_data:e,url_state:u,prompt:p,display:m,max_age:_,ui_locales:h,id_token_hint:o,login_hint:i,acr_values:g,dpopJkt:k,resource:f,request:t,request_uri:n,extraQueryParams:y,extraTokenParams:b,request_type:r,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:w});await this.clearStaleState();const $=S.state;return await this.settings.stateStore.set($.id,$.toStorageString()),S}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),r=new L(k.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const o=await this.settings.stateStore[t?"remove":"get"](r.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:await z.fromStorageString(o),response:r}}async processSigninResponse(e,t,n=!0){const r=this._logger.create("processSigninResponse"),{state:o,response:i}=await this.readSigninResponseState(e,n);if(r.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(i,o,t)}catch(s){if(!(s instanceof E&&this.settings.dpop))throw s;{const e=await this.getDpopProof(this.settings.dpop.store,s.nonce);t.DPoP=e,await this._validator.validateSigninResponse(i,o,t)}}return i}async getDpopProof(e,t){let n,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(n=await f.generateDPoPKeys(),r=new B(n,t),await e.set(this.settings.client_id,r)),await f.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:r={}}){const o=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),i=new L(new URLSearchParams);return Object.assign(i,o),await this._validator.validateCredentialsResponse(i,n),i}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,extraTokenParams:i}){var s;const a=this._logger.create("useRefreshToken");let u,l;if(void 0===this.settings.refreshTokenAllowedScope)u=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");u=((null==(s=e.scope)?void 0:s.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);o={...o,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,...i})}catch(d){if(!(d instanceof E&&this.settings.dpop))throw d;o.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,...i})}const c=new L(new URLSearchParams);return Object.assign(c,l),a.debug("validating response",c),await this._validator.validateRefreshResponse(c,{...e,scope:u}),c}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:o,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),u=await this.metadataService.getEndSessionEndpoint();if(!u)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",u),n||!i||t||(n=this.settings.client_id);const l=new q({url:u,id_token_hint:t,client_id:n,post_logout_redirect_uri:i,state_data:e,extraQueryParams:s,request_type:r,url_state:o});await this.clearStaleState();const c=l.state;return c&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),l}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),r=new Z(k.readParams(e,this.settings.response_mode));if(!r.state){if(n.debug("No state in response"),r.error)throw n.warn("Response was error:",r.error),new x(r);return{state:void 0,response:r}}const o=await this.settings.stateStore[t?"remove":"get"](r.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:await j.fromStorageString(o),response:r}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:r}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,n)):t.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),j.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},V=class{constructor(e){this._userManager=e,this._logger=new m("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const r=this._userManager.settings.client_id,o=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,s=new $(this._callback,r,e,o,i);await s.load(),this._checkSessionIFrame=s,s.start(t)}else n.warn("no check session iframe found in the metadata")}catch(r){n.error("Error from getCheckSessionIframe:",r instanceof Error?r.message:r)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(n){e.error("error from querySessionStatus",n instanceof Error?n.message:n)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),n?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},G=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new m("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return m.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},K="oidc-client",Y=class{constructor(){this._abort=new v("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:n,keepOpen:r}=await new Promise(((n,r)=>{const o=o=>{var i;const s=o.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(o.origin===a&&(null==s?void 0:s.source)===K){try{const n=k.readParams(s.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),o.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(new Error("Invalid response from window"))}n(s)}};window.addEventListener("message",o,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",o,!1)));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",o,!1),this._disposeHandlers.add((()=>i.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),r(e)})))}));return t.debug("got response from window"),this._dispose(),r||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,r=window.location.origin){const o={source:K,url:t,keepOpen:n},i=new m("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(o,r);else{i.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const n=new BroadcastChannel(`oidc-client-popup-${e}`);n.postMessage(o),n.close()}}},X={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Q="_blank",ee=60,te=2,ne=class extends A{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=X,popupWindowTarget:o=Q,redirectMethod:i="assign",redirectTarget:s="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:u=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:c=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:p=!0,validateSubOnSilentRenew:m=!0,includeIdTokenInSilentRenew:_=!1,monitorSession:h=!1,monitorAnonymousSession:g=!1,checkSessionIntervalInSeconds:f=te,query_status_response_type:v="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:k=!1,includeIdTokenInSilentSignout:w=!1,accessTokenExpiringNotificationTimeInSeconds:x=ee,userStore:I}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=r,this.popupWindowTarget=o,this.redirectMethod=i,this.redirectTarget=s,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=u,this.silent_redirect_uri=c,this.silentRequestTimeoutInSeconds=d||l||10,this.automaticSilentRenew=p,this.validateSubOnSilentRenew=m,this.includeIdTokenInSilentRenew=_,this.monitorSession=h,this.monitorAnonymousSession=g,this.checkSessionIntervalInSeconds=f,this.stopCheckSessionOnError=y,this.query_status_response_type=v,this.revokeTokenTypes=b,this.revokeTokensOnSignout=k,this.includeIdTokenInSilentSignout=w,this.accessTokenExpiringNotificationTimeInSeconds=x,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new O;this.userStore=new N({store:e})}}},re=class e extends Y{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new m("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new I("IFrame timed out without a response"))}),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const n=e.target;null==(t=n.parentNode)||t.removeChild(n),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},oe=class{constructor(e){this._settings=e,this._logger=new m("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new re({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),re.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ie=class extends Y{constructor({popupWindowTarget:e=Q,popupWindowFeatures:t={},popupSignal:n}){super(),this._logger=new m("PopupWindow");const r=y.center({...X,...t});this._window=window.open(void 0,e,y.serialize(r)),n&&n.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=n.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const n=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),r(),this._disposeHandlers.delete(r))}),500),r=()=>clearInterval(n);return this._disposeHandlers.add(r),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},se=class{constructor(e){this._settings=e,this._logger=new m("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n}){return new ie({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ie.notifyOpener(e,t)}},ae=class{constructor(e){this._settings=e,this._logger=new m("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let r=window.self;"top"===t&&(r=null!=(n=window.top)?n:window.self);const o=r.location[e].bind(r.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return o(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),r.stop()}}}async callback(){}},ue=class extends S{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new m("UserManagerEvents"),this._userLoaded=new v("User loaded"),this._userUnloaded=new v("User unloaded"),this._silentRenewError=new v("Silent renew error"),this._userSignedIn=new v("User signed in"),this._userSignedOut=new v("User signed out"),this._userSessionChanged=new v("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},le=class{constructor(e){this._userManager=e,this._logger=new m("SilentRenewService"),this._isStarted=!1,this._retryTimer=new b("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof I)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},ce=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},de=class{constructor(e,t,n,r){this._logger=new m("UserManager"),this.settings=new ne(e),this._client=new J(e),this._redirectNavigator=null!=t?t:new ae(this.settings),this._popupNavigator=null!=n?n:new se(this.settings),this._iframeNavigator=null!=r?r:new oe(this.settings),this._events=new ue(this.settings),this._silentRenewService=new le(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new V(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),n=await this._loadUser();return n?(t.info("user loaded"),await this._events.load(n,e),n):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:n,...r}=e;let o;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signinStart({request_type:"si:r",dpopJkt:o,...r},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const r=this._logger.create("signinResourceOwnerCredential"),o=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug("got signin response");const i=await this._buildUser(o);return i.profile&&i.profile.sub?r.info("success, signed in subject",i.profile.sub):r.info("no subject"),i}async signinPopup(e={}){var t;const n=this._logger.create("signinPopup");let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:o,popupWindowTarget:i,popupSignal:s,...a}=e,u=this.settings.popup_redirect_uri;u||n.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:o,popupWindowTarget:i,popupSignal:s}),c=await this._signin({request_type:"si:p",redirect_uri:u,display:"popup",dpopJkt:r,...a},l);return c&&(c.profile&&c.profile.sub?n.info("success, signed in subject",c.profile.sub):n.info("no subject")),c}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t,n;const r=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:o,...i}=e;let s,a=await this._loadUser();if(null==a?void 0:a.refresh_token){r.debug("using refresh token");const e=new ce(a);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:o})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const u=this.settings.silent_redirect_uri;let l;u||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:o});return a=await this._signin({request_type:"si:s",redirect_uri:u,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:s,...i},c,l),a&&((null==(n=a.profile)?void 0:n.sub)?r.info("success, signed in subject",a.profile.sub):r.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new G({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:n,...r}=e,o=this.settings.silent_redirect_uri;o||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),s=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:o,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...r},s);try{const e={},n=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),n.session_state&&n.profile.sub?(t.info("success for subject",n.profile.sub),{session_state:n.session_state,sub:n.profile.sub}):(t.info("success, user not authenticated"),null)}catch(u){if(this.settings.monitorAnonymousSession&&u instanceof x)switch(u.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:u.session_state}}throw u}}async _signin(e,t,n){const r=await this._signinStart(e,t);return await this._signinEnd(r.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const r=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(r){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),r}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),r=await this._client.processSigninResponse(e,{});n.debug("got signin response");return await this._buildUser(r,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),r=new G(e);if(t){if(t!==r.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",r.profile.sub),new x({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(r),n.debug("user stored"),await this._events.load(r),r}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...r}=e,o=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},o),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o,...i}=e,s=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o});await this._signout({request_type:"so:p",post_logout_redirect_uri:s,state:null==s?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const r=this._logger.create("_signoutStart");try{const o=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(o);const i=e.id_token_hint||o&&o.id_token;i&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),r.debug("user removed, creating signout request");const s=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:s.url,state:null==(n=s.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(o){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),o}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...o}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,s=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:s,id_token_hint:i,...o},a),n.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const n=this._logger.create("_revokeInternal");if(!e)return;const r=t.filter((t=>"string"==typeof e[t]));if(r.length){for(const t of r)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),await this._events.load(e)}else n.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),G.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,n,r){var o,i;const s=await(null==(i=null==(o=this.settings.dpop)?void 0:o.store)?void 0:i.get(this.settings.client_id));if(s)return await f.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:n,keyPair:s.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const n=await f.generateDPoPKeys();t=new B(n),await e.store.set(this.settings.client_id,t)}return await f.generateDPoPJkt(t.keys)}},pe=n.createContext(void 0);pe.displayName="AuthContext";var me={isLoading:!0,isAuthenticated:!1},_e=(e,t)=>{switch(t.type){case"INITIALISED":case"USER_LOADED":return{...e,user:t.user,isLoading:!1,isAuthenticated:!!t.user&&!t.user.expired,error:void 0};case"USER_SIGNED_OUT":case"USER_UNLOADED":return{...e,user:void 0,isAuthenticated:!1};case"NAVIGATOR_INIT":return{...e,isLoading:!0,activeNavigator:t.method};case"NAVIGATOR_CLOSE":return{...e,isLoading:!1,activeNavigator:void 0};case"ERROR":{const n=t.error;return n.toString=()=>`${n.name}: ${n.message}`,{...e,isLoading:!1,error:n}}default:{const n=new TypeError(`unknown type ${t.type}`),r={name:n.name,message:n.message,innerError:n,stack:n.stack,source:"unknown",toString:()=>`${r.name}: ${r.message}`};return{...e,isLoading:!1,error:r}}}},he=ye("signinCallback","Sign-in failed"),ge=ye("signoutCallback","Sign-out failed"),fe=ye("renewSilent","Renew silent failed");function ve(e,t){return{name:be(e,"name",(()=>"Error")),message:be(e,"message",(()=>t)),stack:be(e,"stack",(()=>(new Error).stack)),innerError:e}}function ye(e,t){return n=>({...ve(n,t),source:e})}function be(e,t,n){if(e&&"object"==typeof e){const n=e[t];if("string"==typeof n)return n}return n()}var ke,we=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],xe=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],Ie=e=>()=>{throw new Error(`UserManager#${e} was called from an unsupported context. If this is a server-rendered page, defer this call with useEffect() or pass a custom UserManager implementation.`)},Se="undefined"==typeof window?null:de,$e=e=>{const{children:t,onSigninCallback:r,skipSigninCallback:o,matchSignoutCallback:i,onSignoutCallback:s,onRemoveUser:a,userManager:u=null,...l}=e,[c]=n.useState((()=>null!=u?u:Se?new Se(l):{settings:l})),[d,p]=n.useReducer(_e,me),m=n.useMemo((()=>Object.assign({settings:c.settings,events:c.events},Object.fromEntries(we.map((e=>{var t,n;return[e,null!=(n=null==(t=c[e])?void 0:t.bind(c))?n:Ie(e)]}))),Object.fromEntries(xe.map((e=>[e,c[e]?async t=>{p({type:"NAVIGATOR_INIT",method:e});try{return await c[e](t)}catch(n){return p({type:"ERROR",error:{...ve(n,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{p({type:"NAVIGATOR_CLOSE"})}}:Ie(e)]))))),[c]),_=n.useRef(!1);n.useEffect((()=>{c&&!_.current&&(_.current=!0,(async()=>{try{let e=null;((e=window.location)=>{let t=new URLSearchParams(e.search);return!!((t.get("code")||t.get("error"))&&t.get("state")||(t=new URLSearchParams(e.hash.replace("#","?")),(t.get("code")||t.get("error"))&&t.get("state")))})()&&!o&&(e=await c.signinCallback(),r&&await r(e)),e=e||await c.getUser(),p({type:"INITIALISED",user:e})}catch(e){p({type:"ERROR",error:he(e)})}try{if(i&&i(c.settings)){const e=await c.signoutCallback();s&&await s(e)}}catch(e){p({type:"ERROR",error:ge(e)})}})())}),[c,o,r,s,i]),n.useEffect((()=>{if(!c)return;const e=e=>{p({type:"USER_LOADED",user:e})};c.events.addUserLoaded(e);const t=()=>{p({type:"USER_UNLOADED"})};c.events.addUserUnloaded(t);const n=()=>{p({type:"USER_SIGNED_OUT"})};c.events.addUserSignedOut(n);const r=e=>{p({type:"ERROR",error:fe(e)})};return c.events.addSilentRenewError(r),()=>{c.events.removeUserLoaded(e),c.events.removeUserUnloaded(t),c.events.removeUserSignedOut(n),c.events.removeSilentRenewError(r)}}),[c]);const h=n.useCallback((async()=>{await c.removeUser(),a&&await a()}),[c,a]),g=n.useMemo((()=>({...d,...m,removeUser:h})),[d,m,h]);return n.createElement(pe.Provider,{value:g},t)},Oe=()=>{const e=n.useContext(pe);return e||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component."),e},Ee="vercel.ai.error",Te=Symbol.for(Ee),Re=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[ke]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ee)}static hasMarker(e,t){const n=Symbol.for(t);return null!=e&&"object"==typeof e&&n in e&&"boolean"==typeof e[n]&&!0===e[n]}};ke=Te;var Ne,Ae=Re,Ce="AI_APICallError",Pe=`vercel.ai.error.${Ce}`,Ue=Symbol.for(Pe),je=class extends Ae{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:i,cause:s,isRetryable:a=null!=r&&(408===r||409===r||429===r||r>=500),data:u}){super({name:Ce,message:e,cause:s}),this[Ne]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=i,this.isRetryable=a,this.data=u}static isInstance(e){return Ae.hasMarker(e,Pe)}};Ne=Ue;var ze,De="AI_EmptyResponseBodyError",Me=`vercel.ai.error.${De}`,Le=Symbol.for(Me),qe=class extends Ae{constructor({message:e="Empty response body"}={}){super({name:De,message:e}),this[ze]=!0}static isInstance(e){return Ae.hasMarker(e,Me)}};function Ze(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.message:JSON.stringify(e)}ze=Le;var Fe,We="AI_InvalidArgumentError",He=`vercel.ai.error.${We}`,Be=Symbol.for(He),Je=class extends Ae{constructor({message:e,cause:t,argument:n}){super({name:We,message:e,cause:t}),this[Fe]=!0,this.argument=n}static isInstance(e){return Ae.hasMarker(e,He)}};Fe=Be;var Ve,Ge="AI_InvalidPromptError",Ke=`vercel.ai.error.${Ge}`,Ye=Symbol.for(Ke),Xe=class extends Ae{constructor({prompt:e,message:t,cause:n}){super({name:Ge,message:`Invalid prompt: ${t}`,cause:n}),this[Ve]=!0,this.prompt=e}static isInstance(e){return Ae.hasMarker(e,Ke)}};Ve=Ye;var Qe,et="AI_InvalidResponseDataError",tt=`vercel.ai.error.${et}`,nt=Symbol.for(tt),rt=class extends Ae{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:et,message:t}),this[Qe]=!0,this.data=e}static isInstance(e){return Ae.hasMarker(e,tt)}};Qe=nt;var ot,it="AI_JSONParseError",st=`vercel.ai.error.${it}`,at=Symbol.for(st),ut=class extends Ae{constructor({text:e,cause:t}){super({name:it,message:`JSON parsing failed: Text: ${e}.\nError message: ${Ze(t)}`,cause:t}),this[ot]=!0,this.text=e}static isInstance(e){return Ae.hasMarker(e,st)}};ot=at;var lt,ct="AI_LoadAPIKeyError",dt=`vercel.ai.error.${ct}`,pt=Symbol.for(dt),mt=class extends Ae{constructor({message:e}){super({name:ct,message:e}),this[lt]=!0}static isInstance(e){return Ae.hasMarker(e,dt)}};lt=pt;var _t,ht="AI_NoSuchModelError",gt=`vercel.ai.error.${ht}`,ft=Symbol.for(gt),vt=class extends Ae{constructor({errorName:e=ht,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[_t]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return Ae.hasMarker(e,gt)}};_t=ft;var yt,bt="AI_TooManyEmbeddingValuesForCallError",kt=`vercel.ai.error.${bt}`,wt=Symbol.for(kt),xt=class extends Ae{constructor(e){super({name:bt,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[yt]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Ae.hasMarker(e,kt)}};yt=wt;var It,St="AI_TypeValidationError",$t=`vercel.ai.error.${St}`,Ot=Symbol.for($t);It=Ot;var Et,Tt=class e extends Ae{constructor({value:e,cause:t}){super({name:St,message:`Type validation failed: Value: ${JSON.stringify(e)}.\nError message: ${Ze(t)}`,cause:t}),this[It]=!0,this.value=e}static isInstance(e){return Ae.hasMarker(e,$t)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}},Rt="AI_UnsupportedFunctionalityError",Nt=`vercel.ai.error.${Rt}`,At=Symbol.for(Nt),Ct=class extends Ae{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Rt,message:t}),this[Et]=!0,this.functionality=e}static isInstance(e){return Ae.hasMarker(e,Nt)}};Et=At;class Pt 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 Ut(e){}function jt(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=Ut,onError:n=Ut,onRetry:r=Ut,onComment:o}=e;let i,s="",a=!0,u="",l="";function c(e){if(""===e)return u.length>0&&t({id:i,event:l||void 0,data:u.endsWith("\n")?u.slice(0,-1):u}),i=void 0,u="",void(l="");if(e.startsWith(":"))return void(o&&o(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1===n)d(e,"",e);else{const t=e.slice(0,n),r=" "===e[n+1]?2:1;d(t,e.slice(n+r),e)}}function d(e,t,o){switch(e){case"event":l=t;break;case"data":u=`${u}${t}\n`;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new Pt(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new Pt(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:o}))}}return{feed:function(e){const t=a?e.replace(/^\xEF\xBB\xBF/,""):e,[n,r]=function(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),i=e.indexOf("\n",r);let s=-1;if(-1!==o&&-1!==i?s=Math.min(o,i):-1!==o?s=o===e.length-1?-1:o:-1!==i&&(s=i),-1===s){n=e.slice(r);break}{const n=e.slice(r,s);t.push(n),r=s+1,"\r"===e[r-1]&&"\n"===e[r]&&r++}}return[t,n]}(`${s}${t}`);for(const o of n)c(o);s=r,a=!1},reset:function(e={}){s&&e.consume&&c(s),a=!0,i=void 0,u="",l="",s=""}}}class zt extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(o){r=jt({onEvent:e=>{o.enqueue(e)},onError(t){"terminate"===e?o.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}}const Dt=Object.freeze({status:"aborted"});function Mt(e,t,n){function r(n,r){var o;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(o=n._zod).traits??(o.traits=new Set),n._zod.traits.add(e),t(n,r);for(const e in s.prototype)e in n||Object.defineProperty(n,e,{value:s.prototype[e].bind(n)});n._zod.constr=s,n._zod.def=r}const o=(null==n?void 0:n.Parent)??Object;class i extends o{}function s(e){var t;const o=(null==n?void 0:n.Parent)?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const n of o._zod.deferred)n();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>{var r,o;return!!((null==n?void 0:n.Parent)&&t instanceof n.Parent)||(null==(o=null==(r=null==t?void 0:t._zod)?void 0:r.traits)?void 0:o.has(e))}}),Object.defineProperty(s,"name",{value:e}),s}const Lt=Symbol("zod_brand");class qt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Zt={};function Ft(e){return e&&Object.assign(Zt,e),Zt}function Wt(e){const t=Object.values(e).filter((e=>"number"==typeof e));return Object.entries(e).filter((([e,n])=>-1===t.indexOf(+e))).map((([e,t])=>t))}function Ht(e,t="|"){return e.map((e=>_n(e))).join(t)}function Bt(e,t){return"bigint"==typeof t?t.toString():t}function Jt(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Vt(e){return null==e}function Gt(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Kt(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(0===o&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);(null==e?void 0:e[1])&&(o=Number.parseInt(e[1]))}const i=n>o?n:o;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}const Yt=Symbol("evaluating");function Xt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Yt)return void 0===r&&(r=Yt,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Qt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function en(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function tn(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function nn(e){return JSON.stringify(e)}const rn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function on(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const sn=Jt((()=>{var e;if("undefined"!=typeof navigator&&(null==(e=null==navigator?void 0:navigator.userAgent)?void 0:e.includes("Cloudflare")))return!1;try{return new Function(""),!0}catch(t){return!1}}));function an(e){if(!1===on(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==on(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function un(e){return an(e)?{...e}:e}const ln=new Set(["string","number","symbol"]),cn=new Set(["string","number","bigint","boolean","symbol","undefined"]);function dn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!(null==n?void 0:n.parent)||(r._zod.parent=e),r}function mn(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==(null==t?void 0:t.message)){if(void 0!==(null==t?void 0:t.error))throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function _n(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function hn(e){return Object.keys(e).filter((t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout))}const gn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},fn={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vn(e,t){const n=e._zod.def;return pn(e,tn(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return en(this,"shape",e),e},checks:[]}))}function yn(e,t){const n=e._zod.def,r=tn(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return en(this,"shape",r),r},checks:[]});return pn(e,r)}function bn(e,t){if(!an(t))throw new Error("Invalid input to extend: expected a plain object");const n=tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return en(this,"shape",n),n},checks:[]});return pn(e,n)}function kn(e,t){const n=tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return en(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return pn(e,n)}function wn(e,t,n){const r=tn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return en(this,"shape",o),o},checks:[]});return pn(t,r)}function xn(e,t,n){const r=tn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return en(this,"shape",o),o},checks:[]});return pn(t,r)}function In(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(!0!==(null==(n=e.issues[r])?void 0:n.continue))return!0;return!1}function Sn(e,t){return t.map((t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t}))}function $n(e){return"string"==typeof e?e:null==e?void 0:e.message}function On(e,t,n){var r,o,i,s,a,u;const l={...e,path:e.path??[]};if(!e.message){const c=$n(null==(i=null==(o=null==(r=e.inst)?void 0:r._zod.def)?void 0:o.error)?void 0:i.call(o,e))??$n(null==(s=null==t?void 0:t.error)?void 0:s.call(t,e))??$n(null==(a=n.customError)?void 0:a.call(n,e))??$n(null==(u=n.localeError)?void 0:u.call(n,e))??"Invalid input";l.message=c}return delete l.inst,delete l.continue,(null==t?void 0:t.reportInput)||delete l.input,l}function En(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Tn(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Rn(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Nn=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:fn,Class:class{constructor(...e){}},NUMBER_FORMAT_RANGES:gn,aborted:In,allowsEval:sn,assert:function(e){},assertEqual:function(e){return e},assertIs:function(e){},assertNever:function(e){throw new Error},assertNotEqual:function(e){return e},assignProp:en,cached:Jt,captureStackTrace:rn,cleanEnum:function(e){return Object.entries(e).filter((([e,t])=>Number.isNaN(Number.parseInt(e,10)))).map((e=>e[1]))},cleanRegex:Gt,clone:pn,cloneDef:function(e){return tn(e._zod.def)},createTransparentProxy:function(e){let t;return new Proxy({},{get:(n,r,o)=>(t??(t=e()),Reflect.get(t,r,o)),set:(n,r,o,i)=>(t??(t=e()),Reflect.set(t,r,o,i)),has:(n,r)=>(t??(t=e()),Reflect.has(t,r)),deleteProperty:(n,r)=>(t??(t=e()),Reflect.deleteProperty(t,r)),ownKeys:n=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(n,r)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)),defineProperty:(n,r,o)=>(t??(t=e()),Reflect.defineProperty(t,r,o))})},defineLazy:Xt,esc:nn,escapeRegex:dn,extend:bn,finalizeIssue:On,floatSafeRemainder:Kt,getElementAtPath:function(e,t){return t?t.reduce(((e,t)=>null==e?void 0:e[t]),e):e},getEnumValues:Wt,getLengthableOrigin:Tn,getParsedType:e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},getSizableOrigin:En,isObject:on,isPlainObject:an,issue:Rn,joinValues:Ht,jsonStringifyReplacer:Bt,merge:kn,mergeDefs:tn,normalizeParams:mn,nullish:Vt,numKeys:function(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t},objectClone:Qt,omit:yn,optionalKeys:hn,partial:wn,pick:vn,prefixIssues:Sn,primitiveTypes:cn,promiseAllObject:function(e){const t=Object.keys(e),n=t.map((t=>e[t]));return Promise.all(n).then((e=>{const n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n}))},propertyKeyTypes:ln,randomString:function(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let r=0;r<e;r++)n+=t[Math.floor(26*Math.random())];return n},required:xn,shallowClone:un,stringifyPrimitive:_n,unwrapMessage:$n},Symbol.toStringTag,{value:"Module"})),An=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cn=Mt("$ZodError",An),Pn=Mt("$ZodError",An,{Parent:Error});function Un(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function jn(e,t){const n=t||function(e){return e.message},r={_errors:[]},o=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map((e=>o({issues:e})));else if("invalid_key"===t.code)o({issues:t.issues});else if("invalid_element"===t.code)o({issues:t.issues});else if(0===t.path.length)r._errors.push(n(t));else{let e=r,o=0;for(;o<t.path.length;){const r=t.path[o];o===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],o++}}};return o(e),r}function zn(e,t){const n=t||function(e){return e.message},r={errors:[]},o=(e,t=[])=>{var i,s;for(const a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map((e=>o({issues:e},a.path)));else if("invalid_key"===a.code)o({issues:a.issues},a.path);else if("invalid_element"===a.code)o({issues:a.issues},a.path);else{const e=[...t,...a.path];if(0===e.length){r.errors.push(n(a));continue}let o=r,u=0;for(;u<e.length;){const t=e[u],r=u===e.length-1;"string"==typeof t?(o.properties??(o.properties={}),(i=o.properties)[t]??(i[t]={errors:[]}),o=o.properties[t]):(o.items??(o.items=[]),(s=o.items)[t]??(s[t]={errors:[]}),o=o.items[t]),r&&o.errors.push(n(a)),u++}}};return o(e),r}function Dn(e){const t=[],n=e.map((e=>"object"==typeof e?e.key:e));for(const r of n)"number"==typeof r?t.push(`[${r}]`):"symbol"==typeof r?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Mn(e){var t;const n=[],r=[...e.issues].sort(((e,t)=>(e.path??[]).length-(t.path??[]).length));for(const o of r)n.push(`✖ ${o.message}`),(null==(t=o.path)?void 0:t.length)&&n.push(` → at ${Dn(o.path)}`);return n.join("\n")}const Ln=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new qt;if(s.issues.length){const t=new((null==o?void 0:o.Err)??e)(s.issues.map((e=>On(e,i,Ft()))));throw rn(t,null==o?void 0:o.callee),t}return s.value},qn=Ln(Pn),Zn=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new((null==o?void 0:o.Err)??e)(s.issues.map((e=>On(e,i,Ft()))));throw rn(t,null==o?void 0:o.callee),t}return s.value},Fn=Zn(Pn),Wn=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new qt;return i.issues.length?{success:!1,error:new(e??Cn)(i.issues.map((e=>On(e,o,Ft()))))}:{success:!0,data:i.value}},Hn=Wn(Pn),Bn=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map((e=>On(e,o,Ft()))))}:{success:!0,data:i.value}},Jn=Bn(Pn),Vn=/^[cC][^\s-]{8,}$/,Gn=/^[0-9a-z]+$/,Kn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yn=/^[0-9a-vA-V]{20}$/,Xn=/^[A-Za-z0-9]{27}$/,Qn=/^[a-zA-Z0-9_-]{21}$/,er=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,nr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,rr=nr(4),or=nr(6),ir=nr(7),sr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function ar(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}const ur=/^(?:(?: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])$/,lr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,cr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,dr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mr=/^[A-Za-z0-9_-]*$/,_r=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,hr=/^\+(?:[0-9]){6,14}[0-9]$/,gr="(?:(?:\\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])))",fr=new RegExp(`^${gr}$`);function vr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yr(e){return new RegExp(`^${vr(e)}$`)}function br(e){const t=vr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${gr}T(?:${r})$`)}const kr=e=>{const t=e?`[\\s\\S]{${(null==e?void 0:e.minimum)??0},${(null==e?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},wr=/^\d+n?$/,xr=/^\d+$/,Ir=/^-?\d+(?:\.\d+)?/i,Sr=/true|false/i,$r=/null/i,Or=/undefined/i,Er=/^[^A-Z]*$/,Tr=/^[^a-z]*$/,Rr=Object.freeze(Object.defineProperty({__proto__:null,base64:pr,base64url:mr,bigint:wr,boolean:Sr,browserEmail:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,cidrv4:cr,cidrv6:dr,cuid:Vn,cuid2:Gn,date:fr,datetime:br,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,duration:er,e164:hr,email:sr,emoji:ar,extendedDuration:/^[-+]?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)?)??$/,guid:tr,hostname:_r,html5Email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,idnEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,integer:xr,ipv4:ur,ipv6:lr,ksuid:Xn,lowercase:Er,nanoid:Qn,null:$r,number:Ir,rfc5322Email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,string:kr,time:yr,ulid:Kn,undefined:Or,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,uppercase:Tr,uuid:nr,uuid4:rr,uuid6:or,uuid7:ir,xid:Yn},Symbol.toStringTag,{value:"Module"})),Nr=Mt("$ZodCheck",((e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])})),Ar={number:"number",bigint:"bigint",object:"date"},Cr=Mt("$ZodCheckLessThan",((e,t)=>{Nr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),Pr=Mt("$ZodCheckGreaterThan",((e,t)=>{Nr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),Ur=Mt("$ZodCheckMultipleOf",((e,t)=>{Nr.init(e,t),e._zod.onattach.push((e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)})),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===Kt(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}})),jr=Mt("$ZodCheckNumberFormat",((e,t)=>{var n;Nr.init(e,t),t.format=t.format||"float64";const r=null==(n=t.format)?void 0:n.includes("int"),o=r?"int":"number",[i,s]=gn[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=s,r&&(n.pattern=xr)})),e._zod.check=n=>{const a=n.value;if(r){if(!Number.isInteger(a))return void n.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?n.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):n.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}))}a<i&&n.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&n.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}})),zr=Mt("$ZodCheckBigIntFormat",((e,t)=>{Nr.init(e,t);const[n,r]=fn[t.format];e._zod.onattach.push((e=>{const o=e._zod.bag;o.format=t.format,o.minimum=n,o.maximum=r})),e._zod.check=o=>{const i=o.value;i<n&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),i>r&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:r,inst:e})}})),Dr=Mt("$ZodCheckMaxSize",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;r.size<=t.maximum||n.issues.push({origin:En(r),code:"too_big",maximum:t.maximum,input:r,inst:e,continue:!t.abort})}})),Mr=Mt("$ZodCheckMinSize",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;r.size>=t.minimum||n.issues.push({origin:En(r),code:"too_small",minimum:t.minimum,input:r,inst:e,continue:!t.abort})}})),Lr=Mt("$ZodCheckSizeEquals",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size})),e._zod.check=n=>{const r=n.value,o=r.size;if(o===t.size)return;const i=o>t.size;n.issues.push({origin:En(r),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),qr=Mt("$ZodCheckMaxLength",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=Tn(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),Zr=Mt("$ZodCheckMinLength",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=Tn(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),Fr=Mt("$ZodCheckLengthEquals",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length})),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=Tn(r),s=o>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),Wr=Mt("$ZodCheckStringFormat",((e,t)=>{var n,r;Nr.init(e,t),e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))})),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})})),Hr=Mt("$ZodCheckRegex",((e,t)=>{Wr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}})),Br=Mt("$ZodCheckLowerCase",((e,t)=>{t.pattern??(t.pattern=Er),Wr.init(e,t)})),Jr=Mt("$ZodCheckUpperCase",((e,t)=>{t.pattern??(t.pattern=Tr),Wr.init(e,t)})),Vr=Mt("$ZodCheckIncludes",((e,t)=>{Nr.init(e,t);const n=dn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)})),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}})),Gr=Mt("$ZodCheckStartsWith",((e,t)=>{Nr.init(e,t);const n=new RegExp(`^${dn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}})),Kr=Mt("$ZodCheckEndsWith",((e,t)=>{Nr.init(e,t);const n=new RegExp(`.*${dn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}));function Yr(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues))}const Xr=Mt("$ZodCheckProperty",((e,t)=>{Nr.init(e,t),e._zod.check=e=>{const n=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then((n=>Yr(n,e,t.property)));Yr(n,e,t.property)}})),Qr=Mt("$ZodCheckMimeType",((e,t)=>{Nr.init(e,t);const n=new Set(t.mime);e._zod.onattach.push((e=>{e._zod.bag.mime=t.mime})),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}})),eo=Mt("$ZodCheckOverwrite",((e,t)=>{Nr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class to{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter((e=>e)),n=Math.min(...t.map((e=>e.length-e.trimStart().length))),r=t.map((e=>e.slice(n))).map((e=>" ".repeat(2*this.indent)+e));for(const o of r)this.content.push(o)}compile(){return new Function(...null==this?void 0:this.args,[...((null==this?void 0:this.content)??[""]).map((e=>` ${e}`))].join("\n"))}}const no={major:4,minor:0,patch:17},ro=Mt("$ZodType",((e,t)=>{var n,r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=no;const o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(const i of o)for(const t of i._zod.onattach)t(e);if(0===o.length)(r=e._zod).deferred??(r.deferred=[]),null==(n=e._zod.deferred)||n.push((()=>{e._zod.run=e._zod.parse}));else{const t=(e,t,n)=>{let r,o=In(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&!1===(null==n?void 0:n.async))throw new qt;if(r||s instanceof Promise)r=(r??Promise.resolve()).then((async()=>{await s;e.issues.length!==t&&(o||(o=In(e,t)))}));else{if(e.issues.length===t)continue;o||(o=In(e,t))}}return r?r.then((()=>e)):e};e._zod.run=(n,r)=>{const i=e._zod.parse(n,r);if(i instanceof Promise){if(!1===r.async)throw new qt;return i.then((e=>t(e,o,r)))}return t(i,o,r)}}e["~standard"]={validate:t=>{var n;try{const r=Hn(e,t);return r.success?{value:r.data}:{issues:null==(n=r.error)?void 0:n.issues}}catch(r){return Jn(e,t).then((e=>{var t;return e.success?{value:e.data}:{issues:null==(t=e.error)?void 0:t.issues}}))}},vendor:"zod",version:1}})),oo=Mt("$ZodString",((e,t)=>{var n;ro.init(e,t),e._zod.pattern=[...(null==(n=null==e?void 0:e._zod.bag)?void 0:n.patterns)??[]].pop()??kr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}})),io=Mt("$ZodStringFormat",((e,t)=>{Wr.init(e,t),oo.init(e,t)})),so=Mt("$ZodGUID",((e,t)=>{t.pattern??(t.pattern=tr),io.init(e,t)})),ao=Mt("$ZodUUID",((e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nr(e))}else t.pattern??(t.pattern=nr());io.init(e,t)})),uo=Mt("$ZodEmail",((e,t)=>{t.pattern??(t.pattern=sr),io.init(e,t)})),lo=Mt("$ZodURL",((e,t)=>{io.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_r.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}})),co=Mt("$ZodEmoji",((e,t)=>{t.pattern??(t.pattern=ar()),io.init(e,t)})),po=Mt("$ZodNanoID",((e,t)=>{t.pattern??(t.pattern=Qn),io.init(e,t)})),mo=Mt("$ZodCUID",((e,t)=>{t.pattern??(t.pattern=Vn),io.init(e,t)})),_o=Mt("$ZodCUID2",((e,t)=>{t.pattern??(t.pattern=Gn),io.init(e,t)})),ho=Mt("$ZodULID",((e,t)=>{t.pattern??(t.pattern=Kn),io.init(e,t)})),go=Mt("$ZodXID",((e,t)=>{t.pattern??(t.pattern=Yn),io.init(e,t)})),fo=Mt("$ZodKSUID",((e,t)=>{t.pattern??(t.pattern=Xn),io.init(e,t)})),vo=Mt("$ZodISODateTime",((e,t)=>{t.pattern??(t.pattern=br(t)),io.init(e,t)})),yo=Mt("$ZodISODate",((e,t)=>{t.pattern??(t.pattern=fr),io.init(e,t)})),bo=Mt("$ZodISOTime",((e,t)=>{t.pattern??(t.pattern=yr(t)),io.init(e,t)})),ko=Mt("$ZodISODuration",((e,t)=>{t.pattern??(t.pattern=er),io.init(e,t)})),wo=Mt("$ZodIPv4",((e,t)=>{t.pattern??(t.pattern=ur),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv4"}))})),xo=Mt("$ZodIPv6",((e,t)=>{t.pattern??(t.pattern=lr),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv6"})),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}})),Io=Mt("$ZodCIDRv4",((e,t)=>{t.pattern??(t.pattern=cr),io.init(e,t)})),So=Mt("$ZodCIDRv6",((e,t)=>{t.pattern??(t.pattern=dr),io.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const e=Number(o);if(`${e}`!==o)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}}));function $o(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Oo=Mt("$ZodBase64",((e,t)=>{t.pattern??(t.pattern=pr),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64"})),e._zod.check=n=>{$o(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}));function Eo(e){if(!mr.test(e))return!1;const t=e.replace(/[-_]/g,(e=>"-"===e?"+":"/"));return $o(t.padEnd(4*Math.ceil(t.length/4),"="))}const To=Mt("$ZodBase64URL",((e,t)=>{t.pattern??(t.pattern=mr),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64url"})),e._zod.check=n=>{Eo(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}})),Ro=Mt("$ZodE164",((e,t)=>{t.pattern??(t.pattern=hr),io.init(e,t)}));function No(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return(!("typ"in o)||"JWT"===(null==o?void 0:o.typ))&&(!!o.alg&&(!t||"alg"in o&&o.alg===t))}catch{return!1}}const Ao=Mt("$ZodJWT",((e,t)=>{io.init(e,t),e._zod.check=n=>{No(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}})),Co=Mt("$ZodCustomStringFormat",((e,t)=>{io.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}})),Po=Mt("$ZodNumber",((e,t)=>{ro.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ir,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}})),Uo=Mt("$ZodNumber",((e,t)=>{jr.init(e,t),Po.init(e,t)})),jo=Mt("$ZodBoolean",((e,t)=>{ro.init(e,t),e._zod.pattern=Sr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const o=n.value;return"boolean"==typeof o||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}})),zo=Mt("$ZodBigInt",((e,t)=>{ro.init(e,t),e._zod.pattern=wr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(o){}return"bigint"==typeof n.value||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}})),Do=Mt("$ZodBigInt",((e,t)=>{zr.init(e,t),zo.init(e,t)})),Mo=Mt("$ZodSymbol",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return"symbol"==typeof r||t.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),t}})),Lo=Mt("$ZodUndefined",((e,t)=>{ro.init(e,t),e._zod.pattern=Or,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),t}})),qo=Mt("$ZodNull",((e,t)=>{ro.init(e,t),e._zod.pattern=$r,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}})),Zo=Mt("$ZodAny",((e,t)=>{ro.init(e,t),e._zod.parse=e=>e})),Fo=Mt("$ZodUnknown",((e,t)=>{ro.init(e,t),e._zod.parse=e=>e})),Wo=Mt("$ZodNever",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)})),Ho=Mt("$ZodVoid",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),t}})),Bo=Mt("$ZodDate",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}const o=n.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),n}}));function Jo(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues)),t.value[n]=e.value}const Vo=Mt("$ZodArray",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const s=o[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then((t=>Jo(t,n,e)))):Jo(a,n,e)}return i.length?Promise.all(i).then((()=>n)):n}}));function Go(e,t,n,r){e.issues.length&&t.issues.push(...Sn(n,e.issues)),void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Ko=Mt("$ZodObject",((e,t)=>{ro.init(e,t);const n=Jt((()=>{const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=hn(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}));Xt(e._zod,"propValues",(()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n}));let r;const o=on,i=!Zt.jitless,s=i&&sn.value,a=t.catchall;let u;e._zod.parse=(l,c)=>{u??(u=n.value);const d=l.value;if(!o(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;const p=[];if(i&&s&&!1===(null==c?void 0:c.async)&&!0!==c.jitless)r||(r=(e=>{const t=new to(["shape","payload","ctx"]),r=n.value,o=e=>{const t=nn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let s=0;for(const n of r.keys)i[n]="key_"+s++;t.write("const newResult = {}");for(const n of r.keys){const e=i[n],r=nn(n);t.write(`const ${e} = ${o(n)};`),t.write(`\n if (${e}.issues.length) {\n payload.issues = payload.issues.concat(${e}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${r}, ...iss.path] : [${r}]\n })));\n }\n \n if (${e}.value === undefined) {\n if (${r} in input) {\n newResult[${r}] = undefined;\n }\n } else {\n newResult[${r}] = ${e}.value;\n }\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),l=r(l,c);else{l.value={};const e=u.shape;for(const t of u.keys){const n=e[t]._zod.run({value:d[t],issues:[]},c);n instanceof Promise?p.push(n.then((e=>Go(e,l,t,d)))):Go(n,l,t,d)}}if(!a)return p.length?Promise.all(p).then((()=>l)):l;const m=[],_=u.keySet,h=a._zod,g=h.def.type;for(const e of Object.keys(d)){if(_.has(e))continue;if("never"===g){m.push(e);continue}const t=h.run({value:d[e],issues:[]},c);t instanceof Promise?p.push(t.then((t=>Go(t,l,e,d)))):Go(t,l,e,d)}return m.length&&l.issues.push({code:"unrecognized_keys",keys:m,input:d,inst:e}),p.length?Promise.all(p).then((()=>l)):l}}));function Yo(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter((e=>!In(e)));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((e=>e.issues.map((e=>On(e,r,Ft())))))}),t)}const Xo=Mt("$ZodUnion",((e,t)=>{ro.init(e,t),Xt(e._zod,"optin",(()=>t.options.some((e=>"optional"===e._zod.optin))?"optional":void 0)),Xt(e._zod,"optout",(()=>t.options.some((e=>"optional"===e._zod.optout))?"optional":void 0)),Xt(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values)))return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))})),Xt(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>Gt(e.source))).join("|")})$`)}}));const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then((t=>Yo(t,o,e,i))):Yo(a,o,e,i)}})),Qo=Mt("$ZodDiscriminatedUnion",((e,t)=>{Xo.init(e,t);const n=e._zod.parse;Xt(e._zod,"propValues",(()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e}));const r=Jt((()=>{var e;const n=t.options,r=new Map;for(const o of n){const n=null==(e=o._zod.propValues)?void 0:e[t.discriminator];if(!n||0===n.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const e of n){if(r.has(e))throw new Error(`Duplicate discriminator value "${String(e)}"`);r.set(e,o)}}return r}));e._zod.parse=(o,i)=>{const s=o.value;if(!on(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const a=r.value.get(null==s?void 0:s[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),o)}})),ei=Mt("$ZodIntersection",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then((([t,n])=>ni(e,t,n))):ni(e,o,i)}}));function ti(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(an(e)&&an(t)){const n=Object.keys(t),r=Object.keys(e).filter((e=>-1!==n.indexOf(e))),o={...e,...t};for(const i of r){const n=ti(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=ti(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ni(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),In(e))return e;const r=ti(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const ri=Mt("$ZodTuple",((e,t)=>{ro.init(e,t);const n=t.items,r=n.length-[...n].reverse().findIndex((e=>"optional"!==e._zod.optin));e._zod.parse=(o,i)=>{const s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];const a=[];if(!t.rest){const t=s.length>n.length,i=s.length<r-1;if(t||i)return o.issues.push({...t?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},input:s,inst:e,origin:"array"}),o}let u=-1;for(const e of n){if(u++,u>=s.length&&u>=r)continue;const t=e._zod.run({value:s[u],issues:[]},i);t instanceof Promise?a.push(t.then((e=>oi(e,o,u)))):oi(t,o,u)}if(t.rest){const e=s.slice(n.length);for(const n of e){u++;const e=t.rest._zod.run({value:n,issues:[]},i);e instanceof Promise?a.push(e.then((e=>oi(e,o,u)))):oi(e,o,u)}}return a.length?Promise.all(a).then((()=>o)):o}}));function oi(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues)),t.value[n]=e.value}const ii=Mt("$ZodRecord",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!an(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;n.value={};for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const s=t.valueType._zod.run({value:o[e],issues:[]},r);s instanceof Promise?i.push(s.then((t=>{t.issues.length&&n.issues.push(...Sn(e,t.issues)),n.value[e]=t.value}))):(s.issues.length&&n.issues.push(...Sn(e,s.issues)),n.value[e]=s.value)}let a;for(const e in o)s.has(e)||(a=a??[],a.push(e));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.value={};for(const s of Reflect.ownKeys(o)){if("__proto__"===s)continue;const a=t.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map((e=>On(e,r,Ft()))),input:s,path:[s],inst:e}),n.value[a.value]=a.value;continue}const u=t.valueType._zod.run({value:o[s],issues:[]},r);u instanceof Promise?i.push(u.then((e=>{e.issues.length&&n.issues.push(...Sn(s,e.issues)),n.value[a.value]=e.value}))):(u.issues.length&&n.issues.push(...Sn(s,u.issues)),n.value[a.value]=u.value)}}return i.length?Promise.all(i).then((()=>n)):n}})),si=Mt("$ZodMap",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),n;const i=[];n.value=new Map;for(const[s,a]of o){const u=t.keyType._zod.run({value:s,issues:[]},r),l=t.valueType._zod.run({value:a,issues:[]},r);u instanceof Promise||l instanceof Promise?i.push(Promise.all([u,l]).then((([t,i])=>{ai(t,i,n,s,o,e,r)}))):ai(u,l,n,s,o,e,r)}return i.length?Promise.all(i).then((()=>n)):n}}));function ai(e,t,n,r,o,i,s){e.issues.length&&(ln.has(typeof r)?n.issues.push(...Sn(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map((e=>On(e,s,Ft())))})),t.issues.length&&(ln.has(typeof r)?n.issues.push(...Sn(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:r,issues:t.issues.map((e=>On(e,s,Ft())))})),n.value.set(e.value,t.value)}const ui=Mt("$ZodSet",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),n;const i=[];n.value=new Set;for(const e of o){const o=t.valueType._zod.run({value:e,issues:[]},r);o instanceof Promise?i.push(o.then((e=>li(e,n)))):li(o,n)}return i.length?Promise.all(i).then((()=>n)):n}}));function li(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const ci=Mt("$ZodEnum",((e,t)=>{ro.init(e,t);const n=Wt(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((e=>ln.has(typeof e))).map((e=>"string"==typeof e?dn(e):e.toString())).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}})),di=Mt("$ZodLiteral",((e,t)=>{if(ro.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map((e=>"string"==typeof e?dn(e):e?dn(e.toString()):String(e))).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}})),pi=Mt("$ZodFile",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return r instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),t}})),mi=Mt("$ZodTransform",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>{const r=t.transform(e.value,e);if(n.async){return(r instanceof Promise?r:Promise.resolve(r)).then((t=>(e.value=t,e)))}if(r instanceof Promise)throw new qt;return e.value=r,e}}));function _i(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const hi=Mt("$ZodOptional",((e,t)=>{ro.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Xt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0)),Xt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Gt(e.source)})?$`):void 0})),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>_i(t,e.value))):_i(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}})),gi=Mt("$ZodNullable",((e,t)=>{ro.init(e,t),Xt(e._zod,"optin",(()=>t.innerType._zod.optin)),Xt(e._zod,"optout",(()=>t.innerType._zod.optout)),Xt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Gt(e.source)}|null)$`):void 0})),Xt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0)),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)})),fi=Mt("$ZodDefault",((e,t)=>{ro.init(e,t),e._zod.optin="optional",Xt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((e=>vi(e,t))):vi(r,t)}}));function vi(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const yi=Mt("$ZodPrefault",((e,t)=>{ro.init(e,t),e._zod.optin="optional",Xt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))})),bi=Mt("$ZodNonOptional",((e,t)=>{ro.init(e,t),Xt(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>void 0!==e))):void 0})),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then((t=>ki(t,e))):ki(o,e)}}));function ki(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const wi=Mt("$ZodSuccess",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>(e.value=0===t.issues.length,e))):(e.value=0===r.issues.length,e)}})),xi=Mt("$ZodCatch",((e,t)=>{ro.init(e,t),Xt(e._zod,"optin",(()=>t.innerType._zod.optin)),Xt(e._zod,"optout",(()=>t.innerType._zod.optout)),Xt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>On(e,n,Ft())))},input:e.value}),e.issues=[]),e))):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>On(e,n,Ft())))},input:e.value}),e.issues=[]),e)}})),Ii=Mt("$ZodNaN",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)})),Si=Mt("$ZodPipe",((e,t)=>{ro.init(e,t),Xt(e._zod,"values",(()=>t.in._zod.values)),Xt(e._zod,"optin",(()=>t.in._zod.optin)),Xt(e._zod,"optout",(()=>t.out._zod.optout)),Xt(e._zod,"propValues",(()=>t.in._zod.propValues)),e._zod.parse=(e,n)=>{const r=t.in._zod.run(e,n);return r instanceof Promise?r.then((e=>$i(e,t,n))):$i(r,t,n)}}));function $i(e,t,n){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Oi=Mt("$ZodReadonly",((e,t)=>{ro.init(e,t),Xt(e._zod,"propValues",(()=>t.innerType._zod.propValues)),Xt(e._zod,"values",(()=>t.innerType._zod.values)),Xt(e._zod,"optin",(()=>t.innerType._zod.optin)),Xt(e._zod,"optout",(()=>t.innerType._zod.optout)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ei):Ei(r)}}));function Ei(e){return e.value=Object.freeze(e.value),e}const Ti=Mt("$ZodTemplateLiteral",((e,t)=>{ro.init(e,t);const n=[];for(const r of t.parts)if("object"==typeof r&&null!==r){if(!r._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);const e=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!e)throw new Error(`Invalid template literal part: ${r._zod.traits}`);const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;n.push(e.slice(t,o))}else{if(null!==r&&!cn.has(typeof r))throw new Error(`Invalid template literal part: ${r}`);n.push(dn(`${r}`))}e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(n,r)=>"string"!=typeof n.value?(n.issues.push({input:n.value,inst:e,expected:"template_literal",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)})),Ri=Mt("$ZodPromise",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then((e=>t.innerType._zod.run({value:e,issues:[]},n)))})),Ni=Mt("$ZodLazy",((e,t)=>{ro.init(e,t),Xt(e._zod,"innerType",(()=>t.getter())),Xt(e._zod,"pattern",(()=>e._zod.innerType._zod.pattern)),Xt(e._zod,"propValues",(()=>e._zod.innerType._zod.propValues)),Xt(e._zod,"optin",(()=>e._zod.innerType._zod.optin??void 0)),Xt(e._zod,"optout",(()=>e._zod.innerType._zod.optout??void 0)),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)})),Ai=Mt("$ZodCustom",((e,t)=>{Nr.init(e,t),ro.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((t=>Ci(t,n,r,e)));Ci(o,n,r,e)}}));function Ci(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Rn(e))}}const Pi=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(t){return e[t]??null}const n={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return e=>{switch(e.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${e.expected}، ولكن تم إدخال ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`مدخلات غير مقبولة: يفترض إدخال ${_n(e.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?` أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()} ${r.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()} ${r.unit}`:`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`نَص غير مقبول: يجب أن يبدأ بـ "${e.prefix}"`:"ends_with"===t.format?`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`:"includes"===t.format?`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`:"regex"===t.format?`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`:`${n[t.format]??e.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${e.divisor}`;case"unrecognized_keys":return`معرف${e.keys.length>1?"ات":""} غريب${e.keys.length>1?"ة":""}: ${Ht(e.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${e.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${e.origin}`}}};const Ui=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${e.expected}, daxil olan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Yanlış dəyər: gözlənilən ${_n(e.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()} ${r.unit??"element"}`:`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`:"ends_with"===t.format?`Yanlış mətn: "${t.suffix}" ilə bitməlidir`:"includes"===t.format?`Yanlış mətn: "${t.includes}" daxil olmalıdır`:"regex"===t.format?`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${n[t.format]??e.format}`}case"not_multiple_of":return`Yanlış ədəd: ${e.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${e.keys.length>1?"lar":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilində yanlış açar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${e.origin} daxilində yanlış dəyər`}}};function ji(e,t,n,r){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?r:1===i?t:i>=2&&i<=4?n:r}const zi=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(t){return e[t]??null}const n={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return e=>{switch(e.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${e.expected}, атрымана ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"лік";case"object":if(Array.isArray(e))return"масіў";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Няправільны ўвод: чакалася ${_n(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=ji(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна ${r.verb} ${n}${e.maximum.toString()} ${t}`}return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна быць ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=ji(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Занадта малы: чакалася, што ${e.origin} павінна ${r.verb} ${n}${e.minimum.toString()} ${t}`}return`Занадта малы: чакалася, што ${e.origin} павінна быць ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Няправільны радок: павінен пачынацца з "${t.prefix}"`:"ends_with"===t.format?`Няправільны радок: павінен заканчвацца на "${t.suffix}"`:"includes"===t.format?`Няправільны радок: павінен змяшчаць "${t.includes}"`:"regex"===t.format?`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`:`Няправільны ${n[t.format]??e.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${e.keys.length>1?"ключы":"ключ"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${e.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${e.origin}`}}};const Di=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus invàlid: s'esperava ${e.expected}, s'ha rebut ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Valor invàlid: s'esperava ${_n(e.values[0])}`:`Opció invàlida: s'esperava una de ${Ht(e.values," o ")}`;case"too_big":{const n=e.inclusive?"com a màxim":"menys de",r=t(e.origin);return r?`Massa gran: s'esperava que ${e.origin??"el valor"} contingués ${n} ${e.maximum.toString()} ${r.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"com a mínim":"més de",r=t(e.origin);return r?`Massa petit: s'esperava que ${e.origin} contingués ${n} ${e.minimum.toString()} ${r.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Format invàlid: ha de començar amb "${t.prefix}"`:"ends_with"===t.format?`Format invàlid: ha d'acabar amb "${t.suffix}"`:"includes"===t.format?`Format invàlid: ha d'incloure "${t.includes}"`:"regex"===t.format?`Format invàlid: ha de coincidir amb el patró ${t.pattern}`:`Format invàlid per a ${n[t.format]??e.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${e.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${e.origin}`}}};const Mi=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(t){return e[t]??null}const n={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatný vstup: očekáváno ${e.expected}, obdrženo ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":if(Array.isArray(e))return"pole";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neplatný vstup: očekáváno ${_n(e.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Hodnota je příliš velká: ${e.origin??"hodnota"} musí mít ${n}${e.maximum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš velká: ${e.origin??"hodnota"} musí být ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Hodnota je příliš malá: ${e.origin??"hodnota"} musí mít ${n}${e.minimum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš malá: ${e.origin??"hodnota"} musí být ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neplatný řetězec: musí začínat na "${t.prefix}"`:"ends_with"===t.format?`Neplatný řetězec: musí končit na "${t.suffix}"`:"includes"===t.format?`Neplatný řetězec: musí obsahovat "${t.includes}"`:"regex"===t.format?`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`:`Neplatný formát ${n[t.format]??e.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${e.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${Ht(e.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${e.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${e.origin}`}}};const Li=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function n(t){return e[t]??null}function r(e){return t[e]??e}const o={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldigt input: forventede ${r(e.expected)}, fik ${r((e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tal";case"object":return Array.isArray(e)?"liste":null===e?"null":Object.getPrototypeOf(e)!==Object.prototype&&e.constructor?e.constructor.name:"objekt"}return t})(e.input))}`;case"invalid_value":return 1===e.values.length?`Ugyldig værdi: forventede ${_n(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${Ht(e.values,"|")}`;case"too_big":{const t=e.inclusive?"<=":"<",o=n(e.origin),i=r(e.origin);return o?`For stor: forventede ${i??"value"} ${o.verb} ${t} ${e.maximum.toString()} ${o.unit??"elementer"}`:`For stor: forventede ${i??"value"} havde ${t} ${e.maximum.toString()}`}case"too_small":{const t=e.inclusive?">=":">",o=n(e.origin),i=r(e.origin);return o?`For lille: forventede ${i} ${o.verb} ${t} ${e.minimum.toString()} ${o.unit}`:`For lille: forventede ${i} havde ${t} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: skal starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: skal ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: skal indeholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: skal matche mønsteret ${t.pattern}`:`Ugyldig ${o[t.format]??e.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${e.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${e.origin}`;default:return"Ugyldigt input"}}};const qi=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(t){return e[t]??null}const n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${e.expected}, erhalten ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":if(Array.isArray(e))return"Array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ungültige Eingabe: erwartet ${_n(e.values[0])}`:`Ungültige Option: erwartet eine von ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ${r.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ist`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ${r.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ist`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ungültiger String: muss mit "${t.prefix}" beginnen`:"ends_with"===t.format?`Ungültiger String: muss mit "${t.suffix}" enden`:"includes"===t.format?`Ungültiger String: muss "${t.includes}" enthalten`:"regex"===t.format?`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`:`Ungültig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${e.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${e.origin}`}}};const Zi=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${_n(e.values[0])}`:`Invalid option: expected one of ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function Fi(){return{localeError:Zi()}}const Wi=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(t){return e[t]??null}const n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return e=>{switch(e.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${e.expected}, riceviĝis ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":if(Array.isArray(e))return"tabelo";if(null===e)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nevalida enigo: atendiĝis ${_n(e.values[0])}`:`Nevalida opcio: atendiĝis unu el ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()} ${r.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Tro malgranda: atendiĝis ke ${e.origin} havu ${n}${e.minimum.toString()} ${r.unit}`:`Tro malgranda: atendiĝis ke ${e.origin} estu ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`:"ends_with"===t.format?`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`:"includes"===t.format?`Nevalida karaktraro: devas inkluzivi "${t.includes}"`:"regex"===t.format?`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`:`Nevalida ${n[t.format]??e.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${e.divisor}`;case"unrecognized_keys":return`Nekonata${e.keys.length>1?"j":""} ŝlosilo${e.keys.length>1?"j":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${e.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${e.origin}`}}};const Hi=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inválida: se esperaba ${e.expected}, recibido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"arreglo";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: se esperaba ${_n(e.values[0])}`:`Opción inválida: se esperaba una de ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Demasiado pequeño: se esperaba que ${e.origin} tuviera ${n}${e.minimum.toString()} ${r.unit}`:`Demasiado pequeño: se esperaba que ${e.origin} fuera ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Cadena inválida: debe comenzar con "${t.prefix}"`:"ends_with"===t.format?`Cadena inválida: debe terminar en "${t.suffix}"`:"includes"===t.format?`Cadena inválida: debe incluir "${t.includes}"`:"regex"===t.format?`Cadena inválida: debe coincidir con el patrón ${t.pattern}`:`Inválido ${n[t.format]??e.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Llave inválida en ${e.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inválido en ${e.origin}`}}};const Bi=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(t){return e[t]??null}const n={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return e=>{switch(e.code){case"invalid_type":return`ورودی نامعتبر: می‌بایست ${e.expected} می‌بود، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"آرایه";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} دریافت شد`;case"invalid_value":return 1===e.values.length?`ورودی نامعتبر: می‌بایست ${_n(e.values[0])} می‌بود`:`گزینه نامعتبر: می‌بایست یکی از ${Ht(e.values,"|")} می‌بود`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصر"} باشد`:`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} باشد`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} باشد`:`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} باشد`}case"invalid_format":{const t=e;return"starts_with"===t.format?`رشته نامعتبر: باید با "${t.prefix}" شروع شود`:"ends_with"===t.format?`رشته نامعتبر: باید با "${t.suffix}" تمام شود`:"includes"===t.format?`رشته نامعتبر: باید شامل "${t.includes}" باشد`:"regex"===t.format?`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`:`${n[t.format]??e.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${e.divisor} باشد`;case"unrecognized_keys":return`کلید${e.keys.length>1?"های":""} ناشناس: ${Ht(e.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${e.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${e.origin}`}}};const Ji=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(t){return e[t]??null}const n={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Virheellinen syöte: täytyy olla ${_n(e.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Liian suuri: ${r.subject} täytyy olla ${n}${e.maximum.toString()} ${r.unit}`.trim():`Liian suuri: arvon täytyy olla ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Liian pieni: ${r.subject} täytyy olla ${n}${e.minimum.toString()} ${r.unit}`.trim():`Liian pieni: arvon täytyy olla ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Virheellinen syöte: täytyy alkaa "${t.prefix}"`:"ends_with"===t.format?`Virheellinen syöte: täytyy loppua "${t.suffix}"`:"includes"===t.format?`Virheellinen syöte: täytyy sisältää "${t.includes}"`:"regex"===t.format?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`:`Virheellinen ${n[t.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${Ht(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};const Vi=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : ${e.expected} attendu, ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":if(Array.isArray(e))return"tableau";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} reçu`;case"invalid_value":return 1===e.values.length?`Entrée invalide : ${_n(e.values[0])} attendu`:`Option invalide : une valeur parmi ${Ht(e.values,"|")} attendue`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Trop grand : ${e.origin??"valeur"} doit ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"élément(s)"}`:`Trop grand : ${e.origin??"valeur"} doit être ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Trop petit : ${e.origin} doit ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : ${e.origin} doit être ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au modèle ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Ht(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Gi=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : attendu ${e.expected}, reçu ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrée invalide : attendu ${_n(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"≤":"<",r=t(e.origin);return r?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${n}${e.maximum.toString()} ${r.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"≥":">",r=t(e.origin);return r?`Trop petit : attendu que ${e.origin} ait ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : attendu que ${e.origin} soit ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au motif ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Ht(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Ki=()=>{const e={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function t(t){return e[t]??null}const n={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return e=>{switch(e.code){case"invalid_type":return`קלט לא תקין: צריך ${e.expected}, התקבל ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`קלט לא תקין: צריך ${_n(e.values[0])}`:`קלט לא תקין: צריך אחת מהאפשרויות ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()} ${r.unit}`:`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`מחרוזת לא תקינה: חייבת להתחיל ב"${t.prefix}"`:"ends_with"===t.format?`מחרוזת לא תקינה: חייבת להסתיים ב "${t.suffix}"`:"includes"===t.format?`מחרוזת לא תקינה: חייבת לכלול "${t.includes}"`:"regex"===t.format?`מחרוזת לא תקינה: חייבת להתאים לתבנית ${t.pattern}`:`${n[t.format]??e.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${e.divisor}`;case"unrecognized_keys":return`מפתח${e.keys.length>1?"ות":""} לא מזוה${e.keys.length>1?"ים":"ה"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${e.origin}`;case"invalid_union":default:return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${e.origin}`}}};const Yi=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(t){return e[t]??null}const n={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${e.expected}, a kapott érték ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"szám";case"object":if(Array.isArray(e))return"tömb";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Érvénytelen bemenet: a várt érték ${_n(e.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Túl nagy: ${e.origin??"érték"} mérete túl nagy ${n}${e.maximum.toString()} ${r.unit??"elem"}`:`Túl nagy: a bemeneti érték ${e.origin??"érték"} túl nagy: ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Túl kicsi: a bemeneti érték ${e.origin} mérete túl kicsi ${n}${e.minimum.toString()} ${r.unit}`:`Túl kicsi: a bemeneti érték ${e.origin} túl kicsi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`:"ends_with"===t.format?`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`:"includes"===t.format?`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`:"regex"===t.format?`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`:`Érvénytelen ${n[t.format]??e.format}`}case"not_multiple_of":return`Érvénytelen szám: ${e.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${e.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${e.origin}`}}};const Xi=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak valid: diharapkan ${_n(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: diharapkan ${e.origin} memiliki ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak valid: harus dimulai dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak valid: harus berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak valid: harus menyertakan "${t.includes}"`:"regex"===t.format?`String tidak valid: harus sesuai pola ${t.pattern}`:`${n[t.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`}}};const Qi=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(t){return e[t]??null}const n={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return e=>{switch(e.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":if(Array.isArray(e))return"fylki";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} þar sem á að vera ${e.expected}`;case"invalid_value":return 1===e.values.length?`Rangt gildi: gert ráð fyrir ${_n(e.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} hafi ${n}${e.maximum.toString()} ${r.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} sé ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Of lítið: gert er ráð fyrir að ${e.origin} hafi ${n}${e.minimum.toString()} ${r.unit}`:`Of lítið: gert er ráð fyrir að ${e.origin} sé ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ógildur strengur: verður að byrja á "${t.prefix}"`:"ends_with"===t.format?`Ógildur strengur: verður að enda á "${t.suffix}"`:"includes"===t.format?`Ógildur strengur: verður að innihalda "${t.includes}"`:"regex"===t.format?`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`:`Rangt ${n[t.format]??e.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${e.divisor}`;case"unrecognized_keys":return`Óþekkt ${e.keys.length>1?"ir lyklar":"ur lykill"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${e.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${e.origin}`}}};const es=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(t){return e[t]??null}const n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":if(Array.isArray(e))return"vettore";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input non valido: atteso ${_n(e.values[0])}`:`Opzione non valida: atteso uno tra ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Troppo grande: ${e.origin??"valore"} deve avere ${n}${e.maximum.toString()} ${r.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Troppo piccolo: ${e.origin} deve avere ${n}${e.minimum.toString()} ${r.unit}`:`Troppo piccolo: ${e.origin} deve essere ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Stringa non valida: deve iniziare con "${t.prefix}"`:"ends_with"===t.format?`Stringa non valida: deve terminare con "${t.suffix}"`:"includes"===t.format?`Stringa non valida: deve includere "${t.includes}"`:"regex"===t.format?`Stringa non valida: deve corrispondere al pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`}}};const ts=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(t){return e[t]??null}const n={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return e=>{switch(e.code){case"invalid_type":return`無効な入力: ${e.expected}が期待されましたが、${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"数値";case"object":if(Array.isArray(e))return"配列";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}が入力されました`;case"invalid_value":return 1===e.values.length?`無効な入力: ${_n(e.values[0])}が期待されました`:`無効な選択: ${Ht(e.values,"、")}のいずれかである必要があります`;case"too_big":{const n=e.inclusive?"以下である":"より小さい",r=t(e.origin);return r?`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${r.unit??"要素"}${n}必要があります`:`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${n}必要があります`}case"too_small":{const n=e.inclusive?"以上である":"より大きい",r=t(e.origin);return r?`小さすぎる値: ${e.origin}は${e.minimum.toString()}${r.unit}${n}必要があります`:`小さすぎる値: ${e.origin}は${e.minimum.toString()}${n}必要があります`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無効な文字列: "${t.prefix}"で始まる必要があります`:"ends_with"===t.format?`無効な文字列: "${t.suffix}"で終わる必要があります`:"includes"===t.format?`無効な文字列: "${t.includes}"を含む必要があります`:"regex"===t.format?`無効な文字列: パターン${t.pattern}に一致する必要があります`:`無効な${n[t.format]??e.format}`}case"not_multiple_of":return`無効な数値: ${e.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${e.keys.length>1?"群":""}: ${Ht(e.keys,"、")}`;case"invalid_key":return`${e.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${e.origin}内の無効な値`}}};const ns=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(t){return e[t]??null}const n={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return e=>{switch(e.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e.expected} ប៉ុន្តែទទួលបាន ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":if(Array.isArray(e))return"អារេ (Array)";if(null===e)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${_n(e.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()} ${r.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()} ${r.unit}`:`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`:"ends_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`:"includes"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`:"regex"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`:`មិនត្រឹមត្រូវ៖ ${n[t.format]??e.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${e.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${Ht(e.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`}}};const rs=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return e=>{switch(e.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${e.expected}, 받은 타입은 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}입니다`;case"invalid_value":return 1===e.values.length?`잘못된 입력: 값은 ${_n(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${Ht(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const n=e.inclusive?"이하":"미만",r="미만"===n?"이어야 합니다":"여야 합니다",o=t(e.origin),i=(null==o?void 0:o.unit)??"요소";return o?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${i} ${n}${r}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${n}${r}`}case"too_small":{const n=e.inclusive?"이상":"초과",r="이상"===n?"이어야 합니다":"여야 합니다",o=t(e.origin),i=(null==o?void 0:o.unit)??"요소";return o?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${i} ${n}${r}`:`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()} ${n}${r}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`:"ends_with"===t.format?`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`:"includes"===t.format?`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`:"regex"===t.format?`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`:`잘못된 ${n[t.format]??e.format}`}case"not_multiple_of":return`잘못된 숫자: ${e.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${Ht(e.keys,", ")}`;case"invalid_key":return`잘못된 키: ${e.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${e.origin}`}}};const os=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(t){return e[t]??null}const n={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return e=>{switch(e.code){case"invalid_type":return`Грешен внес: се очекува ${e.expected}, примено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"број";case"object":if(Array.isArray(e))return"низа";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${_n(e.values[0])}`:`Грешана опција: се очекува една ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Премногу голем: се очекува ${e.origin??"вредноста"} да има ${n}${e.maximum.toString()} ${r.unit??"елементи"}`:`Премногу голем: се очекува ${e.origin??"вредноста"} да биде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Премногу мал: се очекува ${e.origin} да има ${n}${e.minimum.toString()} ${r.unit}`:`Премногу мал: се очекува ${e.origin} да биде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неважечка низа: мора да започнува со "${t.prefix}"`:"ends_with"===t.format?`Неважечка низа: мора да завршува со "${t.suffix}"`:"includes"===t.format?`Неважечка низа: мора да вклучува "${t.includes}"`:"regex"===t.format?`Неважечка низа: мора да одгоара на патернот ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${e.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${e.origin}`}}};const is=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak sah: dijangka ${_n(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: dijangka ${e.origin??"nilai"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: dijangka ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak sah: mesti bermula dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak sah: mesti berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak sah: mesti mengandungi "${t.includes}"`:"regex"===t.format?`String tidak sah: mesti sepadan dengan corak ${t.pattern}`:`${n[t.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Ht(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`}}};const ss=()=>{const e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(t){return e[t]??null}const n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ongeldige invoer: verwacht ${_n(e.values[0])}`:`Ongeldige optie: verwacht één van ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} ${r.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} is`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} ${r.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} is`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ongeldige tekst: moet met "${t.prefix}" beginnen`:"ends_with"===t.format?`Ongeldige tekst: moet op "${t.suffix}" eindigen`:"includes"===t.format?`Ongeldige tekst: moet "${t.includes}" bevatten`:"regex"===t.format?`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`:`Ongeldig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`}}};const as=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(t){return e[t]??null}const n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":if(Array.isArray(e))return"liste";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ugyldig verdi: forventet ${_n(e.values[0])}`:`Ugyldig valg: forventet en av ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()} ${r.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()} ${r.unit}`:`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: må starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: må ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: må inneholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: må matche mønsteret ${t.pattern}`:`Ugyldig ${n[t.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${e.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`}}};const us=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`Fâsit giren: umulan ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":if(Array.isArray(e))return"saf";if(null===e)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Fâsit giren: umulan ${_n(e.values[0])}`:`Fâsit tercih: mûteberler ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} ${r.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} olmalıydı.`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} ${r.unit} sahip olmalıydı.`:`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} olmalıydı.`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Fâsit metin: "${t.prefix}" ile başlamalı.`:"ends_with"===t.format?`Fâsit metin: "${t.suffix}" ile bitmeli.`:"includes"===t.format?`Fâsit metin: "${t.includes}" ihtivâ etmeli.`:"regex"===t.format?`Fâsit metin: ${t.pattern} nakşına uymalı.`:`Fâsit ${n[t.format]??e.format}`}case"not_multiple_of":return`Fâsit sayı: ${e.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`${e.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${e.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};const ls=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(t){return e[t]??null}const n={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return e=>{switch(e.code){case"invalid_type":return`ناسم ورودي: باید ${e.expected} وای, مګر ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"ارې";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} ترلاسه شو`;case"invalid_value":return 1===e.values.length?`ناسم ورودي: باید ${_n(e.values[0])} وای`:`ناسم انتخاب: باید یو له ${Ht(e.values,"|")} څخه وای`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصرونه"} ولري`:`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} وي`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} ولري`:`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} وي`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ناسم متن: باید د "${t.prefix}" سره پیل شي`:"ends_with"===t.format?`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`:"includes"===t.format?`ناسم متن: باید "${t.includes}" ولري`:"regex"===t.format?`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`:`${n[t.format]??e.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${e.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${e.keys.length>1?"کلیډونه":"کلیډ"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${e.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${e.origin} کې`}}};const cs=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(t){return e[t]??null}const n={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return e=>{switch(e.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${e.expected}, otrzymano ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":if(Array.isArray(e))return"tablica";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nieprawidłowe dane wejściowe: oczekiwano ${_n(e.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Za duża wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.maximum.toString()} ${r.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Za mała wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.minimum.toString()} ${r.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`:"ends_with"===t.format?`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`:"includes"===t.format?`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`:"regex"===t.format?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`:`Nieprawidłow(y/a/e) ${n[t.format]??e.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${e.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${e.origin}`}}};const ds=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(t){return e[t]??null}const n={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inválido: esperado ${e.expected}, recebido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"array";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: esperado ${_n(e.values[0])}`:`Opção inválida: esperada uma das ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Muito pequeno: esperado que ${e.origin} tivesse ${n}${e.minimum.toString()} ${r.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Texto inválido: deve começar com "${t.prefix}"`:"ends_with"===t.format?`Texto inválido: deve terminar com "${t.suffix}"`:"includes"===t.format?`Texto inválido: deve incluir "${t.includes}"`:"regex"===t.format?`Texto inválido: deve corresponder ao padrão ${t.pattern}`:`${n[t.format]??e.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Chave inválida em ${e.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${e.origin}`;default:return"Campo inválido"}}};function ps(e,t,n,r){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?r:1===i?t:i>=2&&i<=4?n:r}const ms=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(t){return e[t]??null}const n={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return e=>{switch(e.code){case"invalid_type":return`Неверный ввод: ожидалось ${e.expected}, получено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"массив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неверный ввод: ожидалось ${_n(e.values[0])}`:`Неверный вариант: ожидалось одно из ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=ps(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет иметь ${n}${e.maximum.toString()} ${t}`}return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=ps(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Слишком маленькое значение: ожидалось, что ${e.origin} будет иметь ${n}${e.minimum.toString()} ${t}`}return`Слишком маленькое значение: ожидалось, что ${e.origin} будет ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неверная строка: должна начинаться с "${t.prefix}"`:"ends_with"===t.format?`Неверная строка: должна заканчиваться на "${t.suffix}"`:"includes"===t.format?`Неверная строка: должна содержать "${t.includes}"`:"regex"===t.format?`Неверная строка: должна соответствовать шаблону ${t.pattern}`:`Неверный ${n[t.format]??e.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспознанн${e.keys.length>1?"ые":"ый"} ключ${e.keys.length>1?"и":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${e.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${e.origin}`}}};const _s=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(t){return e[t]??null}const n={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${e.expected}, prejeto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"število";case"object":if(Array.isArray(e))return"tabela";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neveljaven vnos: pričakovano ${_n(e.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} imelo ${n}${e.maximum.toString()} ${r.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Premajhno: pričakovano, da bo ${e.origin} imelo ${n}${e.minimum.toString()} ${r.unit}`:`Premajhno: pričakovano, da bo ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neveljaven niz: mora se začeti z "${t.prefix}"`:"ends_with"===t.format?`Neveljaven niz: mora se končati z "${t.suffix}"`:"includes"===t.format?`Neveljaven niz: mora vsebovati "${t.includes}"`:"regex"===t.format?`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`:`Neveljaven ${n[t.format]??e.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i ključi":" ključ"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${e.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`}}};const hs=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(t){return e[t]??null}const n={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${e.expected}, fick ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":if(Array.isArray(e))return"lista";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ogiltig inmatning: förväntat ${_n(e.values[0])}`:`Ogiltigt val: förväntade en av ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`För stor(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()} ${r.unit??"element"}`:`För stor(t): förväntat ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()} ${r.unit}`:`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ogiltig sträng: måste börja med "${t.prefix}"`:"ends_with"===t.format?`Ogiltig sträng: måste sluta med "${t.suffix}"`:"includes"===t.format?`Ogiltig sträng: måste innehålla "${t.includes}"`:"regex"===t.format?`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`:`Ogiltig(t) ${n[t.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${e.origin??"värdet"}`}}};const gs=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(t){return e[t]??null}const n={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e.expected}, பெறப்பட்டது ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"எண் அல்லாதது":"எண்";case"object":if(Array.isArray(e))return"அணி";if(null===e)return"வெறுமை";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${_n(e.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${Ht(e.values,"|")} இல் ஒன்று`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ${r.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ${r.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const t=e;return"starts_with"===t.format?`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`:"ends_with"===t.format?`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`:"includes"===t.format?`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`:"regex"===t.format?`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${n[t.format]??e.format}`}case"not_multiple_of":return`தவறான எண்: ${e.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${e.keys.length>1?"கள்":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`${e.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${e.origin} இல் தவறான மதிப்பு`}}};const fs=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(t){return e[t]??null}const n={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return e=>{switch(e.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e.expected} แต่ได้รับ ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":if(Array.isArray(e))return"อาร์เรย์ (Array)";if(null===e)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ค่าไม่ถูกต้อง: ควรเป็น ${_n(e.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"ไม่เกิน":"น้อยกว่า",r=t(e.origin);return r?`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()} ${r.unit??"รายการ"}`:`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"อย่างน้อย":"มากกว่า",r=t(e.origin);return r?`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()} ${r.unit}`:`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`:"ends_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`:"includes"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`:"regex"===t.format?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`:`รูปแบบไม่ถูกต้อง: ${n[t.format]??e.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${e.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${Ht(e.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${e.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${e.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};const vs=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(t){return e[t]??null}const n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return e=>{switch(e.code){case"invalid_type":return`Geçersiz değer: beklenen ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Geçersiz değer: beklenen ${_n(e.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()} ${r.unit??"öğe"}`:`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Geçersiz metin: "${t.prefix}" ile başlamalı`:"ends_with"===t.format?`Geçersiz metin: "${t.suffix}" ile bitmeli`:"includes"===t.format?`Geçersiz metin: "${t.includes}" içermeli`:"regex"===t.format?`Geçersiz metin: ${t.pattern} desenine uymalı`:`Geçersiz ${n[t.format]??e.format}`}case"not_multiple_of":return`Geçersiz sayı: ${e.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${e.keys.length>1?"lar":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`${e.origin} içinde geçersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${e.origin} içinde geçersiz değer`}}};const ys=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(t){return e[t]??null}const n={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return e=>{switch(e.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${e.expected}, отримано ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"масив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неправильні вхідні дані: очікується ${_n(e.values[0])}`:`Неправильна опція: очікується одне з ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Занадто велике: очікується, що ${e.origin??"значення"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"елементів"}`:`Занадто велике: очікується, що ${e.origin??"значення"} буде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Занадто мале: очікується, що ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Занадто мале: очікується, що ${e.origin} буде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неправильний рядок: повинен починатися з "${t.prefix}"`:"ends_with"===t.format?`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`:"includes"===t.format?`Неправильний рядок: повинен містити "${t.includes}"`:"regex"===t.format?`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`:`Неправильний ${n[t.format]??e.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${e.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${e.keys.length>1?"і":""}: ${Ht(e.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${e.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${e.origin}`}}};const bs=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(t){return e[t]??null}const n={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return e=>{switch(e.code){case"invalid_type":return`غلط ان پٹ: ${e.expected} متوقع تھا، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"نمبر";case"object":if(Array.isArray(e))return"آرے";if(null===e)return"نل";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} موصول ہوا`;case"invalid_value":return 1===e.values.length?`غلط ان پٹ: ${_n(e.values[0])} متوقع تھا`:`غلط آپشن: ${Ht(e.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`بہت بڑا: ${e.origin??"ویلیو"} کے ${n}${e.maximum.toString()} ${r.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${e.origin??"ویلیو"} کا ${n}${e.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`بہت چھوٹا: ${e.origin} کے ${n}${e.minimum.toString()} ${r.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${e.origin} کا ${n}${e.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const t=e;return"starts_with"===t.format?`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`:"ends_with"===t.format?`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`:"includes"===t.format?`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`:"regex"===t.format?`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`:`غلط ${n[t.format]??e.format}`}case"not_multiple_of":return`غلط نمبر: ${e.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${e.keys.length>1?"ز":""}: ${Ht(e.keys,"، ")}`;case"invalid_key":return`${e.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${e.origin} میں غلط ویلیو`}}};const ks=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(t){return e[t]??null}const n={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return e=>{switch(e.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${e.expected}, nhận được ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"số";case"object":if(Array.isArray(e))return"mảng";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Đầu vào không hợp lệ: mong đợi ${_n(e.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Quá lớn: mong đợi ${e.origin??"giá trị"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"phần tử"}`:`Quá lớn: mong đợi ${e.origin??"giá trị"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Quá nhỏ: mong đợi ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Quá nhỏ: mong đợi ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`:"ends_with"===t.format?`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`:"includes"===t.format?`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`:"regex"===t.format?`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`:`${n[t.format]??e.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${e.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${Ht(e.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${e.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${e.origin}`}}};const ws=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(t){return e[t]??null}const n={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return e=>{switch(e.code){case"invalid_type":return`无效输入:期望 ${e.expected},实际接收 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"非数字(NaN)":"数字";case"object":if(Array.isArray(e))return"数组";if(null===e)return"空值(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`无效输入:期望 ${_n(e.values[0])}`:`无效选项:期望以下之一 ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()} ${r.unit??"个元素"}`:`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`无效字符串:必须以 "${t.prefix}" 开头`:"ends_with"===t.format?`无效字符串:必须以 "${t.suffix}" 结尾`:"includes"===t.format?`无效字符串:必须包含 "${t.includes}"`:"regex"===t.format?`无效字符串:必须满足正则表达式 ${t.pattern}`:`无效${n[t.format]??e.format}`}case"not_multiple_of":return`无效数字:必须是 ${e.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${Ht(e.keys,", ")}`;case"invalid_key":return`${e.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${e.origin} 中包含无效值(value)`}}};const xs=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(t){return e[t]??null}const n={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return e=>{switch(e.code){case"invalid_type":return`無效的輸入值:預期為 ${e.expected},但收到 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`無效的輸入值:預期為 ${_n(e.values[0])}`:`無效的選項:預期為以下其中之一 ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()} ${r.unit??"個元素"}`:`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()} ${r.unit}`:`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無效的字串:必須以 "${t.prefix}" 開頭`:"ends_with"===t.format?`無效的字串:必須以 "${t.suffix}" 結尾`:"includes"===t.format?`無效的字串:必須包含 "${t.includes}"`:"regex"===t.format?`無效的字串:必須符合格式 ${t.pattern}`:`無效的 ${n[t.format]??e.format}`}case"not_multiple_of":return`無效的數字:必須為 ${e.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${e.keys.length>1?"們":""}:${Ht(e.keys,"、")}`;case"invalid_key":return`${e.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${e.origin} 中有無效的值`}}};const Is=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(t){return e[t]??null}const n={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return e=>{switch(e.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${e.expected}, àmọ̀ a rí ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nọ́mbà";case"object":if(Array.isArray(e))return"akopọ";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ìbáwọlé aṣìṣe: a ní láti fi ${_n(e.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${Ht(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tó pọ̀ jù: a ní láti jẹ́ pé ${e.origin??"iye"} ${r.verb} ${n}${e.maximum} ${r.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${n}${e.maximum}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Kéré ju: a ní láti jẹ́ pé ${e.origin} ${r.verb} ${n}${e.minimum} ${r.unit}`:`Kéré ju: a ní láti jẹ́ ${n}${e.minimum}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`:"ends_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`:"includes"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`:"regex"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`:`Aṣìṣe: ${n[t.format]??e.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${e.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${Ht(e.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${e.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${e.origin}`}}};const Ss=Object.freeze(Object.defineProperty({__proto__:null,ar:function(){return{localeError:Pi()}},az:function(){return{localeError:Ui()}},be:function(){return{localeError:zi()}},ca:function(){return{localeError:Di()}},cs:function(){return{localeError:Mi()}},da:function(){return{localeError:Li()}},de:function(){return{localeError:qi()}},en:Fi,eo:function(){return{localeError:Wi()}},es:function(){return{localeError:Hi()}},fa:function(){return{localeError:Bi()}},fi:function(){return{localeError:Ji()}},fr:function(){return{localeError:Vi()}},frCA:function(){return{localeError:Gi()}},he:function(){return{localeError:Ki()}},hu:function(){return{localeError:Yi()}},id:function(){return{localeError:Xi()}},is:function(){return{localeError:Qi()}},it:function(){return{localeError:es()}},ja:function(){return{localeError:ts()}},kh:function(){return{localeError:ns()}},ko:function(){return{localeError:rs()}},mk:function(){return{localeError:os()}},ms:function(){return{localeError:is()}},nl:function(){return{localeError:ss()}},no:function(){return{localeError:as()}},ota:function(){return{localeError:us()}},pl:function(){return{localeError:cs()}},ps:function(){return{localeError:ls()}},pt:function(){return{localeError:ds()}},ru:function(){return{localeError:ms()}},sl:function(){return{localeError:_s()}},sv:function(){return{localeError:hs()}},ta:function(){return{localeError:gs()}},th:function(){return{localeError:fs()}},tr:function(){return{localeError:vs()}},ua:function(){return{localeError:ys()}},ur:function(){return{localeError:bs()}},vi:function(){return{localeError:ks()}},yo:function(){return{localeError:Is()}},zhCN:function(){return{localeError:ws()}},zhTW:function(){return{localeError:xs()}}},Symbol.toStringTag,{value:"Module"})),$s=Symbol("ZodOutput"),Os=Symbol("ZodInput");class Es{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&"object"==typeof n&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Ts(){return new Es}const Rs=Ts();function Ns(e,t){return new e({type:"string",...mn(t)})}function As(e,t){return new e({type:"string",coerce:!0,...mn(t)})}function Cs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...mn(t)})}function Ps(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...mn(t)})}function Us(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...mn(t)})}function js(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...mn(t)})}function zs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...mn(t)})}function Ds(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...mn(t)})}function Ms(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...mn(t)})}function Ls(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...mn(t)})}function qs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...mn(t)})}function Zs(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...mn(t)})}function Fs(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...mn(t)})}function Ws(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...mn(t)})}function Hs(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...mn(t)})}function Bs(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...mn(t)})}function Js(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...mn(t)})}function Vs(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...mn(t)})}function Gs(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...mn(t)})}function Ks(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...mn(t)})}function Ys(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...mn(t)})}function Xs(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...mn(t)})}function Qs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...mn(t)})}function ea(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...mn(t)})}const ta={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function na(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...mn(t)})}function ra(e,t){return new e({type:"string",format:"date",check:"string_format",...mn(t)})}function oa(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...mn(t)})}function ia(e,t){return new e({type:"string",format:"duration",check:"string_format",...mn(t)})}function sa(e,t){return new e({type:"number",checks:[],...mn(t)})}function aa(e,t){return new e({type:"number",coerce:!0,checks:[],...mn(t)})}function ua(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...mn(t)})}function la(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...mn(t)})}function ca(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...mn(t)})}function da(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...mn(t)})}function pa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...mn(t)})}function ma(e,t){return new e({type:"boolean",...mn(t)})}function _a(e,t){return new e({type:"boolean",coerce:!0,...mn(t)})}function ha(e,t){return new e({type:"bigint",...mn(t)})}function ga(e,t){return new e({type:"bigint",coerce:!0,...mn(t)})}function fa(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...mn(t)})}function va(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...mn(t)})}function ya(e,t){return new e({type:"symbol",...mn(t)})}function ba(e,t){return new e({type:"undefined",...mn(t)})}function ka(e,t){return new e({type:"null",...mn(t)})}function wa(e){return new e({type:"any"})}function xa(e){return new e({type:"unknown"})}function Ia(e,t){return new e({type:"never",...mn(t)})}function Sa(e,t){return new e({type:"void",...mn(t)})}function $a(e,t){return new e({type:"date",...mn(t)})}function Oa(e,t){return new e({type:"date",coerce:!0,...mn(t)})}function Ea(e,t){return new e({type:"nan",...mn(t)})}function Ta(e,t){return new Cr({check:"less_than",...mn(t),value:e,inclusive:!1})}function Ra(e,t){return new Cr({check:"less_than",...mn(t),value:e,inclusive:!0})}function Na(e,t){return new Pr({check:"greater_than",...mn(t),value:e,inclusive:!1})}function Aa(e,t){return new Pr({check:"greater_than",...mn(t),value:e,inclusive:!0})}function Ca(e){return Na(0,e)}function Pa(e){return Ta(0,e)}function Ua(e){return Ra(0,e)}function ja(e){return Aa(0,e)}function za(e,t){return new Ur({check:"multiple_of",...mn(t),value:e})}function Da(e,t){return new Dr({check:"max_size",...mn(t),maximum:e})}function Ma(e,t){return new Mr({check:"min_size",...mn(t),minimum:e})}function La(e,t){return new Lr({check:"size_equals",...mn(t),size:e})}function qa(e,t){return new qr({check:"max_length",...mn(t),maximum:e})}function Za(e,t){return new Zr({check:"min_length",...mn(t),minimum:e})}function Fa(e,t){return new Fr({check:"length_equals",...mn(t),length:e})}function Wa(e,t){return new Hr({check:"string_format",format:"regex",...mn(t),pattern:e})}function Ha(e){return new Br({check:"string_format",format:"lowercase",...mn(e)})}function Ba(e){return new Jr({check:"string_format",format:"uppercase",...mn(e)})}function Ja(e,t){return new Vr({check:"string_format",format:"includes",...mn(t),includes:e})}function Va(e,t){return new Gr({check:"string_format",format:"starts_with",...mn(t),prefix:e})}function Ga(e,t){return new Kr({check:"string_format",format:"ends_with",...mn(t),suffix:e})}function Ka(e,t,n){return new Xr({check:"property",property:e,schema:t,...mn(n)})}function Ya(e,t){return new Qr({check:"mime_type",mime:e,...mn(t)})}function Xa(e){return new eo({check:"overwrite",tx:e})}function Qa(e){return Xa((t=>t.normalize(e)))}function eu(){return Xa((e=>e.trim()))}function tu(){return Xa((e=>e.toLowerCase()))}function nu(){return Xa((e=>e.toUpperCase()))}function ru(e,t,n){return new e({type:"array",element:t,...mn(n)})}function ou(e,t,n,r){const o=n instanceof ro;return new e({type:"tuple",items:t,rest:o?n:null,...mn(o?r:n)})}function iu(e,t){return new e({type:"file",...mn(t)})}function su(e,t,n){const r=mn(n);r.abort??(r.abort=!0);return new e({type:"custom",check:"custom",fn:t,...r})}function au(e,t,n){return new e({type:"custom",check:"custom",fn:t,...mn(n)})}function uu(e){const t=lu((n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Rn(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(Rn(r))}},e(n.value,n))));return t}function lu(e,t){const n=new Nr({check:"custom",...mn(t)});return n._zod.check=e,n}function cu(e,t){const n=mn(t);let r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(r=r.map((e=>"string"==typeof e?e.toLowerCase():e)),o=o.map((e=>"string"==typeof e?e.toLowerCase():e)));const i=new Set(r),s=new Set(o),a=e.Pipe??Si,u=e.Boolean??jo,l=e.String??oo,c=new(e.Transform??mi)({type:"transform",transform:(e,t)=>{let r=e;return"sensitive"!==n.case&&(r=r.toLowerCase()),!!i.has(r)||!s.has(r)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:t.value,inst:c,continue:!1}),{})},error:n.error}),d=new a({type:"pipe",in:new l({type:"string",error:n.error}),out:c,error:n.error});return new a({type:"pipe",in:d,out:new u({type:"boolean",error:n.error}),error:n.error})}function du(e,t,n,r={}){const o=mn(r),i={...mn(r),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...o};n instanceof RegExp&&(i.pattern=n);return new e(i)}class pu{constructor(e){this._def=e,this.def=e}implement(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=(...n)=>{const r=this._def.input?qn(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const o=e(...r);return this._def.output?qn(this._def.output,o,void 0,{callee:t}):o};return t}implementAsync(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=async(...n)=>{const r=this._def.input?await Fn(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const o=await e(...r);return this._def.output?Fn(this._def.output,o,void 0,{callee:t}):o};return t}input(...e){const t=this.constructor;return Array.isArray(e[0])?new t({type:"function",input:new ri({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new t({type:"function",input:e[0],output:this._def.output})}output(e){return new(0,this.constructor)({type:"function",input:this._def.input,output:e})}}function mu(e){return new pu({type:"function",input:Array.isArray(null==e?void 0:e.input)?ou(ri,null==e?void 0:e.input):(null==e?void 0:e.input)??ru(Vo,xa(Fo)),output:(null==e?void 0:e.output)??xa(Fo)})}class _u{constructor(e){this.counter=0,this.metadataRegistry=(null==e?void 0:e.metadata)??Rs,this.target=(null==e?void 0:e.target)??"draft-2020-12",this.unrepresentable=(null==e?void 0:e.unrepresentable)??"throw",this.override=(null==e?void 0:e.override)??(()=>{}),this.io=(null==e?void 0:e.io)??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n,r,o,i;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},u=this.seen.get(e);if(u){u.count++;return t.schemaPath.includes(e)&&(u.cycle=t.path),u.schema}const l={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,l);const c=null==(r=(n=e._zod).toJSONSchema)?void 0:r.call(n);if(c)l.schema=c;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},r=e._zod.parent;if(r)l.ref=r,this.process(r,n),this.seen.get(r).isParent=!0;else{const t=l.schema;switch(s.type){case"string":{const n=t;n.type="string";const{minimum:r,maximum:o,format:i,patterns:s,contentEncoding:u}=e._zod.bag;if("number"==typeof r&&(n.minLength=r),"number"==typeof o&&(n.maxLength=o),i&&(n.format=a[i]??i,""===n.format&&delete n.format),u&&(n.contentEncoding=u),s&&s.size>0){const e=[...s];1===e.length?n.pattern=e[0].source:e.length>1&&(l.schema.allOf=[...e.map((e=>({..."draft-7"===this.target||"draft-4"===this.target?{type:"string"}:{},pattern:e.source})))])}break}case"number":{const n=t,{minimum:r,maximum:o,format:i,multipleOf:s,exclusiveMaximum:a,exclusiveMinimum:u}=e._zod.bag;"string"==typeof i&&i.includes("int")?n.type="integer":n.type="number","number"==typeof u&&("draft-4"===this.target?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u),"number"==typeof r&&(n.minimum=r,"number"==typeof u&&"draft-4"!==this.target&&(u>=r?delete n.minimum:delete n.exclusiveMinimum)),"number"==typeof a&&("draft-4"===this.target?(n.maximum=a,n.exclusiveMaximum=!0):n.exclusiveMaximum=a),"number"==typeof o&&(n.maximum=o,"number"==typeof a&&"draft-4"!==this.target&&(a<=o?delete n.maximum:delete n.exclusiveMaximum)),"number"==typeof s&&(n.multipleOf=s);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const r=t,{minimum:o,maximum:i}=e._zod.bag;"number"==typeof o&&(r.minItems=o),"number"==typeof i&&(r.maxItems=i),r.type="array",r.items=this.process(s.element,{...n,path:[...n.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const r=s.shape;for(const t in r)e.properties[t]=this.process(r[t],{...n,path:[...n.path,"properties",t]});const i=new Set(Object.keys(r)),a=new Set([...i].filter((e=>{const t=s.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout})));a.size>0&&(e.required=Array.from(a)),"never"===(null==(o=s.catchall)?void 0:o._zod.def.type)?e.additionalProperties=!1:s.catchall?s.catchall&&(e.additionalProperties=this.process(s.catchall,{...n,path:[...n.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=s.options.map(((e,t)=>this.process(e,{...n,path:[...n.path,"anyOf",t]})));break;case"intersection":{const e=t,r=this.process(s.left,{...n,path:[...n.path,"allOf",0]}),o=this.process(s.right,{...n,path:[...n.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,a=[...i(r)?r.allOf:[r],...i(o)?o.allOf:[o]];e.allOf=a;break}case"tuple":{const r=t;r.type="array";const o=s.items.map(((e,t)=>this.process(e,{...n,path:[...n.path,"prefixItems",t]})));if("draft-2020-12"===this.target?r.prefixItems=o:r.items=o,s.rest){const e=this.process(s.rest,{...n,path:[...n.path,"items"]});"draft-2020-12"===this.target?r.items=e:r.additionalItems=e}s.rest&&(r.items=this.process(s.rest,{...n,path:[...n.path,"items"]}));const{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(r.minItems=i),"number"==typeof a&&(r.maxItems=a);break}case"record":{const e=t;e.type="object","draft-4"!==this.target&&(e.propertyNames=this.process(s.keyType,{...n,path:[...n.path,"propertyNames"]})),e.additionalProperties=this.process(s.valueType,{...n,path:[...n.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,n=Wt(s.entries);n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),e.enum=n;break}case"literal":{const e=t,n=[];for(const t of s.values)if(void 0===t){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");n.push(Number(t))}else n.push(t);if(0===n.length);else if(1===n.length){const t=n[0];e.type=null===t?"null":typeof t,"draft-4"===this.target?e.enum=[t]:e.const=t}else n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),n.every((e=>"boolean"==typeof e))&&(e.type="string"),n.every((e=>null===e))&&(e.type="null"),e.enum=n;break}case"file":{const n=t,r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:i,mime:s}=e._zod.bag;void 0!==o&&(r.minLength=o),void 0!==i&&(r.maxLength=i),s?1===s.length?(r.contentMediaType=s[0],Object.assign(n,r)):n.anyOf=s.map((e=>({...r,contentMediaType:e}))):Object.assign(n,r);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(s.innerType,n);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(s.innerType,n),l.ref=s.innerType;break;case"success":t.type="boolean";break;case"default":this.process(s.innerType,n),l.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue));break;case"prefault":this.process(s.innerType,n),l.ref=s.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break;case"catch":{let e;this.process(s.innerType,n),l.ref=s.innerType;try{e=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const n=t,r=e._zod.pattern;if(!r)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=r.source;break}case"pipe":{const e="input"===this.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;this.process(e,n),l.ref=e;break}case"readonly":this.process(s.innerType,n),l.ref=s.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,n),l.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const d=this.metadataRegistry.get(e);d&&Object.assign(l.schema,d),"input"===this.io&&gu(e)&&(delete l.schema.examples,delete l.schema.default),"input"===this.io&&l.schema._prefault&&((i=l.schema).default??(i.default=l.schema._prefault)),delete l.schema._prefault;return this.seen.get(e).schema}emit(e,t){var n,r,o,i,s,a;const u={cycles:(null==t?void 0:t.cycles)??"ref",reused:(null==t?void 0:t.reused)??"inline",external:(null==t?void 0:t.external)??void 0},l=this.seen.get(e);if(!l)throw new Error("Unprocessed schema. This is a bug in Zod.");const c=e=>{var t;const n="draft-2020-12"===this.target?"$defs":"definitions";if(u.external){const r=null==(t=u.external.registry.get(e[0]))?void 0:t.id,o=u.external.uri??(e=>e);if(r)return{ref:o(r)};const i=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=i,{defId:i,ref:`${o("__shared")}#/${n}/${i}`}}if(e[1]===l)return{ref:"#"};const r=`#/${n}/`,o=e[1].schema.id??"__schema"+this.counter++;return{defId:o,ref:r+o}},d=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:n,defId:r}=c(e);t.def={...t.schema},r&&(t.defId=r);const o=t.schema;for(const i in o)delete o[i];o.$ref=n};if("throw"===u.cycles)for(const g of this.seen.entries()){const e=g[1];if(e.cycle)throw new Error(`Cycle detected: #/${null==(n=e.cycle)?void 0:n.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const g of this.seen.entries()){const t=g[1];if(e===g[0]){d(g);continue}if(u.external){const t=null==(r=u.external.registry.get(g[0]))?void 0:r.id;if(e!==g[0]&&t){d(g);continue}}(null==(o=this.metadataRegistry.get(g[0]))?void 0:o.id)?d(g):(t.cycle||t.count>1&&"ref"===u.reused)&&d(g)}const p=(e,t)=>{const n=this.seen.get(e),r=n.def??n.schema,o={...r};if(null===n.ref)return;const i=n.ref;if(n.ref=null,i){p(i,t);const e=this.seen.get(i).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target?(Object.assign(r,e),Object.assign(r,o)):(r.allOf=r.allOf??[],r.allOf.push(e))}n.isParent||this.override({zodSchema:e,jsonSchema:r,path:n.path??[]})};for(const g of[...this.seen.entries()].reverse())p(g[0],{target:this.target});const m={};if("draft-2020-12"===this.target?m.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?m.$schema="http://json-schema.org/draft-07/schema#":"draft-4"===this.target?m.$schema="http://json-schema.org/draft-04/schema#":console.warn(`Invalid target: ${this.target}`),null==(i=u.external)?void 0:i.uri){const t=null==(s=u.external.registry.get(e))?void 0:s.id;if(!t)throw new Error("Schema is missing an `id` property");m.$id=u.external.uri(t)}Object.assign(m,l.def);const _=(null==(a=u.external)?void 0:a.defs)??{};for(const g of this.seen.entries()){const e=g[1];e.def&&e.defId&&(_[e.defId]=e.def)}u.external||Object.keys(_).length>0&&("draft-2020-12"===this.target?m.$defs=_:m.definitions=_);try{return JSON.parse(JSON.stringify(m))}catch(h){throw new Error("Error converting schema to JSON.")}}}function hu(e,t){if(e instanceof Es){const n=new _u(t),r={};for(const t of e._idmap.entries()){const[e,r]=t;n.process(r)}const o={},i={registry:e,uri:null==t?void 0:t.uri,defs:r};for(const s of e._idmap.entries()){const[e,r]=s;o[e]=n.emit(r,{...t,external:i})}if(Object.keys(r).length>0){const e="draft-2020-12"===n.target?"$defs":"definitions";o.__shared={[e]:r}}return{schemas:o}}const n=new _u(t);return n.process(e),n.emit(e,t)}function gu(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return gu(r.element,n);case"object":for(const e in r.shape)if(gu(r.shape[e],n))return!0;return!1;case"union":for(const e of r.options)if(gu(e,n))return!0;return!1;case"intersection":return gu(r.left,n)||gu(r.right,n);case"tuple":for(const e of r.items)if(gu(e,n))return!0;return!(!r.rest||!gu(r.rest,n));case"record":case"map":return gu(r.keyType,n)||gu(r.valueType,n);case"set":return gu(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return gu(r.innerType,n);case"lazy":return gu(r.getter(),n);case"transform":return!0;case"pipe":return gu(r.in,n)||gu(r.out,n)}throw new Error(`Unknown schema type: ${r.type}`)}const fu=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),vu=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Zo,$ZodArray:Vo,$ZodAsyncError:qt,$ZodBase64:Oo,$ZodBase64URL:To,$ZodBigInt:zo,$ZodBigIntFormat:Do,$ZodBoolean:jo,$ZodCIDRv4:Io,$ZodCIDRv6:So,$ZodCUID:mo,$ZodCUID2:_o,$ZodCatch:xi,$ZodCheck:Nr,$ZodCheckBigIntFormat:zr,$ZodCheckEndsWith:Kr,$ZodCheckGreaterThan:Pr,$ZodCheckIncludes:Vr,$ZodCheckLengthEquals:Fr,$ZodCheckLessThan:Cr,$ZodCheckLowerCase:Br,$ZodCheckMaxLength:qr,$ZodCheckMaxSize:Dr,$ZodCheckMimeType:Qr,$ZodCheckMinLength:Zr,$ZodCheckMinSize:Mr,$ZodCheckMultipleOf:Ur,$ZodCheckNumberFormat:jr,$ZodCheckOverwrite:eo,$ZodCheckProperty:Xr,$ZodCheckRegex:Hr,$ZodCheckSizeEquals:Lr,$ZodCheckStartsWith:Gr,$ZodCheckStringFormat:Wr,$ZodCheckUpperCase:Jr,$ZodCustom:Ai,$ZodCustomStringFormat:Co,$ZodDate:Bo,$ZodDefault:fi,$ZodDiscriminatedUnion:Qo,$ZodE164:Ro,$ZodEmail:uo,$ZodEmoji:co,$ZodEnum:ci,$ZodError:Cn,$ZodFile:pi,$ZodFunction:pu,$ZodGUID:so,$ZodIPv4:wo,$ZodIPv6:xo,$ZodISODate:yo,$ZodISODateTime:vo,$ZodISODuration:ko,$ZodISOTime:bo,$ZodIntersection:ei,$ZodJWT:Ao,$ZodKSUID:fo,$ZodLazy:Ni,$ZodLiteral:di,$ZodMap:si,$ZodNaN:Ii,$ZodNanoID:po,$ZodNever:Wo,$ZodNonOptional:bi,$ZodNull:qo,$ZodNullable:gi,$ZodNumber:Po,$ZodNumberFormat:Uo,$ZodObject:Ko,$ZodOptional:hi,$ZodPipe:Si,$ZodPrefault:yi,$ZodPromise:Ri,$ZodReadonly:Oi,$ZodRealError:Pn,$ZodRecord:ii,$ZodRegistry:Es,$ZodSet:ui,$ZodString:oo,$ZodStringFormat:io,$ZodSuccess:wi,$ZodSymbol:Mo,$ZodTemplateLiteral:Ti,$ZodTransform:mi,$ZodTuple:ri,$ZodType:ro,$ZodULID:ho,$ZodURL:lo,$ZodUUID:ao,$ZodUndefined:Lo,$ZodUnion:Xo,$ZodUnknown:Fo,$ZodVoid:Ho,$ZodXID:go,$brand:Lt,$constructor:Mt,$input:Os,$output:$s,Doc:to,JSONSchema:fu,JSONSchemaGenerator:_u,NEVER:Dt,TimePrecision:ta,_any:wa,_array:ru,_base64:Ys,_base64url:Xs,_bigint:ha,_boolean:ma,_catch:function(e,t,n){return new e({type:"catch",innerType:t,catchValue:"function"==typeof n?n:()=>n})},_check:lu,_cidrv4:Gs,_cidrv6:Ks,_coercedBigint:ga,_coercedBoolean:_a,_coercedDate:Oa,_coercedNumber:aa,_coercedString:As,_cuid:Zs,_cuid2:Fs,_custom:su,_date:$a,_default:function(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof n?n():un(n)}})},_discriminatedUnion:function(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...mn(r)})},_e164:Qs,_email:Cs,_emoji:Ls,_endsWith:Ga,_enum:function(e,t,n){return new e({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map((e=>[e,e]))):t,...mn(n)})},_file:iu,_float32:la,_float64:ca,_gt:Na,_gte:Aa,_guid:Ps,_includes:Ja,_int:ua,_int32:da,_int64:fa,_intersection:function(e,t,n){return new e({type:"intersection",left:t,right:n})},_ipv4:Js,_ipv6:Vs,_isoDate:ra,_isoDateTime:na,_isoDuration:ia,_isoTime:oa,_jwt:ea,_ksuid:Bs,_lazy:function(e,t){return new e({type:"lazy",getter:t})},_length:Fa,_literal:function(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...mn(n)})},_lowercase:Ha,_lt:Ta,_lte:Ra,_map:function(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...mn(r)})},_max:Ra,_maxLength:qa,_maxSize:Da,_mime:Ya,_min:Aa,_minLength:Za,_minSize:Ma,_multipleOf:za,_nan:Ea,_nanoid:qs,_nativeEnum:function(e,t,n){return new e({type:"enum",entries:t,...mn(n)})},_negative:Pa,_never:Ia,_nonnegative:ja,_nonoptional:function(e,t,n){return new e({type:"nonoptional",innerType:t,...mn(n)})},_nonpositive:Ua,_normalize:Qa,_null:ka,_nullable:function(e,t){return new e({type:"nullable",innerType:t})},_number:sa,_optional:function(e,t){return new e({type:"optional",innerType:t})},_overwrite:Xa,_parse:Ln,_parseAsync:Zn,_pipe:function(e,t,n){return new e({type:"pipe",in:t,out:n})},_positive:Ca,_promise:function(e,t){return new e({type:"promise",innerType:t})},_property:Ka,_readonly:function(e,t){return new e({type:"readonly",innerType:t})},_record:function(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...mn(r)})},_refine:au,_regex:Wa,_safeParse:Wn,_safeParseAsync:Bn,_set:function(e,t,n){return new e({type:"set",valueType:t,...mn(n)})},_size:La,_startsWith:Va,_string:Ns,_stringFormat:du,_stringbool:cu,_success:function(e,t){return new e({type:"success",innerType:t})},_superRefine:uu,_symbol:ya,_templateLiteral:function(e,t,n){return new e({type:"template_literal",parts:t,...mn(n)})},_toLowerCase:tu,_toUpperCase:nu,_transform:function(e,t){return new e({type:"transform",transform:t})},_trim:eu,_tuple:ou,_uint32:pa,_uint64:va,_ulid:Ws,_undefined:ba,_union:function(e,t,n){return new e({type:"union",options:t,...mn(n)})},_unknown:xa,_uppercase:Ba,_url:Ms,_uuid:Us,_uuidv4:js,_uuidv6:zs,_uuidv7:Ds,_void:Sa,_xid:Hs,clone:pn,config:Ft,flattenError:Un,formatError:jn,function:mu,globalConfig:Zt,globalRegistry:Rs,isValidBase64:$o,isValidBase64URL:Eo,isValidJWT:No,locales:Ss,parse:qn,parseAsync:Fn,prettifyError:Mn,regexes:Rr,registry:Ts,safeParse:Hn,safeParseAsync:Jn,toDotPath:Dn,toJSONSchema:hu,treeifyError:zn,util:Nn,version:no},Symbol.toStringTag,{value:"Module"})),yu=Mt("ZodISODateTime",((e,t)=>{vo.init(e,t),Mu.init(e,t)}));function bu(e){return na(yu,e)}const ku=Mt("ZodISODate",((e,t)=>{yo.init(e,t),Mu.init(e,t)}));function wu(e){return ra(ku,e)}const xu=Mt("ZodISOTime",((e,t)=>{bo.init(e,t),Mu.init(e,t)}));function Iu(e){return oa(xu,e)}const Su=Mt("ZodISODuration",((e,t)=>{ko.init(e,t),Mu.init(e,t)}));function $u(e){return ia(Su,e)}const Ou=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:ku,ZodISODateTime:yu,ZodISODuration:Su,ZodISOTime:xu,date:wu,datetime:bu,duration:$u,time:Iu},Symbol.toStringTag,{value:"Module"})),Eu=(e,t)=>{Cn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>jn(e,t)},flatten:{value:t=>Un(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Bt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Bt,2)}},isEmpty:{get:()=>0===e.issues.length}})},Tu=Mt("ZodError",Eu),Ru=Mt("ZodError",Eu,{Parent:Error}),Nu=Ln(Ru),Au=Zn(Ru),Cu=Wn(Ru),Pu=Bn(Ru),Uu=Mt("ZodType",((e,t)=>(ro.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map((e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]}),e.clone=(t,n)=>pn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>Nu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Cu(e,t,n),e.parseAsync=async(t,n)=>Au(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Pu(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(wc(t,n)),e.superRefine=t=>e.check(xc(t)),e.overwrite=t=>e.check(Xa(t)),e.optional=()=>Ql(e),e.nullable=()=>tc(e),e.nullish=()=>Ql(tc(e)),e.nonoptional=t=>ac(e,t),e.array=()=>El(e),e.or=t=>Pl([e,t]),e.and=t=>Dl(e,t),e.transform=t=>mc(e,Yl(t)),e.default=t=>rc(e,t),e.prefault=t=>ic(e,t),e.catch=t=>cc(e,t),e.pipe=t=>mc(e,t),e.readonly=()=>hc(e),e.describe=t=>{const n=e.clone();return Rs.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){var t;return null==(t=Rs.get(e))?void 0:t.description},configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Rs.get(e);const n=e.clone();return Rs.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),ju=Mt("_ZodString",((e,t)=>{oo.init(e,t),Uu.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Wa(...t)),e.includes=(...t)=>e.check(Ja(...t)),e.startsWith=(...t)=>e.check(Va(...t)),e.endsWith=(...t)=>e.check(Ga(...t)),e.min=(...t)=>e.check(Za(...t)),e.max=(...t)=>e.check(qa(...t)),e.length=(...t)=>e.check(Fa(...t)),e.nonempty=(...t)=>e.check(Za(1,...t)),e.lowercase=t=>e.check(Ha(t)),e.uppercase=t=>e.check(Ba(t)),e.trim=()=>e.check(eu()),e.normalize=(...t)=>e.check(Qa(...t)),e.toLowerCase=()=>e.check(tu()),e.toUpperCase=()=>e.check(nu())})),zu=Mt("ZodString",((e,t)=>{oo.init(e,t),ju.init(e,t),e.email=t=>e.check(Cs(Lu,t)),e.url=t=>e.check(Ms(Fu,t)),e.jwt=t=>e.check(ea(il,t)),e.emoji=t=>e.check(Ls(Wu,t)),e.guid=t=>e.check(Ps(qu,t)),e.uuid=t=>e.check(Us(Zu,t)),e.uuidv4=t=>e.check(js(Zu,t)),e.uuidv6=t=>e.check(zs(Zu,t)),e.uuidv7=t=>e.check(Ds(Zu,t)),e.nanoid=t=>e.check(qs(Hu,t)),e.guid=t=>e.check(Ps(qu,t)),e.cuid=t=>e.check(Zs(Bu,t)),e.cuid2=t=>e.check(Fs(Ju,t)),e.ulid=t=>e.check(Ws(Vu,t)),e.base64=t=>e.check(Ys(tl,t)),e.base64url=t=>e.check(Xs(rl,t)),e.xid=t=>e.check(Hs(Gu,t)),e.ksuid=t=>e.check(Bs(Ku,t)),e.ipv4=t=>e.check(Js(Yu,t)),e.ipv6=t=>e.check(Vs(Xu,t)),e.cidrv4=t=>e.check(Gs(Qu,t)),e.cidrv6=t=>e.check(Ks(el,t)),e.e164=t=>e.check(Qs(ol,t)),e.datetime=t=>e.check(bu(t)),e.date=t=>e.check(wu(t)),e.time=t=>e.check(Iu(t)),e.duration=t=>e.check($u(t))}));function Du(e){return Ns(zu,e)}const Mu=Mt("ZodStringFormat",((e,t)=>{io.init(e,t),ju.init(e,t)})),Lu=Mt("ZodEmail",((e,t)=>{uo.init(e,t),Mu.init(e,t)}));const qu=Mt("ZodGUID",((e,t)=>{so.init(e,t),Mu.init(e,t)}));const Zu=Mt("ZodUUID",((e,t)=>{ao.init(e,t),Mu.init(e,t)}));const Fu=Mt("ZodURL",((e,t)=>{lo.init(e,t),Mu.init(e,t)}));const Wu=Mt("ZodEmoji",((e,t)=>{co.init(e,t),Mu.init(e,t)}));const Hu=Mt("ZodNanoID",((e,t)=>{po.init(e,t),Mu.init(e,t)}));const Bu=Mt("ZodCUID",((e,t)=>{mo.init(e,t),Mu.init(e,t)}));const Ju=Mt("ZodCUID2",((e,t)=>{_o.init(e,t),Mu.init(e,t)}));const Vu=Mt("ZodULID",((e,t)=>{ho.init(e,t),Mu.init(e,t)}));const Gu=Mt("ZodXID",((e,t)=>{go.init(e,t),Mu.init(e,t)}));const Ku=Mt("ZodKSUID",((e,t)=>{fo.init(e,t),Mu.init(e,t)}));const Yu=Mt("ZodIPv4",((e,t)=>{wo.init(e,t),Mu.init(e,t)}));const Xu=Mt("ZodIPv6",((e,t)=>{xo.init(e,t),Mu.init(e,t)}));const Qu=Mt("ZodCIDRv4",((e,t)=>{Io.init(e,t),Mu.init(e,t)}));const el=Mt("ZodCIDRv6",((e,t)=>{So.init(e,t),Mu.init(e,t)}));const tl=Mt("ZodBase64",((e,t)=>{Oo.init(e,t),Mu.init(e,t)}));function nl(e){return Ys(tl,e)}const rl=Mt("ZodBase64URL",((e,t)=>{To.init(e,t),Mu.init(e,t)}));const ol=Mt("ZodE164",((e,t)=>{Ro.init(e,t),Mu.init(e,t)}));const il=Mt("ZodJWT",((e,t)=>{Ao.init(e,t),Mu.init(e,t)}));const sl=Mt("ZodCustomStringFormat",((e,t)=>{Co.init(e,t),Mu.init(e,t)}));const al=Mt("ZodNumber",((e,t)=>{Po.init(e,t),Uu.init(e,t),e.gt=(t,n)=>e.check(Na(t,n)),e.gte=(t,n)=>e.check(Aa(t,n)),e.min=(t,n)=>e.check(Aa(t,n)),e.lt=(t,n)=>e.check(Ta(t,n)),e.lte=(t,n)=>e.check(Ra(t,n)),e.max=(t,n)=>e.check(Ra(t,n)),e.int=t=>e.check(cl(t)),e.safe=t=>e.check(cl(t)),e.positive=t=>e.check(Na(0,t)),e.nonnegative=t=>e.check(Aa(0,t)),e.negative=t=>e.check(Ta(0,t)),e.nonpositive=t=>e.check(Ra(0,t)),e.multipleOf=(t,n)=>e.check(za(t,n)),e.step=(t,n)=>e.check(za(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}));function ul(e){return sa(al,e)}const ll=Mt("ZodNumberFormat",((e,t)=>{Uo.init(e,t),al.init(e,t)}));function cl(e){return ua(ll,e)}const dl=Mt("ZodBoolean",((e,t)=>{jo.init(e,t),Uu.init(e,t)}));function pl(e){return ma(dl,e)}const ml=Mt("ZodBigInt",((e,t)=>{zo.init(e,t),Uu.init(e,t),e.gte=(t,n)=>e.check(Aa(t,n)),e.min=(t,n)=>e.check(Aa(t,n)),e.gt=(t,n)=>e.check(Na(t,n)),e.gte=(t,n)=>e.check(Aa(t,n)),e.min=(t,n)=>e.check(Aa(t,n)),e.lt=(t,n)=>e.check(Ta(t,n)),e.lte=(t,n)=>e.check(Ra(t,n)),e.max=(t,n)=>e.check(Ra(t,n)),e.positive=t=>e.check(Na(BigInt(0),t)),e.negative=t=>e.check(Ta(BigInt(0),t)),e.nonpositive=t=>e.check(Ra(BigInt(0),t)),e.nonnegative=t=>e.check(Aa(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(za(t,n));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null}));const _l=Mt("ZodBigIntFormat",((e,t)=>{Do.init(e,t),ml.init(e,t)}));const hl=Mt("ZodSymbol",((e,t)=>{Mo.init(e,t),Uu.init(e,t)}));const gl=Mt("ZodUndefined",((e,t)=>{Lo.init(e,t),Uu.init(e,t)}));const fl=Mt("ZodNull",((e,t)=>{qo.init(e,t),Uu.init(e,t)}));function vl(e){return ka(fl,e)}const yl=Mt("ZodAny",((e,t)=>{Zo.init(e,t),Uu.init(e,t)}));function bl(){return wa(yl)}const kl=Mt("ZodUnknown",((e,t)=>{Fo.init(e,t),Uu.init(e,t)}));function wl(){return xa(kl)}const xl=Mt("ZodNever",((e,t)=>{Wo.init(e,t),Uu.init(e,t)}));function Il(e){return Ia(xl,e)}const Sl=Mt("ZodVoid",((e,t)=>{Ho.init(e,t),Uu.init(e,t)}));const $l=Mt("ZodDate",((e,t)=>{Bo.init(e,t),Uu.init(e,t),e.min=(t,n)=>e.check(Aa(t,n)),e.max=(t,n)=>e.check(Ra(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}));const Ol=Mt("ZodArray",((e,t)=>{Vo.init(e,t),Uu.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Za(t,n)),e.nonempty=t=>e.check(Za(1,t)),e.max=(t,n)=>e.check(qa(t,n)),e.length=(t,n)=>e.check(Fa(t,n)),e.unwrap=()=>e.element}));function El(e,t){return ru(Ol,e,t)}const Tl=Mt("ZodObject",((e,t)=>{Ko.init(e,t),Uu.init(e,t),Xt(e,"shape",(()=>t.shape)),e.keyof=()=>Bl(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wl()}),e.loose=()=>e.clone({...e._zod.def,catchall:wl()}),e.strict=()=>e.clone({...e._zod.def,catchall:Il()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>bn(e,t),e.merge=t=>kn(e,t),e.pick=t=>vn(e,t),e.omit=t=>yn(e,t),e.partial=(...t)=>wn(Xl,e,t[0]),e.required=(...t)=>xn(sc,e,t[0])}));function Rl(e,t){const n={type:"object",get shape(){return en(this,"shape",e?Qt(e):{}),this.shape},...mn(t)};return new Tl(n)}function Nl(e,t){return new Tl({type:"object",get shape(){return en(this,"shape",Qt(e)),this.shape},catchall:Il(),...mn(t)})}function Al(e,t){return new Tl({type:"object",get shape(){return en(this,"shape",Qt(e)),this.shape},catchall:wl(),...mn(t)})}const Cl=Mt("ZodUnion",((e,t)=>{Xo.init(e,t),Uu.init(e,t),e.options=t.options}));function Pl(e,t){return new Cl({type:"union",options:e,...mn(t)})}const Ul=Mt("ZodDiscriminatedUnion",((e,t)=>{Cl.init(e,t),Qo.init(e,t)}));function jl(e,t,n){return new Ul({type:"union",options:t,discriminator:e,...mn(n)})}const zl=Mt("ZodIntersection",((e,t)=>{ei.init(e,t),Uu.init(e,t)}));function Dl(e,t){return new zl({type:"intersection",left:e,right:t})}const Ml=Mt("ZodTuple",((e,t)=>{ri.init(e,t),Uu.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})}));function Ll(e,t,n){const r=t instanceof ro;return new Ml({type:"tuple",items:e,rest:r?t:null,...mn(r?n:t)})}const ql=Mt("ZodRecord",((e,t)=>{ii.init(e,t),Uu.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));function Zl(e,t,n){return new ql({type:"record",keyType:e,valueType:t,...mn(n)})}const Fl=Mt("ZodMap",((e,t)=>{si.init(e,t),Uu.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));const Wl=Mt("ZodSet",((e,t)=>{ui.init(e,t),Uu.init(e,t),e.min=(...t)=>e.check(Ma(...t)),e.nonempty=t=>e.check(Ma(1,t)),e.max=(...t)=>e.check(Da(...t)),e.size=(...t)=>e.check(La(...t))}));const Hl=Mt("ZodEnum",((e,t)=>{ci.init(e,t),Uu.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new Hl({...t,checks:[],...mn(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Hl({...t,checks:[],...mn(r),entries:o})}}));function Bl(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new Hl({type:"enum",entries:n,...mn(t)})}const Jl=Mt("ZodLiteral",((e,t)=>{di.init(e,t),Uu.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}));function Vl(e,t){return new Jl({type:"literal",values:Array.isArray(e)?e:[e],...mn(t)})}const Gl=Mt("ZodFile",((e,t)=>{pi.init(e,t),Uu.init(e,t),e.min=(t,n)=>e.check(Ma(t,n)),e.max=(t,n)=>e.check(Da(t,n)),e.mime=(t,n)=>e.check(Ya(Array.isArray(t)?t:[t],n))}));const Kl=Mt("ZodTransform",((e,t)=>{mi.init(e,t),Uu.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if("string"==typeof r)n.issues.push(Rn(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Rn(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then((e=>(n.value=e,n))):(n.value=o,n)}}));function Yl(e){return new Kl({type:"transform",transform:e})}const Xl=Mt("ZodOptional",((e,t)=>{hi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function Ql(e){return new Xl({type:"optional",innerType:e})}const ec=Mt("ZodNullable",((e,t)=>{gi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function tc(e){return new ec({type:"nullable",innerType:e})}const nc=Mt("ZodDefault",((e,t)=>{fi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}));function rc(e,t){return new nc({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():un(t)}})}const oc=Mt("ZodPrefault",((e,t)=>{yi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ic(e,t){return new oc({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():un(t)}})}const sc=Mt("ZodNonOptional",((e,t)=>{bi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ac(e,t){return new sc({type:"nonoptional",innerType:e,...mn(t)})}const uc=Mt("ZodSuccess",((e,t)=>{wi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const lc=Mt("ZodCatch",((e,t)=>{xi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));function cc(e,t){return new lc({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const dc=Mt("ZodNaN",((e,t)=>{Ii.init(e,t),Uu.init(e,t)}));const pc=Mt("ZodPipe",((e,t)=>{Si.init(e,t),Uu.init(e,t),e.in=t.in,e.out=t.out}));function mc(e,t){return new pc({type:"pipe",in:e,out:t})}const _c=Mt("ZodReadonly",((e,t)=>{Oi.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function hc(e){return new _c({type:"readonly",innerType:e})}const gc=Mt("ZodTemplateLiteral",((e,t)=>{Ti.init(e,t),Uu.init(e,t)}));const fc=Mt("ZodLazy",((e,t)=>{Ni.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.getter()}));function vc(e){return new fc({type:"lazy",getter:e})}const yc=Mt("ZodPromise",((e,t)=>{Ri.init(e,t),Uu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const bc=Mt("ZodCustom",((e,t)=>{Ai.init(e,t),Uu.init(e,t)}));function kc(e,t){return su(bc,e??(()=>!0),t)}function wc(e,t={}){return au(bc,e,t)}function xc(e){return uu(e)}function Ic(e,t={error:`Input not instance of ${e.name}`}){const n=new bc({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...mn(t)});return n._zod.bag.Class=e,n}var Sc;function $c(e){return aa(al,e)}Sc||(Sc={});const Oc=Object.freeze(Object.defineProperty({__proto__:null,bigint:function(e){return ga(ml,e)},boolean:function(e){return _a(dl,e)},date:function(e){return Oa($l,e)},number:$c,string:function(e){return As(zu,e)}},Symbol.toStringTag,{value:"Module"}));Ft(Fi());const Ec=Object.freeze(Object.defineProperty({__proto__:null,$brand:Lt,$input:Os,$output:$s,NEVER:Dt,TimePrecision:ta,ZodAny:yl,ZodArray:Ol,ZodBase64:tl,ZodBase64URL:rl,ZodBigInt:ml,ZodBigIntFormat:_l,ZodBoolean:dl,ZodCIDRv4:Qu,ZodCIDRv6:el,ZodCUID:Bu,ZodCUID2:Ju,ZodCatch:lc,ZodCustom:bc,ZodCustomStringFormat:sl,ZodDate:$l,ZodDefault:nc,ZodDiscriminatedUnion:Ul,ZodE164:ol,ZodEmail:Lu,ZodEmoji:Wu,ZodEnum:Hl,ZodError:Tu,ZodFile:Gl,get ZodFirstPartyTypeKind(){return Sc},ZodGUID:qu,ZodIPv4:Yu,ZodIPv6:Xu,ZodISODate:ku,ZodISODateTime:yu,ZodISODuration:Su,ZodISOTime:xu,ZodIntersection:zl,ZodIssueCode:{invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},ZodJWT:il,ZodKSUID:Ku,ZodLazy:fc,ZodLiteral:Jl,ZodMap:Fl,ZodNaN:dc,ZodNanoID:Hu,ZodNever:xl,ZodNonOptional:sc,ZodNull:fl,ZodNullable:ec,ZodNumber:al,ZodNumberFormat:ll,ZodObject:Tl,ZodOptional:Xl,ZodPipe:pc,ZodPrefault:oc,ZodPromise:yc,ZodReadonly:_c,ZodRealError:Ru,ZodRecord:ql,ZodSet:Wl,ZodString:zu,ZodStringFormat:Mu,ZodSuccess:uc,ZodSymbol:hl,ZodTemplateLiteral:gc,ZodTransform:Kl,ZodTuple:Ml,ZodType:Uu,ZodULID:Vu,ZodURL:Fu,ZodUUID:Zu,ZodUndefined:gl,ZodUnion:Cl,ZodUnknown:kl,ZodVoid:Sl,ZodXID:Gu,_ZodString:ju,_default:rc,any:bl,array:El,base64:nl,base64url:function(e){return Xs(rl,e)},bigint:function(e){return ha(ml,e)},boolean:pl,catch:cc,check:function(e){const t=new Nr({check:"custom"});return t._zod.check=e,t},cidrv4:function(e){return Gs(Qu,e)},cidrv6:function(e){return Ks(el,e)},clone:pn,coerce:Oc,config:Ft,core:vu,cuid:function(e){return Zs(Bu,e)},cuid2:function(e){return Fs(Ju,e)},custom:kc,date:function(e){return $a($l,e)},discriminatedUnion:jl,e164:function(e){return Qs(ol,e)},email:function(e){return Cs(Lu,e)},emoji:function(e){return Ls(Wu,e)},endsWith:Ga,enum:Bl,file:function(e){return iu(Gl,e)},flattenError:Un,float32:function(e){return la(ll,e)},float64:function(e){return ca(ll,e)},formatError:jn,function:mu,getErrorMap:function(){return Ft().customError},globalRegistry:Rs,gt:Na,gte:Aa,guid:function(e){return Ps(qu,e)},hostname:function(e){return du(sl,"hostname",_r,e)},includes:Ja,instanceof:Ic,int:cl,int32:function(e){return da(ll,e)},int64:function(e){return fa(_l,e)},intersection:Dl,ipv4:function(e){return Js(Yu,e)},ipv6:function(e){return Vs(Xu,e)},iso:Ou,json:function(e){const t=vc((()=>Pl([Du(e),ul(),pl(),vl(),El(t),Zl(Du(),t)])));return t},jwt:function(e){return ea(il,e)},keyof:function(e){const t=e._zod.def.shape;return Bl(Object.keys(t))},ksuid:function(e){return Bs(Ku,e)},lazy:vc,length:Fa,literal:Vl,locales:Ss,looseObject:Al,lowercase:Ha,lt:Ta,lte:Ra,map:function(e,t,n){return new Fl({type:"map",keyType:e,valueType:t,...mn(n)})},maxLength:qa,maxSize:Da,mime:Ya,minLength:Za,minSize:Ma,multipleOf:za,nan:function(e){return Ea(dc,e)},nanoid:function(e){return qs(Hu,e)},nativeEnum:function(e,t){return new Hl({type:"enum",entries:e,...mn(t)})},negative:Pa,never:Il,nonnegative:ja,nonoptional:ac,nonpositive:Ua,normalize:Qa,null:vl,nullable:tc,nullish:function(e){return Ql(tc(e))},number:ul,object:Rl,optional:Ql,overwrite:Xa,parse:Nu,parseAsync:Au,partialRecord:function(e,t,n){const r=pn(e);return r._zod.values=void 0,new ql({type:"record",keyType:r,valueType:t,...mn(n)})},pipe:mc,positive:Ca,prefault:ic,preprocess:function(e,t){return mc(Yl(e),t)},prettifyError:Mn,promise:function(e){return new yc({type:"promise",innerType:e})},property:Ka,readonly:hc,record:Zl,refine:wc,regex:Wa,regexes:Rr,registry:Ts,safeParse:Cu,safeParseAsync:Pu,set:function(e,t){return new Wl({type:"set",valueType:e,...mn(t)})},setErrorMap:function(e){Ft({customError:e})},size:La,startsWith:Va,strictObject:Nl,string:Du,stringFormat:function(e,t,n={}){return du(sl,e,t,n)},stringbool:(...e)=>cu({Pipe:pc,Boolean:dl,String:zu,Transform:Kl},...e),success:function(e){return new uc({type:"success",innerType:e})},superRefine:xc,symbol:function(e){return ya(hl,e)},templateLiteral:function(e,t){return new gc({type:"template_literal",parts:e,...mn(t)})},toJSONSchema:hu,toLowerCase:tu,toUpperCase:nu,transform:Yl,treeifyError:zn,trim:eu,tuple:Ll,uint32:function(e){return pa(ll,e)},uint64:function(e){return va(_l,e)},ulid:function(e){return Ws(Vu,e)},undefined:function(e){return ba(gl,e)},union:Pl,unknown:wl,uppercase:Ba,url:function(e){return Ms(Fu,e)},uuid:function(e){return Us(Zu,e)},uuidv4:function(e){return js(Zu,e)},uuidv6:function(e){return zs(Zu,e)},uuidv7:function(e){return Ds(Zu,e)},void:function(e){return Sa(Sl,e)},xid:function(e){return Hs(Gu,e)}},Symbol.toStringTag,{value:"Module"})),Tc=Symbol("Let zodToJsonSchema decide on which parser to use"),Rc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Nc=e=>{const t=(e=>"string"==typeof e?{...Rc,name:e}:{...Rc,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function Ac(e,t,n,r){(null==r?void 0:r.errorMessages)&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Cc(e,t,n,r,o){e[t]=n,Ac(e,t,r,o)}const Pc=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Uc(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Pc(t,e.currentPath):t.join("/")}}function jc(e,t){return ld(e.type._def,t)}function zc(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(((n,r)=>zc(e,t,n)))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Dc(e,t)}}const Dc=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Cc(n,"minimum",r.value,r.message,t);break;case"max":Cc(n,"maximum",r.value,r.message,t)}return n};let Mc;const Lc=/^[cC][^\s-]{8,}$/,qc=/^[0-9a-z]+$/,Zc=/^[0-9A-HJKMNP-TV-Z]{26}$/,Fc=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Wc=()=>(void 0===Mc&&(Mc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Mc),Hc=/^(?:(?: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])$/,Bc=/^(([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])$/,Jc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gc=/^[a-zA-Z0-9_-]{21}$/,Kc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Yc(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Cc(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Cc(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ed(n,"email",r.message,t);break;case"format:idn-email":ed(n,"idn-email",r.message,t);break;case"pattern:zod":td(n,Fc,r.message,t)}break;case"url":ed(n,"uri",r.message,t);break;case"uuid":ed(n,"uuid",r.message,t);break;case"regex":td(n,r.regex,r.message,t);break;case"cuid":td(n,Lc,r.message,t);break;case"cuid2":td(n,qc,r.message,t);break;case"startsWith":td(n,RegExp(`^${Xc(r.value,t)}`),r.message,t);break;case"endsWith":td(n,RegExp(`${Xc(r.value,t)}$`),r.message,t);break;case"datetime":ed(n,"date-time",r.message,t);break;case"date":ed(n,"date",r.message,t);break;case"time":ed(n,"time",r.message,t);break;case"duration":ed(n,"duration",r.message,t);break;case"length":Cc(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Cc(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":td(n,RegExp(Xc(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&ed(n,"ipv4",r.message,t),"v4"!==r.version&&ed(n,"ipv6",r.message,t);break;case"base64url":td(n,Vc,r.message,t);break;case"jwt":td(n,Kc,r.message,t);break;case"cidr":"v6"!==r.version&&td(n,Hc,r.message,t),"v4"!==r.version&&td(n,Bc,r.message,t);break;case"emoji":td(n,Wc(),r.message,t);break;case"ulid":td(n,Zc,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":ed(n,"binary",r.message,t);break;case"contentEncoding:base64":Cc(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":td(n,Jc,r.message,t)}break;case"nanoid":td(n,Gc,r.message,t)}return n}function Xc(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)Qc.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const Qc=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ed(e,t,n,r){var o;e.format||(null==(o=e.anyOf)?void 0:o.some((e=>e.format)))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Cc(e,"format",t,n,r)}function td(e,t,n,r){var o;e.pattern||(null==(o=e.allOf)?void 0:o.some((e=>e.pattern)))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:nd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Cc(e,"pattern",nd(t,r),n,r)}function nd(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),o=e.flags.includes("m"),i=e.flags.includes("s"),s=r?e.source.toLowerCase():e.source;let a="",u=!1,l=!1,c=!1;for(let d=0;d<s.length;d++)if(u)a+=s[d],u=!1;else{if(r)if(l){if(s[d].match(/[a-z]/)){c?(a+=s[d],a+=`${s[d-2]}-${s[d]}`.toUpperCase(),c=!1):"-"===s[d+1]&&(null==(n=s[d+2])?void 0:n.match(/[a-z]/))?(a+=s[d],c=!0):a+=`${s[d]}${s[d].toUpperCase()}`;continue}}else if(s[d].match(/[a-z]/)){a+=`[${s[d]}${s[d].toUpperCase()}]`;continue}if(o){if("^"===s[d]){a+="(^|(?<=[\r\n]))";continue}if("$"===s[d]){a+="($|(?=[\r\n]))";continue}}i&&"."===s[d]?a+=l?`${s[d]}\r\n`:`[${s[d]}\r\n]`:(a+=s[d],"\\"===s[d]?u=!0:l&&"]"===s[d]?l=!1:l||"["!==s[d]||(l=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function rd(e,t){var n,r,o,i,s,a;if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&(null==(n=e.keyType)?void 0:n._def.typeName)===Sc.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((n,r)=>({...n,[r]:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Uc(t)})),{}),additionalProperties:t.rejectedAdditionalProperties};const u={type:"object",additionalProperties:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return u;if((null==(r=e.keyType)?void 0:r._def.typeName)===Sc.ZodString&&(null==(o=e.keyType._def.checks)?void 0:o.length)){const{type:n,...r}=Yc(e.keyType._def,t);return{...u,propertyNames:r}}if((null==(i=e.keyType)?void 0:i._def.typeName)===Sc.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if((null==(s=e.keyType)?void 0:s._def.typeName)===Sc.ZodBranded&&e.keyType._def.type._def.typeName===Sc.ZodString&&(null==(a=e.keyType._def.type._def.checks)?void 0:a.length)){const{type:n,...r}=jc(e.keyType._def,t);return{...u,propertyNames:r}}return u}const od={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const id=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,n)=>ld(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return n.length?{anyOf:n}:void 0};function sd(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},o=[],i=e.shape();for(const a in i){let e=i[a];if(void 0===e||void 0===e._def)continue;let s=ad(e);s&&n&&("ZodOptional"===e._def.typeName&&(e=e._def.innerType),e.isNullable()||(e=e.nullable()),s=!1);const u=ld(e._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});void 0!==u&&(r.properties[a]=u,s||o.push(a))}o.length&&(r.required=o);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ld(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(r.additionalProperties=s),r}function ad(e){try{return e.isOptional()}catch{return!0}}const ud=(e,t,n)=>{switch(t){case Sc.ZodString:return Yc(e,n);case Sc.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Ac(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Cc(n,"minimum",r.value,r.message,t):Cc(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Cc(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Cc(n,"maximum",r.value,r.message,t):Cc(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Cc(n,"maximum",r.value,r.message,t));break;case"multipleOf":Cc(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Sc.ZodObject:return sd(e,n);case Sc.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Cc(n,"minimum",r.value,r.message,t):Cc(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Cc(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Cc(n,"maximum",r.value,r.message,t):Cc(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Cc(n,"maximum",r.value,r.message,t));break;case"multipleOf":Cc(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Sc.ZodBoolean:return{type:"boolean"};case Sc.ZodDate:return zc(e,n);case Sc.ZodUndefined:return function(e){return{not:Uc(e)}}(n);case Sc.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case Sc.ZodArray:return function(e,t){var n,r,o;const i={type:"array"};return(null==(n=e.type)?void 0:n._def)&&(null==(o=null==(r=e.type)?void 0:r._def)?void 0:o.typeName)!==Sc.ZodAny&&(i.items=ld(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Cc(i,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Cc(i,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Cc(i,"minItems",e.exactLength.value,e.exactLength.message,t),Cc(i,"maxItems",e.exactLength.value,e.exactLength.message,t)),i}(e,n);case Sc.ZodUnion:case Sc.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return id(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((e=>e._def.typeName in od&&(!e._def.checks||!e._def.checks.length)))){const e=n.reduce(((e,t)=>{const n=od[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e}),[]);return{type:e.length>1?e:e[0]}}if(n.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=n.reduce(((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===n.length){const t=e.filter(((e,t,n)=>n.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:n.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(n.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:n.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return id(e,t)}(e,n);case Sc.ZodIntersection:return function(e,t){const n=[ld(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ld(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;o.push(t)}else o.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t})),o.length?{allOf:o,...r}:void 0}(e,n);case Sc.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,n)=>ld(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:ld(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,n)=>ld(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,n);case Sc.ZodRecord:return rd(e,n);case Sc.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case Sc.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Sc.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),r=Array.from(new Set(n.map((e=>typeof e))));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case Sc.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:od[e.innerType._def.typeName],nullable:!0}:{type:[od[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=ld(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ld(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case Sc.ZodOptional:return((e,t)=>{var n;if(t.currentPath.toString()===(null==(n=t.propertyPath)?void 0:n.toString()))return ld(e.innerType._def,t);const r=ld(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Uc(t)},r]}:Uc(t)})(e,n);case Sc.ZodMap:return function(e,t){return"record"===t.mapStrategy?rd(e,t):{type:"array",maxItems:125,items:{type:"array",items:[ld(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Uc(t),ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Uc(t)],minItems:2,maxItems:2}}}(e,n);case Sc.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Cc(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Cc(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case Sc.ZodLazy:return()=>e.getter()._def;case Sc.ZodPromise:return function(e,t){return ld(e.type._def,t)}(e,n);case Sc.ZodNaN:case Sc.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Uc({...e,currentPath:[...e.currentPath,"not"]})}}(n);case Sc.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ld(e.schema._def,t):Uc(t)}(e,n);case Sc.ZodAny:return Uc(n);case Sc.ZodUnknown:return function(e){return Uc(e)}(n);case Sc.ZodDefault:return function(e,t){return{...ld(e.innerType._def,t),default:e.defaultValue()}}(e,n);case Sc.ZodBranded:return jc(e,n);case Sc.ZodReadonly:case Sc.ZodCatch:return((e,t)=>ld(e.innerType._def,t))(e,n);case Sc.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ld(e.in._def,t);if("output"===t.pipeStrategy)return ld(e.out._def,t);const n=ld(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ld(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter((e=>void 0!==e))}})(e,n);case Sc.ZodFunction:case Sc.ZodVoid:case Sc.ZodSymbol:default:return}};function ld(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const i=null==(r=t.override)?void 0:r.call(t,e,t,o,n);if(i!==Tc)return i}if(o&&!n){const e=cd(o,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const s=ud(e,e.typeName,t),a="function"==typeof s?ld(s(),t):s;if(a&&dd(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return i.jsonSchema=a,n}return i.jsonSchema=a,a}const cd=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Pc(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,n)=>t.currentPath[n]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Uc(t)):"seen"===t.$refStrategy?Uc(t):void 0}},dd=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),pd=(e,t)=>{const n=Nc(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,r])=>({...e,[t]:ld(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Uc(n)})),{}):void 0;const o="string"==typeof t?t:"title"===(null==t?void 0:t.nameStrategy)||null==t?void 0:t.name,i=ld(e._def,void 0===o?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??Uc(n),s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(i.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=void 0===o?r?{...i,[n.definitionPath]:r}:i:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:i}};return"jsonSchema7"===n.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function md(...e){return e.reduce(((e,t)=>({...e,...null!=t?t:{}})),{})}function _d(e){return Object.fromEntries([...e.headers])}var hd=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const e=n.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n[Math.random()*e|0];return r.join("")};if(null==e)return o;if(n.includes(r))throw new Je({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},gd=hd();function fd(e){return(e instanceof Error||e instanceof DOMException)&&("AbortError"===e.name||"ResponseAborted"===e.name||"TimeoutError"===e.name)}var vd=["fetch failed","failed to fetch"];function yd({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if("string"==typeof e)return e;if(null!=e)throw new mt({message:`${r} API key must be a string.`});if("undefined"==typeof process)throw new mt({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(null==(e=process.env[t]))throw new mt({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if("string"!=typeof e)throw new mt({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var bd=/"__proto__"\s*:/,kd=/"constructor"\s*:/;function wd(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===bd.test(e)&&!1===kd.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}function xd(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return wd(e)}finally{Error.stackTraceLimit=t}}var Id=Symbol.for("vercel.ai.validator");function Sd(e){return function(e){return"object"==typeof e&&null!==e&&Id in e&&!0===e[Id]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Tt({value:e,cause:n.issues})}},{[Id]:!0,validate:n});var t,n}async function $d({value:e,schema:t}){const n=Sd(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Tt.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Tt.wrap({value:e,cause:r}),rawValue:e}}}async function Od({text:e,schema:t}){try{const n=xd(e);return null==t?n:async function({value:e,schema:t}){const n=await $d({value:e,schema:t});if(!n.success)throw Tt.wrap({value:e,cause:n.error});return n.value}({value:n,schema:t})}catch(n){if(ut.isInstance(n)||Tt.isInstance(n))throw n;throw new ut({text:e,cause:n})}}async function Ed({text:e,schema:t}){try{const n=xd(e);return null==t?{success:!0,value:n,rawValue:n}:await $d({value:n,schema:t})}catch(n){return{success:!1,error:ut.isInstance(n)?n:new ut({text:e,cause:n}),rawValue:void 0}}}function Td(e){try{return xd(e),!0}catch(t){return!1}}function Rd({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new zt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Ed({text:e,schema:t}))}}))}async function Nd({provider:e,providerOptions:t,schema:n}){if(null==(null==t?void 0:t[e]))return;const r=await $d({value:t[e],schema:n});if(!r.success)throw new Je({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Ad=()=>globalThis.fetch,Cd=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s})=>Pd({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s}),Pd=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:i,fetch:s=Ad()})=>{try{const l=await s(e,{method:"POST",headers:(a=t,Object.fromEntries(Object.entries(a).filter((([e,t])=>null!=t)))),body:n.content,signal:i}),c=_d(l);if(!l.ok){let t;try{t=await o({response:l,url:e,requestBodyValues:n.values})}catch(u){if(fd(u)||je.isInstance(u))throw u;throw new je({message:"Failed to process error response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:l,url:e,requestBodyValues:n.values})}catch(u){if(u instanceof Error&&(fd(u)||je.isInstance(u)))throw u;throw new je({message:"Failed to process successful response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(u){throw function({error:e,url:t,requestBodyValues:n}){if(fd(e))return e;if(e instanceof TypeError&&vd.includes(e.message.toLowerCase())){const r=e.cause;if(null!=r)return new je({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}({error:u,url:e,requestBodyValues:n.values})}var a};function Ud({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:o,execute:r,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u})}function jd({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u})}async function zd(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var Dd=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:i})=>{const s=await r.text(),a=_d(r);if(""===s.trim())return{responseHeaders:a,value:new je({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})};try{const u=await Od({text:s,schema:e});return{responseHeaders:a,value:new je({message:t(u),url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,data:u,isRetryable:null==n?void 0:n(r,u)})}}catch(u){return{responseHeaders:a,value:new je({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})}}},Md=e=>async({response:t})=>{const n=_d(t);if(null==t.body)throw new qe({});return{responseHeaders:n,value:Rd({stream:t.body,schema:e})}},Ld=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),i=await Ed({text:o,schema:e}),s=_d(t);if(!i.success)throw new je({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:s,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:s,value:i.value,rawValue:i.rawValue}};function qd(e,t){return function(e){return"_zod"in e}(e)?function(e){return Fd(hu(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Pu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return Fd(pd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var Zd=Symbol.for("vercel.ai.schema");function Fd(e,{validate:t}={}){return{[Zd]:!0,_type:void 0,[Id]:!0,jsonSchema:e,validate:t}}function Wd(e){return null==e?Fd({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&Zd in t&&!0===t[Zd]&&"jsonSchema"in t&&"validate"in t?e:qd(e);var t}var{btoa:Hd,atob:Bd}=globalThis;function Jd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Bd(t);return Uint8Array.from(n,(e=>e.codePointAt(0)))}function Vd(e){return e instanceof Uint8Array?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Hd(t)}(e):e}function Gd(e){return null==e?void 0:e.replace(/\/$/,"")}var Kd=Rl({error:Rl({message:Du(),type:Du().nullish(),param:bl().nullish(),code:Pl([Du(),ul()]).nullish()})}),Yd=Dd({errorSchema:Kd,errorToMessage:e=>e.error.message});function Xd({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function Qd(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var ep=Rl({logitBias:Zl($c(),ul()).optional(),logprobs:Pl([pl(),ul()]).optional(),parallelToolCalls:pl().optional(),user:Du().optional(),reasoningEffort:Bl(["minimal","low","medium","high"]).optional(),maxCompletionTokens:ul().optional(),store:pl().optional(),metadata:Zl(Du().max(64),Du().max(512)).optional(),prediction:Zl(Du(),bl()).optional(),structuredOutputs:pl().optional(),serviceTier:Bl(["auto","flex","priority"]).optional(),strictJsonSchema:pl().optional(),textVerbosity:Bl(["low","medium","high"]).optional(),promptCacheKey:Du().optional(),safetyIdentifier:Du().optional()}),tp=Rl({key:Du(),type:Bl(["eq","ne","gt","gte","lt","lte"]),value:Pl([Du(),ul(),pl()])}),np=Rl({type:Bl(["and","or"]),filters:El(Pl([tp,vc((()=>np))]))}),rp=Pl([tp,np]),op=Rl({vectorStoreIds:El(Du()).optional(),maxNumResults:ul().optional(),ranking:Rl({ranker:Bl(["auto","default-2024-08-21"]).optional()}).optional(),filters:rp.optional()}),ip=Ud({id:"openai.file_search",name:"file_search",inputSchema:Rl({query:Du()})}),sp=Rl({searchContextSize:Bl(["low","medium","high"]).optional(),userLocation:Rl({type:Vl("approximate"),country:Du().optional(),city:Du().optional(),region:Du().optional(),timezone:Du().optional()}).optional()}),ap=Ud({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:Rl({action:jl("type",[Rl({type:Vl("search"),query:Du()}),Rl({type:Vl("open_page"),url:Du()}),Rl({type:Vl("find"),url:Du(),pattern:Du()})]).nullish()})});var up=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_,h,g;const f=[],v=null!=(m=await Nd({provider:"openai",providerOptions:p,schema:ep}))?m:{},y=null==(_=v.structuredOutputs)||_;null!=o&&f.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==u?void 0:u.type)||null==u.schema||y||f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:k}=function({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:i}of e)switch(o){case"system":switch(t){case"system":n.push({role:"system",content:i});break;case"developer":n.push({role:"developer",content:i});break;case"remove":r.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===i.length&&"text"===i[0].type){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map(((e,t)=>{var n,r,o;switch(e.type){case"text":return{type:"text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"image_url",image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Vd(e.data)}`,detail:null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.imageDetail}}}if(!e.mediaType.startsWith("audio/")){if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new Ct({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(o=e.filename)?o:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vd(e.data)}`}}}throw new Ct({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new Ct({functionality:"audio file parts with URLs"});switch(e.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Vd(e.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Vd(e.data),format:"mp3"}};default:throw new Ct({functionality:`audio content parts with media type ${e.mediaType}`})}}}))});break;case"assistant":{let e="";const t=[];for(const n of i)switch(n.type){case"text":e+=n.text;break;case"tool-call":t.push({id:n.toolCallId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.input)}})}n.push({role:"assistant",content:e,tool_calls:t.length>0?t:void 0});break}case"tool":for(const e of i){const t=e.output;let r;switch(t.type){case"text":case"error-text":r=t.value;break;case"content":case"json":case"error-json":r=JSON.stringify(t.value)}n.push({role:"tool",tool_call_id:e.toolCallId,content:r})}break;default:throw new Error(`Unsupported role: ${o}`)}return{messages:n,warnings:r}}({prompt:e,systemMessageMode:mp(this.modelId)});f.push(...k);const w=null!=(h=v.strictJsonSchema)&&h,x={model:this.modelId,logit_bias:v.logitBias,logprobs:!0===v.logprobs||"number"==typeof v.logprobs||void 0,top_logprobs:"number"==typeof v.logprobs?v.logprobs:"boolean"==typeof v.logprobs&&v.logprobs?0:void 0,user:v.user,parallel_tool_calls:v.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:s,response_format:"json"===(null==u?void 0:u.type)?y&&null!=u.schema?{type:"json_schema",json_schema:{schema:u.schema,strict:w,name:null!=(g=u.name)?g:"response",description:u.description}}:{type:"json_object"}:void 0,stop:a,seed:l,verbosity:v.textVerbosity,max_completion_tokens:v.maxCompletionTokens,store:v.store,metadata:v.metadata,prediction:v.prediction,reasoning_effort:v.reasoningEffort,service_tier:v.serviceTier,prompt_cache_key:v.promptCacheKey,safety_identifier:v.safetyIdentifier,messages:b};var I;pp(this.modelId)?(null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=x.frequency_penalty&&(x.frequency_penalty=void 0,f.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=x.presence_penalty&&(x.presence_penalty=void 0,f.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=x.logit_bias&&(x.logit_bias=void 0,f.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=x.logprobs&&(x.logprobs=void 0,f.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=x.top_logprobs&&(x.top_logprobs=void 0,f.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=x.max_tokens&&(null==x.max_completion_tokens&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==v.serviceTier||((I=this.modelId).startsWith("o3")||I.startsWith("o4-mini")||I.startsWith("gpt-5")&&!I.startsWith("gpt-5-chat"))||(f.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),"priority"!==v.serviceTier||function(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}(this.modelId)||(f.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:S,toolChoice:$,toolWarnings:O}=function({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){const o=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:o};const i=[];for(const a of e)switch(a.type){case"function":i.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:n?r:void 0}});break;case"provider-defined":switch(a.id){case"openai.file_search":{const e=op.parse(a.args);i.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=sp.parse(a.args);i.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}default:o.push({type:"unsupported-tool",tool:a})}break;default:o.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:i,toolChoice:void 0,toolWarnings:o};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:i,toolChoice:s,toolWarnings:o};case"tool":return{tools:i,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:throw new Ct({functionality:`tool choice type: ${s}`})}}({tools:c,toolChoice:d,structuredOutputs:y,strictJsonSchema:w});return{args:{...x,tools:S,tool_choice:$},warnings:[...f,...O]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_;const{args:h,warnings:g}=await this.getArgs(e),{responseHeaders:f,value:v,rawValue:y}=await Cd({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:h,failedResponseHandler:Yd,successfulResponseHandler:Ld(cp),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.choices[0],k=[],w=b.message.content;null!=w&&w.length>0&&k.push({type:"text",text:w});for(const $ of null!=(t=b.message.tool_calls)?t:[])k.push({type:"tool-call",toolCallId:null!=(n=$.id)?n:gd(),toolName:$.function.name,input:$.function.arguments});for(const $ of null!=(r=b.message.annotations)?r:[])k.push({type:"source",sourceType:"url",id:gd(),url:$.url,title:$.title});const x=null==(o=v.usage)?void 0:o.completion_tokens_details,I=null==(i=v.usage)?void 0:i.prompt_tokens_details,S={openai:{}};return null!=(null==x?void 0:x.accepted_prediction_tokens)&&(S.openai.acceptedPredictionTokens=null==x?void 0:x.accepted_prediction_tokens),null!=(null==x?void 0:x.rejected_prediction_tokens)&&(S.openai.rejectedPredictionTokens=null==x?void 0:x.rejected_prediction_tokens),null!=(null==(s=b.logprobs)?void 0:s.content)&&(S.openai.logprobs=b.logprobs.content),{content:k,finishReason:Qd(b.finish_reason),usage:{inputTokens:null!=(u=null==(a=v.usage)?void 0:a.prompt_tokens)?u:void 0,outputTokens:null!=(c=null==(l=v.usage)?void 0:l.completion_tokens)?c:void 0,totalTokens:null!=(p=null==(d=v.usage)?void 0:d.total_tokens)?p:void 0,reasoningTokens:null!=(m=null==x?void 0:x.reasoning_tokens)?m:void 0,cachedInputTokens:null!=(_=null==I?void 0:I.cached_tokens)?_:void 0},request:{body:h},response:{...Xd(v),headers:f,body:y},warnings:g,providerMetadata:S}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Cd({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:r,failedResponseHandler:Yd,successfulResponseHandler:Md(dp),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0,c=!1;const d={openai:{}};return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,i,p,m,_,h,g,f,v,y,b,k,w,x,I,S,$,O,E,T,R,N,A;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const C=t.value;if("error"in C)return a="error",void n.enqueue({type:"error",error:C.error});l&&(l=!1,n.enqueue({type:"response-metadata",...Xd(C)})),null!=C.usage&&(u.inputTokens=null!=(r=C.usage.prompt_tokens)?r:void 0,u.outputTokens=null!=(o=C.usage.completion_tokens)?o:void 0,u.totalTokens=null!=(i=C.usage.total_tokens)?i:void 0,u.reasoningTokens=null!=(m=null==(p=C.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?m:void 0,u.cachedInputTokens=null!=(h=null==(_=C.usage.prompt_tokens_details)?void 0:_.cached_tokens)?h:void 0,null!=(null==(g=C.usage.completion_tokens_details)?void 0:g.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(f=C.usage.completion_tokens_details)?void 0:f.accepted_prediction_tokens),null!=(null==(v=C.usage.completion_tokens_details)?void 0:v.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(y=C.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens));const P=C.choices[0];if(null!=(null==P?void 0:P.finish_reason)&&(a=Qd(P.finish_reason)),null!=(null==(b=null==P?void 0:P.logprobs)?void 0:b.content)&&(d.openai.logprobs=P.logprobs.content),null==(null==P?void 0:P.delta))return;const U=P.delta;if(null!=U.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:U.content})),null!=U.tool_calls)for(const e of U.tool_calls){const t=e.index;if(null==s[t]){if("function"!==e.type)throw new rt({data:e,message:"Expected 'function' type."});if(null==e.id)throw new rt({data:e,message:"Expected 'id' to be a string."});if(null==(null==(k=e.function)?void 0:k.name))throw new rt({data:e,message:"Expected 'function.name' to be a string."});n.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),s[t]={id:e.id,type:"function",function:{name:e.function.name,arguments:null!=(w=e.function.arguments)?w:""},hasFinished:!1};const r=s[t];null!=(null==(x=r.function)?void 0:x.name)&&null!=(null==(I=r.function)?void 0:I.arguments)&&(r.function.arguments.length>0&&n.enqueue({type:"tool-input-delta",id:r.id,delta:r.function.arguments}),Td(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(S=r.id)?S:gd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}const r=s[t];r.hasFinished||(null!=(null==($=e.function)?void 0:$.arguments)&&(r.function.arguments+=null!=(E=null==(O=e.function)?void 0:O.arguments)?E:""),n.enqueue({type:"tool-input-delta",id:r.id,delta:null!=(T=e.function.arguments)?T:""}),null!=(null==(R=r.function)?void 0:R.name)&&null!=(null==(N=r.function)?void 0:N.arguments)&&Td(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(A=r.id)?A:gd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(null!=U.annotations)for(const e of U.annotations)n.enqueue({type:"source",sourceType:"url",id:gd(),url:e.url,title:e.title})},flush(e){c&&e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:a,usage:u,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:o}}}},lp=Rl({prompt_tokens:ul().nullish(),completion_tokens:ul().nullish(),total_tokens:ul().nullish(),prompt_tokens_details:Rl({cached_tokens:ul().nullish()}).nullish(),completion_tokens_details:Rl({reasoning_tokens:ul().nullish(),accepted_prediction_tokens:ul().nullish(),rejected_prediction_tokens:ul().nullish()}).nullish()}).nullish(),cp=Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:El(Rl({message:Rl({role:Vl("assistant").nullish(),content:Du().nullish(),tool_calls:El(Rl({id:Du().nullish(),type:Vl("function"),function:Rl({name:Du(),arguments:Du()})})).nullish(),annotations:El(Rl({type:Vl("url_citation"),start_index:ul(),end_index:ul(),url:Du(),title:Du()})).nullish()}),index:ul(),logprobs:Rl({content:El(Rl({token:Du(),logprob:ul(),top_logprobs:El(Rl({token:Du(),logprob:ul()}))})).nullish()}).nullish(),finish_reason:Du().nullish()})),usage:lp}),dp=Pl([Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:El(Rl({delta:Rl({role:Bl(["assistant"]).nullish(),content:Du().nullish(),tool_calls:El(Rl({index:ul(),id:Du().nullish(),type:Vl("function").nullish(),function:Rl({name:Du().nullish(),arguments:Du().nullish()})})).nullish(),annotations:El(Rl({type:Vl("url_citation"),start_index:ul(),end_index:ul(),url:Du(),title:Du()})).nullish()}).nullish(),logprobs:Rl({content:El(Rl({token:Du(),logprob:ul(),top_logprobs:El(Rl({token:Du(),logprob:ul()}))})).nullish()}).nullish(),finish_reason:Du().nullish(),index:ul()})),usage:lp}),Kd]);function pp(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function mp(e){var t,n;return pp(e)?null!=(n=null==(t=_p[e])?void 0:t.systemMessageMode)?n:"developer":"system"}var _p={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function hp({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function gp(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var fp=Rl({echo:pl().optional(),logitBias:Zl(Du(),ul()).optional(),suffix:Du().optional(),user:Du().optional(),logprobs:Pl([pl(),ul()]).optional()}),vp=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,tools:l,toolChoice:c,seed:d,providerOptions:p}){const m=[],_={...await Nd({provider:"openai",providerOptions:p,schema:fp}),...await Nd({provider:this.providerOptionsName,providerOptions:p,schema:fp})};null!=o&&m.push({type:"unsupported-setting",setting:"topK"}),(null==l?void 0:l.length)&&m.push({type:"unsupported-setting",setting:"tools"}),null!=c&&m.push({type:"unsupported-setting",setting:"toolChoice"}),null!=u&&"text"!==u.type&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:h,stopSequences:g}=function({prompt:e,user:t="user",assistant:n="assistant"}){let r="";"system"===e[0].role&&(r+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:o,content:i}of e)switch(o){case"system":throw new Xe({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":r+=`${t}:\n${i.map((e=>{if("text"===e.type)return e.text})).filter(Boolean).join("")}\n\n`;break;case"assistant":r+=`${n}:\n${i.map((e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new Ct({functionality:"tool-call messages"})}})).join("")}\n\n`;break;case"tool":throw new Ct({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${o}`)}return r+=`${n}:\n`,{prompt:r,stopSequences:[`\n${t}:`]}}({prompt:e}),f=[...null!=g?g:[],...null!=a?a:[]];return{args:{model:this.modelId,echo:_.echo,logit_bias:_.logitBias,logprobs:!0===(null==_?void 0:_.logprobs)?0:!1===(null==_?void 0:_.logprobs)||null==_?void 0:_.logprobs,suffix:_.suffix,user:_.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:s,seed:d,prompt:h,stop:f.length>0?f:void 0},warnings:m}}async doGenerate(e){var t,n,r;const{args:o,warnings:i}=await this.getArgs(e),{responseHeaders:s,value:a,rawValue:u}=await Cd({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:o,failedResponseHandler:Yd,successfulResponseHandler:Ld(bp),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return null!=l.logprobs&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:null==(t=a.usage)?void 0:t.prompt_tokens,outputTokens:null==(n=a.usage)?void 0:n.completion_tokens,totalTokens:null==(r=a.usage)?void 0:r.total_tokens},finishReason:gp(l.finish_reason),request:{body:o},response:{...hp(a),headers:s,body:u},providerMetadata:c,warnings:i}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Cd({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:r,failedResponseHandler:Yd,successfulResponseHandler:Md(kp),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0;return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const r=t.value;if("error"in r)return s="error",void n.enqueue({type:"error",error:r.error});l&&(l=!1,n.enqueue({type:"response-metadata",...hp(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(u.inputTokens=r.usage.prompt_tokens,u.outputTokens=r.usage.completion_tokens,u.totalTokens=r.usage.total_tokens);const o=r.choices[0];null!=(null==o?void 0:o.finish_reason)&&(s=gp(o.finish_reason)),null!=(null==o?void 0:o.logprobs)&&(a.openai.logprobs=o.logprobs),null!=(null==o?void 0:o.text)&&o.text.length>0&&n.enqueue({type:"text-delta",id:"0",delta:o.text})},flush(e){l||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:u})}})),request:{body:r},response:{headers:o}}}},yp=Rl({prompt_tokens:ul(),completion_tokens:ul(),total_tokens:ul()}),bp=Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:El(Rl({text:Du(),finish_reason:Du(),logprobs:Rl({tokens:El(Du()),token_logprobs:El(ul()),top_logprobs:El(Zl(Du(),ul())).nullish()}).nullish()})),usage:yp.nullish()}),kp=Pl([Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:El(Rl({text:Du(),finish_reason:Du().nullish(),index:ul(),logprobs:Rl({tokens:El(Du()),token_logprobs:El(ul()),top_logprobs:El(Zl(Du(),ul())).nullish()}).nullish()})),usage:yp.nullish()}),Kd]),wp=Rl({dimensions:ul().optional(),user:Du().optional()}),xp=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new xt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=null!=(o=await Nd({provider:"openai",providerOptions:r,schema:wp}))?o:{},{responseHeaders:s,value:a,rawValue:u}=await Cd({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:md(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:i.dimensions,user:i.user},failedResponseHandler:Yd,successfulResponseHandler:Ld(Ip),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.data.map((e=>e.embedding)),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:s,body:u}}}},Ip=Rl({data:El(Rl({embedding:El(ul())})),usage:Rl({prompt_tokens:ul()}).nullish()}),Sp={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},$p=new Set(["gpt-image-1"]),Op=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=Sp[this.modelId])?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:i,headers:s,abortSignal:a}){var u,l,c,d;const p=[];null!=r&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),null!=o&&p.push({type:"unsupported-setting",setting:"seed"});const m=null!=(c=null==(l=null==(u=this.config._internal)?void 0:u.currentDate)?void 0:l.call(u))?c:new Date,{value:_,responseHeaders:h}=await Cd({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:md(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...null!=(d=i.openai)?d:{},...$p.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Yd,successfulResponseHandler:Ld(Ep),abortSignal:a,fetch:this.config.fetch});return{images:_.data.map((e=>e.b64_json)),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:_.data.map((e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null))}}}}},Ep=Rl({data:El(Rl({b64_json:Du(),revised_prompt:Du().optional()}))}),Tp=Rl({container:Pl([Du(),Rl({fileIds:El(Du()).optional()})]).optional()}),Rp={codeInterpreter:Ud({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:Rl({})}),fileSearch:ip,webSearchPreview:ap};function Np(e,t){return!!t&&t.some((t=>e.startsWith(t)))}var Ap=Rl({itemId:Du().nullish(),reasoningEncryptedContent:Du().nullish()});function Cp({finishReason:e,hasToolCalls:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var Pp=Rl({type:Vl("web_search_call"),id:Du(),status:Du(),action:jl("type",[Rl({type:Vl("search"),query:Du()}),Rl({type:Vl("open_page"),url:Du()}),Rl({type:Vl("find"),url:Du(),pattern:Du()})]).nullish()}),Up=El(Rl({token:Du(),logprob:ul(),top_logprobs:El(Rl({token:Du(),logprob:ul()}))})),jp=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:i,frequencyPenalty:s,seed:a,prompt:u,providerOptions:l,tools:c,toolChoice:d,responseFormat:p}){var m,_;const h=[],g=function(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};if(e.startsWith("gpt-5-chat"))return{...r,isReasoningModel:!1};if(e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use"))return e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"};return{...r,isReasoningModel:!1}}(this.modelId);null!=o&&h.push({type:"unsupported-setting",setting:"topK"}),null!=a&&h.push({type:"unsupported-setting",setting:"seed"}),null!=i&&h.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=s&&h.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=n&&h.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:f,warnings:v}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,o,i,s,a,u;const l=[],c=[];for(const{role:d,content:p}of e)switch(d){case"system":switch(t){case"system":l.push({role:"system",content:p});break;case"developer":l.push({role:"developer",content:p});break;case"remove":c.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":l.push({role:"user",content:p.map(((e,t)=>{var r,o,i;switch(e.type){case"text":return{type:"input_text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"input_image",...e.data instanceof URL?{image_url:e.data.toString()}:"string"==typeof e.data&&Np(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Vd(e.data)}`},detail:null==(o=null==(r=e.providerOptions)?void 0:r.openai)?void 0:o.imageDetail}}if("application/pdf"===e.mediaType)return e.data instanceof URL?{type:"input_file",file_url:e.data.toString()}:{type:"input_file",..."string"==typeof e.data&&Np(e.data,n)?{file_id:e.data}:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vd(e.data)}`}};throw new Ct({functionality:`file part media type ${e.mediaType}`})}}))});break;case"assistant":{const e={};for(const t of p)switch(t.type){case"text":l.push({role:"assistant",content:[{type:"output_text",text:t.text}],id:null!=(i=null==(o=null==(r=t.providerOptions)?void 0:r.openai)?void 0:o.itemId)?i:void 0});break;case"tool-call":if(t.providerExecuted)break;l.push({type:"function_call",call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:null!=(u=null==(a=null==(s=t.providerOptions)?void 0:s.openai)?void 0:a.itemId)?u:void 0});break;case"tool-result":c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break;case"reasoning":{const n=await Nd({provider:"openai",providerOptions:t.providerOptions,schema:Ap}),r=null==n?void 0:n.itemId;if(null!=r){const o=e[r],i=[];t.text.length>0?i.push({type:"summary_text",text:t.text}):void 0!==o&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),void 0===o?(e[r]={type:"reasoning",id:r,encrypted_content:null==n?void 0:n.reasoningEncryptedContent,summary:i},l.push(e[r])):o.summary.push(...i)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case"tool":for(const e of p){const t=e.output;let n;switch(t.type){case"text":case"error-text":n=t.value;break;case"content":case"json":case"error-json":n=JSON.stringify(t.value)}l.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${d}`)}return{messages:l,warnings:c}}({prompt:u,systemMessageMode:g.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});h.push(...v);const y=await Nd({provider:"openai",providerOptions:l,schema:Fp}),b=null!=(m=null==y?void 0:y.strictJsonSchema)&&m,k="number"==typeof(null==y?void 0:y.logprobs)?null==y?void 0:y.logprobs:!0===(null==y?void 0:y.logprobs)?20:void 0,w=k?Array.isArray(null==y?void 0:y.include)?[...null==y?void 0:y.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:null==y?void 0:y.include,x={model:this.modelId,input:f,temperature:t,top_p:r,max_output_tokens:e,...("json"===(null==p?void 0:p.type)||(null==y?void 0:y.textVerbosity))&&{text:{..."json"===(null==p?void 0:p.type)&&{format:null!=p.schema?{type:"json_schema",strict:b,name:null!=(_=p.name)?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(null==y?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},metadata:null==y?void 0:y.metadata,parallel_tool_calls:null==y?void 0:y.parallelToolCalls,previous_response_id:null==y?void 0:y.previousResponseId,store:null==y?void 0:y.store,user:null==y?void 0:y.user,instructions:null==y?void 0:y.instructions,service_tier:null==y?void 0:y.serviceTier,include:w,prompt_cache_key:null==y?void 0:y.promptCacheKey,safety_identifier:null==y?void 0:y.safetyIdentifier,top_logprobs:k,...g.isReasoningModel&&(null!=(null==y?void 0:y.reasoningEffort)||null!=(null==y?void 0:y.reasoningSummary))&&{reasoning:{...null!=(null==y?void 0:y.reasoningEffort)&&{effort:y.reasoningEffort},...null!=(null==y?void 0:y.reasoningSummary)&&{summary:y.reasoningSummary}}},...g.requiredAutoTruncation&&{truncation:"auto"}};g.isReasoningModel?(null!=x.temperature&&(x.temperature=void 0,h.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,h.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==y?void 0:y.reasoningEffort)&&h.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==y?void 0:y.reasoningSummary)&&h.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==y?void 0:y.serviceTier)||g.supportsFlexProcessing||(h.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete x.service_tier),"priority"!==(null==y?void 0:y.serviceTier)||g.supportsPriorityProcessing||(h.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete x.service_tier);const{tools:I,toolChoice:S,toolWarnings:$}=function({tools:e,toolChoice:t,strictJsonSchema:n}){const r=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const s of e)switch(s.type){case"function":o.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,strict:n});break;case"provider-defined":switch(s.id){case"openai.file_search":{const e=op.parse(s.args);o.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=sp.parse(s.args);o.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=Tp.parse(s.args);o.push({type:"code_interpreter",container:null==e.container?{type:"auto",file_ids:void 0}:"string"==typeof e.container?e.container:{type:"auto",file_ids:e.container.fileIds}});break}default:r.push({type:"unsupported-tool",tool:s})}break;default:r.push({type:"unsupported-tool",tool:s})}if(null==t)return{tools:o,toolChoice:void 0,toolWarnings:r};const i=t.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:r};case"tool":return{tools:o,toolChoice:"code_interpreter"===t.toolName||"file_search"===t.toolName||"web_search_preview"===t.toolName?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:throw new Ct({functionality:`tool choice type: ${i}`})}}({tools:c,toolChoice:d,strictJsonSchema:b});return{args:{...x,tools:I,tool_choice:S},warnings:[...h,...$]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_;const{args:h,warnings:g}=await this.getArgs(e),f=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:v,value:y,rawValue:b}=await Cd({url:f,headers:md(this.config.headers(),e.headers),body:h,failedResponseHandler:Yd,successfulResponseHandler:Ld(Rl({id:Du(),created_at:ul(),error:Rl({code:Du(),message:Du()}).nullish(),model:Du(),output:El(jl("type",[Rl({type:Vl("message"),role:Vl("assistant"),id:Du(),content:El(Rl({type:Vl("output_text"),text:Du(),logprobs:Up.nullish(),annotations:El(jl("type",[Rl({type:Vl("url_citation"),start_index:ul(),end_index:ul(),url:Du(),title:Du()}),Rl({type:Vl("file_citation"),start_index:ul(),end_index:ul(),file_id:Du(),quote:Du()})]))}))}),Rl({type:Vl("function_call"),call_id:Du(),name:Du(),arguments:Du(),id:Du()}),Pp,Rl({type:Vl("computer_call"),id:Du(),status:Du().optional()}),Rl({type:Vl("file_search_call"),id:Du(),status:Du().optional(),queries:El(Du()).nullish(),results:El(Rl({attributes:Rl({file_id:Du(),filename:Du(),score:ul(),text:Du()})})).nullish()}),Rl({type:Vl("reasoning"),id:Du(),encrypted_content:Du().nullish(),summary:El(Rl({type:Vl("summary_text"),text:Du()}))})])),incomplete_details:Rl({reason:Du()}).nullable(),usage:zp})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(y.error)throw new je({message:y.error.message,url:f,requestBodyValues:h,statusCode:400,responseHeaders:v,responseBody:b,isRetryable:!1});const k=[],w=[];for(const I of y.output)switch(I.type){case"reasoning":0===I.summary.length&&I.summary.push({type:"summary_text",text:""});for(const e of I.summary)k.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:I.id,reasoningEncryptedContent:null!=(t=I.encrypted_content)?t:null}}});break;case"message":for(const t of I.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&w.push(t.logprobs),k.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:I.id}}});for(const e of t.annotations)"url_citation"===e.type?k.push({type:"source",sourceType:"url",id:null!=(s=null==(i=(o=this.config).generateId)?void 0:i.call(o))?s:gd(),url:e.url,title:e.title}):"file_citation"===e.type&&k.push({type:"source",sourceType:"document",id:null!=(l=null==(u=(a=this.config).generateId)?void 0:u.call(a))?l:gd(),mediaType:"text/plain",title:e.quote,filename:e.file_id})}break;case"function_call":k.push({type:"tool-call",toolCallId:I.call_id,toolName:I.name,input:I.arguments,providerMetadata:{openai:{itemId:I.id}}});break;case"web_search_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"web_search_preview",input:JSON.stringify({action:I.action}),providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"web_search_preview",result:{status:I.status},providerExecuted:!0});break;case"computer_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"computer_use",input:"",providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.status||"completed"},providerExecuted:!0});break;case"file_search_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"file_search",input:"",providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.status||"completed",...I.queries&&{queries:I.queries},...I.results&&{results:I.results}},providerExecuted:!0})}const x={openai:{responseId:y.id}};return w.length>0&&(x.openai.logprobs=w),{content:k,finishReason:Cp({finishReason:null==(c=y.incomplete_details)?void 0:c.reason,hasToolCalls:k.some((e=>"tool-call"===e.type))}),usage:{inputTokens:y.usage.input_tokens,outputTokens:y.usage.output_tokens,totalTokens:y.usage.input_tokens+y.usage.output_tokens,reasoningTokens:null!=(p=null==(d=y.usage.output_tokens_details)?void 0:d.reasoning_tokens)?p:void 0,cachedInputTokens:null!=(_=null==(m=y.usage.input_tokens_details)?void 0:m.cached_tokens)?_:void 0},request:{body:h},response:{id:y.id,timestamp:new Date(1e3*y.created_at),modelId:y.model,headers:v,body:b},providerMetadata:x,warnings:g}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:o}=await Cd({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Yd,successfulResponseHandler:Md(Lp),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=this;let s="unknown";const a={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let l=null;const c={};let d=!1;const p={};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,m,_,h,g,f,v,y,b,k,w,x,I,S,$;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const O=t.value;if(Zp(O))"function_call"===O.item.type?(c[O.output_index]={toolName:O.item.name,toolCallId:O.item.call_id},n.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:O.item.name})):"web_search_call"===O.item.type?(c[O.output_index]={toolName:"web_search_preview",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"web_search_preview"})):"computer_call"===O.item.type?(c[O.output_index]={toolName:"computer_use",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"computer_use"})):"file_search_call"===O.item.type?(c[O.output_index]={toolName:"file_search",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"file_search"})):"message"===O.item.type?n.enqueue({type:"text-start",id:O.item.id,providerMetadata:{openai:{itemId:O.item.id}}}):function(e){return Zp(e)&&"reasoning"===e.item.type}(O)&&(p[O.item.id]={encryptedContent:O.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${O.item.id}:0`,providerMetadata:{openai:{itemId:O.item.id,reasoningEncryptedContent:null!=(r=O.item.encrypted_content)?r:null}}}));else if(qp(O)){if("function_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.call_id}),n.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:O.item.name,input:O.item.arguments,providerMetadata:{openai:{itemId:O.item.id}}});else if("web_search_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"web_search_preview",input:JSON.stringify({action:O.item.action}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"web_search_preview",result:{status:O.item.status},providerExecuted:!0});else if("computer_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:O.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"file_search",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:O.item.status||"completed",...O.item.queries&&{queries:O.item.queries},...O.item.results&&{results:O.item.results}},providerExecuted:!0});else if("message"===O.item.type)n.enqueue({type:"text-end",id:O.item.id});else if(function(e){return qp(e)&&"reasoning"===e.item.type}(O)){const e=p[O.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${O.item.id}:${t}`,providerMetadata:{openai:{itemId:O.item.id,reasoningEncryptedContent:null!=(o=O.item.encrypted_content)?o:null}}});delete p[O.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(O)){const e=c[O.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:O.delta})}else!function(e){return"response.created"===e.type}(O)?!function(e){return"response.output_text.delta"===e.type}(O)?!function(e){return"response.reasoning_summary_part.added"===e.type}(O)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(O)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(O)?!function(e){return"response.output_text.annotation.added"===e.type}(O)?function(e){return"error"===e.type}(O)&&n.enqueue({type:"error",error:O}):"url_citation"===O.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=(x=null==(w=(k=i.config).generateId)?void 0:w.call(k))?x:gd(),url:O.annotation.url,title:O.annotation.title}):"file_citation"===O.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=($=null==(S=(I=i.config).generateId)?void 0:S.call(I))?$:gd(),mediaType:"text/plain",title:O.annotation.quote,filename:O.annotation.file_id}):(s=Cp({finishReason:null==(g=O.response.incomplete_details)?void 0:g.reason,hasToolCalls:d}),a.inputTokens=O.response.usage.input_tokens,a.outputTokens=O.response.usage.output_tokens,a.totalTokens=O.response.usage.input_tokens+O.response.usage.output_tokens,a.reasoningTokens=null!=(v=null==(f=O.response.usage.output_tokens_details)?void 0:f.reasoning_tokens)?v:void 0,a.cachedInputTokens=null!=(b=null==(y=O.response.usage.input_tokens_details)?void 0:y.cached_tokens)?b:void 0):n.enqueue({type:"reasoning-delta",id:`${O.item_id}:${O.summary_index}`,delta:O.delta,providerMetadata:{openai:{itemId:O.item_id}}}):O.summary_index>0&&(null==(m=p[O.item_id])||m.summaryParts.push(O.summary_index),n.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{openai:{itemId:O.item_id,reasoningEncryptedContent:null!=(h=null==(_=p[O.item_id])?void 0:_.encryptedContent)?h:null}}})):(n.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),O.logprobs&&u.push(O.logprobs)):(l=O.response.id,n.enqueue({type:"response-metadata",id:O.response.id,timestamp:new Date(1e3*O.response.created_at),modelId:O.response.model}))},flush(e){const t={openai:{responseId:l}};u.length>0&&(t.openai.logprobs=u),e.enqueue({type:"finish",finishReason:s,usage:a,providerMetadata:t})}})),request:{body:t},response:{headers:r}}}},zp=Rl({input_tokens:ul(),input_tokens_details:Rl({cached_tokens:ul().nullish()}).nullish(),output_tokens:ul(),output_tokens_details:Rl({reasoning_tokens:ul().nullish()}).nullish()}),Dp=Rl({type:Vl("response.output_text.delta"),item_id:Du(),delta:Du(),logprobs:Up.nullish()}),Mp=Rl({type:Vl("error"),code:Du(),message:Du(),param:Du().nullish(),sequence_number:ul()}),Lp=Pl([Dp,Rl({type:Bl(["response.completed","response.incomplete"]),response:Rl({incomplete_details:Rl({reason:Du()}).nullish(),usage:zp})}),Rl({type:Vl("response.created"),response:Rl({id:Du(),created_at:ul(),model:Du()})}),Rl({type:Vl("response.output_item.added"),output_index:ul(),item:jl("type",[Rl({type:Vl("message"),id:Du()}),Rl({type:Vl("reasoning"),id:Du(),encrypted_content:Du().nullish()}),Rl({type:Vl("function_call"),id:Du(),call_id:Du(),name:Du(),arguments:Du()}),Rl({type:Vl("web_search_call"),id:Du(),status:Du(),action:Rl({type:Vl("search"),query:Du().optional()}).nullish()}),Rl({type:Vl("computer_call"),id:Du(),status:Du()}),Rl({type:Vl("file_search_call"),id:Du(),status:Du(),queries:El(Du()).nullish(),results:El(Rl({attributes:Rl({file_id:Du(),filename:Du(),score:ul(),text:Du()})})).optional()})])}),Rl({type:Vl("response.output_item.done"),output_index:ul(),item:jl("type",[Rl({type:Vl("message"),id:Du()}),Rl({type:Vl("reasoning"),id:Du(),encrypted_content:Du().nullish()}),Rl({type:Vl("function_call"),id:Du(),call_id:Du(),name:Du(),arguments:Du(),status:Vl("completed")}),Pp,Rl({type:Vl("computer_call"),id:Du(),status:Vl("completed")}),Rl({type:Vl("file_search_call"),id:Du(),status:Vl("completed"),queries:El(Du()).nullish(),results:El(Rl({attributes:Rl({file_id:Du(),filename:Du(),score:ul(),text:Du()})})).nullish()})])}),Rl({type:Vl("response.function_call_arguments.delta"),item_id:Du(),output_index:ul(),delta:Du()}),Rl({type:Vl("response.output_text.annotation.added"),annotation:jl("type",[Rl({type:Vl("url_citation"),url:Du(),title:Du()}),Rl({type:Vl("file_citation"),file_id:Du(),quote:Du()})])}),Rl({type:Vl("response.reasoning_summary_part.added"),item_id:Du(),summary_index:ul()}),Rl({type:Vl("response.reasoning_summary_text.delta"),item_id:Du(),summary_index:ul(),delta:Du()}),Mp,Rl({type:Du()}).loose()]);function qp(e){return"response.output_item.done"===e.type}function Zp(e){return"response.output_item.added"===e.type}var Fp=Rl({metadata:bl().nullish(),parallelToolCalls:pl().nullish(),previousResponseId:Du().nullish(),store:pl().nullish(),user:Du().nullish(),reasoningEffort:Du().nullish(),strictJsonSchema:pl().nullish(),instructions:Du().nullish(),reasoningSummary:Du().nullish(),serviceTier:Bl(["auto","flex","priority"]).nullish(),include:El(Bl(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:Bl(["low","medium","high"]).nullish(),promptCacheKey:Du().nullish(),safetyIdentifier:Du().nullish(),logprobs:Pl([pl(),ul().min(1).max(20)]).optional()}),Wp=Rl({instructions:Du().nullish(),speed:ul().min(.25).max(4).default(1).nullish()}),Hp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:i,providerOptions:s}){const a=[],u=await Nd({provider:"openai",providerOptions:s,schema:Wp}),l={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?l.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),u){const e={};for(const t in e){const n=e[t];void 0!==n&&(l[t]=n)}}return i&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${i}" was ignored.`}),{requestBody:l,warnings:a}}async doGenerate(e){var t,n,r;const o=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{requestBody:i,warnings:s}=await this.getArgs(e),{value:a,responseHeaders:u,rawValue:l}=await Cd({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:i,failedResponseHandler:Yd,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=_d(e);if(!e.body)throw new je({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(o){throw new je({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:s,request:{body:JSON.stringify(i)},response:{timestamp:o,modelId:this.modelId,headers:u,body:l}}}},Bp=Rl({include:El(Du()).optional(),language:Du().optional(),prompt:Du().optional(),temperature:ul().min(0).max(1).default(0).optional(),timestampGranularities:El(Bl(["word","segment"])).default(["segment"]).optional()}),Jp={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Vp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=await Nd({provider:"openai",providerOptions:n,schema:Bp}),o=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([Jd(e)]);if(o.append("model",this.modelId),o.append("file",new File([i],"audio",{type:t})),r){const e={include:r.include,language:r.language,prompt:r.prompt,response_format:"verbose_json",temperature:r.temperature,timestamp_granularities:r.timestampGranularities};for(const[t,n]of Object.entries(e))null!=n&&o.append(t,String(n))}return{formData:o,warnings:[]}}async doGenerate(e){var t,n,r,o,i,s,a,u;const l=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{formData:c,warnings:d}=await this.getArgs(e),{value:p,responseHeaders:m,rawValue:_}=await(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s})=>Pd({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s}))({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),formData:c,failedResponseHandler:Yd,successfulResponseHandler:Ld(Gp),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=null!=p.language&&p.language in Jp?Jp[p.language]:void 0;return{text:p.text,segments:null!=(a=null!=(s=null==(o=p.segments)?void 0:o.map((e=>({text:e.text,startSecond:e.start,endSecond:e.end}))))?s:null==(i=p.words)?void 0:i.map((e=>({text:e.word,startSecond:e.start,endSecond:e.end}))))?a:[],language:h,durationInSeconds:null!=(u=p.duration)?u:void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:m,body:_}}}},Gp=Rl({text:Du(),language:Du().nullish(),duration:ul().nullish(),words:El(Rl({word:Du(),start:ul(),end:ul()})).nullish(),segments:El(Rl({id:ul(),seek:ul(),start:ul(),end:ul(),text:Du(),tokens:El(ul()),temperature:ul(),avg_logprob:ul(),compression_ratio:ul(),no_speech_prob:ul()})).nullish()});function Kp(e={}){var t,n;const r=null!=(t=Gd(e.baseURL))?t:"https://api.openai.com/v1",o=null!=(n=e.name)?n:"openai",i=()=>({Authorization:`Bearer ${yd({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),s=t=>new xp(t,{provider:`${o}.embedding`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),a=t=>new Op(t,{provider:`${o}.image`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),u=t=>new Vp(t,{provider:`${o}.transcription`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),l=t=>new Hp(t,{provider:`${o}.speech`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),c=e=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(e)},d=t=>new jp(t,{provider:`${o}.responses`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(e){return c(e)};return p.languageModel=c,p.chat=t=>new up(t,{provider:`${o}.chat`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),p.completion=t=>new vp(t,{provider:`${o}.completion`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),p.responses=d,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=a,p.imageModel=a,p.transcription=u,p.transcriptionModel=u,p.speech=l,p.speechModel=l,p.tools=Rp,p}var Yp=Kp(),Xp=Dd({errorSchema:Rl({type:Vl("error"),error:Rl({type:Du(),message:Du()})}),errorToMessage:e=>e.error.message}),Qp=Rl({citations:Rl({enabled:pl()}).optional(),title:Du().optional(),context:Du().optional()}),em=Rl({sendReasoning:pl().optional(),thinking:Rl({type:Pl([Vl("enabled"),Vl("disabled")]),budgetTokens:ul().optional()}).optional(),disableParallelToolUse:pl().optional()});function tm(e){var t;const n=null==e?void 0:e.anthropic;return null!=(t=null==n?void 0:n.cacheControl)?t:null==n?void 0:n.cache_control}var nm=Rl({maxUses:ul().optional(),allowedDomains:El(Du()).optional(),blockedDomains:El(Du()).optional(),userLocation:Rl({type:Vl("approximate"),city:Du().optional(),region:Du().optional(),country:Du().optional(),timezone:Du().optional()}).optional()}),rm=El(Rl({url:Du(),title:Du(),pageAge:Du().nullable(),encryptedContent:Du(),type:Du()})),om=jd({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Rl({query:Du()}),outputSchema:rm});function im(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var sm=Rl({type:Vl("code_execution_result"),stdout:Du(),stderr:Du(),return_code:ul()}),am=jd({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Rl({code:Du()}),outputSchema:sm});function um(e){if("string"==typeof e)return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return(new TextDecoder).decode(e);if(e instanceof URL)throw new Ct({functionality:"URL-based text documents are not supported for citations"});throw new Ct({functionality:"unsupported data type for text documents: "+typeof e})}async function lm({prompt:e,sendReasoning:t,warnings:n}){var r,o,i,s,a;const u=new Set,l=function(e){const t=[];let n;for(const r of e){const{role:e}=r;switch(e){case"system":"system"!==(null==n?void 0:n.type)&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break;case"assistant":"assistant"!==(null==n?void 0:n.type)&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break;case"user":case"tool":"user"!==(null==n?void 0:n.type)&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break;default:throw new Error(`Unsupported role: ${e}`)}}return t}(e);let c;const d=[];async function p(e){var t,n;const r=await Nd({provider:"anthropic",providerOptions:e,schema:Qp});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function m(e){const t=await Nd({provider:"anthropic",providerOptions:e,schema:Qp});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let _=0;_<l.length;_++){const e=l[_],h=_===l.length-1,g=e.type;switch(g){case"system":if(null!=c)throw new Ct({functionality:"Multiple system messages that are separated by user/assistant messages"});c=e.messages.map((({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:tm(t)})));break;case"user":{const t=[];for(const n of e.messages){const{role:e,content:a}=n;switch(e){case"user":for(let e=0;e<a.length;e++){const s=a[e],l=e===a.length-1,c=null!=(r=tm(s.providerOptions))?r:l?tm(n.providerOptions):void 0;switch(s.type){case"text":t.push({type:"text",text:s.text,cache_control:c});break;case"file":if(s.mediaType.startsWith("image/"))t.push({type:"image",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"image/*"===s.mediaType?"image/jpeg":s.mediaType,data:Vd(s.data)},cache_control:c});else if("application/pdf"===s.mediaType){u.add("pdfs-2024-09-25");const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"application/pdf",data:Vd(s.data)},title:null!=(o=n.title)?o:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}else{if("text/plain"!==s.mediaType)throw new Ct({functionality:`media type: ${s.mediaType}`});{const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"text",media_type:"text/plain",data:um(s.data)},title:null!=(i=n.title)?i:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}}}}break;case"tool":for(let e=0;e<a.length;e++){const r=a[e],o=e===a.length-1,i=null!=(s=tm(r.providerOptions))?s:o?tm(n.providerOptions):void 0,u=r.output;let l;switch(u.type){case"content":l=u.value.map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,cache_control:void 0};case"media":if(e.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data},cache_control:void 0};throw new Ct({functionality:`media type: ${e.mediaType}`})}}));break;case"text":case"error-text":l=u.value;break;default:l=JSON.stringify(u.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:l,is_error:"error-text"===u.type||"error-json"===u.type||void 0,cache_control:i})}break;default:throw new Error(`Unsupported role: ${e}`)}}d.push({role:"user",content:t});break}case"assistant":{const r=[];for(let o=0;o<e.messages.length;o++){const i=e.messages[o],s=o===e.messages.length-1,{content:u}=i;for(let e=0;e<u.length;e++){const o=u[e],l=e===u.length-1,c=null!=(a=tm(o.providerOptions))?a:l?tm(i.providerOptions):void 0;switch(o.type){case"text":r.push({type:"text",text:h&&s&&l?o.text.trim():o.text,cache_control:c});break;case"reasoning":if(t){const e=await Nd({provider:"anthropic",providerOptions:o.providerOptions,schema:fm});null!=e?null!=e.signature?r.push({type:"thinking",thinking:o.text,signature:e.signature,cache_control:c}):null!=e.redactedData?r.push({type:"redacted_thinking",data:e.redactedData,cache_control:c}):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":if(o.providerExecuted){if("web_search"===o.toolName){r.push({type:"server_tool_use",id:o.toolCallId,name:"web_search",input:o.input,cache_control:c});break}if("code_execution"===o.toolName){r.push({type:"server_tool_use",id:o.toolCallId,name:"code_execution",input:o.input,cache_control:c});break}n.push({type:"other",message:`provider executed tool call for tool ${o.toolName} is not supported`});break}r.push({type:"tool_use",id:o.toolCallId,name:o.toolName,input:o.input,cache_control:c});break;case"tool-result":if("web_search"===o.toolName){const e=o.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${o.toolName} is not supported`});break}const t=rm.parse(e.value);r.push({type:"web_search_tool_result",tool_use_id:o.toolCallId,content:t.map((e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type}))),cache_control:c});break}if("code_execution"===o.toolName){const e=o.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${o.toolName} is not supported`});break}const t=sm.parse(e.value);r.push({type:"code_execution_tool_result",tool_use_id:o.toolCallId,content:{type:t.type,stdout:t.stdout,stderr:t.stderr,return_code:t.return_code},cache_control:c});break}n.push({type:"other",message:`provider executed tool result for tool ${o.toolName} is not supported`})}}}d.push({role:"assistant",content:r});break}default:throw new Error(`content type: ${g}`)}}return{prompt:{system:c,messages:d},betas:u}}function cm({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var dm={webSearchResult:Rl({type:Vl("web_search_result_location"),cited_text:Du(),url:Du(),title:Du(),encrypted_index:Du()}),pageLocation:Rl({type:Vl("page_location"),cited_text:Du(),document_index:ul(),document_title:Du().nullable(),start_page_number:ul(),end_page_number:ul()}),charLocation:Rl({type:Vl("char_location"),cited_text:Du(),document_index:ul(),document_title:Du().nullable(),start_char_index:ul(),end_char_index:ul()})},pm=jl("type",[dm.webSearchResult,dm.pageLocation,dm.charLocation]);function mm(e,t,n,r){if("page_location"===e.type||"char_location"===e.type){const o=function(e,t,n){var r;const o=t[e.document_index];if(!o)return null;const i="page_location"===e.type?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:"source",sourceType:"document",id:n(),mediaType:o.mediaType,title:null!=(r=e.document_title)?r:o.title,filename:o.filename,providerMetadata:{anthropic:i}}}(e,t,n);o&&r(o)}}jl("type",[dm.pageLocation,dm.charLocation]);var _m=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:gd}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_,h;const g=[];null!=i&&g.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=s&&g.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=l&&g.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==u?void 0:u.type)&&(null==u.schema?g.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):null!=c&&g.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const f="json"===(null==u?void 0:u.type)&&null!=u.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:u.schema}:void 0,v=await Nd({provider:"anthropic",providerOptions:p,schema:em}),{prompt:y,betas:b}=await lm({prompt:e,sendReasoning:null==(m=null==v?void 0:v.sendReasoning)||m,warnings:g}),k="enabled"===(null==(_=null==v?void 0:v.thinking)?void 0:_.type),w=null==(h=null==v?void 0:v.thinking)?void 0:h.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:o,top_p:r,stop_sequences:a,...k&&{thinking:{type:"enabled",budget_tokens:w}},system:y.system,messages:y.messages};if(k){if(null==w)throw new Ct({functionality:"thinking requires a budget"});null!=x.temperature&&(x.temperature=void 0,g.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=o&&(x.top_k=void 0,g.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),null!=r&&(x.top_p=void 0,g.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),x.max_tokens=t+w}const{tools:I,toolChoice:S,toolWarnings:$,betas:O}=function({tools:e,toolChoice:t,disableParallelToolUse:n}){e=(null==e?void 0:e.length)?e:void 0;const r=[],o=new Set;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:o};const i=[];for(const a of e)if(im(a))i.push(a);else switch(a.type){case"function":const e=tm(a.providerOptions);i.push({name:a.name,description:a.description,input_schema:a.inputSchema,cache_control:e});break;case"provider-defined":switch(a.id){case"anthropic.computer_20250124":o.add("computer-use-2025-01-24"),i.push({name:"computer",type:"computer_20250124",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.computer_20241022":o.add("computer-use-2024-10-22"),i.push({name:"computer",type:"computer_20241022",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),i.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":o.add("computer-use-2025-01-24"),i.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":o.add("computer-use-2024-10-22"),i.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{const e=nm.parse(a.args);i.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case"anthropic.code_execution_20250522":o.add("code-execution-2025-05-22"),i.push({type:"code_execution_20250522",name:"code_execution"});break;default:r.push({type:"unsupported-tool",tool:a})}break;default:r.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:i,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:o};const s=t.type;switch(s){case"auto":return{tools:i,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:r,betas:o};case"required":return{tools:i,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:r,betas:o};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:o};case"tool":return{tools:i,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:o};default:throw new Ct({functionality:`tool choice type: ${s}`})}}(null!=f?{tools:[f],toolChoice:{type:"tool",toolName:f.name},disableParallelToolUse:null==v?void 0:v.disableParallelToolUse}:{tools:null!=c?c:[],toolChoice:d,disableParallelToolUse:null==v?void 0:v.disableParallelToolUse});return{args:{...x,tools:I,tool_choice:S},warnings:[...g,...$],betas:new Set([...b,...O]),usesJsonResponseTool:null!=f}}async getHeaders({betas:e,headers:t}){return md(await zd(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{},t)}buildRequestUrl(e){var t,n,r;return null!=(r=null==(n=(t=this.config).buildRequestUrl)?void 0:n.call(t,this.config.baseURL,e))?r:`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return null!=(r=null==(n=(t=this.config).transformRequestBody)?void 0:n.call(t,e))?r:e}extractCitationDocuments(e){return e.filter((e=>"user"===e.role)).flatMap((e=>e.content)).filter((e=>{var t,n;if("file"!==e.type)return!1;if("application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;const r=null==(t=e.providerOptions)?void 0:t.anthropic,o=null==r?void 0:r.citations;return null!=(n=null==o?void 0:o.enabled)&&n})).map((e=>{var t;const n=e;return{title:null!=(t=n.filename)?t:"Untitled Document",filename:n.filename,mediaType:n.mediaType}}))}async doGenerate(e){var t,n,r,o,i;const{args:s,warnings:a,betas:u,usesJsonResponseTool:l}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:m}=await Cd({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:u,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Xp,successfulResponseHandler:Ld(hm),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=[];for(const h of p.content)switch(h.type){case"text":if(!l&&(_.push({type:"text",text:h.text}),h.citations))for(const e of h.citations)mm(e,c,this.generateId,(e=>_.push(e)));break;case"thinking":_.push({type:"reasoning",text:h.thinking,providerMetadata:{anthropic:{signature:h.signature}}});break;case"redacted_thinking":_.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:h.data}}});break;case"tool_use":_.push(l?{type:"text",text:JSON.stringify(h.input)}:{type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input)});break;case"server_tool_use":"web_search"!==h.name&&"code_execution"!==h.name||_.push({type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input),providerExecuted:!0});break;case"web_search_tool_result":if(Array.isArray(h.content)){_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",result:h.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const e of h.content)_.push({type:"source",sourceType:"url",id:this.generateId(),url:e.url,title:e.title,providerMetadata:{anthropic:{pageAge:null!=(t=e.page_age)?t:null}}})}else _.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0});break;case"code_execution_tool_result":"code_execution_result"===h.content.type?_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",result:{type:h.content.type,stdout:h.content.stdout,stderr:h.content.stderr,return_code:h.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===h.content.type&&_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0})}return{content:_,finishReason:cm({finishReason:p.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:null!=(n=p.usage.cache_read_input_tokens)?n:void 0},request:{body:s},response:{id:null!=(r=p.id)?r:void 0,modelId:null!=(o=p.model)?o:void 0,headers:d,body:m},warnings:a,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:null!=(i=p.usage.cache_creation_input_tokens)?i:null}}}}async doStream(e){const{args:t,warnings:n,betas:r,usesJsonResponseTool:o}=await this.getArgs(e),i=this.extractCitationDocuments(e.prompt),s={...t,stream:!0},{responseHeaders:a,value:u}=await Cd({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Xp,successfulResponseHandler:Md(gm),abortSignal:e.abortSignal,fetch:this.config.fetch});let l="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,m;const _=this.generateId;return{stream:u.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,u,h,g,f;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const v=t.value;switch(v.type){case"ping":return;case"content_block_start":{const e=v.content_block.type;switch(m=e,e){case"text":return d[v.index]={type:"text"},void n.enqueue({type:"text-start",id:String(v.index)});case"thinking":return d[v.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(v.index)});case"redacted_thinking":return d[v.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(v.index),providerMetadata:{anthropic:{redactedData:v.content_block.data}}});case"tool_use":return d[v.index]=o?{type:"text"}:{type:"tool-call",toolCallId:v.content_block.id,toolName:v.content_block.name,input:""},void n.enqueue(o?{type:"text-start",id:String(v.index)}:{type:"tool-input-start",id:v.content_block.id,toolName:v.content_block.name});case"server_tool_use":return void("web_search"!==v.content_block.name&&"code_execution"!==v.content_block.name||(d[v.index]={type:"tool-call",toolCallId:v.content_block.id,toolName:v.content_block.name,input:"",providerExecuted:!0},n.enqueue({type:"tool-input-start",id:v.content_block.id,toolName:v.content_block.name,providerExecuted:!0})));case"web_search_tool_result":{const e=v.content_block;if(Array.isArray(e.content)){n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",result:e.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const t of e.content)n.enqueue({type:"source",sourceType:"url",id:_(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}})}else n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const e=v.content_block;return void("code_execution_result"===e.content.type?n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===e.content.type&&n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0}))}default:throw new Error(`Unsupported content block type: ${e}`)}}case"content_block_stop":if(null!=d[v.index]){const e=d[v.index];switch(e.type){case"text":n.enqueue({type:"text-end",id:String(v.index)});break;case"reasoning":n.enqueue({type:"reasoning-end",id:String(v.index)});break;case"tool-call":o||(n.enqueue({type:"tool-input-end",id:e.toolCallId}),n.enqueue(e))}delete d[v.index]}return void(m=void 0);case"content_block_delta":{const e=v.delta.type;switch(e){case"text_delta":if(o)return;return void n.enqueue({type:"text-delta",id:String(v.index),delta:v.delta.text});case"thinking_delta":return void n.enqueue({type:"reasoning-delta",id:String(v.index),delta:v.delta.thinking});case"signature_delta":return void("thinking"===m&&n.enqueue({type:"reasoning-delta",id:String(v.index),delta:"",providerMetadata:{anthropic:{signature:v.delta.signature}}}));case"input_json_delta":{const e=d[v.index],t=v.delta.partial_json;if(o){if("text"!==(null==e?void 0:e.type))return;n.enqueue({type:"text-delta",id:String(v.index),delta:t})}else{if("tool-call"!==(null==e?void 0:e.type))return;n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t}return}case"citations_delta":return void mm(v.delta.citation,i,_,(e=>n.enqueue(e)));default:throw new Error(`Unsupported delta type: ${e}`)}}case"message_start":return c.inputTokens=v.message.usage.input_tokens,c.cachedInputTokens=null!=(s=v.message.usage.cache_read_input_tokens)?s:void 0,p={anthropic:{usage:v.message.usage,cacheCreationInputTokens:null!=(a=v.message.usage.cache_creation_input_tokens)?a:null}},void n.enqueue({type:"response-metadata",id:null!=(u=v.message.id)?u:void 0,modelId:null!=(h=v.message.model)?h:void 0});case"message_delta":return c.outputTokens=v.usage.output_tokens,c.totalTokens=(null!=(g=c.inputTokens)?g:0)+(null!=(f=v.usage.output_tokens)?f:0),void(l=cm({finishReason:v.delta.stop_reason,isJsonResponseFromTool:o}));case"message_stop":return void n.enqueue({type:"finish",finishReason:l,usage:c,providerMetadata:p});case"error":return void n.enqueue({type:"error",error:v.error});default:throw new Error(`Unsupported chunk type: ${v}`)}}})),request:{body:s},response:{headers:a}}}},hm=Rl({type:Vl("message"),id:Du().nullish(),model:Du().nullish(),content:El(jl("type",[Rl({type:Vl("text"),text:Du(),citations:El(pm).optional()}),Rl({type:Vl("thinking"),thinking:Du(),signature:Du()}),Rl({type:Vl("redacted_thinking"),data:Du()}),Rl({type:Vl("tool_use"),id:Du(),name:Du(),input:wl()}),Rl({type:Vl("server_tool_use"),id:Du(),name:Du(),input:Zl(Du(),wl()).nullish()}),Rl({type:Vl("web_search_tool_result"),tool_use_id:Du(),content:Pl([El(Rl({type:Vl("web_search_result"),url:Du(),title:Du(),encrypted_content:Du(),page_age:Du().nullish()})),Rl({type:Vl("web_search_tool_result_error"),error_code:Du()})])}),Rl({type:Vl("code_execution_tool_result"),tool_use_id:Du(),content:Pl([Rl({type:Vl("code_execution_result"),stdout:Du(),stderr:Du(),return_code:ul()}),Rl({type:Vl("code_execution_tool_result_error"),error_code:Du()})])})])),stop_reason:Du().nullish(),usage:Al({input_tokens:ul(),output_tokens:ul(),cache_creation_input_tokens:ul().nullish(),cache_read_input_tokens:ul().nullish()})}),gm=jl("type",[Rl({type:Vl("message_start"),message:Rl({id:Du().nullish(),model:Du().nullish(),usage:Al({input_tokens:ul(),output_tokens:ul(),cache_creation_input_tokens:ul().nullish(),cache_read_input_tokens:ul().nullish()})})}),Rl({type:Vl("content_block_start"),index:ul(),content_block:jl("type",[Rl({type:Vl("text"),text:Du()}),Rl({type:Vl("thinking"),thinking:Du()}),Rl({type:Vl("tool_use"),id:Du(),name:Du()}),Rl({type:Vl("redacted_thinking"),data:Du()}),Rl({type:Vl("server_tool_use"),id:Du(),name:Du(),input:Zl(Du(),wl()).nullish()}),Rl({type:Vl("web_search_tool_result"),tool_use_id:Du(),content:Pl([El(Rl({type:Vl("web_search_result"),url:Du(),title:Du(),encrypted_content:Du(),page_age:Du().nullish()})),Rl({type:Vl("web_search_tool_result_error"),error_code:Du()})])}),Rl({type:Vl("code_execution_tool_result"),tool_use_id:Du(),content:Pl([Rl({type:Vl("code_execution_result"),stdout:Du(),stderr:Du(),return_code:ul()}),Rl({type:Vl("code_execution_tool_result_error"),error_code:Du()})])})])}),Rl({type:Vl("content_block_delta"),index:ul(),delta:jl("type",[Rl({type:Vl("input_json_delta"),partial_json:Du()}),Rl({type:Vl("text_delta"),text:Du()}),Rl({type:Vl("thinking_delta"),thinking:Du()}),Rl({type:Vl("signature_delta"),signature:Du()}),Rl({type:Vl("citations_delta"),citation:pm})])}),Rl({type:Vl("content_block_stop"),index:ul()}),Rl({type:Vl("error"),error:Rl({type:Du(),message:Du()})}),Rl({type:Vl("message_delta"),delta:Rl({stop_reason:Du().nullish()}),usage:Rl({output_tokens:ul()})}),Rl({type:Vl("message_stop")}),Rl({type:Vl("ping")})]),fm=Rl({signature:Du().optional(),redactedData:Du().optional()}),vm=Ud({id:"anthropic.bash_20241022",name:"bash",inputSchema:Ec.object({command:Ec.string(),restart:Ec.boolean().optional()})}),ym=Ud({id:"anthropic.bash_20250124",name:"bash",inputSchema:Ec.object({command:Ec.string(),restart:Ec.boolean().optional()})}),bm=Ud({id:"anthropic.computer_20241022",name:"computer",inputSchema:Rl({action:Bl(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:El(ul().int()).optional(),text:Du().optional()})}),km=Ud({id:"anthropic.computer_20250124",name:"computer",inputSchema:Rl({action:Bl(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ll([ul().int(),ul().int()]).optional(),duration:ul().optional(),scroll_amount:ul().optional(),scroll_direction:Bl(["up","down","left","right"]).optional(),start_coordinate:Ll([ul().int(),ul().int()]).optional(),text:Du().optional()})}),wm={bash_20241022:vm,bash_20250124:ym,textEditor_20241022:Ud({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Rl({command:Bl(["view","create","str_replace","insert","undo_edit"]),path:Du(),file_text:Du().optional(),insert_line:ul().int().optional(),new_str:Du().optional(),old_str:Du().optional(),view_range:El(ul().int()).optional()})}),textEditor_20250124:Ud({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:Rl({command:Bl(["view","create","str_replace","insert","undo_edit"]),path:Du(),file_text:Du().optional(),insert_line:ul().int().optional(),new_str:Du().optional(),old_str:Du().optional(),view_range:El(ul().int()).optional()})}),textEditor_20250429:Ud({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Rl({command:Bl(["view","create","str_replace","insert"]),path:Du(),file_text:Du().optional(),insert_line:ul().int().optional(),new_str:Du().optional(),old_str:Du().optional(),view_range:El(ul().int()).optional()})}),computer_20241022:bm,computer_20250124:km,webSearch_20250305:(e={})=>om(e),codeExecution_20250522:(e={})=>am(e)};function xm(e={}){var t;const n=null!=(t=Gd(e.baseURL))?t:"https://api.anthropic.com/v1",r=()=>({"anthropic-version":"2023-06-01","x-api-key":yd({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers}),o=t=>{var o;return new _m(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(o=e.generateId)?o:gd,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},i=function(e){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(e)};return i.languageModel=o,i.chat=o,i.messages=o,i.textEmbeddingModel=e=>{throw new vt({modelId:e,modelType:"textEmbeddingModel"})},i.imageModel=e=>{throw new vt({modelId:e,modelType:"imageModel"})},i.tools=wm,i}var Im=xm(),Sm=Dd({errorSchema:Rl({error:Rl({code:ul().nullable(),message:Du(),status:Du()})}),errorToMessage:e=>e.error.message}),$m=Rl({outputDimensionality:ul().optional(),taskType:Bl(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),Om=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){const o=await Nd({provider:"google",providerOptions:r,schema:$m});if(e.length>this.maxEmbeddingsPerCall)throw new xt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=md(await zd(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await Cd({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:i,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:null==o?void 0:o.outputDimensionality,taskType:null==o?void 0:o.taskType},failedResponseHandler:Sm,successfulResponseHandler:Ld(Tm),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:s}}}const{responseHeaders:s,value:a,rawValue:u}=await Cd({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:i,body:{requests:e.map((e=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:e}]},outputDimensionality:null==o?void 0:o.outputDimensionality,taskType:null==o?void 0:o.taskType})))},failedResponseHandler:Sm,successfulResponseHandler:Ld(Em),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map((e=>e.values)),usage:void 0,response:{headers:s,body:u}}}},Em=Rl({embeddings:El(Rl({values:El(ul())}))}),Tm=Rl({embedding:Rl({values:El(ul())})});function Rm(e){if(null==e||function(e){return null!=e&&"object"==typeof e&&"object"===e.type&&(null==e.properties||0===Object.keys(e.properties).length)&&!e.additionalProperties}(e))return;if("boolean"==typeof e)return{type:"boolean",properties:{}};const{type:t,description:n,required:r,properties:o,items:i,allOf:s,anyOf:a,oneOf:u,format:l,const:c,minLength:d,enum:p}=e,m={};if(n&&(m.description=n),r&&(m.required=r),l&&(m.format=l),void 0!==c&&(m.enum=[c]),t&&(Array.isArray(t)?t.includes("null")?(m.type=t.filter((e=>"null"!==e))[0],m.nullable=!0):m.type=t:m.type="null"===t?"null":t),void 0!==p&&(m.enum=p),null!=o&&(m.properties=Object.entries(o).reduce(((e,[t,n])=>(e[t]=Rm(n),e)),{})),i&&(m.items=Array.isArray(i)?i.map(Rm):Rm(i)),s&&(m.allOf=s.map(Rm)),a)if(a.some((e=>"object"==typeof e&&"null"===(null==e?void 0:e.type)))){const e=a.filter((e=>!("object"==typeof e&&"null"===(null==e?void 0:e.type))));if(1===e.length){const t=Rm(e[0]);"object"==typeof t&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(Rm),m.nullable=!0}else m.anyOf=a.map(Rm);return u&&(m.oneOf=u.map(Rm)),void 0!==d&&(m.minLength=d),m}function Nm(e){return e.includes("/")?e:`models/${e}`}var Am=Rl({responseModalities:El(Bl(["TEXT","IMAGE"])).optional(),thinkingConfig:Rl({thinkingBudget:ul().optional(),includeThoughts:pl().optional()}).optional(),cachedContent:Du().optional(),structuredOutputs:pl().optional(),safetySettings:El(Rl({category:Bl(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Bl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Bl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:pl().optional(),labels:Zl(Du(),Du()).optional()});function Cm({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var Pm=Rl({web:Rl({uri:Du(),title:Du()}).nullish(),retrievedContext:Rl({uri:Du(),title:Du()}).nullish()}),Um=Rl({webSearchQueries:El(Du()).nullish(),retrievalQueries:El(Du()).nullish(),searchEntryPoint:Rl({renderedContent:Du()}).nullish(),groundingChunks:El(Pm).nullish(),groundingSupports:El(Rl({segment:Rl({startIndex:ul().nullish(),endIndex:ul().nullish(),text:Du().nullish()}),segment_text:Du().nullish(),groundingChunkIndices:El(ul()).nullish(),supportChunkIndices:El(ul()).nullish(),confidenceScores:El(ul()).nullish(),confidenceScore:El(ul()).nullish()})).nullish(),retrievalMetadata:Pl([Rl({webDynamicRetrievalScore:ul()}),Rl({})]).nullish()}),jm=Ud({id:"google.google_search",name:"google_search",inputSchema:Rl({mode:Bl(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:ul().default(1)})}),zm=Rl({retrievedUrl:Du(),urlRetrievalStatus:Du()}),Dm=Rl({urlMetadata:El(zm)}),Mm=Ud({id:"google.url_context",name:"url_context",inputSchema:Rl({})}),Lm=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:gd}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_;const h=[],g=await Nd({provider:"google",providerOptions:p,schema:Am});!0!==(null==(m=null==g?void 0:g.thinkingConfig)?void 0:m.includeThoughts)||this.config.provider.startsWith("google.vertex.")||h.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});const f=this.modelId.toLowerCase().startsWith("gemma-"),{contents:v,systemInstruction:y}=function(e,t){var n;const r=[],o=[];let i=!0;const s=null!=(n=null==t?void 0:t.isGemmaModel)&&n;for(const{role:a,content:u}of e)switch(a){case"system":if(!i)throw new Ct({functionality:"system messages are only supported at the beginning of the conversation"});r.push({text:u});break;case"user":{i=!1;const e=[];for(const t of u)switch(t.type){case"text":e.push({text:t.text});break;case"file":{const n="image/*"===t.mediaType?"image/jpeg":t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:Vd(t.data)}});break}}o.push({role:"user",parts:e});break}case"assistant":i=!1,o.push({role:"model",parts:u.map((e=>{var t,n,r,o,i,s;switch(e.type){case"text":return 0===e.text.length?void 0:{text:e.text,thoughtSignature:null==(n=null==(t=e.providerOptions)?void 0:t.google)?void 0:n.thoughtSignature};case"reasoning":return 0===e.text.length?void 0:{text:e.text,thought:!0,thoughtSignature:null==(o=null==(r=e.providerOptions)?void 0:r.google)?void 0:o.thoughtSignature};case"file":if("image/png"!==e.mediaType)throw new Ct({functionality:"Only PNG images are supported in assistant messages"});if(e.data instanceof URL)throw new Ct({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:e.mediaType,data:Vd(e.data)}};case"tool-call":return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:null==(s=null==(i=e.providerOptions)?void 0:i.google)?void 0:s.thoughtSignature}}})).filter((e=>void 0!==e))});break;case"tool":i=!1,o.push({role:"user",parts:u.map((e=>({functionResponse:{name:e.toolName,response:{name:e.toolName,content:e.output.value}}})))})}if(s&&r.length>0&&o.length>0&&"user"===o[0].role){const e=r.map((e=>e.text)).join("\n\n");o[0].parts.unshift({text:e+"\n\n"})}return{systemInstruction:r.length>0&&!s?{parts:r}:void 0,contents:o}}(e,{isGemmaModel:f}),{tools:b,toolConfig:k,toolWarnings:w}=function({tools:e,toolChoice:t,modelId:n}){var r;e=(null==e?void 0:e.length)?e:void 0;const o=[],i=n.includes("gemini-2"),s=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(null==e)return{tools:void 0,toolConfig:void 0,toolWarnings:o};const a=e.some((e=>"function"===e.type)),u=e.some((e=>"provider-defined"===e.type));if(a&&u&&o.push({type:"unsupported-tool",tool:e.find((e=>"function"===e.type)),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."}),u){const t={};return e.filter((e=>"provider-defined"===e.type)).forEach((e=>{switch(e.id){case"google.google_search":i?t.googleSearch={}:t.googleSearchRetrieval=s?{dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:{};break;case"google.url_context":i?t.urlContext={}:o.push({type:"unsupported-tool",tool:e,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?t.codeExecution={}:o.push({type:"unsupported-tool",tool:e,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:o.push({type:"unsupported-tool",tool:e})}})),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:o}}const l=[];for(const d of e)"function"===d.type?l.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:Rm(d.inputSchema)}):o.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:o};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:o};default:throw new Ct({functionality:`tool choice type: ${c}`})}}({tools:c,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:o,topP:r,frequencyPenalty:i,presencePenalty:s,stopSequences:a,seed:l,responseMimeType:"json"===(null==u?void 0:u.type)?"application/json":void 0,responseSchema:"json"!==(null==u?void 0:u.type)||null==u.schema||null!=(_=null==g?void 0:g.structuredOutputs)&&!_?void 0:Rm(u.schema),...(null==g?void 0:g.audioTimestamp)&&{audioTimestamp:g.audioTimestamp},responseModalities:null==g?void 0:g.responseModalities,thinkingConfig:null==g?void 0:g.thinkingConfig},contents:v,systemInstruction:f?void 0:y,safetySettings:null==g?void 0:g.safetySettings,tools:b,toolConfig:k,cachedContent:null==g?void 0:g.cachedContent,labels:null==g?void 0:g.labels},warnings:[...h,...w]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p;const{args:m,warnings:_}=await this.getArgs(e),h=JSON.stringify(m),g=md(await zd(this.config.headers),e.headers),{responseHeaders:f,value:v,rawValue:y}=await Cd({url:`${this.config.baseURL}/${Nm(this.modelId)}:generateContent`,headers:g,body:m,failedResponseHandler:Sm,successfulResponseHandler:Ld(Hm),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.candidates[0],k=[],w=null!=(n=null==(t=b.content)?void 0:t.parts)?n:[],x=v.usageMetadata;let I;for(const $ of w)if("executableCode"in $&&(null==(r=$.executableCode)?void 0:r.code)){const e=this.config.generateId();I=e,k.push({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify($.executableCode),providerExecuted:!0})}else"codeExecutionResult"in $&&$.codeExecutionResult?(k.push({type:"tool-result",toolCallId:I,toolName:"code_execution",result:{outcome:$.codeExecutionResult.outcome,output:$.codeExecutionResult.output},providerExecuted:!0}),I=void 0):"text"in $&&null!=$.text&&$.text.length>0?k.push({type:!0===$.thought?"reasoning":"text",text:$.text,providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"functionCall"in $?k.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:$.functionCall.name,input:JSON.stringify($.functionCall.args),providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"inlineData"in $&&k.push({type:"file",data:$.inlineData.data,mediaType:$.inlineData.mimeType});const S=null!=(o=qm({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))?o:[];for(const $ of S)k.push($);return{content:k,finishReason:Cm({finishReason:b.finishReason,hasToolCalls:k.some((e=>"tool-call"===e.type))}),usage:{inputTokens:null!=(i=null==x?void 0:x.promptTokenCount)?i:void 0,outputTokens:null!=(s=null==x?void 0:x.candidatesTokenCount)?s:void 0,totalTokens:null!=(a=null==x?void 0:x.totalTokenCount)?a:void 0,reasoningTokens:null!=(u=null==x?void 0:x.thoughtsTokenCount)?u:void 0,cachedInputTokens:null!=(l=null==x?void 0:x.cachedContentTokenCount)?l:void 0},warnings:_,providerMetadata:{google:{groundingMetadata:null!=(c=b.groundingMetadata)?c:null,urlContextMetadata:null!=(d=b.urlContextMetadata)?d:null,safetyRatings:null!=(p=b.safetyRatings)?p:null,usageMetadata:null!=x?x:null}},request:{body:h},response:{headers:f,body:y}}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),o=md(await zd(this.config.headers),e.headers),{responseHeaders:i,value:s}=await Cd({url:`${this.config.baseURL}/${Nm(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:t,failedResponseHandler:Sm,successfulResponseHandler:Md(Bm),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l;const c=this.config.generateId;let d=!1,p=null,m=null,_=0;const h=new Set;let g;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,i,s,f,v,y,b,k,w,x;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const I=t.value,S=I.usageMetadata;null!=S&&(u.inputTokens=null!=(r=S.promptTokenCount)?r:void 0,u.outputTokens=null!=(o=S.candidatesTokenCount)?o:void 0,u.totalTokens=null!=(i=S.totalTokenCount)?i:void 0,u.reasoningTokens=null!=(s=S.thoughtsTokenCount)?s:void 0,u.cachedInputTokens=null!=(f=S.cachedContentTokenCount)?f:void 0);const $=null==(v=I.candidates)?void 0:v[0];if(null==$)return;const O=$.content,E=qm({groundingMetadata:$.groundingMetadata,generateId:c});if(null!=E)for(const e of E)"url"!==e.sourceType||h.has(e.url)||(h.add(e.url),n.enqueue(e));if(null!=O){const e=null!=(y=O.parts)?y:[];for(const o of e)if("executableCode"in o&&(null==(b=o.executableCode)?void 0:b.code)){const e=c();g=e,n.enqueue({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(o.executableCode),providerExecuted:!0}),d=!0}else if("codeExecutionResult"in o&&o.codeExecutionResult){const e=g;e&&(n.enqueue({type:"tool-result",toolCallId:e,toolName:"code_execution",result:{outcome:o.codeExecutionResult.outcome,output:o.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else"text"in o&&null!=o.text&&o.text.length>0&&(!0===o.thought?(null!==p&&(n.enqueue({type:"text-end",id:p}),p=null),null===m&&(m=String(_++),n.enqueue({type:"reasoning-start",id:m,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})),n.enqueue({type:"reasoning-delta",id:m,delta:o.text,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})):(null!==m&&(n.enqueue({type:"reasoning-end",id:m}),m=null),null===p&&(p=String(_++),n.enqueue({type:"text-start",id:p,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})),n.enqueue({type:"text-delta",id:p,delta:o.text,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})));const t=function(e){return null==e?void 0:e.filter((e=>"inlineData"in e))}(O.parts);if(null!=t)for(const o of t)n.enqueue({type:"file",mediaType:o.inlineData.mimeType,data:o.inlineData.data});const r=function({parts:e,generateId:t}){const n=null==e?void 0:e.filter((e=>"functionCall"in e));return null==n||0===n.length?void 0:n.map((e=>({type:"tool-call",toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0})))}({parts:O.parts,generateId:c});if(null!=r)for(const o of r)n.enqueue({type:"tool-input-start",id:o.toolCallId,toolName:o.toolName,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-input-delta",id:o.toolCallId,delta:o.args,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-input-end",id:o.toolCallId,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.args,providerMetadata:o.providerMetadata}),d=!0}null!=$.finishReason&&(a=Cm({finishReason:$.finishReason,hasToolCalls:d}),l={google:{groundingMetadata:null!=(k=$.groundingMetadata)?k:null,urlContextMetadata:null!=(w=$.urlContextMetadata)?w:null,safetyRatings:null!=(x=$.safetyRatings)?x:null}},null!=S&&(l.google.usageMetadata=S))},flush(e){null!==p&&e.enqueue({type:"text-end",id:p}),null!==m&&e.enqueue({type:"reasoning-end",id:m}),e.enqueue({type:"finish",finishReason:a,usage:u,providerMetadata:l})}})),response:{headers:i},request:{body:r}}}};function qm({groundingMetadata:e,generateId:t}){var n;return null==(n=null==e?void 0:e.groundingChunks)?void 0:n.filter((e=>null!=e.web)).map((e=>({type:"source",sourceType:"url",id:t(),url:e.web.uri,title:e.web.title})))}var Zm=Rl({parts:El(Pl([Rl({functionCall:Rl({name:Du(),args:wl()}),thoughtSignature:Du().nullish()}),Rl({inlineData:Rl({mimeType:Du(),data:Du()})}),Rl({executableCode:Rl({language:Du(),code:Du()}).nullish(),codeExecutionResult:Rl({outcome:Du(),output:Du()}).nullish(),text:Du().nullish(),thought:pl().nullish(),thoughtSignature:Du().nullish()})])).nullish()}),Fm=Rl({category:Du().nullish(),probability:Du().nullish(),probabilityScore:ul().nullish(),severity:Du().nullish(),severityScore:ul().nullish(),blocked:pl().nullish()}),Wm=Rl({cachedContentTokenCount:ul().nullish(),thoughtsTokenCount:ul().nullish(),promptTokenCount:ul().nullish(),candidatesTokenCount:ul().nullish(),totalTokenCount:ul().nullish()}),Hm=Rl({candidates:El(Rl({content:Zm.nullish().or(Rl({}).strict()),finishReason:Du().nullish(),safetyRatings:El(Fm).nullish(),groundingMetadata:Um.nullish(),urlContextMetadata:Dm.nullish()})),usageMetadata:Wm.nullish()}),Bm=Rl({candidates:El(Rl({content:Zm.nullish(),finishReason:Du().nullish(),safetyRatings:El(Fm).nullish(),groundingMetadata:Um.nullish(),urlContextMetadata:Dm.nullish()})).nullish(),usageMetadata:Wm.nullish()}),Jm={googleSearch:jm,urlContext:Mm,codeExecution:jd({id:"google.code_execution",name:"code_execution",inputSchema:Rl({language:Du().describe("The programming language of the code."),code:Du().describe("The code to be executed.")}),outputSchema:Rl({outcome:Du().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:Du().describe("The output from the code execution.")})})},Vm=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=this.settings.maxImagesPerCall)?e:4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;const{prompt:o,n:i=1,size:s="1024x1024",aspectRatio:a="1:1",seed:u,providerOptions:l,headers:c,abortSignal:d}=e,p=[];null!=s&&p.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=u&&p.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});const m=await Nd({provider:"google",providerOptions:l,schema:Km}),_=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,h={sampleCount:i};null!=a&&(h.aspectRatio=a),m&&Object.assign(h,m);const g={instances:[{prompt:o}],parameters:h},{responseHeaders:f,value:v}=await Cd({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:md(await zd(this.config.headers),c),body:g,failedResponseHandler:Sm,successfulResponseHandler:Ld(Gm),abortSignal:d,fetch:this.config.fetch});return{images:v.predictions.map((e=>e.bytesBase64Encoded)),warnings:null!=p?p:[],providerMetadata:{google:{images:v.predictions.map((e=>({})))}},response:{timestamp:_,modelId:this.modelId,headers:f}}}},Gm=Rl({predictions:El(Rl({bytesBase64Encoded:Du()})).default([])}),Km=Rl({personGeneration:Bl(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Bl(["1:1","3:4","4:3","9:16","16:9"]).nullish()});function Ym(e={}){var t;const n=null!=(t=Gd(e.baseURL))?t:"https://generativelanguage.googleapis.com/v1beta",r=()=>({"x-goog-api-key":yd({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers}),o=t=>{var o;return new Lm(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(o=e.generateId)?o:gd,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:e.fetch})},i=t=>new Om(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,o={})=>new Vm(t,o,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),a=function(e){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return o(e)};return a.languageModel=o,a.chat=o,a.generativeAI=o,a.embedding=i,a.textEmbedding=i,a.textEmbeddingModel=i,a.image=s,a.imageModel=s,a.tools=Jm,a}var Xm=Ym(),Qm=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},e_=class{constructor(e){i(this,"getTokenFn"),i(this,"refreshTokenFn"),i(this,"onRefreshErrorFn"),this.getTokenFn=e.getTokenFn,this.refreshTokenFn=e.refreshTokenFn,this.onRefreshErrorFn=e.onRefreshErrorFn}async getAccessToken(){return this.getTokenFn()}async refreshToken(){return this.refreshTokenFn()}onRefreshError(e){this.onRefreshErrorFn&&this.onRefreshErrorFn(e)}},t_={baseUrl:"undefined"!=typeof process&&(null==(r=process.env)?void 0:r.ECHO_BASE_URL)||"https://echo.merit.systems"};var n_="https://echo.router.merit.systems",r_=class{constructor(e,t){i(this,"isRefreshing",!1),i(this,"refreshPromise",null),this.baseUrl=e,this.tokenProvider=t}async request(e,t={}){var n;const r=await this.tokenProvider.getAccessToken(),o=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...r&&{Authorization:`Bearer ${r}`}}});if(401===o.status&&!(null==(n=t.headers)?void 0:n["X-Retry"])){await this.handleTokenRefresh();const n=await this.tokenProvider.getAccessToken();return fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...n&&{Authorization:`Bearer ${n}`},"X-Retry":"true"}})}return o}async handleTokenRefresh(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.performRefresh();try{await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async performRefresh(){try{await this.tokenProvider.refreshToken()}catch(e){throw this.tokenProvider.onRefreshError&&this.tokenProvider.onRefreshError(e),e}}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,n){return this.request(e,{...n,method:"POST",body:t?JSON.stringify(t):null})}async put(e,t,n){return this.request(e,{...n,method:"PUT",body:t?JSON.stringify(t):null})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}},o_=class extends Error{constructor(e,t,n){super(t),i(this,"code"),i(this,"statusCode"),i(this,"endpoint"),this.name="EchoError",this.code=e,void 0!==(null==n?void 0:n.statusCode)&&(this.statusCode=n.statusCode),void 0!==(null==n?void 0:n.endpoint)&&(this.endpoint=n.endpoint)}};function i_(e,t,n){if("TypeError"===e.name)return new o_("NETWORK_ERROR","Network error"+(t?` while ${t}`:""),n?{endpoint:n}:void 0);const r=e.message.match(/^HTTP (\d+): (.*)$/);if(r&&r[1]&&r[2]){const e=parseInt(r[1]),o=r[2];return new o_(`HTTP_${e}`,`${o}${t?` while ${t}`:""}`,n?{statusCode:e,endpoint:n}:{statusCode:e})}return new o_("UNKNOWN_ERROR",`${e.message}${t?` while ${t}`:""}`,n?{endpoint:n}:void 0)}var s_=class{constructor(e){this.http=e}async handleRequest(e,t,n){try{const t=await e();if(!t.ok){const e=await t.text();throw new Error(`HTTP ${t.status}: ${e}`)}return await t.json()}catch(r){if(r instanceof Error)throw i_(r,t,n);throw new o_("UNKNOWN_ERROR","Unknown error occurred",n?{endpoint:n}:void 0)}}},a_=class extends s_{constructor(e,t){super(e),this.baseUrl=t}async listEchoApps(){return(await this.handleRequest((()=>this.http.get("/api/v1/apps")),"listing Echo apps","/api/v1/apps")).apps}async getEchoApp(e){return this.handleRequest((()=>this.http.get(`/api/v1/apps/${e}`)),"fetching Echo app",`/api/v1/apps/${e}`)}getAppUrl(e){return`${this.baseUrl}/apps/${e}`}},u_=class extends s_{constructor(e){super(e)}async getBalance(){return this.handleRequest((()=>this.http.get("/api/v1/balance")),"fetching balance","/api/v1/balance")}async getFreeBalance(e){const t={echoAppId:e};return this.handleRequest((()=>this.http.post("/api/v1/balance/free",t)),"fetching free tier balance","/api/v1/balance/free")}},l_=[{model_id:"claude-3-5-haiku-20241022",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"Anthropic"},{model_id:"claude-3-5-sonnet-20240620",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-5-sonnet-20241022",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-7-sonnet-20250219",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-haiku-20240307",input_cost_per_token:25e-8,output_cost_per_token:125e-8,provider:"Anthropic"},{model_id:"claude-3-opus-20240229",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-opus-4-1-20250805",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-opus-4-20250514",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-sonnet-4-20250514",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"}],c_=[{model_id:"gemini-2.0-flash",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-001",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-exp",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-exp-image-generation",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-001",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-preview",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-preview-02-05",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-preview-image-generation",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp-01-21",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp-1219",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-image-preview",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-lite",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-lite-preview-06-17",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-preview-05-20",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-preview-tts",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-pro",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-03-25",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-05-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-06-05",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-tts",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"}],d_=[{model_id:"gpt-3.5-turbo",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-3.5-turbo-0125",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-3.5-turbo-1106",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-4",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-0125-preview",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-0613",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-1106-preview",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-turbo",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4-turbo-2024-04-09",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4-turbo-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4.1",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"gpt-4.1-2025-04-14",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"gpt-4.1-mini",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4.1-mini-2025-04-14",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4.1-nano",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-4.1-nano-2025-04-14",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-4o",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-05-13",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-08-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-11-20",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-mini",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenAI"},{model_id:"gpt-4o-mini-2024-07-18",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenAI"},{model_id:"gpt-5",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-2025-08-07",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-chat-latest",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-mini",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenAI"},{model_id:"gpt-5-mini-2025-08-07",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenAI"},{model_id:"gpt-5-nano",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-5-nano-2025-08-07",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"o1",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-2024-12-17",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-pro",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-pro-2025-03-19",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o3",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-2025-04-16",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-deep-research",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-deep-research-2025-06-26",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenAI"},{model_id:"o3-mini-2025-01-31",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenAI"},{model_id:"o3-pro",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-pro-2025-06-10",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"}],p_=[{model_id:"agentica-org/deepcoder-14b-preview",input_cost_per_token:15e-9,output_cost_per_token:15e-9,provider:"OpenRouter"},{model_id:"agentica-org/deepcoder-14b-preview:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"ai21/jamba-large-1.7",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"ai21/jamba-mini-1.7",input_cost_per_token:2e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"aion-labs/aion-1.0",input_cost_per_token:4e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"aion-labs/aion-1.0-mini",input_cost_per_token:7e-7,output_cost_per_token:14e-7,provider:"OpenRouter"},{model_id:"aion-labs/aion-rp-llama-3.1-8b",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"alfredpros/codellama-7b-instruct-solidity",input_cost_per_token:7e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"alpindale/goliath-120b",input_cost_per_token:4e-6,output_cost_per_token:55e-7,provider:"OpenRouter"},{model_id:"amazon/nova-lite-v1",input_cost_per_token:6e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"amazon/nova-micro-v1",input_cost_per_token:35e-9,output_cost_per_token:14e-8,provider:"OpenRouter"},{model_id:"amazon/nova-pro-v1",input_cost_per_token:8e-7,output_cost_per_token:32e-7,provider:"OpenRouter"},{model_id:"anthracite-org/magnum-v2-72b",input_cost_per_token:3e-6,output_cost_per_token:3e-6,provider:"OpenRouter"},{model_id:"anthracite-org/magnum-v4-72b",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3-haiku",input_cost_per_token:25e-8,output_cost_per_token:125e-8,provider:"OpenRouter"},{model_id:"anthropic/claude-3-opus",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-haiku",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-haiku-20241022",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-sonnet",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-sonnet-20240620",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.7-sonnet",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.7-sonnet:thinking",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-opus-4",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-opus-4.1",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-sonnet-4",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"arcee-ai/coder-large",input_cost_per_token:5e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"arcee-ai/maestro-reasoning",input_cost_per_token:9e-7,output_cost_per_token:33e-7,provider:"OpenRouter"},{model_id:"arcee-ai/spotlight",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"arcee-ai/virtuoso-large",input_cost_per_token:75e-8,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"arliai/qwq-32b-arliai-rpr-v1",input_cost_per_token:1e-8,output_cost_per_token:4.00032e-8,provider:"OpenRouter"},{model_id:"arliai/qwq-32b-arliai-rpr-v1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-21b-a3b",input_cost_per_token:7e-8,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-300b-a47b",input_cost_per_token:28e-8,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-vl-28b-a3b",input_cost_per_token:14e-8,output_cost_per_token:56e-8,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-vl-424b-a47b",input_cost_per_token:42e-8,output_cost_per_token:125e-8,provider:"OpenRouter"},{model_id:"bytedance/ui-tars-1.5-7b",input_cost_per_token:1e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin-mistral-24b-venice-edition:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin-mixtral-8x22b",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-mistral-24b",input_cost_per_token:3.7022e-8,output_cost_per_token:1.4816e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-mistral-24b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-r1-mistral-24b",input_cost_per_token:1e-8,output_cost_per_token:3.40768e-8,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-r1-mistral-24b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cohere/command",input_cost_per_token:1e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"cohere/command-a",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"cohere/command-r",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-03-2024",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-08-2024",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-plus",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"cohere/command-r-plus-04-2024",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"cohere/command-r-plus-08-2024",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"cohere/command-r7b-12-2024",input_cost_per_token:3.75e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3-0324",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3-0324:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3.1",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-prover-v2",input_cost_per_token:5e-7,output_cost_per_token:218e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528-qwen3-8b",input_cost_per_token:1e-8,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528-qwen3-8b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-70b",input_cost_per_token:2.59154e-8,output_cost_per_token:1.03712e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-70b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-8b",input_cost_per_token:4e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-1.5b",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-14b",input_cost_per_token:15e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-14b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-32b",input_cost_per_token:75e-9,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-v3.1-base",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"eleutherai/llemma_7b",input_cost_per_token:8e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-001",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-exp:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-lite-001",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash-lite",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash-lite-preview-06-17",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-exp-03-25",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-preview",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-preview-05-06",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-flash-1.5",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"google/gemini-flash-1.5-8b",input_cost_per_token:3.75e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"google/gemini-pro-1.5",input_cost_per_token:125e-8,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"google/gemma-2-27b-it",input_cost_per_token:65e-8,output_cost_per_token:65e-8,provider:"OpenRouter"},{model_id:"google/gemma-2-9b-it",input_cost_per_token:1e-8,output_cost_per_token:1.00008e-8,provider:"OpenRouter"},{model_id:"google/gemma-2-9b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-12b-it",input_cost_per_token:4.81286e-8,output_cost_per_token:1.92608e-7,provider:"OpenRouter"},{model_id:"google/gemma-3-12b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-27b-it",input_cost_per_token:6.66396e-8,output_cost_per_token:2.66688e-7,provider:"OpenRouter"},{model_id:"google/gemma-3-27b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-4b-it",input_cost_per_token:2e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"google/gemma-3-4b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3n-e2b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3n-e4b-it",input_cost_per_token:2e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"google/gemma-3n-e4b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"gryphe/mythomax-l2-13b",input_cost_per_token:6e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"inception/mercury",input_cost_per_token:25e-8,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"inception/mercury-coder",input_cost_per_token:25e-8,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"infermatic/mn-inferor-12b",input_cost_per_token:6e-7,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"inflection/inflection-3-pi",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"inflection/inflection-3-productivity",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"liquid/lfm-3b",input_cost_per_token:2e-8,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"liquid/lfm-7b",input_cost_per_token:1e-8,output_cost_per_token:1e-8,provider:"OpenRouter"},{model_id:"mancer/weaver",input_cost_per_token:1125e-9,output_cost_per_token:1125e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3-70b-instruct",input_cost_per_token:3e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3-8b-instruct",input_cost_per_token:3e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b",input_cost_per_token:2e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b-instruct",input_cost_per_token:8e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-70b-instruct",input_cost_per_token:1e-7,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-8b-instruct",input_cost_per_token:15e-9,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-11b-vision-instruct",input_cost_per_token:49e-9,output_cost_per_token:49e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-11b-vision-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-1b-instruct",input_cost_per_token:5e-9,output_cost_per_token:1e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-3b-instruct",input_cost_per_token:3e-9,output_cost_per_token:6e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-3b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-90b-vision-instruct",input_cost_per_token:12e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-70b-instruct",input_cost_per_token:38e-9,output_cost_per_token:12e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-70b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-8b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-maverick",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-maverick:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-scout",input_cost_per_token:8e-8,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-scout:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-2-8b",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-3-8b",input_cost_per_token:2e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-4-12b",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"microsoft/mai-ds-r1",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"microsoft/mai-ds-r1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"microsoft/phi-3-medium-128k-instruct",input_cost_per_token:1e-6,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"microsoft/phi-3-mini-128k-instruct",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-3.5-mini-128k-instruct",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-4",input_cost_per_token:6e-8,output_cost_per_token:14e-8,provider:"OpenRouter"},{model_id:"microsoft/phi-4-multimodal-instruct",input_cost_per_token:5e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-4-reasoning-plus",input_cost_per_token:7e-8,output_cost_per_token:35e-8,provider:"OpenRouter"},{model_id:"microsoft/wizardlm-2-8x22b",input_cost_per_token:48e-8,output_cost_per_token:48e-8,provider:"OpenRouter"},{model_id:"minimax/minimax-01",input_cost_per_token:2e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"minimax/minimax-m1",input_cost_per_token:3e-7,output_cost_per_token:165e-8,provider:"OpenRouter"},{model_id:"mistralai/codestral-2501",input_cost_per_token:3e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/codestral-2508",input_cost_per_token:3e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/devstral-medium",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/devstral-small",input_cost_per_token:7e-8,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"mistralai/devstral-small-2505",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/devstral-small-2505:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/magistral-medium-2506",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"mistralai/magistral-medium-2506:thinking",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"mistralai/magistral-small-2506",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"mistralai/ministral-3b",input_cost_per_token:4e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"mistralai/ministral-8b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct",input_cost_per_token:28e-9,output_cost_per_token:54e-9,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct-v0.1",input_cost_per_token:11e-8,output_cost_per_token:19e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct-v0.3",input_cost_per_token:28e-9,output_cost_per_token:54e-9,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-large",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-large-2407",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-large-2411",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-medium-3",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-medium-3.1",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-nemo",input_cost_per_token:7.5e-9,output_cost_per_token:5e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-nemo:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-saba",input_cost_per_token:2e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small",input_cost_per_token:2e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-24b-instruct-2501",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-24b-instruct-2501:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.1-24b-instruct",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.1-24b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.2-24b-instruct",input_cost_per_token:5e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.2-24b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-tiny",input_cost_per_token:25e-8,output_cost_per_token:25e-8,provider:"OpenRouter"},{model_id:"mistralai/mixtral-8x22b-instruct",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/mixtral-8x7b-instruct",input_cost_per_token:8e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"mistralai/pixtral-12b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/pixtral-large-2411",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"moonshotai/kimi-dev-72b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"moonshotai/kimi-k2",input_cost_per_token:14e-8,output_cost_per_token:249e-8,provider:"OpenRouter"},{model_id:"moonshotai/kimi-k2:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"moonshotai/kimi-vl-a3b-thinking",input_cost_per_token:2.498985e-8,output_cost_per_token:1.00008e-7,provider:"OpenRouter"},{model_id:"moonshotai/kimi-vl-a3b-thinking:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"morph/morph-v3-fast",input_cost_per_token:9e-7,output_cost_per_token:19e-7,provider:"OpenRouter"},{model_id:"morph/morph-v3-large",input_cost_per_token:9e-7,output_cost_per_token:19e-7,provider:"OpenRouter"},{model_id:"neversleep/llama-3-lumimaid-70b",input_cost_per_token:4e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"neversleep/llama-3.1-lumimaid-8b",input_cost_per_token:9e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"neversleep/noromaid-20b",input_cost_per_token:1e-6,output_cost_per_token:175e-8,provider:"OpenRouter"},{model_id:"nousresearch/deephermes-3-llama-3-8b-preview:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"nousresearch/deephermes-3-mistral-24b-preview",input_cost_per_token:9.329544e-8,output_cost_per_token:3.733632e-7,provider:"OpenRouter"},{model_id:"nousresearch/hermes-2-pro-llama-3-8b",input_cost_per_token:25e-9,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"nousresearch/hermes-3-llama-3.1-405b",input_cost_per_token:7e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"nousresearch/hermes-3-llama-3.1-70b",input_cost_per_token:1e-7,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"nousresearch/hermes-4-405b",input_cost_per_token:1e-6,output_cost_per_token:3e-6,provider:"OpenRouter"},{model_id:"nousresearch/hermes-4-70b",input_cost_per_token:13e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"nousresearch/nous-hermes-2-mixtral-8x7b-dpo",input_cost_per_token:6e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-70b-instruct",input_cost_per_token:12e-8,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-ultra-253b-v1",input_cost_per_token:6e-7,output_cost_per_token:18e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-ultra-253b-v1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"nvidia/llama-3.3-nemotron-super-49b-v1",input_cost_per_token:13e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/chatgpt-4o-latest",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"openai/codex-mini",input_cost_per_token:15e-7,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-0613",input_cost_per_token:1e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-16k",input_cost_per_token:3e-6,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-instruct",input_cost_per_token:15e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4",input_cost_per_token:3e-5,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-0314",input_cost_per_token:3e-5,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-1106-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-turbo",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-turbo-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4.1",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4.1-mini",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4.1-nano",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-05-13",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-08-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-11-20",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-audio-preview",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini-2024-07-18",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini-search-preview",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-search-preview",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o:extended",input_cost_per_token:6e-6,output_cost_per_token:18e-6,provider:"OpenRouter"},{model_id:"openai/gpt-5",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-5-chat",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-5-mini",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-5-nano",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/gpt-oss-120b",input_cost_per_token:72e-9,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"openai/gpt-oss-20b",input_cost_per_token:4e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"openai/gpt-oss-20b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"openai/o1",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/o1-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o1-mini-2024-09-12",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o1-pro",input_cost_per_token:15e-5,output_cost_per_token:6e-4,provider:"OpenRouter"},{model_id:"openai/o3",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"openai/o3-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o3-mini-high",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o3-pro",input_cost_per_token:2e-5,output_cost_per_token:8e-5,provider:"OpenRouter"},{model_id:"openai/o4-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o4-mini-high",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"opengvlab/internvl3-14b",input_cost_per_token:2e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openrouter/auto",input_cost_per_token:-1,output_cost_per_token:-1,provider:"OpenRouter"},{model_id:"perplexity/r1-1776",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar",input_cost_per_token:1e-6,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-deep-research",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-pro",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-reasoning",input_cost_per_token:1e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-reasoning-pro",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"pygmalionai/mythalion-13b",input_cost_per_token:7e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2-72b-instruct",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-72b-instruct",input_cost_per_token:5.18308e-8,output_cost_per_token:2.07424e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-72b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-7b-instruct",input_cost_per_token:4e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-coder-32b-instruct",input_cost_per_token:4.99797e-8,output_cost_per_token:2.00016e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-coder-32b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-vl-7b-instruct",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-max",input_cost_per_token:16e-7,output_cost_per_token:64e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-plus",input_cost_per_token:4e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-turbo",input_cost_per_token:5e-8,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-vl-max",input_cost_per_token:8e-7,output_cost_per_token:32e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-vl-plus",input_cost_per_token:21e-8,output_cost_per_token:63e-8,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-32b-instruct",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-32b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-72b-instruct",input_cost_per_token:9.99594e-8,output_cost_per_token:4.00032e-7,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-72b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-14b",input_cost_per_token:6e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-14b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b",input_cost_per_token:13e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b-2507",input_cost_per_token:7.7968332e-8,output_cost_per_token:3.1202496e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b-thinking-2507",input_cost_per_token:7.7968332e-8,output_cost_per_token:3.1202496e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b-instruct-2507",input_cost_per_token:1e-7,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-32b",input_cost_per_token:1.7992692e-8,output_cost_per_token:7.200576e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-4b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-8b",input_cost_per_token:35e-9,output_cost_per_token:138e-9,provider:"OpenRouter"},{model_id:"qwen/qwen3-8b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-coder",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-coder:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwq-32b",input_cost_per_token:75e-9,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"qwen/qwq-32b-preview",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwq-32b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"raifle/sorcererlm-8x22b",input_cost_per_token:45e-7,output_cost_per_token:45e-7,provider:"OpenRouter"},{model_id:"rekaai/reka-flash-3:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"sao10k/l3-euryale-70b",input_cost_per_token:148e-8,output_cost_per_token:148e-8,provider:"OpenRouter"},{model_id:"sao10k/l3-lunaris-8b",input_cost_per_token:2e-8,output_cost_per_token:5e-8,provider:"OpenRouter"},{model_id:"sao10k/l3.1-euryale-70b",input_cost_per_token:65e-8,output_cost_per_token:75e-8,provider:"OpenRouter"},{model_id:"sao10k/l3.3-euryale-70b",input_cost_per_token:65e-8,output_cost_per_token:75e-8,provider:"OpenRouter"},{model_id:"sarvamai/sarvam-m:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"scb10x/llama3.1-typhoon2-70b-instruct",input_cost_per_token:88e-8,output_cost_per_token:88e-8,provider:"OpenRouter"},{model_id:"shisa-ai/shisa-v2-llama3.3-70b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"shisa-ai/shisa-v2-llama3.3-70b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"sophosympatheia/midnight-rose-70b",input_cost_per_token:8e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"switchpoint/router",input_cost_per_token:85e-8,output_cost_per_token:34e-7,provider:"OpenRouter"},{model_id:"tencent/hunyuan-a13b-instruct",input_cost_per_token:3e-8,output_cost_per_token:3e-8,provider:"OpenRouter"},{model_id:"tencent/hunyuan-a13b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"thedrummer/anubis-70b-v1.1",input_cost_per_token:4e-7,output_cost_per_token:7e-7,provider:"OpenRouter"},{model_id:"thedrummer/anubis-pro-105b-v1",input_cost_per_token:5e-7,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"thedrummer/rocinante-12b",input_cost_per_token:17e-8,output_cost_per_token:43e-8,provider:"OpenRouter"},{model_id:"thedrummer/skyfall-36b-v2",input_cost_per_token:4.81286e-8,output_cost_per_token:1.92608e-7,provider:"OpenRouter"},{model_id:"thedrummer/unslopnemo-12b",input_cost_per_token:4e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"thudm/glm-4-32b",input_cost_per_token:55e-8,output_cost_per_token:166e-8,provider:"OpenRouter"},{model_id:"thudm/glm-4.1v-9b-thinking",input_cost_per_token:35e-9,output_cost_per_token:138e-9,provider:"OpenRouter"},{model_id:"thudm/glm-z1-32b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t-chimera",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t-chimera:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t2-chimera:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"undi95/remm-slerp-l2-13b",input_cost_per_token:45e-8,output_cost_per_token:65e-8,provider:"OpenRouter"},{model_id:"x-ai/grok-2-1212",input_cost_per_token:2e-6,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"x-ai/grok-2-vision-1212",input_cost_per_token:2e-6,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"x-ai/grok-3",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-3-beta",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-3-mini",input_cost_per_token:3e-7,output_cost_per_token:5e-7,provider:"OpenRouter"},{model_id:"x-ai/grok-3-mini-beta",input_cost_per_token:3e-7,output_cost_per_token:5e-7,provider:"OpenRouter"},{model_id:"x-ai/grok-4",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-vision-beta",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"z-ai/glm-4-32b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5-air",input_cost_per_token:2e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5-air:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5v",input_cost_per_token:5e-7,output_cost_per_token:18e-7,provider:"OpenRouter"}],m_=[{model_id:"gpt-image-1",image_input_cost_per_token:1e-5,image_output_cost_per_token:4e-5,text_input_cost_per_token:5e-6,provider:"OpenAI"}],__=class extends s_{constructor(e){super(e)}async listSupportedChatModels(){return[...d_,...l_,...c_,...p_]}async listSupportedImageModels(){return m_}},h_=class extends s_{constructor(e){super(e)}async createPaymentLink(e){return this.handleRequest((()=>this.http.post("/api/v1/stripe/payment-link",e)),"creating payment link","/api/v1/stripe/payment-link")}async getPaymentUrl(e,t,n){const r={amount:e,description:t||"Echo Credits"};n&&(r.successUrl=n);try{return(await this.createPaymentLink(r)).paymentLink.url}catch(o){throw o}}},g_=class extends s_{constructor(e){super(e)}async getUserInfo(){return this.handleRequest((()=>this.http.get("/api/v1/user")),"fetching user info","/api/v1/user")}async registerReferralCode(e,t){const n={echoAppId:e,code:t};return this.handleRequest((()=>this.http.post("/api/v1/user/referral",n)),"registering referral code","/api/v1/user/referral")}},f_=class{constructor(e){var t;if(i(this,"http"),i(this,"config"),i(this,"tokenProvider"),i(this,"balance"),i(this,"payments"),i(this,"apps"),i(this,"users"),i(this,"models"),this.config=(t=e,{...t_,...t}),null==e?void 0:e.tokenProvider)this.tokenProvider=e.tokenProvider;else{const e=this.config.apiKey||process.env.ECHO_API_KEY;if(!e)throw new Error("No API key or token provider provided");this.tokenProvider=new Qm(e)}this.http=new r_(this.config.baseUrl,this.tokenProvider),this.balance=new u_(this.http),this.payments=new h_(this.http),this.apps=new a_(this.http,this.config.baseUrl),this.users=new g_(this.http),this.models=new __(this.http)}};function v_({appId:e,baseRouterUrl:t=n_},n,r){const o=async()=>{const o=await n(e);return Kp({baseURL:t,apiKey:o??"",...r&&{fetch:k_(fetch,r)}})};return Object.assign((async e=>(await o())(e)),{languageModel:async e=>(await o()).languageModel(e),chat:async e=>(await o()).chat(e),responses:async e=>(await o()).responses(e),completion:async e=>(await o()).completion(e),embedding:async e=>(await o()).embedding(e),textEmbedding:async e=>(await o()).textEmbedding(e),textEmbeddingModel:async e=>(await o()).textEmbeddingModel(e),image:async e=>(await o()).image(e),imageModel:async e=>(await o()).imageModel(e),transcription:async e=>(await o()).transcription(e),speech:async e=>(await o()).speech(e),tools:Yp.tools})}function y_({appId:e,baseRouterUrl:t=n_},n,r){const o=async()=>{const o=await n(e);return xm({baseURL:t,apiKey:o??"",headers:{"anthropic-dangerous-direct-browser-access":"true"},...r&&{fetch:k_(fetch,r)}})};return Object.assign((async e=>(await o())(e)),{languageModel:async e=>(await o()).languageModel(e),chat:async e=>(await o()).chat(e),messages:async e=>(await o()).messages(e),textEmbeddingModel:async e=>(await o()).textEmbeddingModel(e),imageModel:async e=>(await o()).imageModel(e),tools:Im.tools})}function b_({appId:e,baseRouterUrl:t=n_},n,r){const o=async()=>{const o=await n(e);return Ym({baseURL:t,apiKey:o??"",...r&&{fetch:k_(fetch,r)}})};return Object.assign((async e=>(await o())(e)),{languageModel:async e=>(await o()).languageModel(e),chat:async e=>(await o()).chat(e),image:async(e,t)=>(await o()).image(e,t),imageModel:async e=>(await o()).imageModel(e),textEmbedding:async e=>(await o()).textEmbedding(e),textEmbeddingModel:async e=>(await o()).textEmbeddingModel(e),generativeAI:async e=>(await o()).generativeAI(e),embedding:async e=>(await o()).embedding(e),tools:Xm.tools})}function k_(e,t){return async(n,r)=>{const o=await e(n,r);return 402===o.status&&t(),o}}function w_({apiUrl:e}){var t,r;const o=Oe(),[i,s]=n.useState(null);return n.useEffect((()=>{if(!o.user)return void s(null);const t=new e_({getTokenFn:()=>{var e;return Promise.resolve((null==(e=o.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{const e=await o.signinSilent();if(!e)throw new Error("Silent renew did not yield a new access token");return e.access_token},onRefreshErrorFn:async e=>{console.error("Token refresh failed:",e),await o.removeUser(),await o.clearStaleState()}}),n=new f_({baseUrl:e,tokenProvider:t});return s(n),()=>{s(null)}}),[e,o.user,null==(r=null==(t=o.user)?void 0:t.profile)?void 0:r.sub,o.signinSilent,o.signoutSilent]),i}const x_=n.createContext(null),I_=n.createContext(null);function S_({config:e,children:r}){var o,i,s;const a=Oe(),u=a.user,l=e.baseEchoUrl||"https://echo.merit.systems",c=(null==(o=a.user)?void 0:o.access_token)||null,d=w_({apiUrl:l}),[p,m]=n.useState(!1),{balance:_,freeTierBalance:h,refreshBalance:g,error:f,isLoading:v}=function(e,t){const[r,o]=n.useState(null),[i,s]=n.useState(null),[a,u]=n.useState(null),[l,c]=n.useState(!1),d=n.useCallback((async()=>{if(!e)throw new Error("Not authenticated");c(!0);try{const[n,r]=await Promise.all([e.balance.getBalance(),e.balance.getFreeBalance(t)]);o(n),s(r),u(null)}catch(n){const e=i_(n instanceof Error?n:new Error(String(n)),"refreshing balance");throw u(e.message),e}finally{c(!1)}}),[e,t]);return n.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(o(null),s(null),u(null))}),[e,t,d]),{balance:r,freeTierBalance:i,error:a,isLoading:l,refreshBalance:d}}(d,e.appId),{user:y,error:b,isLoading:k}=function(e){const[t,r]=n.useState(null),[o,i]=n.useState(null),[s,a]=n.useState(!1),u=n.useCallback((async()=>{if(!e)throw new Error("Not authenticated");a(!0);try{const t=await e.users.getUserInfo();r(t),i(null)}catch(t){const e=i_(t instanceof Error?t:new Error(String(t)),"refreshing user");throw i(e.message),e}finally{a(!1)}}),[e]);return n.useEffect((()=>{e?u().catch((e=>{console.error("Error loading initial user:",e)})):(r(null),i(null))}),[e,u]),{user:t,error:o,isLoading:s,refreshUser:u}}(d),{createPaymentLink:w,error:x,isLoading:I}=function(e){const[t,r]=n.useState(null),[o,i]=n.useState(!1);return{createPaymentLink:n.useCallback((async(t,n,o)=>{if(!e)throw new Error("Not authenticated");i(!0);try{const i=await e.payments.createPaymentLink({amount:t,description:n||"Echo Credits",successUrl:o||window.location.origin});return r(null),i.paymentLink.url}catch(s){const e=i_(s instanceof Error?s:new Error(String(s)),"creating payment link");throw r(e.message),e}finally{i(!1)}}),[e]),error:t,isLoading:o}}(d),S=n.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),$=n.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(i=a.user)?void 0:i.access_token]),O=(null==(s=a.error)?void 0:s.message)||f||x||b||null,E=a.isLoading&&!a.isAuthenticated,T=a.isLoading&&a.isAuthenticated,R=E||v||I||k,N=n.useMemo((()=>({user:y,rawUser:u,balance:_,freeTierBalance:h,isAuthenticated:a.isAuthenticated,isLoading:R,error:O,token:c,echoClient:d,signIn:a.signinRedirect,signOut:S,refreshBalance:g,createPaymentLink:w,getToken:$,clearAuth:S,config:e,isInsufficientFunds:p,setIsInsufficientFunds:m})),[y,u,_,h,a.isAuthenticated,R,O,c,d,a.signinRedirect,S,g,w,$,e,p]),A=n.useMemo((()=>({isRefreshing:T})),[T]);return t.jsx(x_.Provider,{value:N,children:t.jsx(I_.Provider,{value:A,children:r})})}function $_(){const e=n.useContext(x_);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}
2
- /*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:O_,setPrototypeOf:E_,isFrozen:T_,getPrototypeOf:R_,getOwnPropertyDescriptor:N_}=Object;let{freeze:A_,seal:C_,create:P_}=Object,{apply:U_,construct:j_}="undefined"!=typeof Reflect&&Reflect;A_||(A_=function(e){return e}),C_||(C_=function(e){return e}),U_||(U_=function(e,t,n){return e.apply(t,n)}),j_||(j_=function(e,t){return new e(...t)});const z_=X_(Array.prototype.forEach),D_=X_(Array.prototype.lastIndexOf),M_=X_(Array.prototype.pop),L_=X_(Array.prototype.push),q_=X_(Array.prototype.splice),Z_=X_(String.prototype.toLowerCase),F_=X_(String.prototype.toString),W_=X_(String.prototype.match),H_=X_(String.prototype.replace),B_=X_(String.prototype.indexOf),J_=X_(String.prototype.trim),V_=X_(Object.prototype.hasOwnProperty),G_=X_(RegExp.prototype.test),K_=(Y_=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return j_(Y_,t)});var Y_;function X_(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return U_(e,t,r)}}function Q_(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z_;E_&&E_(e,null);let r=t.length;for(;r--;){let o=t[r];if("string"==typeof o){const e=n(o);e!==o&&(T_(t)||(t[r]=e),o=e)}e[o]=!0}return e}function eh(e){for(let t=0;t<e.length;t++){V_(e,t)||(e[t]=null)}return e}function th(e){const t=P_(null);for(const[n,r]of O_(e)){V_(e,n)&&(Array.isArray(r)?t[n]=eh(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=th(r):t[n]=r)}return t}function nh(e,t){for(;null!==e;){const n=N_(e,t);if(n){if(n.get)return X_(n.get);if("function"==typeof n.value)return X_(n.value)}e=R_(e)}return function(){return null}}const rh=A_(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),oh=A_(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ih=A_(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),sh=A_(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ah=A_(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),uh=A_(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),lh=A_(["#text"]),ch=A_(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),dh=A_(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),ph=A_(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),mh=A_(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_h=C_(/\{\{[\w\W]*|[\w\W]*\}\}/gm),hh=C_(/<%[\w\W]*|[\w\W]*%>/gm),gh=C_(/\$\{[\w\W]*/gm),fh=C_(/^data-[\-\w.\u00B7-\uFFFF]+$/),vh=C_(/^aria-[\-\w]+$/),yh=C_(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),bh=C_(/^(?:\w+script|data):/i),kh=C_(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),wh=C_(/^html$/i),xh=C_(/^[a-z][.\w]*(-[.\w]+)+$/i);var Ih=Object.freeze({__proto__:null,ARIA_ATTR:vh,ATTR_WHITESPACE:kh,CUSTOM_ELEMENT:xh,DATA_ATTR:fh,DOCTYPE_NAME:wh,ERB_EXPR:hh,IS_ALLOWED_URI:yh,IS_SCRIPT_OR_DATA:bh,MUSTACHE_EXPR:_h,TMPLIT_EXPR:gh});const Sh=1,$h=3,Oh=7,Eh=8,Th=9;var Rh=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const n=t=>e(t);if(n.version="3.2.6",n.removed=[],!t||!t.document||t.document.nodeType!==Th||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const o=r,i=o.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:u,Element:l,NodeFilter:c,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:_}=t,h=l.prototype,g=nh(h,"cloneNode"),f=nh(h,"remove"),v=nh(h,"nextSibling"),y=nh(h,"childNodes"),b=nh(h,"parentNode");if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let k,w="";const{implementation:x,createNodeIterator:I,createDocumentFragment:S,getElementsByTagName:$}=r,{importNode:O}=o;let E={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof O_&&"function"==typeof b&&x&&void 0!==x.createHTMLDocument;const{MUSTACHE_EXPR:T,ERB_EXPR:R,TMPLIT_EXPR:N,DATA_ATTR:A,ARIA_ATTR:C,IS_SCRIPT_OR_DATA:P,ATTR_WHITESPACE:U,CUSTOM_ELEMENT:j}=Ih;let{IS_ALLOWED_URI:z}=Ih,D=null;const M=Q_({},[...rh,...oh,...ih,...ah,...lh]);let L=null;const q=Q_({},[...ch,...dh,...ph,...mh]);let Z=Object.seal(P_(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),F=null,W=null,H=!0,B=!0,J=!1,V=!0,G=!1,K=!0,Y=!1,X=!1,Q=!1,ee=!1,te=!1,ne=!1,re=!0,oe=!1,ie=!0,se=!1,ae={},ue=null;const le=Q_({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ce=null;const de=Q_({},["audio","video","img","source","image","track"]);let pe=null;const me=Q_({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_e="http://www.w3.org/1998/Math/MathML",he="http://www.w3.org/2000/svg",ge="http://www.w3.org/1999/xhtml";let fe=ge,ve=!1,ye=null;const be=Q_({},[_e,he,ge],F_);let ke=Q_({},["mi","mo","mn","ms","mtext"]),we=Q_({},["annotation-xml"]);const xe=Q_({},["title","style","font","a","script"]);let Ie=null;const Se=["application/xhtml+xml","text/html"];let $e=null,Oe=null;const Ee=r.createElement("form"),Te=function(e){return e instanceof RegExp||e instanceof Function},Re=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Oe||Oe!==e){if(e&&"object"==typeof e||(e={}),e=th(e),Ie=-1===Se.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,$e="application/xhtml+xml"===Ie?F_:Z_,D=V_(e,"ALLOWED_TAGS")?Q_({},e.ALLOWED_TAGS,$e):M,L=V_(e,"ALLOWED_ATTR")?Q_({},e.ALLOWED_ATTR,$e):q,ye=V_(e,"ALLOWED_NAMESPACES")?Q_({},e.ALLOWED_NAMESPACES,F_):be,pe=V_(e,"ADD_URI_SAFE_ATTR")?Q_(th(me),e.ADD_URI_SAFE_ATTR,$e):me,ce=V_(e,"ADD_DATA_URI_TAGS")?Q_(th(de),e.ADD_DATA_URI_TAGS,$e):de,ue=V_(e,"FORBID_CONTENTS")?Q_({},e.FORBID_CONTENTS,$e):le,F=V_(e,"FORBID_TAGS")?Q_({},e.FORBID_TAGS,$e):th({}),W=V_(e,"FORBID_ATTR")?Q_({},e.FORBID_ATTR,$e):th({}),ae=!!V_(e,"USE_PROFILES")&&e.USE_PROFILES,H=!1!==e.ALLOW_ARIA_ATTR,B=!1!==e.ALLOW_DATA_ATTR,J=e.ALLOW_UNKNOWN_PROTOCOLS||!1,V=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,G=e.SAFE_FOR_TEMPLATES||!1,K=!1!==e.SAFE_FOR_XML,Y=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,ne=e.RETURN_TRUSTED_TYPE||!1,Q=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,oe=e.SANITIZE_NAMED_PROPS||!1,ie=!1!==e.KEEP_CONTENT,se=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||yh,fe=e.NAMESPACE||ge,ke=e.MATHML_TEXT_INTEGRATION_POINTS||ke,we=e.HTML_INTEGRATION_POINTS||we,Z=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Te(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Te(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Z.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(B=!1),te&&(ee=!0),ae&&(D=Q_({},lh),L=[],!0===ae.html&&(Q_(D,rh),Q_(L,ch)),!0===ae.svg&&(Q_(D,oh),Q_(L,dh),Q_(L,mh)),!0===ae.svgFilters&&(Q_(D,ih),Q_(L,dh),Q_(L,mh)),!0===ae.mathMl&&(Q_(D,ah),Q_(L,ph),Q_(L,mh))),e.ADD_TAGS&&(D===M&&(D=th(D)),Q_(D,e.ADD_TAGS,$e)),e.ADD_ATTR&&(L===q&&(L=th(L)),Q_(L,e.ADD_ATTR,$e)),e.ADD_URI_SAFE_ATTR&&Q_(pe,e.ADD_URI_SAFE_ATTR,$e),e.FORBID_CONTENTS&&(ue===le&&(ue=th(ue)),Q_(ue,e.FORBID_CONTENTS,$e)),ie&&(D["#text"]=!0),Y&&Q_(D,["html","head","body"]),D.table&&(Q_(D,["tbody"]),delete F.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw K_('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw K_('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');k=e.TRUSTED_TYPES_POLICY,w=k.createHTML("")}else void 0===k&&(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(i){return console.warn("TrustedTypes policy "+o+" could not be created."),null}}(_,i)),null!==k&&"string"==typeof w&&(w=k.createHTML(""));A_&&A_(e),Oe=e}},Ne=Q_({},[...oh,...ih,...sh]),Ae=Q_({},[...ah,...uh]),Ce=function(e){L_(n.removed,{element:e});try{b(e).removeChild(e)}catch(t){f(e)}},Pe=function(e,t){try{L_(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){L_(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Ce(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},Ue=function(e){let t=null,n=null;if(Q)e="<remove></remove>"+e;else{const t=W_(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Ie&&fe===ge&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=k?k.createHTML(e):e;if(fe===ge)try{t=(new m).parseFromString(o,Ie)}catch(s){}if(!t||!t.documentElement){t=x.createDocument(fe,"template",null);try{t.documentElement.innerHTML=ve?w:o}catch(s){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),fe===ge?$.call(t,Y?"html":"body")[0]:Y?t.documentElement:i},je=function(e){return I.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ze=function(e){return e instanceof p&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},De=function(e){return"function"==typeof u&&e instanceof u};function Me(e,t,r){z_(e,(e=>{e.call(n,t,r,Oe)}))}const Le=function(e){let t=null;if(Me(E.beforeSanitizeElements,e,null),ze(e))return Ce(e),!0;const r=$e(e.nodeName);if(Me(E.uponSanitizeElement,e,{tagName:r,allowedTags:D}),K&&e.hasChildNodes()&&!De(e.firstElementChild)&&G_(/<[/\w!]/g,e.innerHTML)&&G_(/<[/\w!]/g,e.textContent))return Ce(e),!0;if(e.nodeType===Oh)return Ce(e),!0;if(K&&e.nodeType===Eh&&G_(/<[/\w]/g,e.data))return Ce(e),!0;if(!D[r]||F[r]){if(!F[r]&&Ze(r)){if(Z.tagNameCheck instanceof RegExp&&G_(Z.tagNameCheck,r))return!1;if(Z.tagNameCheck instanceof Function&&Z.tagNameCheck(r))return!1}if(ie&&!ue[r]){const t=b(e)||e.parentNode,n=y(e)||e.childNodes;if(n&&t){for(let r=n.length-1;r>=0;--r){const o=g(n[r],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,v(e))}}}return Ce(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:fe,tagName:"template"});const n=Z_(e.tagName),r=Z_(t.tagName);return!!ye[e.namespaceURI]&&(e.namespaceURI===he?t.namespaceURI===ge?"svg"===n:t.namespaceURI===_e?"svg"===n&&("annotation-xml"===r||ke[r]):Boolean(Ne[n]):e.namespaceURI===_e?t.namespaceURI===ge?"math"===n:t.namespaceURI===he?"math"===n&&we[r]:Boolean(Ae[n]):e.namespaceURI===ge?!(t.namespaceURI===he&&!we[r])&&!(t.namespaceURI===_e&&!ke[r])&&!Ae[n]&&(xe[n]||!Ne[n]):!("application/xhtml+xml"!==Ie||!ye[e.namespaceURI]))}(e)?(Ce(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!G_(/<\/no(script|embed|frames)/i,e.innerHTML)?(G&&e.nodeType===$h&&(t=e.textContent,z_([T,R,N],(e=>{t=H_(t,e," ")})),e.textContent!==t&&(L_(n.removed,{element:e.cloneNode()}),e.textContent=t)),Me(E.afterSanitizeElements,e,null),!1):(Ce(e),!0)},qe=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in r||n in Ee))return!1;if(B&&!W[t]&&G_(A,t));else if(H&&G_(C,t));else if(!L[t]||W[t]){if(!(Ze(e)&&(Z.tagNameCheck instanceof RegExp&&G_(Z.tagNameCheck,e)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(e))&&(Z.attributeNameCheck instanceof RegExp&&G_(Z.attributeNameCheck,t)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(t))||"is"===t&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&G_(Z.tagNameCheck,n)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(n))))return!1}else if(pe[t]);else if(G_(z,H_(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==B_(n,"data:")||!ce[e]){if(J&&!G_(P,H_(n,U,"")));else if(n)return!1}else;return!0},Ze=function(e){return"annotation-xml"!==e&&W_(e,j)},Fe=function(e){Me(E.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||ze(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0};let o=t.length;for(;o--;){const s=t[o],{name:a,namespaceURI:u,value:l}=s,c=$e(a),d=l;let p="value"===a?d:J_(d);if(r.attrName=c,r.attrValue=p,r.keepAttr=!0,r.forceKeepAttr=void 0,Me(E.uponSanitizeAttribute,e,r),p=r.attrValue,!oe||"id"!==c&&"name"!==c||(Pe(a,e),p="user-content-"+p),K&&G_(/((--!?|])>)|<\/(style|title)/i,p)){Pe(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Pe(a,e);continue}if(!V&&G_(/\/>/i,p)){Pe(a,e);continue}G&&z_([T,R,N],(e=>{p=H_(p,e," ")}));const m=$e(e.nodeName);if(qe(m,c,p)){if(k&&"object"==typeof _&&"function"==typeof _.getAttributeType)if(u);else switch(_.getAttributeType(m,c)){case"TrustedHTML":p=k.createHTML(p);break;case"TrustedScriptURL":p=k.createScriptURL(p)}if(p!==d)try{u?e.setAttributeNS(u,a,p):e.setAttribute(a,p),ze(e)?Ce(e):M_(n.removed)}catch(i){Pe(a,e)}}else Pe(a,e)}Me(E.afterSanitizeAttributes,e,null)},We=function e(t){let n=null;const r=je(t);for(Me(E.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Me(E.uponSanitizeShadowNode,n,null),Le(n),Fe(n),n.content instanceof s&&e(n.content);Me(E.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,i=null,a=null,l=null;if(ve=!e,ve&&(e="\x3c!--\x3e"),"string"!=typeof e&&!De(e)){if("function"!=typeof e.toString)throw K_("toString is not a function");if("string"!=typeof(e=e.toString()))throw K_("dirty is not a string, aborting")}if(!n.isSupported)return e;if(X||Re(t),n.removed=[],"string"==typeof e&&(se=!1),se){if(e.nodeName){const t=$e(e.nodeName);if(!D[t]||F[t])throw K_("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof u)r=Ue("\x3c!----\x3e"),i=r.ownerDocument.importNode(e,!0),i.nodeType===Sh&&"BODY"===i.nodeName||"HTML"===i.nodeName?r=i:r.appendChild(i);else{if(!ee&&!G&&!Y&&-1===e.indexOf("<"))return k&&ne?k.createHTML(e):e;if(r=Ue(e),!r)return ee?null:ne?w:""}r&&Q&&Ce(r.firstChild);const c=je(se?e:r);for(;a=c.nextNode();)Le(a),Fe(a),a.content instanceof s&&We(a.content);if(se)return e;if(ee){if(te)for(l=S.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(L.shadowroot||L.shadowrootmode)&&(l=O.call(o,l,!0)),l}let d=Y?r.outerHTML:r.innerHTML;return Y&&D["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&G_(wh,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),G&&z_([T,R,N],(e=>{d=H_(d,e," ")})),k&&ne?k.createHTML(d):d},n.setConfig=function(){Re(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),X=!0},n.clearConfig=function(){Oe=null,X=!1},n.isValidAttribute=function(e,t,n){Oe||Re({});const r=$e(e),o=$e(t);return qe(r,o,n)},n.addHook=function(e,t){"function"==typeof t&&L_(E[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=D_(E[e],t);return-1===n?void 0:q_(E[e],n,1)[0]}return M_(E[e])},n.removeHooks=function(e){E[e]=[]},n.removeAllHooks=function(){E={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Nh=(()=>{if("undefined"!=typeof window)return Rh;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return Rh(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Ah(e){if(!e)return"";const t=String(e);try{let e=Nh.sanitize(t,{ALLOWED_TAGS:[],ALLOWED_ATTR:[],KEEP_CONTENT:!0,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,FORCE_BODY:!0});if(!e.trim()&&t){t.replace(/<[^>]*>/g,"").trim()&&(e=t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim())}return e.trim().slice(0,1e3)}catch{return t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim().slice(0,1e3)}}async function Ch(e,t={}){const{onComplete:n,onError:r}=t,o=function(e){if(!e)return"";const t=Ah(e);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol?t:""}catch{return""}}(e);if(!o){const e=new Error("Invalid payment URL provided");throw null==r||r(e),e}try{window.location.href=o}catch(i){const e=i instanceof Error?i:new Error("Payment flow failed");throw null==r||r(e),e}}const Ph=({className:e="",width:n=16,height:r=16,variant:o="light"})=>{const i="dark"===o?"#DFE2D9":"#232323";return t.jsxs("svg",{id:"Layer_1","data-name":"Layer 1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 226.03 261",className:e,width:n,height:r,"aria-label":"Echo Logo",children:[t.jsx("defs",{children:t.jsx("style",{children:`\n .cls-1 {\n fill: none;\n }\n .cls-3 {\n fill: #7f0404;\n }\n .cls-4 {\n fill: ${i};\n }\n .cls-5 {\n fill: #a50404;\n }\n .cls-6 {\n fill: #cd0202;\n opacity: .9;\n }\n `})}),t.jsx("polygon",{className:"cls-6",points:"59.23 99.45 59.23 161.55 113.02 192.61 113.02 130.5 59.23 99.45"}),t.jsx("polygon",{className:"cls-5",points:"113.02 68.39 113.02 68.39 59.23 99.45 113.02 130.5 166.8 99.45 113.02 68.39"}),t.jsx("polygon",{className:"cls-3",points:"166.8 99.45 113.02 130.5 113.02 192.61 113.02 192.61 166.8 161.55 166.8 99.45"}),t.jsxs("g",{children:[t.jsx("path",{className:"cls-4",d:"m113.02,196.41l-57.08-32.95v-65.91l57.08-32.95,57.08,32.95v65.91l-57.08,32.95Zm-52.53-35.58l52.53,30.33,52.53-30.33v-60.66l-52.53-30.33-52.53,30.33v60.66Z"}),t.jsx("path",{className:"cls-4",d:"m113.02,261L0,195.75V65.25L113.02,0l113.02,65.25v130.5l-113.02,65.25ZM6.82,191.81l106.2,61.31,106.2-61.31v-122.62L113.02,7.88,6.82,69.19v122.62Z"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"3.94",width:"2.27",height:"63.28"}),t.jsx("rect",{className:"cls-4",x:"-.83",y:"176.82",width:"63.28",height:"2.27",transform:"translate(-84.84 39.24) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"194.08",y:"146.32",width:"2.27",height:"63.28",transform:"translate(-56.51 258.05) rotate(-60)"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"130.5",width:"2.27",height:"126.56"}),t.jsx("rect",{className:"cls-4",x:"104.54",y:"97.72",width:"126.56",height:"2.27",transform:"translate(-26.95 97.14) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"57.08",y:"35.58",width:"2.27",height:"126.56",transform:"translate(-56.51 99.84) rotate(-60)"})]})]})};function Uh({onSuccess:e,onError:r,className:o="",children:i}){const{signIn:s,isLoading:a,user:u,error:l}=$_(),[c,d]=n.useState(!1);n.useEffect((()=>{u&&e&&e(u)}),[u,e]),n.useEffect((()=>{l&&r&&r(new Error(l))}),[l,r]);const p=async()=>{try{await s()}catch(e){r&&r(e instanceof Error?e:new Error("Sign in failed"))}};return u?t.jsx("div",{className:`echo-signin-success ${o}`,children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[t.jsx(Ph,{width:16,height:16,variant:"light"}),t.jsxs("span",{children:["Signed in as ",Ah((null==u?void 0:u.name)||(null==u?void 0:u.email))]})]})}):t.jsx("div",{className:`echo-signin ${o}`,children:i?t.jsx("div",{onClick:p,style:{cursor:"pointer"},children:i}):t.jsxs("button",{onClick:p,disabled:a,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:a?"#f3f4f6":c?"#f1f5f9":"#ffffff",color:a?"#9ca3af":"#09090b",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:a?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[t.jsx(Ph,{width:16,height:16,variant:"light"}),t.jsx("span",{children:a?"Signing in...":"Sign in"})]})})}function jh({onSuccess:e,onError:r,className:o="",children:i}){const{signOut:s,isLoading:a,user:u,error:l}=$_(),[c,d]=n.useState(!1),[p,m]=n.useState(!1);n.useEffect((()=>{!u&&e&&p&&(e(),m(!1))}),[u,e,p]),n.useEffect((()=>{l&&r&&r(new Error(l))}),[l,r]);const _=async()=>{try{m(!0),await s()}catch(e){m(!1),r&&r(e instanceof Error?e:new Error("Sign out failed"))}};return u?t.jsx("div",{className:`echo-signout ${o}`,children:i?t.jsx("div",{onClick:_,style:{cursor:"pointer"},children:i}):t.jsxs("button",{onClick:_,disabled:a||p,className:"echo-signout-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:a||p?"#f3f4f6":c?"#fef2f2":"#ffffff",color:a||p?"#9ca3af":c?"#dc2626":"#374151",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:a||p?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[t.jsx(Ph,{width:16,height:16,variant:"light"}),t.jsx("span",{children:a||p?"Signing out...":"Sign out"})]})}):t.jsx("div",{className:`echo-signout-success ${o}`,children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[t.jsx(Ph,{width:16,height:16,variant:"light"}),t.jsx("span",{children:"Signed out"})]})})}const zh=({onAddCredits:e,onCancel:r,isProcessing:o})=>{const[i,s]=n.useState(""),a=n.useRef(null);n.useEffect((()=>{a.current&&a.current.focus()}),[]);const u=()=>{const t=Number(i);t>0&&e(t)},l=""!==i&&Number(i)>0;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),t.jsx("input",{ref:a,type:"number",value:i,onChange:e=>s(e.target.value),placeholder:"0.00",min:"1",step:"0.01",style:{flex:1,padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none"},onKeyDown:e=>{"Enter"===e.key&&l&&!o?u():"Escape"===e.key&&r()}})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsx("button",{onClick:r,style:{flex:1,padding:"8px 16px",backgroundColor:"transparent",color:"#6b7280",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Cancel"}),t.jsx("button",{onClick:u,disabled:!l||o,style:{flex:1,padding:"8px 16px",backgroundColor:l&&!o?"#dc2626":"#9ca3af",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:l&&!o?"pointer":"not-allowed",fontFamily:"HelveticaNowDisplay, sans-serif"},children:o?"Processing...":"Add Credits"})]})]})};function Dh({isOpen:e,onClose:r,onPurchaseComplete:o,onError:i}){const{createPaymentLink:s,user:a,refreshBalance:u}=$_(),[l,c]=n.useState(!1),[d,p]=n.useState(null),[m,_]=n.useState(!1),h=async e=>{if(!a){const e=new Error("Please sign in to purchase tokens");return p(e.message),void(null==i||i(e))}try{c(!0),p(null);const t=await s(e);await Ch(t,{onComplete:async()=>{try{await u(),null==o||o(),r()}catch(e){console.error("Failed to refresh balance:",e)}},onError:e=>{p(e.message),null==i||i(e)}})}catch(t){const e=t instanceof Error?t.message:"Purchase failed";p(e),null==i||i(t instanceof Error?t:new Error(e))}finally{c(!1)}};return e?t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px",margin:0,boxSizing:"border-box",border:"none",outline:"none",textDecoration:"none",listStyle:"none"},onClick:e=>{e.target===e.currentTarget&&r()},children:t.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",margin:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px",boxSizing:"border-box"},children:[t.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx(Ph,{width:20,height:20,variant:"light"}),t.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Insufficient Balance"})]})}),t.jsx("div",{style:{padding:"0 16px 16px 16px"},children:t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"You don't have enough credits to complete this request. Please add credits to your account."})}),t.jsx("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:m?t.jsx(zh,{onAddCredits:h,onCancel:()=>_(!1),isProcessing:l}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsx("button",{onClick:()=>h(10),disabled:l,style:{width:"100%",padding:"12px 16px",backgroundColor:l?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:l?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{l||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{l||(e.currentTarget.style.backgroundColor="#dc2626")},children:l?"Processing...":"Add $10.00"}),t.jsx("button",{onClick:()=>_(!0),disabled:l,style:{width:"100%",padding:"8px 16px",backgroundColor:"transparent",color:"#dc2626",border:"1px solid #dc2626",borderRadius:"6px",fontSize:"14px",cursor:l?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease"},onMouseEnter:e=>{l||(e.currentTarget.style.backgroundColor="#fef2f2",e.currentTarget.style.borderColor="#b91c1c")},onMouseLeave:e=>{l||(e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.borderColor="#dc2626")},children:"Custom Amount"})]})}),d&&t.jsx("div",{style:{padding:"0 16px 16px 16px"},children:t.jsx("div",{style:{padding:"8px 12px",backgroundColor:"#fef2f2",borderRadius:"6px",border:"1px solid #fecaca"},children:t.jsx("p",{style:{color:"#dc2626",margin:0,fontSize:"12px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:d})})}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",padding:"12px 16px",borderTop:"1px solid #f3f4f6",gap:"8px"},children:t.jsx("button",{onClick:r,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})})]})}):null}const Mh=({onAddCredits:e,onCancel:r,isProcessing:o})=>{const[i,s]=n.useState(""),a=n.useRef(null);n.useEffect((()=>{a.current&&a.current.focus()}),[]);const u=""!==i&&Number(i)>0;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),t.jsx("input",{ref:a,type:"number",placeholder:"0.00",value:i,onChange:e=>s(e.target.value),style:{width:"96px",textAlign:"right",padding:"8px 12px",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none",backgroundColor:"#ffffff"},min:"1",step:"0.01"})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("button",{onClick:r,style:{padding:"8px 12px",backgroundColor:"transparent",color:"#6b7280",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",textDecoration:"none"},onMouseEnter:e=>{e.currentTarget.style.color="#111827"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280"},children:"Cancel"}),t.jsx("button",{onClick:()=>{const t=Number(i);t>0&&e(t)},disabled:o||!u,style:{padding:"8px 16px",backgroundColor:o||!u?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:o||!u?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!o&&u&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!o&&u&&(e.currentTarget.style.backgroundColor="#dc2626")},children:o?"Processing...":"Add Credits"})]})]})};const Lh=n.createContext(null);var qh=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const e=n.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n[Math.random()*e|0];return r.join("")};if(null==e)return o;if(n.includes(r))throw new Je({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},Zh=qh(),Fh=/"__proto__"\s*:/,Wh=/"constructor"\s*:/;function Hh(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===Fh.test(e)&&!1===Wh.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}var Bh=Symbol.for("vercel.ai.validator");function Jh(e){return function(e){return"object"==typeof e&&null!==e&&Bh in e&&!0===e[Bh]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Tt({value:e,cause:n.issues})}},{[Bh]:!0,validate:n});var t,n}async function Vh({value:e,schema:t}){const n=await Gh({value:e,schema:t});if(!n.success)throw Tt.wrap({value:e,cause:n.error});return n.value}async function Gh({value:e,schema:t}){const n=Jh(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Tt.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Tt.wrap({value:e,cause:r}),rawValue:e}}}async function Kh({text:e,schema:t}){try{const n=function(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Hh(e)}finally{Error.stackTraceLimit=t}}(e);return null==t?{success:!0,value:n,rawValue:n}:await Gh({value:n,schema:t})}catch(n){return{success:!1,error:ut.isInstance(n)?n:new ut({text:e,cause:n}),rawValue:void 0}}}async function Yh(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}function Xh(e,t){return function(e){return"_zod"in e}(e)?function(e){return eg(hu(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Pu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return eg(pd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var Qh=Symbol.for("vercel.ai.schema");function eg(e,{validate:t}={}){return{[Qh]:!0,_type:void 0,[Bh]:!0,jsonSchema:e,validate:t}}function tg(e){return null==e?eg({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&Qh in t&&!0===t[Qh]&&"jsonSchema"in t&&"validate"in t?e:Xh(e);var t}var ng,rg=Object.defineProperty,og="AI_NoObjectGeneratedError",ig=`vercel.ai.error.${og}`,sg=Symbol.for(ig),ag=class extends Ae{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:og,message:e,cause:t}),this[ng]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return Ae.hasMarker(e,ig)}};ng=sg;var ug=Pl([Du(),Ic(Uint8Array),Ic(ArrayBuffer),kc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),lg=vc((()=>Pl([vl(),Du(),ul(),pl(),Zl(Du(),lg),El(lg)]))),cg=Zl(Du(),Zl(Du(),lg)),dg=Rl({type:Vl("text"),text:Du(),providerOptions:cg.optional()}),pg=Rl({type:Vl("image"),image:Pl([ug,Ic(URL)]),mediaType:Du().optional(),providerOptions:cg.optional()}),mg=Rl({type:Vl("file"),data:Pl([ug,Ic(URL)]),filename:Du().optional(),mediaType:Du(),providerOptions:cg.optional()}),_g=Rl({type:Vl("reasoning"),text:Du(),providerOptions:cg.optional()}),hg=Rl({type:Vl("tool-call"),toolCallId:Du(),toolName:Du(),input:wl(),providerOptions:cg.optional(),providerExecuted:pl().optional()}),gg=jl("type",[Rl({type:Vl("text"),value:Du()}),Rl({type:Vl("json"),value:lg}),Rl({type:Vl("error-text"),value:Du()}),Rl({type:Vl("error-json"),value:lg}),Rl({type:Vl("content"),value:El(Pl([Rl({type:Vl("text"),text:Du()}),Rl({type:Vl("media"),data:Du(),mediaType:Du()})]))})]),fg=Rl({type:Vl("tool-result"),toolCallId:Du(),toolName:Du(),output:gg,providerOptions:cg.optional()}),vg=Rl({role:Vl("system"),content:Du(),providerOptions:cg.optional()}),yg=Rl({role:Vl("user"),content:Pl([Du(),El(Pl([dg,pg,mg]))]),providerOptions:cg.optional()}),bg=Rl({role:Vl("assistant"),content:Pl([Du(),El(Pl([dg,mg,_g,hg,fg]))]),providerOptions:cg.optional()});Pl([vg,yg,bg,Rl({role:Vl("tool"),content:El(fg),providerOptions:cg.optional()})]),qh({prefix:"aitxt",size:24}),TransformStream;var kg=Pl([Nl({type:Vl("text-start"),id:Du(),providerMetadata:cg.optional()}),Nl({type:Vl("text-delta"),id:Du(),delta:Du(),providerMetadata:cg.optional()}),Nl({type:Vl("text-end"),id:Du(),providerMetadata:cg.optional()}),Nl({type:Vl("error"),errorText:Du()}),Nl({type:Vl("tool-input-start"),toolCallId:Du(),toolName:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-delta"),toolCallId:Du(),inputTextDelta:Du()}),Nl({type:Vl("tool-input-available"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:cg.optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-error"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:cg.optional(),dynamic:pl().optional(),errorText:Du()}),Nl({type:Vl("tool-output-available"),toolCallId:Du(),output:wl(),providerExecuted:pl().optional(),dynamic:pl().optional(),preliminary:pl().optional()}),Nl({type:Vl("tool-output-error"),toolCallId:Du(),errorText:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("reasoning"),text:Du(),providerMetadata:cg.optional()}),Nl({type:Vl("reasoning-start"),id:Du(),providerMetadata:cg.optional()}),Nl({type:Vl("reasoning-delta"),id:Du(),delta:Du(),providerMetadata:cg.optional()}),Nl({type:Vl("reasoning-end"),id:Du(),providerMetadata:cg.optional()}),Nl({type:Vl("reasoning-part-finish")}),Nl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:cg.optional()}),Nl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:cg.optional()}),Nl({type:Vl("file"),url:Du(),mediaType:Du(),providerMetadata:cg.optional()}),Nl({type:Du().startsWith("data-"),id:Du().optional(),data:wl(),transient:pl().optional()}),Nl({type:Vl("start-step")}),Nl({type:Vl("finish-step")}),Nl({type:Vl("start"),messageId:Du().optional(),messageMetadata:wl().optional()}),Nl({type:Vl("finish"),messageMetadata:wl().optional()}),Nl({type:Vl("abort")}),Nl({type:Vl("message-metadata"),messageMetadata:wl()})]);function wg(e,t){if(void 0===e&&void 0===t)return;if(void 0===e)return t;if(void 0===t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(void 0===o)continue;const i=r in e?e[r]:void 0,s=!(null===o||"object"!=typeof o||Array.isArray(o)||o instanceof Date||o instanceof RegExp),a=!(null==i||"object"!=typeof i||Array.isArray(i)||i instanceof Date||i instanceof RegExp);n[r]=s&&a?wg(i,o):o}return n}function xg(e){const t=["ROOT"];let n=-1,r=null;function o(e,o,i){switch(e){case'"':n=o,t.pop(),t.push(i),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=o,r=o,t.pop(),t.push(i),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=o,t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"{":n=o,t.pop(),t.push(i),t.push("INSIDE_OBJECT_START");break;case"[":n=o,t.pop(),t.push(i),t.push("INSIDE_ARRAY_START")}}function i(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":o(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":o(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":i(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const o=e.substring(r,u+1);"false".startsWith(o)||"true".startsWith(o)||"null".startsWith(o)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?i(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}async function Ig(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Kh({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Kh({text:xg(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Sg(e){return e.type.startsWith("tool-")}function $g(e){return e.type.split("-").slice(1).join("-")}function Og({lastMessage:e,messageId:t}){return{message:"assistant"===(null==e?void 0:e.role)?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Eg({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:i,onData:s}){return e.pipeThrough(new TransformStream({async transform(e,a){await r((async({state:r,write:u})=>{var l,c,d,p;function m(e){const t=r.message.parts.filter(Sg).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function _(e){const t=r.message.parts.filter((e=>"dynamic-tool"===e.type)).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function h(e){var t;const n=r.message.parts.find((t=>Sg(t)&&t.toolCallId===e.toolCallId)),o=e,i=n;null!=n?(n.state=e.state,i.input=o.input,i.output=o.output,i.errorText=o.errorText,i.rawInput=o.rawInput,i.preliminary=o.preliminary,i.providerExecuted=null!=(t=o.providerExecuted)?t:n.providerExecuted,null!=o.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=o.providerMetadata)):r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,input:o.input,output:o.output,rawInput:o.rawInput,errorText:o.errorText,providerExecuted:o.providerExecuted,preliminary:o.preliminary,...null!=o.providerMetadata?{callProviderMetadata:o.providerMetadata}:{}})}function g(e){var t;const n=r.message.parts.find((t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId)),o=e,i=n;null!=n?(n.state=e.state,i.toolName=e.toolName,i.input=o.input,i.output=o.output,i.errorText=o.errorText,i.rawInput=null!=(t=o.rawInput)?t:i.rawInput,i.preliminary=o.preliminary,null!=o.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=o.providerMetadata)):r.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:o.input,output:o.output,errorText:o.errorText,preliminary:o.preliminary,...null!=o.providerMetadata?{callProviderMetadata:o.providerMetadata}:{}})}async function f(e){if(null!=e){const n=null!=r.message.metadata?wg(r.message.metadata,e):e;null!=t&&await Vh({value:n,schema:t}),r.message.metadata=n}}switch(e.type){case"text-start":{const t={type:"text",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeTextParts[e.id]=t,r.message.parts.push(t),u();break}case"text-delta":{const t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(l=e.providerMetadata)?l:t.providerMetadata,u();break}case"text-end":{const t=r.activeTextParts[e.id];t.state="done",t.providerMetadata=null!=(c=e.providerMetadata)?c:t.providerMetadata,delete r.activeTextParts[e.id],u();break}case"reasoning-start":{const t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),u();break}case"reasoning-delta":{const t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,u();break}case"reasoning-end":{const t=r.activeReasoningParts[e.id];t.providerMetadata=null!=(p=e.providerMetadata)?p:t.providerMetadata,t.state="done",delete r.activeReasoningParts[e.id],u();break}case"file":r.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url}),u();break;case"source-url":r.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),u();break;case"source-document":r.message.parts.push({type:"source-document",sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),u();break;case"tool-input-start":{const t=r.message.parts.filter(Sg);r.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic},e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted}),u();break}case"tool-input-delta":{const t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;const{value:n}=await Ig(t.text);t.dynamic?g({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}):h({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}),u();break}case"tool-input-available":e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u(),i&&!e.providerExecuted&&await i({toolCall:e});break;case"tool-input-error":e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u();break;case"tool-output-available":if(e.dynamic){const t=_(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary})}else{const t=m(e.toolCallId);h({toolCallId:e.toolCallId,toolName:$g(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}u();break;case"tool-output-error":if(e.dynamic){const t=_(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText})}else{const t=m(e.toolCallId);h({toolCallId:e.toolCallId,toolName:$g(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText})}u();break;case"start-step":r.message.parts.push({type:"step-start"});break;case"finish-step":r.activeTextParts={},r.activeReasoningParts={};break;case"start":null!=e.messageId&&(r.message.id=e.messageId),await f(e.messageMetadata),null==e.messageId&&null==e.messageMetadata||u();break;case"finish":case"message-metadata":await f(e.messageMetadata),null!=e.messageMetadata&&u();break;case"error":null==o||o(new Error(e.errorText));break;default:if(function(e){return e.type.startsWith("data-")}(e)){null!=(null==n?void 0:n[e.type])&&await Vh({value:e.data,schema:n[e.type]});const t=e;if(t.transient){null==s||s(t);break}const o=null!=t.id?r.message.parts.find((e=>t.type===e.type&&t.id===e.id)):void 0;null!=o?o.data=t.data:r.message.parts.push(t),null==s||s(t),u()}}a.enqueue(e)}))}}))}qh({prefix:"aitxt",size:24}),qh({prefix:"aiobj",size:24});var Tg=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise(((t,n)=>{this.queue.push((async()=>{try{await e(),t()}catch(r){n(r)}})),this.processQueue()}))}};qh({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)rg(e,n,{get:t[n],enumerable:!0})})({},{object:()=>Ng,text:()=>Rg});var Rg=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),Ng=({schema:e})=>{const t=tg(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await Ig(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Kh({text:e});if(!r.success)throw new ag({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Gh({value:r.value,schema:t});if(!o.success)throw new ag({message:"No object generated: response did not match schema.",cause:o.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},Ag=Al({name:Du(),version:Du()}),Cg=Al({_meta:Ql(Rl({}).loose())}),Pg=Cg,Ug=Rl({method:Du(),params:Ql(Cg)}),jg=Al({experimental:Ql(Rl({}).loose()),logging:Ql(Rl({}).loose()),prompts:Ql(Al({listChanged:Ql(pl())})),resources:Ql(Al({subscribe:Ql(pl()),listChanged:Ql(pl())})),tools:Ql(Al({listChanged:Ql(pl())}))});Pg.extend({protocolVersion:Du(),capabilities:jg,serverInfo:Ag,instructions:Ql(Du())});var zg=Pg.extend({nextCursor:Ql(Du())}),Dg=Rl({name:Du(),description:Ql(Du()),inputSchema:Rl({type:Vl("object"),properties:Ql(Rl({}).loose())}).loose()}).loose();zg.extend({tools:El(Dg)});var Mg=Rl({type:Vl("text"),text:Du()}).loose(),Lg=Rl({type:Vl("image"),data:nl(),mimeType:Du()}).loose(),qg=Rl({uri:Du(),mimeType:Ql(Du())}).loose(),Zg=qg.extend({text:Du()}),Fg=qg.extend({blob:nl()}),Wg=Rl({type:Vl("resource"),resource:Pl([Zg,Fg])}).loose();Pg.extend({content:El(Pl([Mg,Lg,Wg])),isError:pl().default(!1).optional()}).or(Pg.extend({toolResult:wl()}));var Hg="2.0",Bg=Rl({jsonrpc:Vl(Hg),id:Pl([Du(),ul().int()])}).merge(Ug).strict(),Jg=Rl({jsonrpc:Vl(Hg),id:Pl([Du(),ul().int()]),result:Pg}).strict(),Vg=Rl({jsonrpc:Vl(Hg),id:Pl([Du(),ul().int()]),error:Rl({code:ul().int(),message:Du(),data:Ql(wl())})}).strict();Pl([Bg,Rl({jsonrpc:Vl(Hg)}).merge(Rl({method:Du(),params:Ql(Cg)})).strict(),Jg,Vg]);var Gg,Kg,Yg=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:o,prepareSendMessagesRequest:i,prepareReconnectToStreamRequest:s}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=o,this.prepareSendMessagesRequest=i,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:e,...t}){var n,r,o,i,s;const a=await Yh(this.body),u=await Yh(this.headers),l=await Yh(this.credentials),c=await(null==(n=this.prepareSendMessagesRequest)?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...u,...t.headers},credentials:l,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),d=null!=(r=null==c?void 0:c.api)?r:this.api,p=void 0!==(null==c?void 0:c.headers)?c.headers:{...u,...t.headers},m=void 0!==(null==c?void 0:c.body)?c.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},_=null!=(o=null==c?void 0:c.credentials)?o:l,h=null!=(i=this.fetch)?i:globalThis.fetch,g=await h(d,{method:"POST",headers:{"Content-Type":"application/json",...p},body:JSON.stringify(m),credentials:_,signal:e});if(!g.ok)throw new Error(null!=(s=await g.text())?s:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}async reconnectToStream(e){var t,n,r,o,i;const s=await Yh(this.body),a=await Yh(this.headers),u=await Yh(this.credentials),l=await(null==(t=this.prepareReconnectToStreamRequest)?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...s,...e.body},headers:{...a,...e.headers},credentials:u,requestMetadata:e.metadata})),c=null!=(n=null==l?void 0:l.api)?n:`${this.api}/${e.chatId}/stream`,d=void 0!==(null==l?void 0:l.headers)?l.headers:{...a,...e.headers},p=null!=(r=null==l?void 0:l.credentials)?r:u,m=null!=(o=this.fetch)?o:globalThis.fetch,_=await m(c,{method:"GET",headers:d,credentials:p});if(204===_.status)return null;if(!_.ok)throw new Error(null!=(i=await _.text())?i:"Failed to fetch the chat response.");if(!_.body)throw new Error("The response body is empty.");return this.processResponseStream(_.body)}},Xg=class extends Yg{constructor(e={}){super(e)}processResponseStream(e){return function({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new zt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Kh({text:e,schema:t}))}}))}({stream:e,schema:kg}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Qg=class{constructor({generateId:e=Zh,id:t=e(),transport:n=new Xg,messageMetadataSchema:r,dataPartSchemas:o,state:i,onError:s,onToolCall:a,onFinish:u,onData:l,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new Tg,this.sendMessage=async(e,t)=>{var n,r,o,i;if(null==e)return void(await this.makeRequest({trigger:"submit-message",messageId:null==(n=this.lastMessage)?void 0:n.id,...t}));let s;if("text"in e||"files"in e){const t=Array.isArray(e.files)?e.files:await async function(e){if(null==e)return[];if(!(globalThis.FileList&&e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map((async e=>{const{name:t,type:n}=e;return{type:"file",mediaType:n,filename:t,url:await new Promise(((t,n)=>{const r=new FileReader;r.onload=e=>{var n;t(null==(n=e.target)?void 0:n.result)},r.onerror=e=>n(e),r.readAsDataURL(e)}))}})))}(e.files);s={parts:[...t,..."text"in e&&null!=e.text?[{type:"text",text:e.text}]:[]]}}else s=e;if(null!=e.messageId){const t=this.state.messages.findIndex((t=>t.id===e.messageId));if(-1===t)throw new Error(`message with id ${e.messageId} not found`);if("user"!==this.state.messages[t].role)throw new Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...s,id:e.messageId,role:null!=(r=s.role)?r:"user",metadata:e.metadata})}else this.state.pushMessage({...s,id:null!=(o=s.id)?o:this.generateId(),role:null!=(i=s.role)?i:"user",metadata:e.metadata});await this.makeRequest({trigger:"submit-message",messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{const n=null==e?this.state.messages.length-1:this.state.messages.findIndex((t=>t.id===e));if(-1===n)throw new Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,"assistant"===this.messages[n].role?n:n+1),await this.makeRequest({trigger:"regenerate-message",messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:"resume-stream",...e})},this.clearError=()=>{"error"===this.status&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({tool:e,toolCallId:t,output:n})=>this.jobExecutor.run((async()=>{var e,r;const o=this.state.messages,i=o[o.length-1];this.state.replaceMessage(o.length-1,{...i,parts:i.parts.map((e=>Sg(e)&&e.toolCallId===t?{...e,state:"output-available",output:n}:e))}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map((e=>Sg(e)&&e.toolCallId===t?{...e,state:"output-available",output:n,errorText:void 0}:e))),"streaming"!==this.status&&"submitted"!==this.status&&(null==(e=this.sendAutomaticallyWhen)?void 0:e.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:null==(r=this.lastMessage)?void 0:r.id})})),this.stop=async()=>{var e;"streaming"!==this.status&&"submitted"!==this.status||(null==(e=this.activeResponse)?void 0:e.abortController)&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=o,this.state=i,this.onError=s,this.onToolCall=a,this.onFinish=u,this.onData=l,this.sendAutomaticallyWhen=c}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:o}){var i,s,a;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;try{const s={state:Og({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};let a;if(this.activeResponse=s,"resume-stream"===e){const e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(null==e)return void this.setStatus({status:"ready"});a=e}else a=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:s.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:o});const l=e=>this.jobExecutor.run((()=>e({state:s.state,write:()=>{var e;this.setStatus({status:"streaming"});s.state.message.id===(null==(e=this.lastMessage)?void 0:e.id)?this.state.replaceMessage(this.state.messages.length-1,s.state.message):this.state.pushMessage(s.state.message)}})));await async function({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:e}=await n.read();if(e)break}}catch(r){null==t||t(r)}finally{n.releaseLock()}}({stream:Eg({stream:a,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:l,onError:e=>{throw e}}),onError:e=>{throw e}}),null==(i=this.onFinish)||i.call(this,{message:s.state.message}),this.setStatus({status:"ready"})}catch(l){if("AbortError"===l.name)return this.setStatus({status:"ready"}),null;this.onError&&l instanceof Error&&this.onError(l),this.setStatus({status:"error",error:l})}finally{this.activeResponse=void 0}(null==(s=this.sendAutomaticallyWhen)?void 0:s.call(this,{messages:this.state.messages}))&&await this.makeRequest({trigger:"submit-message",messageId:null==(a=this.lastMessage)?void 0:a.id,metadata:t,headers:n,body:r})}},ef=Rl({type:Vl("text"),text:Du(),state:Bl(["streaming","done"]).optional(),providerMetadata:cg.optional()}),tf=Rl({type:Vl("reasoning"),text:Du(),state:Bl(["streaming","done"]).optional(),providerMetadata:cg.optional()}),nf=Rl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:cg.optional()}),rf=Rl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:cg.optional()}),of=Rl({type:Vl("file"),mediaType:Du(),filename:Du().optional(),url:Du(),providerMetadata:cg.optional()}),sf=Rl({type:Vl("step-start")}),af=Rl({type:Du().startsWith("data-"),id:Du().optional(),data:wl()}),uf=[Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:cg.optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:cg.optional(),preliminary:pl().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:cg.optional()})],lf=[Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:cg.optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:cg.optional(),preliminary:pl().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:cg.optional()})];function cf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function df(){if(Kg)return Gg;return Kg=1,Gg=function(e,t){if("function"!=typeof e)throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),s=t-(i-r);s<=0?(r=i,e.apply(this,o)):n=setTimeout((()=>{r=Date.now(),e.apply(this,o)}),s)}}}Rl({id:Du(),role:Bl(["system","user","assistant"]),metadata:wl().optional(),parts:El(Pl([ef,tf,nf,rf,of,sf,af,...uf,...lf]))});const pf=cf(df());var mf,_f,hf,gf,ff,vf,yf,bf,kf,wf=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},xf=(e,t,n)=>(wf(e,t,"read from private field"),n?n.call(e):t.get(e)),If=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Sf=(e,t,n,r)=>(wf(e,t,"write to private field"),t.set(e,n),n);var $f,Of=class{constructor(e=[]){If(this,mf,void 0),If(this,_f,"ready"),If(this,hf,void 0),If(this,gf,new Set),If(this,ff,new Set),If(this,vf,new Set),this.pushMessage=e=>{Sf(this,mf,xf(this,mf).concat(e)),xf(this,yf).call(this)},this.popMessage=()=>{Sf(this,mf,xf(this,mf).slice(0,-1)),xf(this,yf).call(this)},this.replaceMessage=(e,t)=>{Sf(this,mf,[...xf(this,mf).slice(0,e),this.snapshot(t),...xf(this,mf).slice(e+1)]),xf(this,yf).call(this)},this.snapshot=e=>structuredClone(e),this["~registerMessagesCallback"]=(e,t)=>{const n=t?(r=e,null!=(o=t)?pf(r,o):r):e;var r,o;return xf(this,gf).add(n),()=>{xf(this,gf).delete(n)}},this["~registerStatusCallback"]=e=>(xf(this,ff).add(e),()=>{xf(this,ff).delete(e)}),this["~registerErrorCallback"]=e=>(xf(this,vf).add(e),()=>{xf(this,vf).delete(e)}),If(this,yf,(()=>{xf(this,gf).forEach((e=>e()))})),If(this,bf,(()=>{xf(this,ff).forEach((e=>e()))})),If(this,kf,(()=>{xf(this,vf).forEach((e=>e()))})),Sf(this,mf,e)}get status(){return xf(this,_f)}set status(e){Sf(this,_f,e),xf(this,bf).call(this)}get error(){return xf(this,hf)}set error(e){Sf(this,hf,e),xf(this,kf).call(this)}get messages(){return xf(this,mf)}set messages(e){Sf(this,mf,[...e]),xf(this,yf).call(this)}};mf=new WeakMap,_f=new WeakMap,hf=new WeakMap,gf=new WeakMap,ff=new WeakMap,vf=new WeakMap,yf=new WeakMap,bf=new WeakMap,kf=new WeakMap;var Ef=class extends Qg{constructor({messages:e,...t}){const n=new Of(e);super({...t,state:n}),If(this,$f,void 0),this["~registerMessagesCallback"]=(e,t)=>xf(this,$f)["~registerMessagesCallback"](e,t),this["~registerStatusCallback"]=e=>xf(this,$f)["~registerStatusCallback"](e),this["~registerErrorCallback"]=e=>xf(this,$f)["~registerErrorCallback"](e),Sf(this,$f,n)}};$f=new WeakMap;var Tf,Rf=Object.defineProperty,Nf="AI_NoObjectGeneratedError",Af=`vercel.ai.error.${Nf}`,Cf=Symbol.for(Af),Pf=class extends Ae{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:Nf,message:e,cause:t}),this[Tf]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return Ae.hasMarker(e,Af)}};Tf=Cf;var Uf,jf="AI_MessageConversionError",zf=`vercel.ai.error.${jf}`,Df=Symbol.for(zf),Mf=class extends Ae{constructor({originalMessage:e,message:t}){super({name:jf,message:t}),this[Uf]=!0,this.originalMessage=e}static isInstance(e){return Ae.hasMarker(e,zf)}};Uf=Df;var Lf=Pl([Du(),Ic(Uint8Array),Ic(ArrayBuffer),kc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),qf=vc((()=>Pl([vl(),Du(),ul(),pl(),Zl(Du(),qf),El(qf)]))),Zf=Zl(Du(),Zl(Du(),qf)),Ff=Rl({type:Vl("text"),text:Du(),providerOptions:Zf.optional()}),Wf=Rl({type:Vl("image"),image:Pl([Lf,Ic(URL)]),mediaType:Du().optional(),providerOptions:Zf.optional()}),Hf=Rl({type:Vl("file"),data:Pl([Lf,Ic(URL)]),filename:Du().optional(),mediaType:Du(),providerOptions:Zf.optional()}),Bf=Rl({type:Vl("reasoning"),text:Du(),providerOptions:Zf.optional()}),Jf=Rl({type:Vl("tool-call"),toolCallId:Du(),toolName:Du(),input:wl(),providerOptions:Zf.optional(),providerExecuted:pl().optional()}),Vf=jl("type",[Rl({type:Vl("text"),value:Du()}),Rl({type:Vl("json"),value:qf}),Rl({type:Vl("error-text"),value:Du()}),Rl({type:Vl("error-json"),value:qf}),Rl({type:Vl("content"),value:El(Pl([Rl({type:Vl("text"),text:Du()}),Rl({type:Vl("media"),data:Du(),mediaType:Du()})]))})]),Gf=Rl({type:Vl("tool-result"),toolCallId:Du(),toolName:Du(),output:Vf,providerOptions:Zf.optional()}),Kf=Rl({role:Vl("system"),content:Du(),providerOptions:Zf.optional()}),Yf=Rl({role:Vl("user"),content:Pl([Du(),El(Pl([Ff,Wf,Hf]))]),providerOptions:Zf.optional()}),Xf=Rl({role:Vl("assistant"),content:Pl([Du(),El(Pl([Ff,Hf,Bf,Jf,Gf]))]),providerOptions:Zf.optional()});function Qf({output:e,tool:t,errorMode:n}){return"text"===n?{type:"error-text",value:Ze(e)}:"json"===n?{type:"error-json",value:ev(e)}:(null==t?void 0:t.toModelOutput)?t.toModelOutput(e):"string"==typeof e?{type:"text",value:e}:{type:"json",value:ev(e)}}function ev(e){return void 0===e?null:e}function tv(e){const t=["ROOT"];let n=-1,r=null;function o(e,o,i){switch(e){case'"':n=o,t.pop(),t.push(i),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=o,r=o,t.pop(),t.push(i),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=o,t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"{":n=o,t.pop(),t.push(i),t.push("INSIDE_OBJECT_START");break;case"[":n=o,t.pop(),t.push(i),t.push("INSIDE_ARRAY_START")}}function i(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":o(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":o(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":i(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const o=e.substring(r,u+1);"false".startsWith(o)||"true".startsWith(o)||"null".startsWith(o)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?i(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}function nv(e){return e.type.startsWith("tool-")}function rv(e){return e.type.split("-").slice(1).join("-")}Pl([Kf,Yf,Xf,Rl({role:Vl("tool"),content:El(Gf),providerOptions:Zf.optional()})]),hd({prefix:"aitxt",size:24}),TransformStream,Pl([Nl({type:Vl("text-start"),id:Du(),providerMetadata:Zf.optional()}),Nl({type:Vl("text-delta"),id:Du(),delta:Du(),providerMetadata:Zf.optional()}),Nl({type:Vl("text-end"),id:Du(),providerMetadata:Zf.optional()}),Nl({type:Vl("error"),errorText:Du()}),Nl({type:Vl("tool-input-start"),toolCallId:Du(),toolName:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-delta"),toolCallId:Du(),inputTextDelta:Du()}),Nl({type:Vl("tool-input-available"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:Zf.optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-error"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:Zf.optional(),dynamic:pl().optional(),errorText:Du()}),Nl({type:Vl("tool-output-available"),toolCallId:Du(),output:wl(),providerExecuted:pl().optional(),dynamic:pl().optional(),preliminary:pl().optional()}),Nl({type:Vl("tool-output-error"),toolCallId:Du(),errorText:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("reasoning"),text:Du(),providerMetadata:Zf.optional()}),Nl({type:Vl("reasoning-start"),id:Du(),providerMetadata:Zf.optional()}),Nl({type:Vl("reasoning-delta"),id:Du(),delta:Du(),providerMetadata:Zf.optional()}),Nl({type:Vl("reasoning-end"),id:Du(),providerMetadata:Zf.optional()}),Nl({type:Vl("reasoning-part-finish")}),Nl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:Zf.optional()}),Nl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:Zf.optional()}),Nl({type:Vl("file"),url:Du(),mediaType:Du(),providerMetadata:Zf.optional()}),Nl({type:Du().startsWith("data-"),id:Du().optional(),data:wl(),transient:pl().optional()}),Nl({type:Vl("start-step")}),Nl({type:Vl("finish-step")}),Nl({type:Vl("start"),messageId:Du().optional(),messageMetadata:wl().optional()}),Nl({type:Vl("finish"),messageMetadata:wl().optional()}),Nl({type:Vl("abort")}),Nl({type:Vl("message-metadata"),messageMetadata:wl()})]),hd({prefix:"aitxt",size:24}),hd({prefix:"aiobj",size:24}),hd({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)Rf(e,n,{get:t[n],enumerable:!0})})({},{object:()=>iv,text:()=>ov});var ov=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),iv=({schema:e})=>{const t=Wd(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await async function(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Ed({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ed({text:tv(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Ed({text:e});if(!r.success)throw new Pf({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await $d({value:r.value,schema:t});if(!o.success)throw new Pf({message:"No object generated: response did not match schema.",cause:o.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},sv=Al({name:Du(),version:Du()}),av=Al({_meta:Ql(Rl({}).loose())}),uv=av,lv=Rl({method:Du(),params:Ql(av)}),cv=Al({experimental:Ql(Rl({}).loose()),logging:Ql(Rl({}).loose()),prompts:Ql(Al({listChanged:Ql(pl())})),resources:Ql(Al({subscribe:Ql(pl()),listChanged:Ql(pl())})),tools:Ql(Al({listChanged:Ql(pl())}))});uv.extend({protocolVersion:Du(),capabilities:cv,serverInfo:sv,instructions:Ql(Du())});var dv=uv.extend({nextCursor:Ql(Du())}),pv=Rl({name:Du(),description:Ql(Du()),inputSchema:Rl({type:Vl("object"),properties:Ql(Rl({}).loose())}).loose()}).loose();dv.extend({tools:El(pv)});var mv=Rl({type:Vl("text"),text:Du()}).loose(),_v=Rl({type:Vl("image"),data:nl(),mimeType:Du()}).loose(),hv=Rl({uri:Du(),mimeType:Ql(Du())}).loose(),gv=hv.extend({text:Du()}),fv=hv.extend({blob:nl()}),vv=Rl({type:Vl("resource"),resource:Pl([gv,fv])}).loose();uv.extend({content:El(Pl([mv,_v,vv])),isError:pl().default(!1).optional()}).or(uv.extend({toolResult:wl()}));var yv="2.0",bv=Rl({jsonrpc:Vl(yv),id:Pl([Du(),ul().int()])}).merge(lv).strict(),kv=Rl({jsonrpc:Vl(yv),id:Pl([Du(),ul().int()]),result:uv}).strict(),wv=Rl({jsonrpc:Vl(yv),id:Pl([Du(),ul().int()]),error:Rl({code:ul().int(),message:Du(),data:Ql(wl())})}).strict();Pl([bv,Rl({jsonrpc:Vl(yv)}).merge(Rl({method:Du(),params:Ql(av)})).strict(),kv,wv]);var xv=Rl({type:Vl("text"),text:Du(),state:Bl(["streaming","done"]).optional(),providerMetadata:Zf.optional()}),Iv=Rl({type:Vl("reasoning"),text:Du(),state:Bl(["streaming","done"]).optional(),providerMetadata:Zf.optional()}),Sv=Rl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:Zf.optional()}),$v=Rl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:Zf.optional()}),Ov=Rl({type:Vl("file"),mediaType:Du(),filename:Du().optional(),url:Du(),providerMetadata:Zf.optional()}),Ev=Rl({type:Vl("step-start")}),Tv=Rl({type:Du().startsWith("data-"),id:Du().optional(),data:wl()}),Rv=[Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:Zf.optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:Zf.optional(),preliminary:pl().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:Zf.optional()})],Nv=[Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:Zf.optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:Zf.optional(),preliminary:pl().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:Zf.optional()})];function Av(){const e=function(){const e=n.useContext(Lh);if(!e)throw new Error("useChat must be used within an EchoChatProvider");return e}();return{async sendMessages(t){const{messages:n,abortSignal:r,...o}=t,i=function(e,t){const n=[];(null==t?void 0:t.ignoreIncompleteToolCalls)&&(e=e.map((e=>({...e,parts:e.parts.filter((e=>!nv(e)||"input-streaming"!==e.state&&"input-available"!==e.state))}))));for(const r of e)switch(r.role){case"system":{const e=r.parts.filter((e=>"text"===e.type)),t=e.reduce(((e,t)=>null!=t.providerMetadata?{...e,...t.providerMetadata}:e),{});n.push({role:"system",content:e.map((e=>e.text)).join(""),...Object.keys(t).length>0?{providerOptions:t}:{}});break}case"user":n.push({role:"user",content:r.parts.filter((e=>"text"===e.type||"file"===e.type)).map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};case"file":return{type:"file",mediaType:e.mediaType,filename:e.filename,data:e.url,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};default:return e}}))});break;case"assistant":if(null!=r.parts){let e=function(){var e,i;if(0===o.length)return;const s=[];for(const n of o)if("text"===n.type)s.push({type:"text",text:n.text,...null!=n.providerMetadata?{providerOptions:n.providerMetadata}:{}});else if("file"===n.type)s.push({type:"file",mediaType:n.mediaType,filename:n.filename,data:n.url});else if("reasoning"===n.type)s.push({type:"reasoning",text:n.text,providerOptions:n.providerMetadata});else if("dynamic-tool"===n.type){const e=n.toolName;if("input-streaming"===n.state)throw new Mf({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:e,input:n.input,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}})}else{if(!nv(n))throw new Error(`Unsupported part: ${n}`);{const o=rv(n);if("input-streaming"===n.state)throw new Mf({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:o,input:"output-error"===n.state?null!=(e=n.input)?e:n.rawInput:n.input,providerExecuted:n.providerExecuted,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}}),!0!==n.providerExecuted||"output-available"!==n.state&&"output-error"!==n.state||s.push({type:"tool-result",toolCallId:n.toolCallId,toolName:o,output:Qf({output:"output-error"===n.state?n.errorText:n.output,tool:null==(i=null==t?void 0:t.tools)?void 0:i[o],errorMode:"output-error"===n.state?"json":"none"})})}}n.push({role:"assistant",content:s});const a=o.filter((e=>nv(e)&&!0!==e.providerExecuted||"dynamic-tool"===e.type));a.length>0&&n.push({role:"tool",content:a.map((e=>{var n;switch(e.state){case"output-error":case"output-available":{const r="dynamic-tool"===e.type?e.toolName:rv(e);return{type:"tool-result",toolCallId:e.toolCallId,toolName:r,output:Qf({output:"output-error"===e.state?e.errorText:e.output,tool:null==(n=null==t?void 0:t.tools)?void 0:n[r],errorMode:"output-error"===e.state?"text":"none"})}}default:throw new Mf({originalMessage:r,message:`Unsupported tool part state: ${e.state}`})}}))}),o=[]},o=[];for(const t of r.parts)"text"===t.type||"reasoning"===t.type||"file"===t.type||"dynamic-tool"===t.type||nv(t)?o.push(t):"step-start"===t.type&&e();e();break}break;default:{const e=r.role;throw new Mf({originalMessage:r,message:`Unsupported role: ${e}`})}}return n}(n.map((({role:e,parts:t,metadata:n})=>({role:e,parts:t,metadata:n}))));return await e({uiMessages:n,modelMessages:i,abortSignal:r,...o})},reconnectToStream:async()=>null}}Rl({id:Du(),role:Bl(["system","user","assistant"]),metadata:wl().optional(),parts:El(Pl([xv,Iv,Sv,$v,Ov,Ev,Tv,...Rv,...Nv]))}),e.EchoChatProvider=function({chatFn:e,children:n}){return t.jsx(Lh.Provider,{value:e,children:n})},e.EchoProvider=function({config:e,children:r}){const[o,i]=n.useState(!1);if(n.useEffect((()=>{i(!0)}),[]),!o)return null;const s=e.baseEchoUrl||"https://echo.merit.systems",a={userManager:"undefined"!=typeof window&&window.__echoUserManager||new de({authority:s,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",silentRequestTimeoutInSeconds:10,automaticSilentRenew:!0,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${s}/api/oauth/authorize`,token_endpoint:`${s}/api/oauth/token`,userinfo_endpoint:`${s}/api/oauth/userinfo`,issuer:s,jwks_uri:`${s}/.well-known/jwks.json`,end_session_endpoint:`${s}/api/oauth/logout`},userStore:new N({store:window.localStorage})}),onSigninCallback:()=>{window.location.search.includes("code=")&&window.history.replaceState({},document.title,window.location.pathname)}};return t.jsx($e,{...a,children:t.jsx(S_,{config:e,children:r})})},e.EchoSignIn=Uh,e.EchoSignOut=jh,e.EchoTokens=function({onPurchaseComplete:e,onError:r,className:o="",children:i,showAvatar:s=!1}){const{createPaymentLink:a,user:u,balance:l,freeTierBalance:c,refreshBalance:d,isInsufficientFunds:p,setIsInsufficientFunds:m}=$_(),[_,h]=n.useState(!1),[g,f]=n.useState(null),[v,y]=n.useState(!1),[b,k]=n.useState(!1),w=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),x=()=>{var e,t;return(((null==(e=null==c?void 0:c.userSpendInfo)?void 0:e.amountLeft)||0)<0?0:(null==(t=null==c?void 0:c.userSpendInfo)?void 0:t.amountLeft)||0)+((null==l?void 0:l.balance)||0)},I=async t=>{if(!u){const e=new Error("Please sign in to purchase tokens");return f(e.message),void(r&&r(e))}try{h(!0),f(null);const n=await a(t);await Ch(n,{onComplete:async()=>{try{await d(),y(!1),k(!1),e&&l&&e(l)}catch(t){const e=t instanceof Error?t:new Error("Failed to refresh balance");f(e.message),r&&r(e)}finally{h(!1)}},onCancel:()=>{h(!1)},onError:e=>{f(e.message),r&&r(e),h(!1)}})}catch(n){const e=n instanceof Error?n:new Error("Failed to create payment link");f(e.message),r&&r(e),h(!1)}},S=()=>{y(!1),k(!1),f(null)};if(!u)return t.jsx("div",{className:`echo-token-purchase ${o}`,children:i?t.jsxs("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px",textAlign:"center"},children:[t.jsx("p",{style:{margin:"0 0 12px 0"},children:"Please sign in to purchase tokens"}),t.jsx(Uh,{})]}):t.jsx(Uh,{})});const $=()=>{const[e,r]=n.useState(!1);return t.jsxs("button",{onClick:()=>y(!0),className:`echo-token-purchase-compact ${o}`,style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 12px",borderRadius:"8px",backgroundColor:e?"#f1f5f9":"#ffffff",border:"1px solid #e5e7eb",color:"#09090b",fontSize:"14px",fontWeight:"800",cursor:"pointer",backdropFilter:"blur(8px)",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",height:"40px",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[s&&(null==u?void 0:u.picture)?t.jsx("img",{src:u.picture,alt:u.name||u.email||"User avatar",style:{width:"24px",height:"24px",borderRadius:"50%",objectFit:"cover",flexShrink:0},onError:e=>{e.currentTarget.style.display="none"}}):t.jsx(Ph,{width:20,height:20,variant:"light"}),t.jsx("span",{children:w(x())}),t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:e?"#dc2626":"#6b7280",transition:"color 0.2s ease"},children:[t.jsx("path",{d:"M7 7h10v10"}),t.jsx("path",{d:"M7 17 17 7"})]})]})},O=()=>t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px"},onClick:e=>{e.target===e.currentTarget&&S()},children:t.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px"},children:[t.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx(Ph,{width:20,height:20,variant:"light"}),t.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Credits"})]})}),t.jsxs("div",{style:{padding:"0 16px",marginBottom:"16px"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Total Available"}),t.jsx("p",{style:{fontSize:"28px",fontWeight:"700",color:"#111827",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:w(x())}),t.jsxs("div",{style:{marginBottom:"8px"},children:[c&&x()>0&&t.jsxs("div",{style:{marginBottom:"8px"},children:[t.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[t.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#3b82f6"}}),t.jsxs("span",{children:[w(c.userSpendInfo.amountLeft<0?0:c.userSpendInfo.amountLeft)," ","Free Tier",c.userSpendInfo&&c.userSpendInfo.spendLimit&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",w(c.userSpendInfo.amountSpent>c.userSpendInfo.spendLimit?c.userSpendInfo.spendLimit:c.userSpendInfo.amountSpent)," ","of"," ",w(c.userSpendInfo.spendLimit)," ","spent)"]})]})]}),c.userSpendInfo&&c.userSpendInfo.spendLimit&&t.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",marginBottom:"4px",border:"1px solid #d1d5db"},children:t.jsx("div",{style:{width:`${Math.max(0,Math.min(100,Math.max(0,c.userSpendInfo.amountLeft)/(c.userSpendInfo.spendLimit||1)*100))}%`,height:"100%",backgroundColor:"#3b82f6"}})})]}),l&&l.balance>0&&t.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[t.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#dc2626"}}),t.jsxs("span",{children:[w(l.balance)," Paid Credits",l.totalPaid>0&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",w(l.totalSpent)," of"," ",w(l.totalPaid)," spent)"]})]})]}),l.totalPaid>0&&t.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",border:"1px solid #d1d5db"},children:t.jsx("div",{style:{width:`${Math.max(0,Math.min(100,l.balance/l.totalPaid*100))}%`,height:"100%",backgroundColor:"#dc2626"}})})]})]})]}),t.jsxs("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Add Credits"}),b?t.jsx(Mh,{onAddCredits:I,onCancel:()=>k(!1),isProcessing:_}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsx("button",{onClick:()=>I(10),disabled:_,style:{width:"100%",padding:"12px 16px",backgroundColor:_?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:_?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{_||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{_||(e.currentTarget.style.backgroundColor="#dc2626")},children:_?"Processing...":"Add $10 Credits"}),t.jsx("button",{onClick:()=>k(!0),style:{width:"100%",padding:"8px 16px",fontSize:"14px",color:"#6b7280",backgroundColor:"transparent",border:"1px solid #e5e7eb",borderRadius:"6px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.color="#111827",e.currentTarget.style.borderColor="#d1d5db"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280",e.currentTarget.style.borderColor="#e5e7eb"},children:"Choose different amount"})]})]}),g&&t.jsx("div",{style:{margin:"0 16px 12px 16px",padding:"8px 12px",backgroundColor:"#fee2e2",color:"#dc2626",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:g}),t.jsxs("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"space-between",alignItems:"center",borderTop:"1px solid #f3f4f6"},children:[t.jsx(jh,{onSuccess:()=>{console.log("Signed out from credits modal"),S()},onError:e=>{console.error("Sign out error from credits modal:",e)},children:t.jsx("button",{style:{padding:"8px 16px",backgroundColor:"transparent",color:"#dc2626",border:"1px solid #dc2626",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#fef2f2",e.currentTarget.style.borderColor="#b91c1c"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.borderColor="#dc2626"},children:"Sign Out"})}),t.jsx("button",{onClick:S,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})]})]})});return t.jsxs(t.Fragment,{children:[i?t.jsx("div",{onClick:()=>y(!0),style:{cursor:"pointer"},children:i}):t.jsx($,{}),v&&t.jsx(O,{}),t.jsx(Dh,{isOpen:p,onClose:()=>m(!1),onPurchaseComplete:()=>{null==e||e(l),m(!1)},onError:r})]})},e.InsufficientFundsModal=Dh,e.Logo=Ph,e.useChat=function(){return function({experimental_throttle:e,resume:t=!1,...r}={}){const o=n.useRef("chat"in r?r.chat:new Ef(r));("chat"in r&&r.chat!==o.current||"id"in r&&o.current.id!==r.id)&&(o.current="chat"in r?r.chat:new Ef(r));const i="id"in r?r.id:null,s=n.useCallback((t=>o.current["~registerMessagesCallback"](t,e)),[e,i]),a=n.useSyncExternalStore(s,(()=>o.current.messages),(()=>o.current.messages)),u=n.useSyncExternalStore(o.current["~registerStatusCallback"],(()=>o.current.status),(()=>o.current.status)),l=n.useSyncExternalStore(o.current["~registerErrorCallback"],(()=>o.current.error),(()=>o.current.error)),c=n.useCallback((e=>{"function"==typeof e&&(e=e(o.current.messages)),o.current.messages=e}),[o]);return n.useEffect((()=>{t&&o.current.resumeStream()}),[t,o]),{id:o.current.id,messages:a,setMessages:c,sendMessage:o.current.sendMessage,regenerate:o.current.regenerate,clearError:o.current.clearError,stop:o.current.stop,error:l,resumeStream:o.current.resumeStream,status:u,addToolResult:o.current.addToolResult}}({transport:Av()})},e.useEcho=$_,e.useEchoClient=w_,e.useEchoModelProviders=()=>{const{token:e,config:t,setIsInsufficientFunds:r}=$_(),o=()=>r(!0);return n.useMemo((()=>{const n={appId:t.appId,baseRouterUrl:t.baseRouterUrl},r=async()=>e;return{openai:v_(n,r,o),anthropic:y_(n,r,o),google:b_(n,r,o)}}),[e,t.appId,t.baseRouterUrl,r])},e.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:r=!0}=e,{token:o,user:i}=$_(),[s,a]=n.useState(void 0),[u,l]=n.useState(null),[c,d]=n.useState(!1),p=n.useRef(null);return n.useEffect((()=>{if(p.current&&p.current.abort(),!r||!o)return a(void 0),l(null),void d(!1);return(async()=>{const e=new AbortController;p.current=e,d(!0),l(null);try{if(e.signal.aborted)return;const{default:n}=await import("openai");if(e.signal.aborted)return;const r=new n({apiKey:o,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(r)}catch(n){if(!e.signal.aborted){const e=n instanceof Error?n.message:"Failed to load OpenAI";e.includes("Cannot resolve module")||e.includes("Module not found")||e.includes("openai")?l("OpenAI package not found. Please install it with: pnpm add openai"):l(`Failed to initialize OpenAI client: ${e}`),console.error("Error loading OpenAI:",n),a(void 0)}}finally{e.signal.aborted||d(!1)}})(),()=>{p.current&&p.current.abort()}}),[o,i,t,r]),{openai:s,isReady:void 0!==s&&!c,error:u,isLoading:c}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).EchoReactSDK={},e.jsxRuntime,e.React)}(this,(function(e,t,n){"use strict";var r,o=Object.defineProperty,i=(e,t,n)=>((e,t,n)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class s extends Error{}function a(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(n){return atob(t)}}s.prototype.name="InvalidTokenError";var u,l,c,d={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},p=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(p||{});(c=p||(p={})).reset=function(){u=3,l=d},c.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");u=e},c.setLogger=function(e){l=e};var m=class e{constructor(e){this._name=e}debug(...t){u>=4&&l.debug(e._format(this._name,this._method),...t)}info(...t){u>=3&&l.info(e._format(this._name,this._method),...t)}warn(...t){u>=2&&l.warn(e._format(this._name,this._method),...t)}error(...t){u>=1&&l.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,n){const r=new e(`${t}.${n}`);return r.debug("begin"),r}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){u>=4&&l.debug(e._format(t),...n)}static info(t,...n){u>=3&&l.info(e._format(t),...n)}static warn(t,...n){u>=2&&l.warn(e._format(t),...n)}static error(t,...n){u>=1&&l.error(e._format(t),...n)}};p.reset();var _=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new s("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,r=e.split(".")[n];if("string"!=typeof r)throw new s(`Invalid token specified: missing part #${n+1}`);let o;try{o=a(r)}catch(i){throw new s(`Invalid token specified: invalid base64 for part #${n+1} (${i.message})`)}try{return JSON.parse(o)}catch(i){throw new s(`Invalid token specified: invalid json for part #${n+1} (${i.message})`)}}(e)}catch(t){throw m.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,n){const r=`${f.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${f.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,(new TextEncoder).encode(r));return`${r}.${f.encodeBase64Url(new Uint8Array(o))}`}},h=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),g=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return h(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw m.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const n=(new TextEncoder).encode([e,t].join(":"));return h(n)}static async hash(e,t){const n=(new TextEncoder).encode(t),r=await crypto.subtle.digest(e,n);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":n={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const r=await e.hash("SHA-256",JSON.stringify(n));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:r,keyPair:o,nonce:i}){let s,a;const u={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};n&&(s=await e.hash("SHA-256",n),a=e.encodeBase64Url(s),u.ath=a),i&&(u.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",o.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await _.generateSignedJwt(t,u,o.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const n=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(n)}catch(n){throw n instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${n.message}`):n}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};g.encodeBase64Url=e=>h(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var f=g,v=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new m(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},y=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},b=class e extends v{constructor(){super(...arguments),this._logger=new m(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const n=this._logger.create("init");t=Math.max(Math.floor(t),1);const r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle)return void n.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),n.debug("using duration",t),this._expiration=r;const o=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*o)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},k=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},w=";",x=class extends Error{constructor(e,t){var n,r,o;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw m.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(r=e.error_uri)?r:null,this.state=e.userState,this.session_state=null!=(o=e.session_state)?o:null,this.url_state=e.url_state}},I=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},S=class{constructor(e){this._logger=new m("AccessTokenEvents"),this._expiringTimer=new b("Access token expiring"),this._expiredTimer=new b("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const r=n+1;t.debug("registering expired timer, raising in",r,"seconds"),this._expiredTimer.init(r)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},$=class{constructor(e,t,n,r,o){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=o,this._logger=new m("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const i=new URL(n);this._frame_origin=i.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=i.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},O=class{constructor(){this._logger=new m("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},T=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},E=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new m("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...r}=t;if(!n)return await fetch(e,r);const o=new AbortController,i=setTimeout((()=>o.abort()),1e3*n);try{return await fetch(e,{...t,signal:o.signal})}catch(s){if(s instanceof DOMException&&"AbortError"===s.name)throw new I("Network timed out");throw s}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){const o=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let s;t&&(o.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{o.debug("url:",e),s=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:r,credentials:n})}catch(l){throw o.error("Network Error"),l}o.debug("HTTP response received, status",s.status);const a=s.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&o.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),s.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let u;try{u=await s.json()}catch(l){if(o.error("Error parsing JSON response",l),s.ok)throw l;throw new Error(`${s.statusText} (${s.status})`)}if(!s.ok){if(o.error("Error from server:",u),u.error)throw new x(u);throw new Error(`${s.statusText} (${s.status}): ${JSON.stringify(u)}`)}return u}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:o,extraHeaders:i}){const s=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let u;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{s.debug("url:",e),u=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:r,credentials:o})}catch(p){throw s.error("Network error"),p}s.debug("HTTP response received, status",u.status);const l=u.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const c=await u.text();let d={};if(c)try{d=JSON.parse(c)}catch(p){if(s.error("Error parsing JSON response",p),u.ok)throw p;throw new Error(`${u.statusText} (${u.status})`)}if(!u.ok){if(s.error("Error from server:",d),u.headers.has("dpop-nonce")){const e=u.headers.get("dpop-nonce");throw new T(e,`${JSON.stringify(d)}`)}if(d.error)throw new x(d,t);throw new Error(`${u.statusText} (${u.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["accept","content-type"],o=["authorization"];0!==n.length&&n.forEach((n=>{if(r.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be set",n,r);if(o.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n))return void t.warn("Header could not be overridden",n,o);const i="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];i&&""!==i&&(e[n]=i)}))}},R=class{constructor(e){this._settings=e,this._logger=new m("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new E(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const n=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(n.debug("resolved"),void 0===r[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return r[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},N=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new m("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let n=0;n<e;n++){const e=await this._store.key(n);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},A=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:o,client_id:i,client_secret:s,response_type:a="code",scope:u="openid",redirect_uri:l,post_logout_redirect_uri:c,client_authentication:d="client_secret_post",prompt:p,display:m,max_age:_,ui_locales:h,acr_values:g,resource:f,response_mode:v,filterProtocolClaims:y=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:k,staleStateAgeInSeconds:w=900,mergeClaimsStrategy:x={array:"replace"},disablePKCE:I=!1,stateStore:S,revokeTokenAdditionalContentTypes:$,fetchRequestCredentials:T,refreshTokenAllowedScope:E,extraQueryParams:R={},extraTokenParams:A={},extraHeaders:C={},dpop:P,omitScopeWhenRequesting:j=!1}){var U;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=n,this.metadataSeed=o,this.signingKeys=r,this.client_id=i,this.client_secret=s,this.response_type=a,this.scope=u,this.redirect_uri=l,this.post_logout_redirect_uri=c,this.client_authentication=d,this.prompt=p,this.display=m,this.max_age=_,this.ui_locales=h,this.acr_values=g,this.resource=f,this.response_mode=v,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=w,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=j,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=$,this.fetchRequestCredentials=T||"same-origin",this.requestTimeoutInSeconds=k,S)this.stateStore=S;else{const e="undefined"!=typeof window?window.localStorage:new O;this.stateStore=new N({store:e})}if(this.refreshTokenAllowedScope=E,this.extraQueryParams=R,this.extraTokenParams=A,this.extraHeaders=C,this.dpop=P,this.dpop&&!(null==(U=this.dpop)?void 0:U.store))throw new Error("A DPoPStore is required when dpop is enabled")}},C=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new m("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const n=_.decode(e);return t.debug("JWT decoding successful"),n}catch(n){throw t.error("Error parsing JWT response"),n}},this._jsonService=new E(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const r=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",r),r}},P=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new m("TokenClient"),this._jsonService=new E(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:o,...i}){const s=this._logger.create("exchangeCode");n||s.throw(new Error("A client_id is required")),t||s.throw(new Error("A redirect_uri is required")),i.code||s.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,p]of Object.entries(i))null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw s.throw(new Error("A client_secret is required")),null;u=f.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:o});return s.debug("got response"),c}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:r=this._settings.scope,...o}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||s.set("scope",r);for(const[c,d]of Object.entries(o))null!=d&&s.set(c,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw i.throw(new Error("A client_secret is required")),null;a=f.generateBasicAuth(t,n);break;case"client_secret_post":s.append("client_id",t),n&&s.append("client_secret",n)}const u=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:o,...i}){const s=this._logger.create("exchangeRefreshToken");t||s.throw(new Error("A client_id is required")),i.refresh_token||s.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[d,p]of Object.entries(i))Array.isArray(p)?p.forEach((e=>a.append(d,e))):null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw s.throw(new Error("A client_secret is required")),null;u=f.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:o});return s.debug("got response"),c}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const o=new URLSearchParams;for(const[i,s]of Object.entries(e))null!=s&&o.set(i,s);o.set("client_id",this._settings.client_id),this._settings.client_secret&&o.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:o,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),n.debug("got response")}},j=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new m("ResponseValidator"),this._userInfoService=new C(this._settings,this._metadataService),this._tokenClient=new P(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){const r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t,n),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){const n=this._logger.create("validateCredentialsResponse"),r=e.isOpenId&&!!e.id_token;r&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,r),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new x(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new x(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const r=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void r.debug("not loading user info");r.debug("loading user info");const o=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),n&&o.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(o)),r.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,n){const r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");const o=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:n,...t.extraTokenParams});Object.assign(e,o)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const o=_.decode(null!=(n=e.id_token)?n:"");if(o.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=_.decode(t);o.sub!==e.sub&&r.throw(new Error("sub in id_token does not match current sub")),o.auth_time&&o.auth_time!==e.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),o.azp&&o.azp!==e.azp&&r.throw(new Error("azp in id_token does not match original azp")),!o.azp&&e.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=o}},U=class e{constructor(e){this.id=e.id||f.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=b.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new m("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return m.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){const r=m.createStatic("State","clearStaleState"),o=b.getEpochTime()-n,i=await t.getAllKeys();r.debug("got keys",i);for(let a=0;a<i.length;a++){const n=i[a],u=await t.get(n);let l=!1;if(u)try{const t=await e.fromStorageString(u);r.debug("got item from key:",n,t.created),t.created<=o&&(l=!0)}catch(s){r.error("Error parsing state for key:",n,s),l=!0}else r.debug("no item in storage for key:",n),l=!0;l&&(r.debug("removed item for key:",n),t.remove(n))}}},z=class e extends U{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const n=!0===t.code_verifier?f.generateCodeVerifier():t.code_verifier||void 0,r=n?await f.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:r})}toStorageString(){return new m("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){m.createStatic("SigninState","fromStorageString");const n=JSON.parse(t);return e.create(n)}},D=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:r,redirect_uri:o,response_type:i,scope:s,state_data:a,response_mode:u,request_type:l,client_secret:c,nonce:d,url_state:p,resource:m,skipUserInfo:_,extraQueryParams:h,extraTokenParams:g,disablePKCE:f,dpopJkt:v,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!o)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!s)throw this._logger.error("create: No scope passed"),new Error("scope");if(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const k=await z.create({data:a,request_type:l,url_state:p,code_verifier:!f,client_id:r,authority:n,redirect_uri:o,response_mode:u,client_secret:c,scope:s,extraTokenParams:g,skipUserInfo:_}),x=new URL(t);x.searchParams.append("client_id",r),x.searchParams.append("redirect_uri",o),x.searchParams.append("response_type",i),y||x.searchParams.append("scope",s),d&&x.searchParams.append("nonce",d),v&&x.searchParams.append("dpop_jkt",v);let I=k.id;if(p&&(I=`${I}${w}${p}`),x.searchParams.append("state",I),k.code_challenge&&(x.searchParams.append("code_challenge",k.code_challenge),x.searchParams.append("code_challenge_method","S256")),m){(Array.isArray(m)?m:[m]).forEach((e=>x.searchParams.append("resource",e)))}for(const[e,w]of Object.entries({response_mode:u,...b,...h}))null!=w&&x.searchParams.append(e,w.toString());return new e({url:x.href,state:k})}};D._logger=new m("SigninRequest");var M=D,L=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(w);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(w))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},q=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:o,request_type:i,client_id:s,url_state:a}){if(this._logger=new m("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const u=new URL(e);if(n&&u.searchParams.append("id_token_hint",n),s&&u.searchParams.append("client_id",s),r&&(u.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new U({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${w}${a}`),u.searchParams.append("state",e)}for(const[l,c]of Object.entries({...o}))null!=c&&u.searchParams.append(l,c.toString());this.url=u.href}},Z=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(w);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(w))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},F=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],H=["sub","iss","aud","exp","iat"],B=class{constructor(e){this._settings=e,this._logger=new m("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:F;for(const n of e)H.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[r,o]of Object.entries(t))if(n[r]!==o)if(Array.isArray(n[r])||Array.isArray(o))if("replace"==this._settings.mergeClaimsStrategy.array)n[r]=o;else{const e=Array.isArray(n[r])?n[r]:[n[r]];for(const t of Array.isArray(o)?o:[o])e.includes(t)||e.push(t);n[r]=e}else"object"==typeof n[r]&&"object"==typeof o?n[r]=this.mergeClaims(n[r],o):n[r]=o;return n}},W=class{constructor(e,t){this.keys=e,this.nonce=t}},J=class{constructor(e,t){this._logger=new m("OidcClient"),this.settings=e instanceof A?e:new A(e),this.metadataService=null!=t?t:new R(this.settings),this._claimsService=new B(this.settings),this._validator=new j(this.settings,this.metadataService,this._claimsService),this._tokenClient=new P(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:o,login_hint:i,skipUserInfo:s,nonce:a,url_state:u,response_type:l=this.settings.response_type,scope:c=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:m=this.settings.display,max_age:_=this.settings.max_age,ui_locales:h=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:f=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:k,omitScopeWhenRequesting:w=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",I);const S=await M.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:c,state_data:e,url_state:u,prompt:p,display:m,max_age:_,ui_locales:h,id_token_hint:o,login_hint:i,acr_values:g,dpopJkt:k,resource:f,request:t,request_uri:n,extraQueryParams:y,extraTokenParams:b,request_type:r,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:w});await this.clearStaleState();const $=S.state;return await this.settings.stateStore.set($.id,$.toStorageString()),S}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),r=new L(k.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const o=await this.settings.stateStore[t?"remove":"get"](r.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:await z.fromStorageString(o),response:r}}async processSigninResponse(e,t,n=!0){const r=this._logger.create("processSigninResponse"),{state:o,response:i}=await this.readSigninResponseState(e,n);if(r.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(i,o,t)}catch(s){if(!(s instanceof T&&this.settings.dpop))throw s;{const e=await this.getDpopProof(this.settings.dpop.store,s.nonce);t.DPoP=e,await this._validator.validateSigninResponse(i,o,t)}}return i}async getDpopProof(e,t){let n,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(n=await f.generateDPoPKeys(),r=new W(n,t),await e.set(this.settings.client_id,r)),await f.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:r={}}){const o=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),i=new L(new URLSearchParams);return Object.assign(i,o),await this._validator.validateCredentialsResponse(i,n),i}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,extraTokenParams:i}){var s;const a=this._logger.create("useRefreshToken");let u,l;if(void 0===this.settings.refreshTokenAllowedScope)u=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");u=((null==(s=e.scope)?void 0:s.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);o={...o,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,...i})}catch(d){if(!(d instanceof T&&this.settings.dpop))throw d;o.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,...i})}const c=new L(new URLSearchParams);return Object.assign(c,l),a.debug("validating response",c),await this._validator.validateRefreshResponse(c,{...e,scope:u}),c}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:o,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),u=await this.metadataService.getEndSessionEndpoint();if(!u)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",u),n||!i||t||(n=this.settings.client_id);const l=new q({url:u,id_token_hint:t,client_id:n,post_logout_redirect_uri:i,state_data:e,extraQueryParams:s,request_type:r,url_state:o});await this.clearStaleState();const c=l.state;return c&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),l}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),r=new Z(k.readParams(e,this.settings.response_mode));if(!r.state){if(n.debug("No state in response"),r.error)throw n.warn("Response was error:",r.error),new x(r);return{state:void 0,response:r}}const o=await this.settings.stateStore[t?"remove":"get"](r.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:await U.fromStorageString(o),response:r}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:r}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,n)):t.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),U.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},V=class{constructor(e){this._userManager=e,this._logger=new m("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const r=this._userManager.settings.client_id,o=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,s=new $(this._callback,r,e,o,i);await s.load(),this._checkSessionIFrame=s,s.start(t)}else n.warn("no check session iframe found in the metadata")}catch(r){n.error("Error from getCheckSessionIframe:",r instanceof Error?r.message:r)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(n){e.error("error from querySessionStatus",n instanceof Error?n.message:n)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),n?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},K=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new m("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return m.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},G="oidc-client",Y=class{constructor(){this._abort=new v("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:n,keepOpen:r}=await new Promise(((n,r)=>{const o=o=>{var i;const s=o.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(o.origin===a&&(null==s?void 0:s.source)===G){try{const n=k.readParams(s.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),o.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(new Error("Invalid response from window"))}n(s)}};window.addEventListener("message",o,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",o,!1)));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",o,!1),this._disposeHandlers.add((()=>i.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),r(e)})))}));return t.debug("got response from window"),this._dispose(),r||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,r=window.location.origin){const o={source:G,url:t,keepOpen:n},i=new m("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(o,r);else{i.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const n=new BroadcastChannel(`oidc-client-popup-${e}`);n.postMessage(o),n.close()}}},X={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Q="_blank",ee=60,te=2,ne=class extends A{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=X,popupWindowTarget:o=Q,redirectMethod:i="assign",redirectTarget:s="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:u=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:c=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:p=!0,validateSubOnSilentRenew:m=!0,includeIdTokenInSilentRenew:_=!1,monitorSession:h=!1,monitorAnonymousSession:g=!1,checkSessionIntervalInSeconds:f=te,query_status_response_type:v="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:k=!1,includeIdTokenInSilentSignout:w=!1,accessTokenExpiringNotificationTimeInSeconds:x=ee,userStore:I}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=r,this.popupWindowTarget=o,this.redirectMethod=i,this.redirectTarget=s,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=u,this.silent_redirect_uri=c,this.silentRequestTimeoutInSeconds=d||l||10,this.automaticSilentRenew=p,this.validateSubOnSilentRenew=m,this.includeIdTokenInSilentRenew=_,this.monitorSession=h,this.monitorAnonymousSession=g,this.checkSessionIntervalInSeconds=f,this.stopCheckSessionOnError=y,this.query_status_response_type=v,this.revokeTokenTypes=b,this.revokeTokensOnSignout=k,this.includeIdTokenInSilentSignout=w,this.accessTokenExpiringNotificationTimeInSeconds=x,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new O;this.userStore=new N({store:e})}}},re=class e extends Y{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new m("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new I("IFrame timed out without a response"))}),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const n=e.target;null==(t=n.parentNode)||t.removeChild(n),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},oe=class{constructor(e){this._settings=e,this._logger=new m("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new re({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),re.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ie=class extends Y{constructor({popupWindowTarget:e=Q,popupWindowFeatures:t={},popupSignal:n}){super(),this._logger=new m("PopupWindow");const r=y.center({...X,...t});this._window=window.open(void 0,e,y.serialize(r)),n&&n.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=n.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const n=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),r(),this._disposeHandlers.delete(r))}),500),r=()=>clearInterval(n);return this._disposeHandlers.add(r),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},se=class{constructor(e){this._settings=e,this._logger=new m("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n}){return new ie({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ie.notifyOpener(e,t)}},ae=class{constructor(e){this._settings=e,this._logger=new m("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let r=window.self;"top"===t&&(r=null!=(n=window.top)?n:window.self);const o=r.location[e].bind(r.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return o(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),r.stop()}}}async callback(){}},ue=class extends S{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new m("UserManagerEvents"),this._userLoaded=new v("User loaded"),this._userUnloaded=new v("User unloaded"),this._silentRenewError=new v("Silent renew error"),this._userSignedIn=new v("User signed in"),this._userSignedOut=new v("User signed out"),this._userSessionChanged=new v("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},le=class{constructor(e){this._userManager=e,this._logger=new m("SilentRenewService"),this._isStarted=!1,this._retryTimer=new b("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof I)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},ce=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},de=class{constructor(e,t,n,r){this._logger=new m("UserManager"),this.settings=new ne(e),this._client=new J(e),this._redirectNavigator=null!=t?t:new ae(this.settings),this._popupNavigator=null!=n?n:new se(this.settings),this._iframeNavigator=null!=r?r:new oe(this.settings),this._events=new ue(this.settings),this._silentRenewService=new le(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new V(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),n=await this._loadUser();return n?(t.info("user loaded"),await this._events.load(n,e),n):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:n,...r}=e;let o;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signinStart({request_type:"si:r",dpopJkt:o,...r},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const r=this._logger.create("signinResourceOwnerCredential"),o=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug("got signin response");const i=await this._buildUser(o);return i.profile&&i.profile.sub?r.info("success, signed in subject",i.profile.sub):r.info("no subject"),i}async signinPopup(e={}){var t;const n=this._logger.create("signinPopup");let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:o,popupWindowTarget:i,popupSignal:s,...a}=e,u=this.settings.popup_redirect_uri;u||n.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:o,popupWindowTarget:i,popupSignal:s}),c=await this._signin({request_type:"si:p",redirect_uri:u,display:"popup",dpopJkt:r,...a},l);return c&&(c.profile&&c.profile.sub?n.info("success, signed in subject",c.profile.sub):n.info("no subject")),c}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t,n;const r=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:o,...i}=e;let s,a=await this._loadUser();if(null==a?void 0:a.refresh_token){r.debug("using refresh token");const e=new ce(a);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:o})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const u=this.settings.silent_redirect_uri;let l;u||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:o});return a=await this._signin({request_type:"si:s",redirect_uri:u,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:s,...i},c,l),a&&((null==(n=a.profile)?void 0:n.sub)?r.info("success, signed in subject",a.profile.sub):r.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new K({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:n,...r}=e,o=this.settings.silent_redirect_uri;o||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),s=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:o,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...r},s);try{const e={},n=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),n.session_state&&n.profile.sub?(t.info("success for subject",n.profile.sub),{session_state:n.session_state,sub:n.profile.sub}):(t.info("success, user not authenticated"),null)}catch(u){if(this.settings.monitorAnonymousSession&&u instanceof x)switch(u.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:u.session_state}}throw u}}async _signin(e,t,n){const r=await this._signinStart(e,t);return await this._signinEnd(r.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const r=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(r){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),r}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),r=await this._client.processSigninResponse(e,{});n.debug("got signin response");return await this._buildUser(r,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),r=new K(e);if(t){if(t!==r.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",r.profile.sub),new x({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(r),n.debug("user stored"),await this._events.load(r),r}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...r}=e,o=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},o),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o,...i}=e,s=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o});await this._signout({request_type:"so:p",post_logout_redirect_uri:s,state:null==s?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const r=this._logger.create("_signoutStart");try{const o=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(o);const i=e.id_token_hint||o&&o.id_token;i&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),r.debug("user removed, creating signout request");const s=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:s.url,state:null==(n=s.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(o){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),o}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...o}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,s=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:s,id_token_hint:i,...o},a),n.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const n=this._logger.create("_revokeInternal");if(!e)return;const r=t.filter((t=>"string"==typeof e[t]));if(r.length){for(const t of r)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),await this._events.load(e)}else n.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),K.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,n,r){var o,i;const s=await(null==(i=null==(o=this.settings.dpop)?void 0:o.store)?void 0:i.get(this.settings.client_id));if(s)return await f.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:n,keyPair:s.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const n=await f.generateDPoPKeys();t=new W(n),await e.store.set(this.settings.client_id,t)}return await f.generateDPoPJkt(t.keys)}},pe=n.createContext(void 0);pe.displayName="AuthContext";var me={isLoading:!0,isAuthenticated:!1},_e=(e,t)=>{switch(t.type){case"INITIALISED":case"USER_LOADED":return{...e,user:t.user,isLoading:!1,isAuthenticated:!!t.user&&!t.user.expired,error:void 0};case"USER_SIGNED_OUT":case"USER_UNLOADED":return{...e,user:void 0,isAuthenticated:!1};case"NAVIGATOR_INIT":return{...e,isLoading:!0,activeNavigator:t.method};case"NAVIGATOR_CLOSE":return{...e,isLoading:!1,activeNavigator:void 0};case"ERROR":{const n=t.error;return n.toString=()=>`${n.name}: ${n.message}`,{...e,isLoading:!1,error:n}}default:{const n=new TypeError(`unknown type ${t.type}`),r={name:n.name,message:n.message,innerError:n,stack:n.stack,source:"unknown",toString:()=>`${r.name}: ${r.message}`};return{...e,isLoading:!1,error:r}}}},he=ye("signinCallback","Sign-in failed"),ge=ye("signoutCallback","Sign-out failed"),fe=ye("renewSilent","Renew silent failed");function ve(e,t){return{name:be(e,"name",(()=>"Error")),message:be(e,"message",(()=>t)),stack:be(e,"stack",(()=>(new Error).stack)),innerError:e}}function ye(e,t){return n=>({...ve(n,t),source:e})}function be(e,t,n){if(e&&"object"==typeof e){const n=e[t];if("string"==typeof n)return n}return n()}var ke,we=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],xe=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],Ie=e=>()=>{throw new Error(`UserManager#${e} was called from an unsupported context. If this is a server-rendered page, defer this call with useEffect() or pass a custom UserManager implementation.`)},Se="undefined"==typeof window?null:de,$e=e=>{const{children:t,onSigninCallback:r,skipSigninCallback:o,matchSignoutCallback:i,onSignoutCallback:s,onRemoveUser:a,userManager:u=null,...l}=e,[c]=n.useState((()=>null!=u?u:Se?new Se(l):{settings:l})),[d,p]=n.useReducer(_e,me),m=n.useMemo((()=>Object.assign({settings:c.settings,events:c.events},Object.fromEntries(we.map((e=>{var t,n;return[e,null!=(n=null==(t=c[e])?void 0:t.bind(c))?n:Ie(e)]}))),Object.fromEntries(xe.map((e=>[e,c[e]?async t=>{p({type:"NAVIGATOR_INIT",method:e});try{return await c[e](t)}catch(n){return p({type:"ERROR",error:{...ve(n,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{p({type:"NAVIGATOR_CLOSE"})}}:Ie(e)]))))),[c]),_=n.useRef(!1);n.useEffect((()=>{c&&!_.current&&(_.current=!0,(async()=>{try{let e=null;((e=window.location)=>{let t=new URLSearchParams(e.search);return!!((t.get("code")||t.get("error"))&&t.get("state")||(t=new URLSearchParams(e.hash.replace("#","?")),(t.get("code")||t.get("error"))&&t.get("state")))})()&&!o&&(e=await c.signinCallback(),r&&await r(e)),e=e||await c.getUser(),p({type:"INITIALISED",user:e})}catch(e){p({type:"ERROR",error:he(e)})}try{if(i&&i(c.settings)){const e=await c.signoutCallback();s&&await s(e)}}catch(e){p({type:"ERROR",error:ge(e)})}})())}),[c,o,r,s,i]),n.useEffect((()=>{if(!c)return;const e=e=>{p({type:"USER_LOADED",user:e})};c.events.addUserLoaded(e);const t=()=>{p({type:"USER_UNLOADED"})};c.events.addUserUnloaded(t);const n=()=>{p({type:"USER_SIGNED_OUT"})};c.events.addUserSignedOut(n);const r=e=>{p({type:"ERROR",error:fe(e)})};return c.events.addSilentRenewError(r),()=>{c.events.removeUserLoaded(e),c.events.removeUserUnloaded(t),c.events.removeUserSignedOut(n),c.events.removeSilentRenewError(r)}}),[c]);const h=n.useCallback((async()=>{await c.removeUser(),a&&await a()}),[c,a]),g=n.useMemo((()=>({...d,...m,removeUser:h})),[d,m,h]);return n.createElement(pe.Provider,{value:g},t)},Oe=()=>{const e=n.useContext(pe);return e||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component."),e},Te="vercel.ai.error",Ee=Symbol.for(Te),Re=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[ke]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Te)}static hasMarker(e,t){const n=Symbol.for(t);return null!=e&&"object"==typeof e&&n in e&&"boolean"==typeof e[n]&&!0===e[n]}};ke=Ee;var Ne,Ae=Re,Ce="AI_APICallError",Pe=`vercel.ai.error.${Ce}`,je=Symbol.for(Pe),Ue=class extends Ae{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:i,cause:s,isRetryable:a=null!=r&&(408===r||409===r||429===r||r>=500),data:u}){super({name:Ce,message:e,cause:s}),this[Ne]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=i,this.isRetryable=a,this.data=u}static isInstance(e){return Ae.hasMarker(e,Pe)}};Ne=je;var ze,De="AI_EmptyResponseBodyError",Me=`vercel.ai.error.${De}`,Le=Symbol.for(Me),qe=class extends Ae{constructor({message:e="Empty response body"}={}){super({name:De,message:e}),this[ze]=!0}static isInstance(e){return Ae.hasMarker(e,Me)}};function Ze(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.message:JSON.stringify(e)}ze=Le;var Fe,He="AI_InvalidArgumentError",Be=`vercel.ai.error.${He}`,We=Symbol.for(Be),Je=class extends Ae{constructor({message:e,cause:t,argument:n}){super({name:He,message:e,cause:t}),this[Fe]=!0,this.argument=n}static isInstance(e){return Ae.hasMarker(e,Be)}};Fe=We;var Ve,Ke="AI_InvalidPromptError",Ge=`vercel.ai.error.${Ke}`,Ye=Symbol.for(Ge),Xe=class extends Ae{constructor({prompt:e,message:t,cause:n}){super({name:Ke,message:`Invalid prompt: ${t}`,cause:n}),this[Ve]=!0,this.prompt=e}static isInstance(e){return Ae.hasMarker(e,Ge)}};Ve=Ye;var Qe,et="AI_InvalidResponseDataError",tt=`vercel.ai.error.${et}`,nt=Symbol.for(tt),rt=class extends Ae{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:et,message:t}),this[Qe]=!0,this.data=e}static isInstance(e){return Ae.hasMarker(e,tt)}};Qe=nt;var ot,it="AI_JSONParseError",st=`vercel.ai.error.${it}`,at=Symbol.for(st),ut=class extends Ae{constructor({text:e,cause:t}){super({name:it,message:`JSON parsing failed: Text: ${e}.\nError message: ${Ze(t)}`,cause:t}),this[ot]=!0,this.text=e}static isInstance(e){return Ae.hasMarker(e,st)}};ot=at;var lt,ct="AI_LoadAPIKeyError",dt=`vercel.ai.error.${ct}`,pt=Symbol.for(dt),mt=class extends Ae{constructor({message:e}){super({name:ct,message:e}),this[lt]=!0}static isInstance(e){return Ae.hasMarker(e,dt)}};lt=pt;var _t,ht="AI_NoSuchModelError",gt=`vercel.ai.error.${ht}`,ft=Symbol.for(gt),vt=class extends Ae{constructor({errorName:e=ht,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[_t]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return Ae.hasMarker(e,gt)}};_t=ft;var yt,bt="AI_TooManyEmbeddingValuesForCallError",kt=`vercel.ai.error.${bt}`,wt=Symbol.for(kt),xt=class extends Ae{constructor(e){super({name:bt,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[yt]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Ae.hasMarker(e,kt)}};yt=wt;var It,St="AI_TypeValidationError",$t=`vercel.ai.error.${St}`,Ot=Symbol.for($t);It=Ot;var Tt,Et=class e extends Ae{constructor({value:e,cause:t}){super({name:St,message:`Type validation failed: Value: ${JSON.stringify(e)}.\nError message: ${Ze(t)}`,cause:t}),this[It]=!0,this.value=e}static isInstance(e){return Ae.hasMarker(e,$t)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}},Rt="AI_UnsupportedFunctionalityError",Nt=`vercel.ai.error.${Rt}`,At=Symbol.for(Nt),Ct=class extends Ae{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Rt,message:t}),this[Tt]=!0,this.functionality=e}static isInstance(e){return Ae.hasMarker(e,Nt)}};Tt=At;let Pt=class 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 jt(e){}function Ut(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=jt,onError:n=jt,onRetry:r=jt,onComment:o}=e;let i,s="",a=!0,u="",l="";function c(e){if(""===e)return u.length>0&&t({id:i,event:l||void 0,data:u.endsWith("\n")?u.slice(0,-1):u}),i=void 0,u="",void(l="");if(e.startsWith(":"))return void(o&&o(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1===n)d(e,"",e);else{const t=e.slice(0,n),r=" "===e[n+1]?2:1;d(t,e.slice(n+r),e)}}function d(e,t,o){switch(e){case"event":l=t;break;case"data":u=`${u}${t}\n`;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new Pt(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new Pt(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:o}))}}return{feed:function(e){const t=a?e.replace(/^\xEF\xBB\xBF/,""):e,[n,r]=function(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),i=e.indexOf("\n",r);let s=-1;if(-1!==o&&-1!==i?s=Math.min(o,i):-1!==o?s=o===e.length-1?-1:o:-1!==i&&(s=i),-1===s){n=e.slice(r);break}{const n=e.slice(r,s);t.push(n),r=s+1,"\r"===e[r-1]&&"\n"===e[r]&&r++}}return[t,n]}(`${s}${t}`);for(const o of n)c(o);s=r,a=!1},reset:function(e={}){s&&e.consume&&c(s),a=!0,i=void 0,u="",l="",s=""}}}let zt=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(o){r=Ut({onEvent:e=>{o.enqueue(e)},onError(t){"terminate"===e?o.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const Dt=Object.freeze({status:"aborted"});function Mt(e,t,n){function r(n,r){var o;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(o=n._zod).traits??(o.traits=new Set),n._zod.traits.add(e),t(n,r);for(const e in s.prototype)e in n||Object.defineProperty(n,e,{value:s.prototype[e].bind(n)});n._zod.constr=s,n._zod.def=r}const o=(null==n?void 0:n.Parent)??Object;class i extends o{}function s(e){var t;const o=(null==n?void 0:n.Parent)?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const n of o._zod.deferred)n();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>{var r,o;return!!((null==n?void 0:n.Parent)&&t instanceof n.Parent)||(null==(o=null==(r=null==t?void 0:t._zod)?void 0:r.traits)?void 0:o.has(e))}}),Object.defineProperty(s,"name",{value:e}),s}const Lt=Symbol("zod_brand");class qt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Zt={};function Ft(e){return e&&Object.assign(Zt,e),Zt}function Ht(e){const t=Object.values(e).filter((e=>"number"==typeof e));return Object.entries(e).filter((([e,n])=>-1===t.indexOf(+e))).map((([e,t])=>t))}function Bt(e,t="|"){return e.map((e=>_n(e))).join(t)}function Wt(e,t){return"bigint"==typeof t?t.toString():t}function Jt(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Vt(e){return null==e}function Kt(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Gt(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(0===o&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);(null==e?void 0:e[1])&&(o=Number.parseInt(e[1]))}const i=n>o?n:o;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}const Yt=Symbol("evaluating");function Xt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Yt)return void 0===r&&(r=Yt,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Qt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function en(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function tn(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function nn(e){return JSON.stringify(e)}const rn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function on(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const sn=Jt((()=>{var e;if("undefined"!=typeof navigator&&(null==(e=null==navigator?void 0:navigator.userAgent)?void 0:e.includes("Cloudflare")))return!1;try{return new Function(""),!0}catch(t){return!1}}));function an(e){if(!1===on(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==on(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function un(e){return an(e)?{...e}:e}const ln=new Set(["string","number","symbol"]),cn=new Set(["string","number","bigint","boolean","symbol","undefined"]);function dn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!(null==n?void 0:n.parent)||(r._zod.parent=e),r}function mn(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==(null==t?void 0:t.message)){if(void 0!==(null==t?void 0:t.error))throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function _n(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function hn(e){return Object.keys(e).filter((t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout))}const gn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},fn={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vn(e,t){const n=e._zod.def;return pn(e,tn(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return en(this,"shape",e),e},checks:[]}))}function yn(e,t){const n=e._zod.def,r=tn(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return en(this,"shape",r),r},checks:[]});return pn(e,r)}function bn(e,t){if(!an(t))throw new Error("Invalid input to extend: expected a plain object");const n=tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return en(this,"shape",n),n},checks:[]});return pn(e,n)}function kn(e,t){const n=tn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return en(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return pn(e,n)}function wn(e,t,n){const r=tn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return en(this,"shape",o),o},checks:[]});return pn(t,r)}function xn(e,t,n){const r=tn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return en(this,"shape",o),o},checks:[]});return pn(t,r)}function In(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(!0!==(null==(n=e.issues[r])?void 0:n.continue))return!0;return!1}function Sn(e,t){return t.map((t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t}))}function $n(e){return"string"==typeof e?e:null==e?void 0:e.message}function On(e,t,n){var r,o,i,s,a,u;const l={...e,path:e.path??[]};if(!e.message){const c=$n(null==(i=null==(o=null==(r=e.inst)?void 0:r._zod.def)?void 0:o.error)?void 0:i.call(o,e))??$n(null==(s=null==t?void 0:t.error)?void 0:s.call(t,e))??$n(null==(a=n.customError)?void 0:a.call(n,e))??$n(null==(u=n.localeError)?void 0:u.call(n,e))??"Invalid input";l.message=c}return delete l.inst,delete l.continue,(null==t?void 0:t.reportInput)||delete l.input,l}function Tn(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function En(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Rn(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Nn=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:fn,Class:class{constructor(...e){}},NUMBER_FORMAT_RANGES:gn,aborted:In,allowsEval:sn,assert:function(e){},assertEqual:function(e){return e},assertIs:function(e){},assertNever:function(e){throw new Error},assertNotEqual:function(e){return e},assignProp:en,cached:Jt,captureStackTrace:rn,cleanEnum:function(e){return Object.entries(e).filter((([e,t])=>Number.isNaN(Number.parseInt(e,10)))).map((e=>e[1]))},cleanRegex:Kt,clone:pn,cloneDef:function(e){return tn(e._zod.def)},createTransparentProxy:function(e){let t;return new Proxy({},{get:(n,r,o)=>(t??(t=e()),Reflect.get(t,r,o)),set:(n,r,o,i)=>(t??(t=e()),Reflect.set(t,r,o,i)),has:(n,r)=>(t??(t=e()),Reflect.has(t,r)),deleteProperty:(n,r)=>(t??(t=e()),Reflect.deleteProperty(t,r)),ownKeys:n=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(n,r)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)),defineProperty:(n,r,o)=>(t??(t=e()),Reflect.defineProperty(t,r,o))})},defineLazy:Xt,esc:nn,escapeRegex:dn,extend:bn,finalizeIssue:On,floatSafeRemainder:Gt,getElementAtPath:function(e,t){return t?t.reduce(((e,t)=>null==e?void 0:e[t]),e):e},getEnumValues:Ht,getLengthableOrigin:En,getParsedType:e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},getSizableOrigin:Tn,isObject:on,isPlainObject:an,issue:Rn,joinValues:Bt,jsonStringifyReplacer:Wt,merge:kn,mergeDefs:tn,normalizeParams:mn,nullish:Vt,numKeys:function(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t},objectClone:Qt,omit:yn,optionalKeys:hn,partial:wn,pick:vn,prefixIssues:Sn,primitiveTypes:cn,promiseAllObject:function(e){const t=Object.keys(e),n=t.map((t=>e[t]));return Promise.all(n).then((e=>{const n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n}))},propertyKeyTypes:ln,randomString:function(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let r=0;r<e;r++)n+=t[Math.floor(26*Math.random())];return n},required:xn,shallowClone:un,stringifyPrimitive:_n,unwrapMessage:$n},Symbol.toStringTag,{value:"Module"})),An=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Wt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cn=Mt("$ZodError",An),Pn=Mt("$ZodError",An,{Parent:Error});function jn(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Un(e,t){const n=t||function(e){return e.message},r={_errors:[]},o=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map((e=>o({issues:e})));else if("invalid_key"===t.code)o({issues:t.issues});else if("invalid_element"===t.code)o({issues:t.issues});else if(0===t.path.length)r._errors.push(n(t));else{let e=r,o=0;for(;o<t.path.length;){const r=t.path[o];o===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],o++}}};return o(e),r}function zn(e,t){const n=t||function(e){return e.message},r={errors:[]},o=(e,t=[])=>{var i,s;for(const a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map((e=>o({issues:e},a.path)));else if("invalid_key"===a.code)o({issues:a.issues},a.path);else if("invalid_element"===a.code)o({issues:a.issues},a.path);else{const e=[...t,...a.path];if(0===e.length){r.errors.push(n(a));continue}let o=r,u=0;for(;u<e.length;){const t=e[u],r=u===e.length-1;"string"==typeof t?(o.properties??(o.properties={}),(i=o.properties)[t]??(i[t]={errors:[]}),o=o.properties[t]):(o.items??(o.items=[]),(s=o.items)[t]??(s[t]={errors:[]}),o=o.items[t]),r&&o.errors.push(n(a)),u++}}};return o(e),r}function Dn(e){const t=[],n=e.map((e=>"object"==typeof e?e.key:e));for(const r of n)"number"==typeof r?t.push(`[${r}]`):"symbol"==typeof r?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Mn(e){var t;const n=[],r=[...e.issues].sort(((e,t)=>(e.path??[]).length-(t.path??[]).length));for(const o of r)n.push(`✖ ${o.message}`),(null==(t=o.path)?void 0:t.length)&&n.push(` → at ${Dn(o.path)}`);return n.join("\n")}const Ln=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new qt;if(s.issues.length){const t=new((null==o?void 0:o.Err)??e)(s.issues.map((e=>On(e,i,Ft()))));throw rn(t,null==o?void 0:o.callee),t}return s.value},qn=Ln(Pn),Zn=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new((null==o?void 0:o.Err)??e)(s.issues.map((e=>On(e,i,Ft()))));throw rn(t,null==o?void 0:o.callee),t}return s.value},Fn=Zn(Pn),Hn=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new qt;return i.issues.length?{success:!1,error:new(e??Cn)(i.issues.map((e=>On(e,o,Ft()))))}:{success:!0,data:i.value}},Bn=Hn(Pn),Wn=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map((e=>On(e,o,Ft()))))}:{success:!0,data:i.value}},Jn=Wn(Pn),Vn=/^[cC][^\s-]{8,}$/,Kn=/^[0-9a-z]+$/,Gn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yn=/^[0-9a-vA-V]{20}$/,Xn=/^[A-Za-z0-9]{27}$/,Qn=/^[a-zA-Z0-9_-]{21}$/,er=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,nr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,rr=nr(4),or=nr(6),ir=nr(7),sr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function ar(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}const ur=/^(?:(?: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])$/,lr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,cr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,dr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mr=/^[A-Za-z0-9_-]*$/,_r=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,hr=/^\+(?:[0-9]){6,14}[0-9]$/,gr="(?:(?:\\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])))",fr=new RegExp(`^${gr}$`);function vr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yr(e){return new RegExp(`^${vr(e)}$`)}function br(e){const t=vr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${gr}T(?:${r})$`)}const kr=e=>{const t=e?`[\\s\\S]{${(null==e?void 0:e.minimum)??0},${(null==e?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},wr=/^\d+n?$/,xr=/^\d+$/,Ir=/^-?\d+(?:\.\d+)?/i,Sr=/true|false/i,$r=/null/i,Or=/undefined/i,Tr=/^[^A-Z]*$/,Er=/^[^a-z]*$/,Rr=Object.freeze(Object.defineProperty({__proto__:null,base64:pr,base64url:mr,bigint:wr,boolean:Sr,browserEmail:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,cidrv4:cr,cidrv6:dr,cuid:Vn,cuid2:Kn,date:fr,datetime:br,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,duration:er,e164:hr,email:sr,emoji:ar,extendedDuration:/^[-+]?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)?)??$/,guid:tr,hostname:_r,html5Email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,idnEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,integer:xr,ipv4:ur,ipv6:lr,ksuid:Xn,lowercase:Tr,nanoid:Qn,null:$r,number:Ir,rfc5322Email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,string:kr,time:yr,ulid:Gn,undefined:Or,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,uppercase:Er,uuid:nr,uuid4:rr,uuid6:or,uuid7:ir,xid:Yn},Symbol.toStringTag,{value:"Module"})),Nr=Mt("$ZodCheck",((e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])})),Ar={number:"number",bigint:"bigint",object:"date"},Cr=Mt("$ZodCheckLessThan",((e,t)=>{Nr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),Pr=Mt("$ZodCheckGreaterThan",((e,t)=>{Nr.init(e,t);const n=Ar[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),jr=Mt("$ZodCheckMultipleOf",((e,t)=>{Nr.init(e,t),e._zod.onattach.push((e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)})),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===Gt(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}})),Ur=Mt("$ZodCheckNumberFormat",((e,t)=>{var n;Nr.init(e,t),t.format=t.format||"float64";const r=null==(n=t.format)?void 0:n.includes("int"),o=r?"int":"number",[i,s]=gn[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=s,r&&(n.pattern=xr)})),e._zod.check=n=>{const a=n.value;if(r){if(!Number.isInteger(a))return void n.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?n.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):n.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}))}a<i&&n.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&n.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}})),zr=Mt("$ZodCheckBigIntFormat",((e,t)=>{Nr.init(e,t);const[n,r]=fn[t.format];e._zod.onattach.push((e=>{const o=e._zod.bag;o.format=t.format,o.minimum=n,o.maximum=r})),e._zod.check=o=>{const i=o.value;i<n&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),i>r&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:r,inst:e})}})),Dr=Mt("$ZodCheckMaxSize",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;r.size<=t.maximum||n.issues.push({origin:Tn(r),code:"too_big",maximum:t.maximum,input:r,inst:e,continue:!t.abort})}})),Mr=Mt("$ZodCheckMinSize",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;r.size>=t.minimum||n.issues.push({origin:Tn(r),code:"too_small",minimum:t.minimum,input:r,inst:e,continue:!t.abort})}})),Lr=Mt("$ZodCheckSizeEquals",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size})),e._zod.check=n=>{const r=n.value,o=r.size;if(o===t.size)return;const i=o>t.size;n.issues.push({origin:Tn(r),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),qr=Mt("$ZodCheckMaxLength",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=En(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),Zr=Mt("$ZodCheckMinLength",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=En(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),Fr=Mt("$ZodCheckLengthEquals",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Vt(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length})),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=En(r),s=o>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),Hr=Mt("$ZodCheckStringFormat",((e,t)=>{var n,r;Nr.init(e,t),e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))})),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})})),Br=Mt("$ZodCheckRegex",((e,t)=>{Hr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}})),Wr=Mt("$ZodCheckLowerCase",((e,t)=>{t.pattern??(t.pattern=Tr),Hr.init(e,t)})),Jr=Mt("$ZodCheckUpperCase",((e,t)=>{t.pattern??(t.pattern=Er),Hr.init(e,t)})),Vr=Mt("$ZodCheckIncludes",((e,t)=>{Nr.init(e,t);const n=dn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)})),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}})),Kr=Mt("$ZodCheckStartsWith",((e,t)=>{Nr.init(e,t);const n=new RegExp(`^${dn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}})),Gr=Mt("$ZodCheckEndsWith",((e,t)=>{Nr.init(e,t);const n=new RegExp(`.*${dn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}));function Yr(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues))}const Xr=Mt("$ZodCheckProperty",((e,t)=>{Nr.init(e,t),e._zod.check=e=>{const n=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then((n=>Yr(n,e,t.property)));Yr(n,e,t.property)}})),Qr=Mt("$ZodCheckMimeType",((e,t)=>{Nr.init(e,t);const n=new Set(t.mime);e._zod.onattach.push((e=>{e._zod.bag.mime=t.mime})),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}})),eo=Mt("$ZodCheckOverwrite",((e,t)=>{Nr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class to{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter((e=>e)),n=Math.min(...t.map((e=>e.length-e.trimStart().length))),r=t.map((e=>e.slice(n))).map((e=>" ".repeat(2*this.indent)+e));for(const o of r)this.content.push(o)}compile(){return new Function(...null==this?void 0:this.args,[...((null==this?void 0:this.content)??[""]).map((e=>` ${e}`))].join("\n"))}}const no={major:4,minor:0,patch:17},ro=Mt("$ZodType",((e,t)=>{var n,r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=no;const o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(const i of o)for(const t of i._zod.onattach)t(e);if(0===o.length)(r=e._zod).deferred??(r.deferred=[]),null==(n=e._zod.deferred)||n.push((()=>{e._zod.run=e._zod.parse}));else{const t=(e,t,n)=>{let r,o=In(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&!1===(null==n?void 0:n.async))throw new qt;if(r||s instanceof Promise)r=(r??Promise.resolve()).then((async()=>{await s;e.issues.length!==t&&(o||(o=In(e,t)))}));else{if(e.issues.length===t)continue;o||(o=In(e,t))}}return r?r.then((()=>e)):e};e._zod.run=(n,r)=>{const i=e._zod.parse(n,r);if(i instanceof Promise){if(!1===r.async)throw new qt;return i.then((e=>t(e,o,r)))}return t(i,o,r)}}e["~standard"]={validate:t=>{var n;try{const r=Bn(e,t);return r.success?{value:r.data}:{issues:null==(n=r.error)?void 0:n.issues}}catch(r){return Jn(e,t).then((e=>{var t;return e.success?{value:e.data}:{issues:null==(t=e.error)?void 0:t.issues}}))}},vendor:"zod",version:1}})),oo=Mt("$ZodString",((e,t)=>{var n;ro.init(e,t),e._zod.pattern=[...(null==(n=null==e?void 0:e._zod.bag)?void 0:n.patterns)??[]].pop()??kr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}})),io=Mt("$ZodStringFormat",((e,t)=>{Hr.init(e,t),oo.init(e,t)})),so=Mt("$ZodGUID",((e,t)=>{t.pattern??(t.pattern=tr),io.init(e,t)})),ao=Mt("$ZodUUID",((e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nr(e))}else t.pattern??(t.pattern=nr());io.init(e,t)})),uo=Mt("$ZodEmail",((e,t)=>{t.pattern??(t.pattern=sr),io.init(e,t)})),lo=Mt("$ZodURL",((e,t)=>{io.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_r.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}})),co=Mt("$ZodEmoji",((e,t)=>{t.pattern??(t.pattern=ar()),io.init(e,t)})),po=Mt("$ZodNanoID",((e,t)=>{t.pattern??(t.pattern=Qn),io.init(e,t)})),mo=Mt("$ZodCUID",((e,t)=>{t.pattern??(t.pattern=Vn),io.init(e,t)})),_o=Mt("$ZodCUID2",((e,t)=>{t.pattern??(t.pattern=Kn),io.init(e,t)})),ho=Mt("$ZodULID",((e,t)=>{t.pattern??(t.pattern=Gn),io.init(e,t)})),go=Mt("$ZodXID",((e,t)=>{t.pattern??(t.pattern=Yn),io.init(e,t)})),fo=Mt("$ZodKSUID",((e,t)=>{t.pattern??(t.pattern=Xn),io.init(e,t)})),vo=Mt("$ZodISODateTime",((e,t)=>{t.pattern??(t.pattern=br(t)),io.init(e,t)})),yo=Mt("$ZodISODate",((e,t)=>{t.pattern??(t.pattern=fr),io.init(e,t)})),bo=Mt("$ZodISOTime",((e,t)=>{t.pattern??(t.pattern=yr(t)),io.init(e,t)})),ko=Mt("$ZodISODuration",((e,t)=>{t.pattern??(t.pattern=er),io.init(e,t)})),wo=Mt("$ZodIPv4",((e,t)=>{t.pattern??(t.pattern=ur),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv4"}))})),xo=Mt("$ZodIPv6",((e,t)=>{t.pattern??(t.pattern=lr),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv6"})),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}})),Io=Mt("$ZodCIDRv4",((e,t)=>{t.pattern??(t.pattern=cr),io.init(e,t)})),So=Mt("$ZodCIDRv6",((e,t)=>{t.pattern??(t.pattern=dr),io.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const e=Number(o);if(`${e}`!==o)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}}));function $o(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Oo=Mt("$ZodBase64",((e,t)=>{t.pattern??(t.pattern=pr),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64"})),e._zod.check=n=>{$o(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}));function To(e){if(!mr.test(e))return!1;const t=e.replace(/[-_]/g,(e=>"-"===e?"+":"/"));return $o(t.padEnd(4*Math.ceil(t.length/4),"="))}const Eo=Mt("$ZodBase64URL",((e,t)=>{t.pattern??(t.pattern=mr),io.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64url"})),e._zod.check=n=>{To(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}})),Ro=Mt("$ZodE164",((e,t)=>{t.pattern??(t.pattern=hr),io.init(e,t)}));function No(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return(!("typ"in o)||"JWT"===(null==o?void 0:o.typ))&&(!!o.alg&&(!t||"alg"in o&&o.alg===t))}catch{return!1}}const Ao=Mt("$ZodJWT",((e,t)=>{io.init(e,t),e._zod.check=n=>{No(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}})),Co=Mt("$ZodCustomStringFormat",((e,t)=>{io.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}})),Po=Mt("$ZodNumber",((e,t)=>{ro.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ir,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}})),jo=Mt("$ZodNumber",((e,t)=>{Ur.init(e,t),Po.init(e,t)})),Uo=Mt("$ZodBoolean",((e,t)=>{ro.init(e,t),e._zod.pattern=Sr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const o=n.value;return"boolean"==typeof o||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}})),zo=Mt("$ZodBigInt",((e,t)=>{ro.init(e,t),e._zod.pattern=wr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(o){}return"bigint"==typeof n.value||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}})),Do=Mt("$ZodBigInt",((e,t)=>{zr.init(e,t),zo.init(e,t)})),Mo=Mt("$ZodSymbol",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return"symbol"==typeof r||t.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),t}})),Lo=Mt("$ZodUndefined",((e,t)=>{ro.init(e,t),e._zod.pattern=Or,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),t}})),qo=Mt("$ZodNull",((e,t)=>{ro.init(e,t),e._zod.pattern=$r,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}})),Zo=Mt("$ZodAny",((e,t)=>{ro.init(e,t),e._zod.parse=e=>e})),Fo=Mt("$ZodUnknown",((e,t)=>{ro.init(e,t),e._zod.parse=e=>e})),Ho=Mt("$ZodNever",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)})),Bo=Mt("$ZodVoid",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),t}})),Wo=Mt("$ZodDate",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}const o=n.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),n}}));function Jo(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues)),t.value[n]=e.value}const Vo=Mt("$ZodArray",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const s=o[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then((t=>Jo(t,n,e)))):Jo(a,n,e)}return i.length?Promise.all(i).then((()=>n)):n}}));function Ko(e,t,n,r){e.issues.length&&t.issues.push(...Sn(n,e.issues)),void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Go=Mt("$ZodObject",((e,t)=>{ro.init(e,t);const n=Jt((()=>{const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=hn(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}));Xt(e._zod,"propValues",(()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n}));let r;const o=on,i=!Zt.jitless,s=i&&sn.value,a=t.catchall;let u;e._zod.parse=(l,c)=>{u??(u=n.value);const d=l.value;if(!o(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;const p=[];if(i&&s&&!1===(null==c?void 0:c.async)&&!0!==c.jitless)r||(r=(e=>{const t=new to(["shape","payload","ctx"]),r=n.value,o=e=>{const t=nn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let s=0;for(const n of r.keys)i[n]="key_"+s++;t.write("const newResult = {}");for(const n of r.keys){const e=i[n],r=nn(n);t.write(`const ${e} = ${o(n)};`),t.write(`\n if (${e}.issues.length) {\n payload.issues = payload.issues.concat(${e}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${r}, ...iss.path] : [${r}]\n })));\n }\n \n if (${e}.value === undefined) {\n if (${r} in input) {\n newResult[${r}] = undefined;\n }\n } else {\n newResult[${r}] = ${e}.value;\n }\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),l=r(l,c);else{l.value={};const e=u.shape;for(const t of u.keys){const n=e[t]._zod.run({value:d[t],issues:[]},c);n instanceof Promise?p.push(n.then((e=>Ko(e,l,t,d)))):Ko(n,l,t,d)}}if(!a)return p.length?Promise.all(p).then((()=>l)):l;const m=[],_=u.keySet,h=a._zod,g=h.def.type;for(const e of Object.keys(d)){if(_.has(e))continue;if("never"===g){m.push(e);continue}const t=h.run({value:d[e],issues:[]},c);t instanceof Promise?p.push(t.then((t=>Ko(t,l,e,d)))):Ko(t,l,e,d)}return m.length&&l.issues.push({code:"unrecognized_keys",keys:m,input:d,inst:e}),p.length?Promise.all(p).then((()=>l)):l}}));function Yo(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter((e=>!In(e)));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((e=>e.issues.map((e=>On(e,r,Ft())))))}),t)}const Xo=Mt("$ZodUnion",((e,t)=>{ro.init(e,t),Xt(e._zod,"optin",(()=>t.options.some((e=>"optional"===e._zod.optin))?"optional":void 0)),Xt(e._zod,"optout",(()=>t.options.some((e=>"optional"===e._zod.optout))?"optional":void 0)),Xt(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values)))return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))})),Xt(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>Kt(e.source))).join("|")})$`)}}));const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then((t=>Yo(t,o,e,i))):Yo(a,o,e,i)}})),Qo=Mt("$ZodDiscriminatedUnion",((e,t)=>{Xo.init(e,t);const n=e._zod.parse;Xt(e._zod,"propValues",(()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e}));const r=Jt((()=>{var e;const n=t.options,r=new Map;for(const o of n){const n=null==(e=o._zod.propValues)?void 0:e[t.discriminator];if(!n||0===n.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const e of n){if(r.has(e))throw new Error(`Duplicate discriminator value "${String(e)}"`);r.set(e,o)}}return r}));e._zod.parse=(o,i)=>{const s=o.value;if(!on(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const a=r.value.get(null==s?void 0:s[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),o)}})),ei=Mt("$ZodIntersection",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then((([t,n])=>ni(e,t,n))):ni(e,o,i)}}));function ti(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(an(e)&&an(t)){const n=Object.keys(t),r=Object.keys(e).filter((e=>-1!==n.indexOf(e))),o={...e,...t};for(const i of r){const n=ti(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=ti(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ni(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),In(e))return e;const r=ti(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const ri=Mt("$ZodTuple",((e,t)=>{ro.init(e,t);const n=t.items,r=n.length-[...n].reverse().findIndex((e=>"optional"!==e._zod.optin));e._zod.parse=(o,i)=>{const s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];const a=[];if(!t.rest){const t=s.length>n.length,i=s.length<r-1;if(t||i)return o.issues.push({...t?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},input:s,inst:e,origin:"array"}),o}let u=-1;for(const e of n){if(u++,u>=s.length&&u>=r)continue;const t=e._zod.run({value:s[u],issues:[]},i);t instanceof Promise?a.push(t.then((e=>oi(e,o,u)))):oi(t,o,u)}if(t.rest){const e=s.slice(n.length);for(const n of e){u++;const e=t.rest._zod.run({value:n,issues:[]},i);e instanceof Promise?a.push(e.then((e=>oi(e,o,u)))):oi(e,o,u)}}return a.length?Promise.all(a).then((()=>o)):o}}));function oi(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues)),t.value[n]=e.value}const ii=Mt("$ZodRecord",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!an(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;n.value={};for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const s=t.valueType._zod.run({value:o[e],issues:[]},r);s instanceof Promise?i.push(s.then((t=>{t.issues.length&&n.issues.push(...Sn(e,t.issues)),n.value[e]=t.value}))):(s.issues.length&&n.issues.push(...Sn(e,s.issues)),n.value[e]=s.value)}let a;for(const e in o)s.has(e)||(a=a??[],a.push(e));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.value={};for(const s of Reflect.ownKeys(o)){if("__proto__"===s)continue;const a=t.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map((e=>On(e,r,Ft()))),input:s,path:[s],inst:e}),n.value[a.value]=a.value;continue}const u=t.valueType._zod.run({value:o[s],issues:[]},r);u instanceof Promise?i.push(u.then((e=>{e.issues.length&&n.issues.push(...Sn(s,e.issues)),n.value[a.value]=e.value}))):(u.issues.length&&n.issues.push(...Sn(s,u.issues)),n.value[a.value]=u.value)}}return i.length?Promise.all(i).then((()=>n)):n}})),si=Mt("$ZodMap",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),n;const i=[];n.value=new Map;for(const[s,a]of o){const u=t.keyType._zod.run({value:s,issues:[]},r),l=t.valueType._zod.run({value:a,issues:[]},r);u instanceof Promise||l instanceof Promise?i.push(Promise.all([u,l]).then((([t,i])=>{ai(t,i,n,s,o,e,r)}))):ai(u,l,n,s,o,e,r)}return i.length?Promise.all(i).then((()=>n)):n}}));function ai(e,t,n,r,o,i,s){e.issues.length&&(ln.has(typeof r)?n.issues.push(...Sn(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map((e=>On(e,s,Ft())))})),t.issues.length&&(ln.has(typeof r)?n.issues.push(...Sn(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:r,issues:t.issues.map((e=>On(e,s,Ft())))})),n.value.set(e.value,t.value)}const ui=Mt("$ZodSet",((e,t)=>{ro.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),n;const i=[];n.value=new Set;for(const e of o){const o=t.valueType._zod.run({value:e,issues:[]},r);o instanceof Promise?i.push(o.then((e=>li(e,n)))):li(o,n)}return i.length?Promise.all(i).then((()=>n)):n}}));function li(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const ci=Mt("$ZodEnum",((e,t)=>{ro.init(e,t);const n=Ht(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((e=>ln.has(typeof e))).map((e=>"string"==typeof e?dn(e):e.toString())).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}})),di=Mt("$ZodLiteral",((e,t)=>{if(ro.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map((e=>"string"==typeof e?dn(e):e?dn(e.toString()):String(e))).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}})),pi=Mt("$ZodFile",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return r instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),t}})),mi=Mt("$ZodTransform",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>{const r=t.transform(e.value,e);if(n.async){return(r instanceof Promise?r:Promise.resolve(r)).then((t=>(e.value=t,e)))}if(r instanceof Promise)throw new qt;return e.value=r,e}}));function _i(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const hi=Mt("$ZodOptional",((e,t)=>{ro.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Xt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0)),Xt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Kt(e.source)})?$`):void 0})),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>_i(t,e.value))):_i(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}})),gi=Mt("$ZodNullable",((e,t)=>{ro.init(e,t),Xt(e._zod,"optin",(()=>t.innerType._zod.optin)),Xt(e._zod,"optout",(()=>t.innerType._zod.optout)),Xt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Kt(e.source)}|null)$`):void 0})),Xt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0)),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)})),fi=Mt("$ZodDefault",((e,t)=>{ro.init(e,t),e._zod.optin="optional",Xt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((e=>vi(e,t))):vi(r,t)}}));function vi(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const yi=Mt("$ZodPrefault",((e,t)=>{ro.init(e,t),e._zod.optin="optional",Xt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))})),bi=Mt("$ZodNonOptional",((e,t)=>{ro.init(e,t),Xt(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>void 0!==e))):void 0})),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then((t=>ki(t,e))):ki(o,e)}}));function ki(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const wi=Mt("$ZodSuccess",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>(e.value=0===t.issues.length,e))):(e.value=0===r.issues.length,e)}})),xi=Mt("$ZodCatch",((e,t)=>{ro.init(e,t),Xt(e._zod,"optin",(()=>t.innerType._zod.optin)),Xt(e._zod,"optout",(()=>t.innerType._zod.optout)),Xt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>On(e,n,Ft())))},input:e.value}),e.issues=[]),e))):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>On(e,n,Ft())))},input:e.value}),e.issues=[]),e)}})),Ii=Mt("$ZodNaN",((e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)})),Si=Mt("$ZodPipe",((e,t)=>{ro.init(e,t),Xt(e._zod,"values",(()=>t.in._zod.values)),Xt(e._zod,"optin",(()=>t.in._zod.optin)),Xt(e._zod,"optout",(()=>t.out._zod.optout)),Xt(e._zod,"propValues",(()=>t.in._zod.propValues)),e._zod.parse=(e,n)=>{const r=t.in._zod.run(e,n);return r instanceof Promise?r.then((e=>$i(e,t,n))):$i(r,t,n)}}));function $i(e,t,n){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Oi=Mt("$ZodReadonly",((e,t)=>{ro.init(e,t),Xt(e._zod,"propValues",(()=>t.innerType._zod.propValues)),Xt(e._zod,"values",(()=>t.innerType._zod.values)),Xt(e._zod,"optin",(()=>t.innerType._zod.optin)),Xt(e._zod,"optout",(()=>t.innerType._zod.optout)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ti):Ti(r)}}));function Ti(e){return e.value=Object.freeze(e.value),e}const Ei=Mt("$ZodTemplateLiteral",((e,t)=>{ro.init(e,t);const n=[];for(const r of t.parts)if("object"==typeof r&&null!==r){if(!r._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);const e=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!e)throw new Error(`Invalid template literal part: ${r._zod.traits}`);const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;n.push(e.slice(t,o))}else{if(null!==r&&!cn.has(typeof r))throw new Error(`Invalid template literal part: ${r}`);n.push(dn(`${r}`))}e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(n,r)=>"string"!=typeof n.value?(n.issues.push({input:n.value,inst:e,expected:"template_literal",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)})),Ri=Mt("$ZodPromise",((e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then((e=>t.innerType._zod.run({value:e,issues:[]},n)))})),Ni=Mt("$ZodLazy",((e,t)=>{ro.init(e,t),Xt(e._zod,"innerType",(()=>t.getter())),Xt(e._zod,"pattern",(()=>e._zod.innerType._zod.pattern)),Xt(e._zod,"propValues",(()=>e._zod.innerType._zod.propValues)),Xt(e._zod,"optin",(()=>e._zod.innerType._zod.optin??void 0)),Xt(e._zod,"optout",(()=>e._zod.innerType._zod.optout??void 0)),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)})),Ai=Mt("$ZodCustom",((e,t)=>{Nr.init(e,t),ro.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((t=>Ci(t,n,r,e)));Ci(o,n,r,e)}}));function Ci(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Rn(e))}}const Pi=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(t){return e[t]??null}const n={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return e=>{switch(e.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${e.expected}، ولكن تم إدخال ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`مدخلات غير مقبولة: يفترض إدخال ${_n(e.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?` أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()} ${r.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()} ${r.unit}`:`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`نَص غير مقبول: يجب أن يبدأ بـ "${e.prefix}"`:"ends_with"===t.format?`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`:"includes"===t.format?`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`:"regex"===t.format?`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`:`${n[t.format]??e.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${e.divisor}`;case"unrecognized_keys":return`معرف${e.keys.length>1?"ات":""} غريب${e.keys.length>1?"ة":""}: ${Bt(e.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${e.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${e.origin}`}}};const ji=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${e.expected}, daxil olan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Yanlış dəyər: gözlənilən ${_n(e.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()} ${r.unit??"element"}`:`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`:"ends_with"===t.format?`Yanlış mətn: "${t.suffix}" ilə bitməlidir`:"includes"===t.format?`Yanlış mətn: "${t.includes}" daxil olmalıdır`:"regex"===t.format?`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${n[t.format]??e.format}`}case"not_multiple_of":return`Yanlış ədəd: ${e.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${e.keys.length>1?"lar":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilində yanlış açar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${e.origin} daxilində yanlış dəyər`}}};function Ui(e,t,n,r){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?r:1===i?t:i>=2&&i<=4?n:r}const zi=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(t){return e[t]??null}const n={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return e=>{switch(e.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${e.expected}, атрымана ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"лік";case"object":if(Array.isArray(e))return"масіў";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Няправільны ўвод: чакалася ${_n(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=Ui(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна ${r.verb} ${n}${e.maximum.toString()} ${t}`}return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна быць ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=Ui(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Занадта малы: чакалася, што ${e.origin} павінна ${r.verb} ${n}${e.minimum.toString()} ${t}`}return`Занадта малы: чакалася, што ${e.origin} павінна быць ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Няправільны радок: павінен пачынацца з "${t.prefix}"`:"ends_with"===t.format?`Няправільны радок: павінен заканчвацца на "${t.suffix}"`:"includes"===t.format?`Няправільны радок: павінен змяшчаць "${t.includes}"`:"regex"===t.format?`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`:`Няправільны ${n[t.format]??e.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${e.keys.length>1?"ключы":"ключ"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${e.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${e.origin}`}}};const Di=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus invàlid: s'esperava ${e.expected}, s'ha rebut ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Valor invàlid: s'esperava ${_n(e.values[0])}`:`Opció invàlida: s'esperava una de ${Bt(e.values," o ")}`;case"too_big":{const n=e.inclusive?"com a màxim":"menys de",r=t(e.origin);return r?`Massa gran: s'esperava que ${e.origin??"el valor"} contingués ${n} ${e.maximum.toString()} ${r.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"com a mínim":"més de",r=t(e.origin);return r?`Massa petit: s'esperava que ${e.origin} contingués ${n} ${e.minimum.toString()} ${r.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Format invàlid: ha de començar amb "${t.prefix}"`:"ends_with"===t.format?`Format invàlid: ha d'acabar amb "${t.suffix}"`:"includes"===t.format?`Format invàlid: ha d'incloure "${t.includes}"`:"regex"===t.format?`Format invàlid: ha de coincidir amb el patró ${t.pattern}`:`Format invàlid per a ${n[t.format]??e.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${e.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${e.origin}`}}};const Mi=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(t){return e[t]??null}const n={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatný vstup: očekáváno ${e.expected}, obdrženo ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":if(Array.isArray(e))return"pole";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neplatný vstup: očekáváno ${_n(e.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Hodnota je příliš velká: ${e.origin??"hodnota"} musí mít ${n}${e.maximum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš velká: ${e.origin??"hodnota"} musí být ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Hodnota je příliš malá: ${e.origin??"hodnota"} musí mít ${n}${e.minimum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš malá: ${e.origin??"hodnota"} musí být ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neplatný řetězec: musí začínat na "${t.prefix}"`:"ends_with"===t.format?`Neplatný řetězec: musí končit na "${t.suffix}"`:"includes"===t.format?`Neplatný řetězec: musí obsahovat "${t.includes}"`:"regex"===t.format?`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`:`Neplatný formát ${n[t.format]??e.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${e.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${Bt(e.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${e.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${e.origin}`}}};const Li=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function n(t){return e[t]??null}function r(e){return t[e]??e}const o={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldigt input: forventede ${r(e.expected)}, fik ${r((e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tal";case"object":return Array.isArray(e)?"liste":null===e?"null":Object.getPrototypeOf(e)!==Object.prototype&&e.constructor?e.constructor.name:"objekt"}return t})(e.input))}`;case"invalid_value":return 1===e.values.length?`Ugyldig værdi: forventede ${_n(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${Bt(e.values,"|")}`;case"too_big":{const t=e.inclusive?"<=":"<",o=n(e.origin),i=r(e.origin);return o?`For stor: forventede ${i??"value"} ${o.verb} ${t} ${e.maximum.toString()} ${o.unit??"elementer"}`:`For stor: forventede ${i??"value"} havde ${t} ${e.maximum.toString()}`}case"too_small":{const t=e.inclusive?">=":">",o=n(e.origin),i=r(e.origin);return o?`For lille: forventede ${i} ${o.verb} ${t} ${e.minimum.toString()} ${o.unit}`:`For lille: forventede ${i} havde ${t} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: skal starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: skal ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: skal indeholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: skal matche mønsteret ${t.pattern}`:`Ugyldig ${o[t.format]??e.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${e.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${e.origin}`;default:return"Ugyldigt input"}}};const qi=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(t){return e[t]??null}const n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${e.expected}, erhalten ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":if(Array.isArray(e))return"Array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ungültige Eingabe: erwartet ${_n(e.values[0])}`:`Ungültige Option: erwartet eine von ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ${r.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ist`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ${r.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ist`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ungültiger String: muss mit "${t.prefix}" beginnen`:"ends_with"===t.format?`Ungültiger String: muss mit "${t.suffix}" enden`:"includes"===t.format?`Ungültiger String: muss "${t.includes}" enthalten`:"regex"===t.format?`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`:`Ungültig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${e.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${e.origin}`}}};const Zi=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${_n(e.values[0])}`:`Invalid option: expected one of ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function Fi(){return{localeError:Zi()}}const Hi=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(t){return e[t]??null}const n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return e=>{switch(e.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${e.expected}, riceviĝis ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":if(Array.isArray(e))return"tabelo";if(null===e)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nevalida enigo: atendiĝis ${_n(e.values[0])}`:`Nevalida opcio: atendiĝis unu el ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()} ${r.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Tro malgranda: atendiĝis ke ${e.origin} havu ${n}${e.minimum.toString()} ${r.unit}`:`Tro malgranda: atendiĝis ke ${e.origin} estu ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`:"ends_with"===t.format?`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`:"includes"===t.format?`Nevalida karaktraro: devas inkluzivi "${t.includes}"`:"regex"===t.format?`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`:`Nevalida ${n[t.format]??e.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${e.divisor}`;case"unrecognized_keys":return`Nekonata${e.keys.length>1?"j":""} ŝlosilo${e.keys.length>1?"j":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${e.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${e.origin}`}}};const Bi=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inválida: se esperaba ${e.expected}, recibido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"arreglo";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: se esperaba ${_n(e.values[0])}`:`Opción inválida: se esperaba una de ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Demasiado pequeño: se esperaba que ${e.origin} tuviera ${n}${e.minimum.toString()} ${r.unit}`:`Demasiado pequeño: se esperaba que ${e.origin} fuera ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Cadena inválida: debe comenzar con "${t.prefix}"`:"ends_with"===t.format?`Cadena inválida: debe terminar en "${t.suffix}"`:"includes"===t.format?`Cadena inválida: debe incluir "${t.includes}"`:"regex"===t.format?`Cadena inválida: debe coincidir con el patrón ${t.pattern}`:`Inválido ${n[t.format]??e.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Llave inválida en ${e.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inválido en ${e.origin}`}}};const Wi=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(t){return e[t]??null}const n={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return e=>{switch(e.code){case"invalid_type":return`ورودی نامعتبر: می‌بایست ${e.expected} می‌بود، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"آرایه";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} دریافت شد`;case"invalid_value":return 1===e.values.length?`ورودی نامعتبر: می‌بایست ${_n(e.values[0])} می‌بود`:`گزینه نامعتبر: می‌بایست یکی از ${Bt(e.values,"|")} می‌بود`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصر"} باشد`:`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} باشد`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} باشد`:`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} باشد`}case"invalid_format":{const t=e;return"starts_with"===t.format?`رشته نامعتبر: باید با "${t.prefix}" شروع شود`:"ends_with"===t.format?`رشته نامعتبر: باید با "${t.suffix}" تمام شود`:"includes"===t.format?`رشته نامعتبر: باید شامل "${t.includes}" باشد`:"regex"===t.format?`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`:`${n[t.format]??e.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${e.divisor} باشد`;case"unrecognized_keys":return`کلید${e.keys.length>1?"های":""} ناشناس: ${Bt(e.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${e.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${e.origin}`}}};const Ji=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(t){return e[t]??null}const n={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Virheellinen syöte: täytyy olla ${_n(e.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Liian suuri: ${r.subject} täytyy olla ${n}${e.maximum.toString()} ${r.unit}`.trim():`Liian suuri: arvon täytyy olla ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Liian pieni: ${r.subject} täytyy olla ${n}${e.minimum.toString()} ${r.unit}`.trim():`Liian pieni: arvon täytyy olla ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Virheellinen syöte: täytyy alkaa "${t.prefix}"`:"ends_with"===t.format?`Virheellinen syöte: täytyy loppua "${t.suffix}"`:"includes"===t.format?`Virheellinen syöte: täytyy sisältää "${t.includes}"`:"regex"===t.format?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`:`Virheellinen ${n[t.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${Bt(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};const Vi=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : ${e.expected} attendu, ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":if(Array.isArray(e))return"tableau";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} reçu`;case"invalid_value":return 1===e.values.length?`Entrée invalide : ${_n(e.values[0])} attendu`:`Option invalide : une valeur parmi ${Bt(e.values,"|")} attendue`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Trop grand : ${e.origin??"valeur"} doit ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"élément(s)"}`:`Trop grand : ${e.origin??"valeur"} doit être ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Trop petit : ${e.origin} doit ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : ${e.origin} doit être ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au modèle ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Bt(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Ki=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : attendu ${e.expected}, reçu ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrée invalide : attendu ${_n(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"≤":"<",r=t(e.origin);return r?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${n}${e.maximum.toString()} ${r.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"≥":">",r=t(e.origin);return r?`Trop petit : attendu que ${e.origin} ait ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : attendu que ${e.origin} soit ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au motif ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Bt(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Gi=()=>{const e={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function t(t){return e[t]??null}const n={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return e=>{switch(e.code){case"invalid_type":return`קלט לא תקין: צריך ${e.expected}, התקבל ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`קלט לא תקין: צריך ${_n(e.values[0])}`:`קלט לא תקין: צריך אחת מהאפשרויות ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()} ${r.unit}`:`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`מחרוזת לא תקינה: חייבת להתחיל ב"${t.prefix}"`:"ends_with"===t.format?`מחרוזת לא תקינה: חייבת להסתיים ב "${t.suffix}"`:"includes"===t.format?`מחרוזת לא תקינה: חייבת לכלול "${t.includes}"`:"regex"===t.format?`מחרוזת לא תקינה: חייבת להתאים לתבנית ${t.pattern}`:`${n[t.format]??e.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${e.divisor}`;case"unrecognized_keys":return`מפתח${e.keys.length>1?"ות":""} לא מזוה${e.keys.length>1?"ים":"ה"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${e.origin}`;case"invalid_union":default:return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${e.origin}`}}};const Yi=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(t){return e[t]??null}const n={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${e.expected}, a kapott érték ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"szám";case"object":if(Array.isArray(e))return"tömb";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Érvénytelen bemenet: a várt érték ${_n(e.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Túl nagy: ${e.origin??"érték"} mérete túl nagy ${n}${e.maximum.toString()} ${r.unit??"elem"}`:`Túl nagy: a bemeneti érték ${e.origin??"érték"} túl nagy: ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Túl kicsi: a bemeneti érték ${e.origin} mérete túl kicsi ${n}${e.minimum.toString()} ${r.unit}`:`Túl kicsi: a bemeneti érték ${e.origin} túl kicsi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`:"ends_with"===t.format?`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`:"includes"===t.format?`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`:"regex"===t.format?`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`:`Érvénytelen ${n[t.format]??e.format}`}case"not_multiple_of":return`Érvénytelen szám: ${e.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${e.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${e.origin}`}}};const Xi=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak valid: diharapkan ${_n(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: diharapkan ${e.origin} memiliki ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak valid: harus dimulai dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak valid: harus berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak valid: harus menyertakan "${t.includes}"`:"regex"===t.format?`String tidak valid: harus sesuai pola ${t.pattern}`:`${n[t.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`}}};const Qi=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(t){return e[t]??null}const n={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return e=>{switch(e.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":if(Array.isArray(e))return"fylki";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} þar sem á að vera ${e.expected}`;case"invalid_value":return 1===e.values.length?`Rangt gildi: gert ráð fyrir ${_n(e.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} hafi ${n}${e.maximum.toString()} ${r.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} sé ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Of lítið: gert er ráð fyrir að ${e.origin} hafi ${n}${e.minimum.toString()} ${r.unit}`:`Of lítið: gert er ráð fyrir að ${e.origin} sé ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ógildur strengur: verður að byrja á "${t.prefix}"`:"ends_with"===t.format?`Ógildur strengur: verður að enda á "${t.suffix}"`:"includes"===t.format?`Ógildur strengur: verður að innihalda "${t.includes}"`:"regex"===t.format?`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`:`Rangt ${n[t.format]??e.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${e.divisor}`;case"unrecognized_keys":return`Óþekkt ${e.keys.length>1?"ir lyklar":"ur lykill"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${e.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${e.origin}`}}};const es=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(t){return e[t]??null}const n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":if(Array.isArray(e))return"vettore";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input non valido: atteso ${_n(e.values[0])}`:`Opzione non valida: atteso uno tra ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Troppo grande: ${e.origin??"valore"} deve avere ${n}${e.maximum.toString()} ${r.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Troppo piccolo: ${e.origin} deve avere ${n}${e.minimum.toString()} ${r.unit}`:`Troppo piccolo: ${e.origin} deve essere ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Stringa non valida: deve iniziare con "${t.prefix}"`:"ends_with"===t.format?`Stringa non valida: deve terminare con "${t.suffix}"`:"includes"===t.format?`Stringa non valida: deve includere "${t.includes}"`:"regex"===t.format?`Stringa non valida: deve corrispondere al pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`}}};const ts=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(t){return e[t]??null}const n={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return e=>{switch(e.code){case"invalid_type":return`無効な入力: ${e.expected}が期待されましたが、${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"数値";case"object":if(Array.isArray(e))return"配列";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}が入力されました`;case"invalid_value":return 1===e.values.length?`無効な入力: ${_n(e.values[0])}が期待されました`:`無効な選択: ${Bt(e.values,"、")}のいずれかである必要があります`;case"too_big":{const n=e.inclusive?"以下である":"より小さい",r=t(e.origin);return r?`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${r.unit??"要素"}${n}必要があります`:`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${n}必要があります`}case"too_small":{const n=e.inclusive?"以上である":"より大きい",r=t(e.origin);return r?`小さすぎる値: ${e.origin}は${e.minimum.toString()}${r.unit}${n}必要があります`:`小さすぎる値: ${e.origin}は${e.minimum.toString()}${n}必要があります`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無効な文字列: "${t.prefix}"で始まる必要があります`:"ends_with"===t.format?`無効な文字列: "${t.suffix}"で終わる必要があります`:"includes"===t.format?`無効な文字列: "${t.includes}"を含む必要があります`:"regex"===t.format?`無効な文字列: パターン${t.pattern}に一致する必要があります`:`無効な${n[t.format]??e.format}`}case"not_multiple_of":return`無効な数値: ${e.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${e.keys.length>1?"群":""}: ${Bt(e.keys,"、")}`;case"invalid_key":return`${e.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${e.origin}内の無効な値`}}};const ns=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(t){return e[t]??null}const n={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return e=>{switch(e.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e.expected} ប៉ុន្តែទទួលបាន ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":if(Array.isArray(e))return"អារេ (Array)";if(null===e)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${_n(e.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()} ${r.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()} ${r.unit}`:`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`:"ends_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`:"includes"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`:"regex"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`:`មិនត្រឹមត្រូវ៖ ${n[t.format]??e.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${e.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${Bt(e.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`}}};const rs=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return e=>{switch(e.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${e.expected}, 받은 타입은 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}입니다`;case"invalid_value":return 1===e.values.length?`잘못된 입력: 값은 ${_n(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${Bt(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const n=e.inclusive?"이하":"미만",r="미만"===n?"이어야 합니다":"여야 합니다",o=t(e.origin),i=(null==o?void 0:o.unit)??"요소";return o?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${i} ${n}${r}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${n}${r}`}case"too_small":{const n=e.inclusive?"이상":"초과",r="이상"===n?"이어야 합니다":"여야 합니다",o=t(e.origin),i=(null==o?void 0:o.unit)??"요소";return o?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${i} ${n}${r}`:`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()} ${n}${r}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`:"ends_with"===t.format?`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`:"includes"===t.format?`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`:"regex"===t.format?`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`:`잘못된 ${n[t.format]??e.format}`}case"not_multiple_of":return`잘못된 숫자: ${e.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${Bt(e.keys,", ")}`;case"invalid_key":return`잘못된 키: ${e.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${e.origin}`}}};const os=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(t){return e[t]??null}const n={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return e=>{switch(e.code){case"invalid_type":return`Грешен внес: се очекува ${e.expected}, примено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"број";case"object":if(Array.isArray(e))return"низа";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${_n(e.values[0])}`:`Грешана опција: се очекува една ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Премногу голем: се очекува ${e.origin??"вредноста"} да има ${n}${e.maximum.toString()} ${r.unit??"елементи"}`:`Премногу голем: се очекува ${e.origin??"вредноста"} да биде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Премногу мал: се очекува ${e.origin} да има ${n}${e.minimum.toString()} ${r.unit}`:`Премногу мал: се очекува ${e.origin} да биде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неважечка низа: мора да започнува со "${t.prefix}"`:"ends_with"===t.format?`Неважечка низа: мора да завршува со "${t.suffix}"`:"includes"===t.format?`Неважечка низа: мора да вклучува "${t.includes}"`:"regex"===t.format?`Неважечка низа: мора да одгоара на патернот ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${e.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${e.origin}`}}};const is=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak sah: dijangka ${_n(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: dijangka ${e.origin??"nilai"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: dijangka ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak sah: mesti bermula dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak sah: mesti berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak sah: mesti mengandungi "${t.includes}"`:"regex"===t.format?`String tidak sah: mesti sepadan dengan corak ${t.pattern}`:`${n[t.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Bt(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`}}};const ss=()=>{const e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(t){return e[t]??null}const n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ongeldige invoer: verwacht ${_n(e.values[0])}`:`Ongeldige optie: verwacht één van ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} ${r.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} is`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} ${r.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} is`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ongeldige tekst: moet met "${t.prefix}" beginnen`:"ends_with"===t.format?`Ongeldige tekst: moet op "${t.suffix}" eindigen`:"includes"===t.format?`Ongeldige tekst: moet "${t.includes}" bevatten`:"regex"===t.format?`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`:`Ongeldig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`}}};const as=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(t){return e[t]??null}const n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":if(Array.isArray(e))return"liste";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ugyldig verdi: forventet ${_n(e.values[0])}`:`Ugyldig valg: forventet en av ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()} ${r.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()} ${r.unit}`:`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: må starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: må ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: må inneholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: må matche mønsteret ${t.pattern}`:`Ugyldig ${n[t.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${e.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`}}};const us=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`Fâsit giren: umulan ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":if(Array.isArray(e))return"saf";if(null===e)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Fâsit giren: umulan ${_n(e.values[0])}`:`Fâsit tercih: mûteberler ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} ${r.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} olmalıydı.`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} ${r.unit} sahip olmalıydı.`:`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} olmalıydı.`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Fâsit metin: "${t.prefix}" ile başlamalı.`:"ends_with"===t.format?`Fâsit metin: "${t.suffix}" ile bitmeli.`:"includes"===t.format?`Fâsit metin: "${t.includes}" ihtivâ etmeli.`:"regex"===t.format?`Fâsit metin: ${t.pattern} nakşına uymalı.`:`Fâsit ${n[t.format]??e.format}`}case"not_multiple_of":return`Fâsit sayı: ${e.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`${e.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${e.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};const ls=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(t){return e[t]??null}const n={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return e=>{switch(e.code){case"invalid_type":return`ناسم ورودي: باید ${e.expected} وای, مګر ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"ارې";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} ترلاسه شو`;case"invalid_value":return 1===e.values.length?`ناسم ورودي: باید ${_n(e.values[0])} وای`:`ناسم انتخاب: باید یو له ${Bt(e.values,"|")} څخه وای`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصرونه"} ولري`:`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} وي`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} ولري`:`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} وي`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ناسم متن: باید د "${t.prefix}" سره پیل شي`:"ends_with"===t.format?`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`:"includes"===t.format?`ناسم متن: باید "${t.includes}" ولري`:"regex"===t.format?`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`:`${n[t.format]??e.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${e.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${e.keys.length>1?"کلیډونه":"کلیډ"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${e.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${e.origin} کې`}}};const cs=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(t){return e[t]??null}const n={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return e=>{switch(e.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${e.expected}, otrzymano ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":if(Array.isArray(e))return"tablica";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nieprawidłowe dane wejściowe: oczekiwano ${_n(e.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Za duża wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.maximum.toString()} ${r.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Za mała wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.minimum.toString()} ${r.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`:"ends_with"===t.format?`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`:"includes"===t.format?`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`:"regex"===t.format?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`:`Nieprawidłow(y/a/e) ${n[t.format]??e.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${e.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${e.origin}`}}};const ds=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(t){return e[t]??null}const n={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inválido: esperado ${e.expected}, recebido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"array";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: esperado ${_n(e.values[0])}`:`Opção inválida: esperada uma das ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Muito pequeno: esperado que ${e.origin} tivesse ${n}${e.minimum.toString()} ${r.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Texto inválido: deve começar com "${t.prefix}"`:"ends_with"===t.format?`Texto inválido: deve terminar com "${t.suffix}"`:"includes"===t.format?`Texto inválido: deve incluir "${t.includes}"`:"regex"===t.format?`Texto inválido: deve corresponder ao padrão ${t.pattern}`:`${n[t.format]??e.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Chave inválida em ${e.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${e.origin}`;default:return"Campo inválido"}}};function ps(e,t,n,r){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?r:1===i?t:i>=2&&i<=4?n:r}const ms=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(t){return e[t]??null}const n={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return e=>{switch(e.code){case"invalid_type":return`Неверный ввод: ожидалось ${e.expected}, получено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"массив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неверный ввод: ожидалось ${_n(e.values[0])}`:`Неверный вариант: ожидалось одно из ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=ps(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет иметь ${n}${e.maximum.toString()} ${t}`}return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=ps(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Слишком маленькое значение: ожидалось, что ${e.origin} будет иметь ${n}${e.minimum.toString()} ${t}`}return`Слишком маленькое значение: ожидалось, что ${e.origin} будет ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неверная строка: должна начинаться с "${t.prefix}"`:"ends_with"===t.format?`Неверная строка: должна заканчиваться на "${t.suffix}"`:"includes"===t.format?`Неверная строка: должна содержать "${t.includes}"`:"regex"===t.format?`Неверная строка: должна соответствовать шаблону ${t.pattern}`:`Неверный ${n[t.format]??e.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспознанн${e.keys.length>1?"ые":"ый"} ключ${e.keys.length>1?"и":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${e.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${e.origin}`}}};const _s=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(t){return e[t]??null}const n={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${e.expected}, prejeto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"število";case"object":if(Array.isArray(e))return"tabela";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neveljaven vnos: pričakovano ${_n(e.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} imelo ${n}${e.maximum.toString()} ${r.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Premajhno: pričakovano, da bo ${e.origin} imelo ${n}${e.minimum.toString()} ${r.unit}`:`Premajhno: pričakovano, da bo ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neveljaven niz: mora se začeti z "${t.prefix}"`:"ends_with"===t.format?`Neveljaven niz: mora se končati z "${t.suffix}"`:"includes"===t.format?`Neveljaven niz: mora vsebovati "${t.includes}"`:"regex"===t.format?`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`:`Neveljaven ${n[t.format]??e.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i ključi":" ključ"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${e.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`}}};const hs=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(t){return e[t]??null}const n={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${e.expected}, fick ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":if(Array.isArray(e))return"lista";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ogiltig inmatning: förväntat ${_n(e.values[0])}`:`Ogiltigt val: förväntade en av ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`För stor(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()} ${r.unit??"element"}`:`För stor(t): förväntat ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()} ${r.unit}`:`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ogiltig sträng: måste börja med "${t.prefix}"`:"ends_with"===t.format?`Ogiltig sträng: måste sluta med "${t.suffix}"`:"includes"===t.format?`Ogiltig sträng: måste innehålla "${t.includes}"`:"regex"===t.format?`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`:`Ogiltig(t) ${n[t.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${e.origin??"värdet"}`}}};const gs=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(t){return e[t]??null}const n={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e.expected}, பெறப்பட்டது ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"எண் அல்லாதது":"எண்";case"object":if(Array.isArray(e))return"அணி";if(null===e)return"வெறுமை";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${_n(e.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${Bt(e.values,"|")} இல் ஒன்று`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ${r.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ${r.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const t=e;return"starts_with"===t.format?`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`:"ends_with"===t.format?`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`:"includes"===t.format?`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`:"regex"===t.format?`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${n[t.format]??e.format}`}case"not_multiple_of":return`தவறான எண்: ${e.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${e.keys.length>1?"கள்":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`${e.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${e.origin} இல் தவறான மதிப்பு`}}};const fs=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(t){return e[t]??null}const n={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return e=>{switch(e.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e.expected} แต่ได้รับ ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":if(Array.isArray(e))return"อาร์เรย์ (Array)";if(null===e)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ค่าไม่ถูกต้อง: ควรเป็น ${_n(e.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"ไม่เกิน":"น้อยกว่า",r=t(e.origin);return r?`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()} ${r.unit??"รายการ"}`:`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"อย่างน้อย":"มากกว่า",r=t(e.origin);return r?`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()} ${r.unit}`:`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`:"ends_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`:"includes"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`:"regex"===t.format?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`:`รูปแบบไม่ถูกต้อง: ${n[t.format]??e.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${e.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${Bt(e.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${e.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${e.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};const vs=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(t){return e[t]??null}const n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return e=>{switch(e.code){case"invalid_type":return`Geçersiz değer: beklenen ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Geçersiz değer: beklenen ${_n(e.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()} ${r.unit??"öğe"}`:`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Geçersiz metin: "${t.prefix}" ile başlamalı`:"ends_with"===t.format?`Geçersiz metin: "${t.suffix}" ile bitmeli`:"includes"===t.format?`Geçersiz metin: "${t.includes}" içermeli`:"regex"===t.format?`Geçersiz metin: ${t.pattern} desenine uymalı`:`Geçersiz ${n[t.format]??e.format}`}case"not_multiple_of":return`Geçersiz sayı: ${e.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${e.keys.length>1?"lar":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`${e.origin} içinde geçersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${e.origin} içinde geçersiz değer`}}};const ys=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(t){return e[t]??null}const n={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return e=>{switch(e.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${e.expected}, отримано ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"масив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неправильні вхідні дані: очікується ${_n(e.values[0])}`:`Неправильна опція: очікується одне з ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Занадто велике: очікується, що ${e.origin??"значення"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"елементів"}`:`Занадто велике: очікується, що ${e.origin??"значення"} буде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Занадто мале: очікується, що ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Занадто мале: очікується, що ${e.origin} буде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неправильний рядок: повинен починатися з "${t.prefix}"`:"ends_with"===t.format?`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`:"includes"===t.format?`Неправильний рядок: повинен містити "${t.includes}"`:"regex"===t.format?`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`:`Неправильний ${n[t.format]??e.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${e.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${e.keys.length>1?"і":""}: ${Bt(e.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${e.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${e.origin}`}}};const bs=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(t){return e[t]??null}const n={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return e=>{switch(e.code){case"invalid_type":return`غلط ان پٹ: ${e.expected} متوقع تھا، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"نمبر";case"object":if(Array.isArray(e))return"آرے";if(null===e)return"نل";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} موصول ہوا`;case"invalid_value":return 1===e.values.length?`غلط ان پٹ: ${_n(e.values[0])} متوقع تھا`:`غلط آپشن: ${Bt(e.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`بہت بڑا: ${e.origin??"ویلیو"} کے ${n}${e.maximum.toString()} ${r.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${e.origin??"ویلیو"} کا ${n}${e.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`بہت چھوٹا: ${e.origin} کے ${n}${e.minimum.toString()} ${r.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${e.origin} کا ${n}${e.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const t=e;return"starts_with"===t.format?`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`:"ends_with"===t.format?`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`:"includes"===t.format?`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`:"regex"===t.format?`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`:`غلط ${n[t.format]??e.format}`}case"not_multiple_of":return`غلط نمبر: ${e.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${e.keys.length>1?"ز":""}: ${Bt(e.keys,"، ")}`;case"invalid_key":return`${e.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${e.origin} میں غلط ویلیو`}}};const ks=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(t){return e[t]??null}const n={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return e=>{switch(e.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${e.expected}, nhận được ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"số";case"object":if(Array.isArray(e))return"mảng";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Đầu vào không hợp lệ: mong đợi ${_n(e.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Quá lớn: mong đợi ${e.origin??"giá trị"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"phần tử"}`:`Quá lớn: mong đợi ${e.origin??"giá trị"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Quá nhỏ: mong đợi ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Quá nhỏ: mong đợi ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`:"ends_with"===t.format?`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`:"includes"===t.format?`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`:"regex"===t.format?`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`:`${n[t.format]??e.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${e.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${Bt(e.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${e.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${e.origin}`}}};const ws=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(t){return e[t]??null}const n={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return e=>{switch(e.code){case"invalid_type":return`无效输入:期望 ${e.expected},实际接收 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"非数字(NaN)":"数字";case"object":if(Array.isArray(e))return"数组";if(null===e)return"空值(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`无效输入:期望 ${_n(e.values[0])}`:`无效选项:期望以下之一 ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()} ${r.unit??"个元素"}`:`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`无效字符串:必须以 "${t.prefix}" 开头`:"ends_with"===t.format?`无效字符串:必须以 "${t.suffix}" 结尾`:"includes"===t.format?`无效字符串:必须包含 "${t.includes}"`:"regex"===t.format?`无效字符串:必须满足正则表达式 ${t.pattern}`:`无效${n[t.format]??e.format}`}case"not_multiple_of":return`无效数字:必须是 ${e.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${Bt(e.keys,", ")}`;case"invalid_key":return`${e.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${e.origin} 中包含无效值(value)`}}};const xs=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(t){return e[t]??null}const n={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return e=>{switch(e.code){case"invalid_type":return`無效的輸入值:預期為 ${e.expected},但收到 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`無效的輸入值:預期為 ${_n(e.values[0])}`:`無效的選項:預期為以下其中之一 ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()} ${r.unit??"個元素"}`:`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()} ${r.unit}`:`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無效的字串:必須以 "${t.prefix}" 開頭`:"ends_with"===t.format?`無效的字串:必須以 "${t.suffix}" 結尾`:"includes"===t.format?`無效的字串:必須包含 "${t.includes}"`:"regex"===t.format?`無效的字串:必須符合格式 ${t.pattern}`:`無效的 ${n[t.format]??e.format}`}case"not_multiple_of":return`無效的數字:必須為 ${e.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${e.keys.length>1?"們":""}:${Bt(e.keys,"、")}`;case"invalid_key":return`${e.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${e.origin} 中有無效的值`}}};const Is=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(t){return e[t]??null}const n={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return e=>{switch(e.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${e.expected}, àmọ̀ a rí ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nọ́mbà";case"object":if(Array.isArray(e))return"akopọ";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ìbáwọlé aṣìṣe: a ní láti fi ${_n(e.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tó pọ̀ jù: a ní láti jẹ́ pé ${e.origin??"iye"} ${r.verb} ${n}${e.maximum} ${r.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${n}${e.maximum}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Kéré ju: a ní láti jẹ́ pé ${e.origin} ${r.verb} ${n}${e.minimum} ${r.unit}`:`Kéré ju: a ní láti jẹ́ ${n}${e.minimum}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`:"ends_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`:"includes"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`:"regex"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`:`Aṣìṣe: ${n[t.format]??e.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${e.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${Bt(e.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${e.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${e.origin}`}}};const Ss=Object.freeze(Object.defineProperty({__proto__:null,ar:function(){return{localeError:Pi()}},az:function(){return{localeError:ji()}},be:function(){return{localeError:zi()}},ca:function(){return{localeError:Di()}},cs:function(){return{localeError:Mi()}},da:function(){return{localeError:Li()}},de:function(){return{localeError:qi()}},en:Fi,eo:function(){return{localeError:Hi()}},es:function(){return{localeError:Bi()}},fa:function(){return{localeError:Wi()}},fi:function(){return{localeError:Ji()}},fr:function(){return{localeError:Vi()}},frCA:function(){return{localeError:Ki()}},he:function(){return{localeError:Gi()}},hu:function(){return{localeError:Yi()}},id:function(){return{localeError:Xi()}},is:function(){return{localeError:Qi()}},it:function(){return{localeError:es()}},ja:function(){return{localeError:ts()}},kh:function(){return{localeError:ns()}},ko:function(){return{localeError:rs()}},mk:function(){return{localeError:os()}},ms:function(){return{localeError:is()}},nl:function(){return{localeError:ss()}},no:function(){return{localeError:as()}},ota:function(){return{localeError:us()}},pl:function(){return{localeError:cs()}},ps:function(){return{localeError:ls()}},pt:function(){return{localeError:ds()}},ru:function(){return{localeError:ms()}},sl:function(){return{localeError:_s()}},sv:function(){return{localeError:hs()}},ta:function(){return{localeError:gs()}},th:function(){return{localeError:fs()}},tr:function(){return{localeError:vs()}},ua:function(){return{localeError:ys()}},ur:function(){return{localeError:bs()}},vi:function(){return{localeError:ks()}},yo:function(){return{localeError:Is()}},zhCN:function(){return{localeError:ws()}},zhTW:function(){return{localeError:xs()}}},Symbol.toStringTag,{value:"Module"})),$s=Symbol("ZodOutput"),Os=Symbol("ZodInput");class Ts{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&"object"==typeof n&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Es(){return new Ts}const Rs=Es();function Ns(e,t){return new e({type:"string",...mn(t)})}function As(e,t){return new e({type:"string",coerce:!0,...mn(t)})}function Cs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...mn(t)})}function Ps(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...mn(t)})}function js(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...mn(t)})}function Us(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...mn(t)})}function zs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...mn(t)})}function Ds(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...mn(t)})}function Ms(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...mn(t)})}function Ls(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...mn(t)})}function qs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...mn(t)})}function Zs(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...mn(t)})}function Fs(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...mn(t)})}function Hs(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...mn(t)})}function Bs(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...mn(t)})}function Ws(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...mn(t)})}function Js(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...mn(t)})}function Vs(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...mn(t)})}function Ks(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...mn(t)})}function Gs(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...mn(t)})}function Ys(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...mn(t)})}function Xs(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...mn(t)})}function Qs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...mn(t)})}function ea(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...mn(t)})}const ta={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function na(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...mn(t)})}function ra(e,t){return new e({type:"string",format:"date",check:"string_format",...mn(t)})}function oa(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...mn(t)})}function ia(e,t){return new e({type:"string",format:"duration",check:"string_format",...mn(t)})}function sa(e,t){return new e({type:"number",checks:[],...mn(t)})}function aa(e,t){return new e({type:"number",coerce:!0,checks:[],...mn(t)})}function ua(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...mn(t)})}function la(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...mn(t)})}function ca(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...mn(t)})}function da(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...mn(t)})}function pa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...mn(t)})}function ma(e,t){return new e({type:"boolean",...mn(t)})}function _a(e,t){return new e({type:"boolean",coerce:!0,...mn(t)})}function ha(e,t){return new e({type:"bigint",...mn(t)})}function ga(e,t){return new e({type:"bigint",coerce:!0,...mn(t)})}function fa(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...mn(t)})}function va(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...mn(t)})}function ya(e,t){return new e({type:"symbol",...mn(t)})}function ba(e,t){return new e({type:"undefined",...mn(t)})}function ka(e,t){return new e({type:"null",...mn(t)})}function wa(e){return new e({type:"any"})}function xa(e){return new e({type:"unknown"})}function Ia(e,t){return new e({type:"never",...mn(t)})}function Sa(e,t){return new e({type:"void",...mn(t)})}function $a(e,t){return new e({type:"date",...mn(t)})}function Oa(e,t){return new e({type:"date",coerce:!0,...mn(t)})}function Ta(e,t){return new e({type:"nan",...mn(t)})}function Ea(e,t){return new Cr({check:"less_than",...mn(t),value:e,inclusive:!1})}function Ra(e,t){return new Cr({check:"less_than",...mn(t),value:e,inclusive:!0})}function Na(e,t){return new Pr({check:"greater_than",...mn(t),value:e,inclusive:!1})}function Aa(e,t){return new Pr({check:"greater_than",...mn(t),value:e,inclusive:!0})}function Ca(e){return Na(0,e)}function Pa(e){return Ea(0,e)}function ja(e){return Ra(0,e)}function Ua(e){return Aa(0,e)}function za(e,t){return new jr({check:"multiple_of",...mn(t),value:e})}function Da(e,t){return new Dr({check:"max_size",...mn(t),maximum:e})}function Ma(e,t){return new Mr({check:"min_size",...mn(t),minimum:e})}function La(e,t){return new Lr({check:"size_equals",...mn(t),size:e})}function qa(e,t){return new qr({check:"max_length",...mn(t),maximum:e})}function Za(e,t){return new Zr({check:"min_length",...mn(t),minimum:e})}function Fa(e,t){return new Fr({check:"length_equals",...mn(t),length:e})}function Ha(e,t){return new Br({check:"string_format",format:"regex",...mn(t),pattern:e})}function Ba(e){return new Wr({check:"string_format",format:"lowercase",...mn(e)})}function Wa(e){return new Jr({check:"string_format",format:"uppercase",...mn(e)})}function Ja(e,t){return new Vr({check:"string_format",format:"includes",...mn(t),includes:e})}function Va(e,t){return new Kr({check:"string_format",format:"starts_with",...mn(t),prefix:e})}function Ka(e,t){return new Gr({check:"string_format",format:"ends_with",...mn(t),suffix:e})}function Ga(e,t,n){return new Xr({check:"property",property:e,schema:t,...mn(n)})}function Ya(e,t){return new Qr({check:"mime_type",mime:e,...mn(t)})}function Xa(e){return new eo({check:"overwrite",tx:e})}function Qa(e){return Xa((t=>t.normalize(e)))}function eu(){return Xa((e=>e.trim()))}function tu(){return Xa((e=>e.toLowerCase()))}function nu(){return Xa((e=>e.toUpperCase()))}function ru(e,t,n){return new e({type:"array",element:t,...mn(n)})}function ou(e,t,n,r){const o=n instanceof ro;return new e({type:"tuple",items:t,rest:o?n:null,...mn(o?r:n)})}function iu(e,t){return new e({type:"file",...mn(t)})}function su(e,t,n){const r=mn(n);r.abort??(r.abort=!0);return new e({type:"custom",check:"custom",fn:t,...r})}function au(e,t,n){return new e({type:"custom",check:"custom",fn:t,...mn(n)})}function uu(e){const t=lu((n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Rn(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(Rn(r))}},e(n.value,n))));return t}function lu(e,t){const n=new Nr({check:"custom",...mn(t)});return n._zod.check=e,n}function cu(e,t){const n=mn(t);let r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(r=r.map((e=>"string"==typeof e?e.toLowerCase():e)),o=o.map((e=>"string"==typeof e?e.toLowerCase():e)));const i=new Set(r),s=new Set(o),a=e.Pipe??Si,u=e.Boolean??Uo,l=e.String??oo,c=new(e.Transform??mi)({type:"transform",transform:(e,t)=>{let r=e;return"sensitive"!==n.case&&(r=r.toLowerCase()),!!i.has(r)||!s.has(r)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:t.value,inst:c,continue:!1}),{})},error:n.error}),d=new a({type:"pipe",in:new l({type:"string",error:n.error}),out:c,error:n.error});return new a({type:"pipe",in:d,out:new u({type:"boolean",error:n.error}),error:n.error})}function du(e,t,n,r={}){const o=mn(r),i={...mn(r),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...o};n instanceof RegExp&&(i.pattern=n);return new e(i)}class pu{constructor(e){this._def=e,this.def=e}implement(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=(...n)=>{const r=this._def.input?qn(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const o=e(...r);return this._def.output?qn(this._def.output,o,void 0,{callee:t}):o};return t}implementAsync(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=async(...n)=>{const r=this._def.input?await Fn(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const o=await e(...r);return this._def.output?Fn(this._def.output,o,void 0,{callee:t}):o};return t}input(...e){const t=this.constructor;return Array.isArray(e[0])?new t({type:"function",input:new ri({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new t({type:"function",input:e[0],output:this._def.output})}output(e){return new(0,this.constructor)({type:"function",input:this._def.input,output:e})}}function mu(e){return new pu({type:"function",input:Array.isArray(null==e?void 0:e.input)?ou(ri,null==e?void 0:e.input):(null==e?void 0:e.input)??ru(Vo,xa(Fo)),output:(null==e?void 0:e.output)??xa(Fo)})}class _u{constructor(e){this.counter=0,this.metadataRegistry=(null==e?void 0:e.metadata)??Rs,this.target=(null==e?void 0:e.target)??"draft-2020-12",this.unrepresentable=(null==e?void 0:e.unrepresentable)??"throw",this.override=(null==e?void 0:e.override)??(()=>{}),this.io=(null==e?void 0:e.io)??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n,r,o,i;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},u=this.seen.get(e);if(u){u.count++;return t.schemaPath.includes(e)&&(u.cycle=t.path),u.schema}const l={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,l);const c=null==(r=(n=e._zod).toJSONSchema)?void 0:r.call(n);if(c)l.schema=c;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},r=e._zod.parent;if(r)l.ref=r,this.process(r,n),this.seen.get(r).isParent=!0;else{const t=l.schema;switch(s.type){case"string":{const n=t;n.type="string";const{minimum:r,maximum:o,format:i,patterns:s,contentEncoding:u}=e._zod.bag;if("number"==typeof r&&(n.minLength=r),"number"==typeof o&&(n.maxLength=o),i&&(n.format=a[i]??i,""===n.format&&delete n.format),u&&(n.contentEncoding=u),s&&s.size>0){const e=[...s];1===e.length?n.pattern=e[0].source:e.length>1&&(l.schema.allOf=[...e.map((e=>({..."draft-7"===this.target||"draft-4"===this.target?{type:"string"}:{},pattern:e.source})))])}break}case"number":{const n=t,{minimum:r,maximum:o,format:i,multipleOf:s,exclusiveMaximum:a,exclusiveMinimum:u}=e._zod.bag;"string"==typeof i&&i.includes("int")?n.type="integer":n.type="number","number"==typeof u&&("draft-4"===this.target?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u),"number"==typeof r&&(n.minimum=r,"number"==typeof u&&"draft-4"!==this.target&&(u>=r?delete n.minimum:delete n.exclusiveMinimum)),"number"==typeof a&&("draft-4"===this.target?(n.maximum=a,n.exclusiveMaximum=!0):n.exclusiveMaximum=a),"number"==typeof o&&(n.maximum=o,"number"==typeof a&&"draft-4"!==this.target&&(a<=o?delete n.maximum:delete n.exclusiveMaximum)),"number"==typeof s&&(n.multipleOf=s);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const r=t,{minimum:o,maximum:i}=e._zod.bag;"number"==typeof o&&(r.minItems=o),"number"==typeof i&&(r.maxItems=i),r.type="array",r.items=this.process(s.element,{...n,path:[...n.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const r=s.shape;for(const t in r)e.properties[t]=this.process(r[t],{...n,path:[...n.path,"properties",t]});const i=new Set(Object.keys(r)),a=new Set([...i].filter((e=>{const t=s.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout})));a.size>0&&(e.required=Array.from(a)),"never"===(null==(o=s.catchall)?void 0:o._zod.def.type)?e.additionalProperties=!1:s.catchall?s.catchall&&(e.additionalProperties=this.process(s.catchall,{...n,path:[...n.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=s.options.map(((e,t)=>this.process(e,{...n,path:[...n.path,"anyOf",t]})));break;case"intersection":{const e=t,r=this.process(s.left,{...n,path:[...n.path,"allOf",0]}),o=this.process(s.right,{...n,path:[...n.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,a=[...i(r)?r.allOf:[r],...i(o)?o.allOf:[o]];e.allOf=a;break}case"tuple":{const r=t;r.type="array";const o=s.items.map(((e,t)=>this.process(e,{...n,path:[...n.path,"prefixItems",t]})));if("draft-2020-12"===this.target?r.prefixItems=o:r.items=o,s.rest){const e=this.process(s.rest,{...n,path:[...n.path,"items"]});"draft-2020-12"===this.target?r.items=e:r.additionalItems=e}s.rest&&(r.items=this.process(s.rest,{...n,path:[...n.path,"items"]}));const{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(r.minItems=i),"number"==typeof a&&(r.maxItems=a);break}case"record":{const e=t;e.type="object","draft-4"!==this.target&&(e.propertyNames=this.process(s.keyType,{...n,path:[...n.path,"propertyNames"]})),e.additionalProperties=this.process(s.valueType,{...n,path:[...n.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,n=Ht(s.entries);n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),e.enum=n;break}case"literal":{const e=t,n=[];for(const t of s.values)if(void 0===t){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");n.push(Number(t))}else n.push(t);if(0===n.length);else if(1===n.length){const t=n[0];e.type=null===t?"null":typeof t,"draft-4"===this.target?e.enum=[t]:e.const=t}else n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),n.every((e=>"boolean"==typeof e))&&(e.type="string"),n.every((e=>null===e))&&(e.type="null"),e.enum=n;break}case"file":{const n=t,r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:i,mime:s}=e._zod.bag;void 0!==o&&(r.minLength=o),void 0!==i&&(r.maxLength=i),s?1===s.length?(r.contentMediaType=s[0],Object.assign(n,r)):n.anyOf=s.map((e=>({...r,contentMediaType:e}))):Object.assign(n,r);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(s.innerType,n);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(s.innerType,n),l.ref=s.innerType;break;case"success":t.type="boolean";break;case"default":this.process(s.innerType,n),l.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue));break;case"prefault":this.process(s.innerType,n),l.ref=s.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break;case"catch":{let e;this.process(s.innerType,n),l.ref=s.innerType;try{e=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const n=t,r=e._zod.pattern;if(!r)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=r.source;break}case"pipe":{const e="input"===this.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;this.process(e,n),l.ref=e;break}case"readonly":this.process(s.innerType,n),l.ref=s.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,n),l.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const d=this.metadataRegistry.get(e);d&&Object.assign(l.schema,d),"input"===this.io&&gu(e)&&(delete l.schema.examples,delete l.schema.default),"input"===this.io&&l.schema._prefault&&((i=l.schema).default??(i.default=l.schema._prefault)),delete l.schema._prefault;return this.seen.get(e).schema}emit(e,t){var n,r,o,i,s,a;const u={cycles:(null==t?void 0:t.cycles)??"ref",reused:(null==t?void 0:t.reused)??"inline",external:(null==t?void 0:t.external)??void 0},l=this.seen.get(e);if(!l)throw new Error("Unprocessed schema. This is a bug in Zod.");const c=e=>{var t;const n="draft-2020-12"===this.target?"$defs":"definitions";if(u.external){const r=null==(t=u.external.registry.get(e[0]))?void 0:t.id,o=u.external.uri??(e=>e);if(r)return{ref:o(r)};const i=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=i,{defId:i,ref:`${o("__shared")}#/${n}/${i}`}}if(e[1]===l)return{ref:"#"};const r=`#/${n}/`,o=e[1].schema.id??"__schema"+this.counter++;return{defId:o,ref:r+o}},d=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:n,defId:r}=c(e);t.def={...t.schema},r&&(t.defId=r);const o=t.schema;for(const i in o)delete o[i];o.$ref=n};if("throw"===u.cycles)for(const g of this.seen.entries()){const e=g[1];if(e.cycle)throw new Error(`Cycle detected: #/${null==(n=e.cycle)?void 0:n.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const g of this.seen.entries()){const t=g[1];if(e===g[0]){d(g);continue}if(u.external){const t=null==(r=u.external.registry.get(g[0]))?void 0:r.id;if(e!==g[0]&&t){d(g);continue}}(null==(o=this.metadataRegistry.get(g[0]))?void 0:o.id)?d(g):(t.cycle||t.count>1&&"ref"===u.reused)&&d(g)}const p=(e,t)=>{const n=this.seen.get(e),r=n.def??n.schema,o={...r};if(null===n.ref)return;const i=n.ref;if(n.ref=null,i){p(i,t);const e=this.seen.get(i).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target?(Object.assign(r,e),Object.assign(r,o)):(r.allOf=r.allOf??[],r.allOf.push(e))}n.isParent||this.override({zodSchema:e,jsonSchema:r,path:n.path??[]})};for(const g of[...this.seen.entries()].reverse())p(g[0],{target:this.target});const m={};if("draft-2020-12"===this.target?m.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?m.$schema="http://json-schema.org/draft-07/schema#":"draft-4"===this.target?m.$schema="http://json-schema.org/draft-04/schema#":console.warn(`Invalid target: ${this.target}`),null==(i=u.external)?void 0:i.uri){const t=null==(s=u.external.registry.get(e))?void 0:s.id;if(!t)throw new Error("Schema is missing an `id` property");m.$id=u.external.uri(t)}Object.assign(m,l.def);const _=(null==(a=u.external)?void 0:a.defs)??{};for(const g of this.seen.entries()){const e=g[1];e.def&&e.defId&&(_[e.defId]=e.def)}u.external||Object.keys(_).length>0&&("draft-2020-12"===this.target?m.$defs=_:m.definitions=_);try{return JSON.parse(JSON.stringify(m))}catch(h){throw new Error("Error converting schema to JSON.")}}}function hu(e,t){if(e instanceof Ts){const n=new _u(t),r={};for(const t of e._idmap.entries()){const[e,r]=t;n.process(r)}const o={},i={registry:e,uri:null==t?void 0:t.uri,defs:r};for(const s of e._idmap.entries()){const[e,r]=s;o[e]=n.emit(r,{...t,external:i})}if(Object.keys(r).length>0){const e="draft-2020-12"===n.target?"$defs":"definitions";o.__shared={[e]:r}}return{schemas:o}}const n=new _u(t);return n.process(e),n.emit(e,t)}function gu(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return gu(r.element,n);case"object":for(const e in r.shape)if(gu(r.shape[e],n))return!0;return!1;case"union":for(const e of r.options)if(gu(e,n))return!0;return!1;case"intersection":return gu(r.left,n)||gu(r.right,n);case"tuple":for(const e of r.items)if(gu(e,n))return!0;return!(!r.rest||!gu(r.rest,n));case"record":case"map":return gu(r.keyType,n)||gu(r.valueType,n);case"set":return gu(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return gu(r.innerType,n);case"lazy":return gu(r.getter(),n);case"transform":return!0;case"pipe":return gu(r.in,n)||gu(r.out,n)}throw new Error(`Unknown schema type: ${r.type}`)}const fu=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),vu=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Zo,$ZodArray:Vo,$ZodAsyncError:qt,$ZodBase64:Oo,$ZodBase64URL:Eo,$ZodBigInt:zo,$ZodBigIntFormat:Do,$ZodBoolean:Uo,$ZodCIDRv4:Io,$ZodCIDRv6:So,$ZodCUID:mo,$ZodCUID2:_o,$ZodCatch:xi,$ZodCheck:Nr,$ZodCheckBigIntFormat:zr,$ZodCheckEndsWith:Gr,$ZodCheckGreaterThan:Pr,$ZodCheckIncludes:Vr,$ZodCheckLengthEquals:Fr,$ZodCheckLessThan:Cr,$ZodCheckLowerCase:Wr,$ZodCheckMaxLength:qr,$ZodCheckMaxSize:Dr,$ZodCheckMimeType:Qr,$ZodCheckMinLength:Zr,$ZodCheckMinSize:Mr,$ZodCheckMultipleOf:jr,$ZodCheckNumberFormat:Ur,$ZodCheckOverwrite:eo,$ZodCheckProperty:Xr,$ZodCheckRegex:Br,$ZodCheckSizeEquals:Lr,$ZodCheckStartsWith:Kr,$ZodCheckStringFormat:Hr,$ZodCheckUpperCase:Jr,$ZodCustom:Ai,$ZodCustomStringFormat:Co,$ZodDate:Wo,$ZodDefault:fi,$ZodDiscriminatedUnion:Qo,$ZodE164:Ro,$ZodEmail:uo,$ZodEmoji:co,$ZodEnum:ci,$ZodError:Cn,$ZodFile:pi,$ZodFunction:pu,$ZodGUID:so,$ZodIPv4:wo,$ZodIPv6:xo,$ZodISODate:yo,$ZodISODateTime:vo,$ZodISODuration:ko,$ZodISOTime:bo,$ZodIntersection:ei,$ZodJWT:Ao,$ZodKSUID:fo,$ZodLazy:Ni,$ZodLiteral:di,$ZodMap:si,$ZodNaN:Ii,$ZodNanoID:po,$ZodNever:Ho,$ZodNonOptional:bi,$ZodNull:qo,$ZodNullable:gi,$ZodNumber:Po,$ZodNumberFormat:jo,$ZodObject:Go,$ZodOptional:hi,$ZodPipe:Si,$ZodPrefault:yi,$ZodPromise:Ri,$ZodReadonly:Oi,$ZodRealError:Pn,$ZodRecord:ii,$ZodRegistry:Ts,$ZodSet:ui,$ZodString:oo,$ZodStringFormat:io,$ZodSuccess:wi,$ZodSymbol:Mo,$ZodTemplateLiteral:Ei,$ZodTransform:mi,$ZodTuple:ri,$ZodType:ro,$ZodULID:ho,$ZodURL:lo,$ZodUUID:ao,$ZodUndefined:Lo,$ZodUnion:Xo,$ZodUnknown:Fo,$ZodVoid:Bo,$ZodXID:go,$brand:Lt,$constructor:Mt,$input:Os,$output:$s,Doc:to,JSONSchema:fu,JSONSchemaGenerator:_u,NEVER:Dt,TimePrecision:ta,_any:wa,_array:ru,_base64:Ys,_base64url:Xs,_bigint:ha,_boolean:ma,_catch:function(e,t,n){return new e({type:"catch",innerType:t,catchValue:"function"==typeof n?n:()=>n})},_check:lu,_cidrv4:Ks,_cidrv6:Gs,_coercedBigint:ga,_coercedBoolean:_a,_coercedDate:Oa,_coercedNumber:aa,_coercedString:As,_cuid:Zs,_cuid2:Fs,_custom:su,_date:$a,_default:function(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof n?n():un(n)}})},_discriminatedUnion:function(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...mn(r)})},_e164:Qs,_email:Cs,_emoji:Ls,_endsWith:Ka,_enum:function(e,t,n){return new e({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map((e=>[e,e]))):t,...mn(n)})},_file:iu,_float32:la,_float64:ca,_gt:Na,_gte:Aa,_guid:Ps,_includes:Ja,_int:ua,_int32:da,_int64:fa,_intersection:function(e,t,n){return new e({type:"intersection",left:t,right:n})},_ipv4:Js,_ipv6:Vs,_isoDate:ra,_isoDateTime:na,_isoDuration:ia,_isoTime:oa,_jwt:ea,_ksuid:Ws,_lazy:function(e,t){return new e({type:"lazy",getter:t})},_length:Fa,_literal:function(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...mn(n)})},_lowercase:Ba,_lt:Ea,_lte:Ra,_map:function(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...mn(r)})},_max:Ra,_maxLength:qa,_maxSize:Da,_mime:Ya,_min:Aa,_minLength:Za,_minSize:Ma,_multipleOf:za,_nan:Ta,_nanoid:qs,_nativeEnum:function(e,t,n){return new e({type:"enum",entries:t,...mn(n)})},_negative:Pa,_never:Ia,_nonnegative:Ua,_nonoptional:function(e,t,n){return new e({type:"nonoptional",innerType:t,...mn(n)})},_nonpositive:ja,_normalize:Qa,_null:ka,_nullable:function(e,t){return new e({type:"nullable",innerType:t})},_number:sa,_optional:function(e,t){return new e({type:"optional",innerType:t})},_overwrite:Xa,_parse:Ln,_parseAsync:Zn,_pipe:function(e,t,n){return new e({type:"pipe",in:t,out:n})},_positive:Ca,_promise:function(e,t){return new e({type:"promise",innerType:t})},_property:Ga,_readonly:function(e,t){return new e({type:"readonly",innerType:t})},_record:function(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...mn(r)})},_refine:au,_regex:Ha,_safeParse:Hn,_safeParseAsync:Wn,_set:function(e,t,n){return new e({type:"set",valueType:t,...mn(n)})},_size:La,_startsWith:Va,_string:Ns,_stringFormat:du,_stringbool:cu,_success:function(e,t){return new e({type:"success",innerType:t})},_superRefine:uu,_symbol:ya,_templateLiteral:function(e,t,n){return new e({type:"template_literal",parts:t,...mn(n)})},_toLowerCase:tu,_toUpperCase:nu,_transform:function(e,t){return new e({type:"transform",transform:t})},_trim:eu,_tuple:ou,_uint32:pa,_uint64:va,_ulid:Hs,_undefined:ba,_union:function(e,t,n){return new e({type:"union",options:t,...mn(n)})},_unknown:xa,_uppercase:Wa,_url:Ms,_uuid:js,_uuidv4:Us,_uuidv6:zs,_uuidv7:Ds,_void:Sa,_xid:Bs,clone:pn,config:Ft,flattenError:jn,formatError:Un,function:mu,globalConfig:Zt,globalRegistry:Rs,isValidBase64:$o,isValidBase64URL:To,isValidJWT:No,locales:Ss,parse:qn,parseAsync:Fn,prettifyError:Mn,regexes:Rr,registry:Es,safeParse:Bn,safeParseAsync:Jn,toDotPath:Dn,toJSONSchema:hu,treeifyError:zn,util:Nn,version:no},Symbol.toStringTag,{value:"Module"})),yu=Mt("ZodISODateTime",((e,t)=>{vo.init(e,t),Mu.init(e,t)}));function bu(e){return na(yu,e)}const ku=Mt("ZodISODate",((e,t)=>{yo.init(e,t),Mu.init(e,t)}));function wu(e){return ra(ku,e)}const xu=Mt("ZodISOTime",((e,t)=>{bo.init(e,t),Mu.init(e,t)}));function Iu(e){return oa(xu,e)}const Su=Mt("ZodISODuration",((e,t)=>{ko.init(e,t),Mu.init(e,t)}));function $u(e){return ia(Su,e)}const Ou=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:ku,ZodISODateTime:yu,ZodISODuration:Su,ZodISOTime:xu,date:wu,datetime:bu,duration:$u,time:Iu},Symbol.toStringTag,{value:"Module"})),Tu=(e,t)=>{Cn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>Un(e,t)},flatten:{value:t=>jn(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Wt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Wt,2)}},isEmpty:{get:()=>0===e.issues.length}})},Eu=Mt("ZodError",Tu),Ru=Mt("ZodError",Tu,{Parent:Error}),Nu=Ln(Ru),Au=Zn(Ru),Cu=Hn(Ru),Pu=Wn(Ru),ju=Mt("ZodType",((e,t)=>(ro.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map((e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]}),e.clone=(t,n)=>pn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>Nu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Cu(e,t,n),e.parseAsync=async(t,n)=>Au(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Pu(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(wc(t,n)),e.superRefine=t=>e.check(xc(t)),e.overwrite=t=>e.check(Xa(t)),e.optional=()=>Ql(e),e.nullable=()=>tc(e),e.nullish=()=>Ql(tc(e)),e.nonoptional=t=>ac(e,t),e.array=()=>Tl(e),e.or=t=>Pl([e,t]),e.and=t=>Dl(e,t),e.transform=t=>mc(e,Yl(t)),e.default=t=>rc(e,t),e.prefault=t=>ic(e,t),e.catch=t=>cc(e,t),e.pipe=t=>mc(e,t),e.readonly=()=>hc(e),e.describe=t=>{const n=e.clone();return Rs.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){var t;return null==(t=Rs.get(e))?void 0:t.description},configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Rs.get(e);const n=e.clone();return Rs.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),Uu=Mt("_ZodString",((e,t)=>{oo.init(e,t),ju.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Ha(...t)),e.includes=(...t)=>e.check(Ja(...t)),e.startsWith=(...t)=>e.check(Va(...t)),e.endsWith=(...t)=>e.check(Ka(...t)),e.min=(...t)=>e.check(Za(...t)),e.max=(...t)=>e.check(qa(...t)),e.length=(...t)=>e.check(Fa(...t)),e.nonempty=(...t)=>e.check(Za(1,...t)),e.lowercase=t=>e.check(Ba(t)),e.uppercase=t=>e.check(Wa(t)),e.trim=()=>e.check(eu()),e.normalize=(...t)=>e.check(Qa(...t)),e.toLowerCase=()=>e.check(tu()),e.toUpperCase=()=>e.check(nu())})),zu=Mt("ZodString",((e,t)=>{oo.init(e,t),Uu.init(e,t),e.email=t=>e.check(Cs(Lu,t)),e.url=t=>e.check(Ms(Fu,t)),e.jwt=t=>e.check(ea(il,t)),e.emoji=t=>e.check(Ls(Hu,t)),e.guid=t=>e.check(Ps(qu,t)),e.uuid=t=>e.check(js(Zu,t)),e.uuidv4=t=>e.check(Us(Zu,t)),e.uuidv6=t=>e.check(zs(Zu,t)),e.uuidv7=t=>e.check(Ds(Zu,t)),e.nanoid=t=>e.check(qs(Bu,t)),e.guid=t=>e.check(Ps(qu,t)),e.cuid=t=>e.check(Zs(Wu,t)),e.cuid2=t=>e.check(Fs(Ju,t)),e.ulid=t=>e.check(Hs(Vu,t)),e.base64=t=>e.check(Ys(tl,t)),e.base64url=t=>e.check(Xs(rl,t)),e.xid=t=>e.check(Bs(Ku,t)),e.ksuid=t=>e.check(Ws(Gu,t)),e.ipv4=t=>e.check(Js(Yu,t)),e.ipv6=t=>e.check(Vs(Xu,t)),e.cidrv4=t=>e.check(Ks(Qu,t)),e.cidrv6=t=>e.check(Gs(el,t)),e.e164=t=>e.check(Qs(ol,t)),e.datetime=t=>e.check(bu(t)),e.date=t=>e.check(wu(t)),e.time=t=>e.check(Iu(t)),e.duration=t=>e.check($u(t))}));function Du(e){return Ns(zu,e)}const Mu=Mt("ZodStringFormat",((e,t)=>{io.init(e,t),Uu.init(e,t)})),Lu=Mt("ZodEmail",((e,t)=>{uo.init(e,t),Mu.init(e,t)}));const qu=Mt("ZodGUID",((e,t)=>{so.init(e,t),Mu.init(e,t)}));const Zu=Mt("ZodUUID",((e,t)=>{ao.init(e,t),Mu.init(e,t)}));const Fu=Mt("ZodURL",((e,t)=>{lo.init(e,t),Mu.init(e,t)}));const Hu=Mt("ZodEmoji",((e,t)=>{co.init(e,t),Mu.init(e,t)}));const Bu=Mt("ZodNanoID",((e,t)=>{po.init(e,t),Mu.init(e,t)}));const Wu=Mt("ZodCUID",((e,t)=>{mo.init(e,t),Mu.init(e,t)}));const Ju=Mt("ZodCUID2",((e,t)=>{_o.init(e,t),Mu.init(e,t)}));const Vu=Mt("ZodULID",((e,t)=>{ho.init(e,t),Mu.init(e,t)}));const Ku=Mt("ZodXID",((e,t)=>{go.init(e,t),Mu.init(e,t)}));const Gu=Mt("ZodKSUID",((e,t)=>{fo.init(e,t),Mu.init(e,t)}));const Yu=Mt("ZodIPv4",((e,t)=>{wo.init(e,t),Mu.init(e,t)}));const Xu=Mt("ZodIPv6",((e,t)=>{xo.init(e,t),Mu.init(e,t)}));const Qu=Mt("ZodCIDRv4",((e,t)=>{Io.init(e,t),Mu.init(e,t)}));const el=Mt("ZodCIDRv6",((e,t)=>{So.init(e,t),Mu.init(e,t)}));const tl=Mt("ZodBase64",((e,t)=>{Oo.init(e,t),Mu.init(e,t)}));function nl(e){return Ys(tl,e)}const rl=Mt("ZodBase64URL",((e,t)=>{Eo.init(e,t),Mu.init(e,t)}));const ol=Mt("ZodE164",((e,t)=>{Ro.init(e,t),Mu.init(e,t)}));const il=Mt("ZodJWT",((e,t)=>{Ao.init(e,t),Mu.init(e,t)}));const sl=Mt("ZodCustomStringFormat",((e,t)=>{Co.init(e,t),Mu.init(e,t)}));const al=Mt("ZodNumber",((e,t)=>{Po.init(e,t),ju.init(e,t),e.gt=(t,n)=>e.check(Na(t,n)),e.gte=(t,n)=>e.check(Aa(t,n)),e.min=(t,n)=>e.check(Aa(t,n)),e.lt=(t,n)=>e.check(Ea(t,n)),e.lte=(t,n)=>e.check(Ra(t,n)),e.max=(t,n)=>e.check(Ra(t,n)),e.int=t=>e.check(cl(t)),e.safe=t=>e.check(cl(t)),e.positive=t=>e.check(Na(0,t)),e.nonnegative=t=>e.check(Aa(0,t)),e.negative=t=>e.check(Ea(0,t)),e.nonpositive=t=>e.check(Ra(0,t)),e.multipleOf=(t,n)=>e.check(za(t,n)),e.step=(t,n)=>e.check(za(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}));function ul(e){return sa(al,e)}const ll=Mt("ZodNumberFormat",((e,t)=>{jo.init(e,t),al.init(e,t)}));function cl(e){return ua(ll,e)}const dl=Mt("ZodBoolean",((e,t)=>{Uo.init(e,t),ju.init(e,t)}));function pl(e){return ma(dl,e)}const ml=Mt("ZodBigInt",((e,t)=>{zo.init(e,t),ju.init(e,t),e.gte=(t,n)=>e.check(Aa(t,n)),e.min=(t,n)=>e.check(Aa(t,n)),e.gt=(t,n)=>e.check(Na(t,n)),e.gte=(t,n)=>e.check(Aa(t,n)),e.min=(t,n)=>e.check(Aa(t,n)),e.lt=(t,n)=>e.check(Ea(t,n)),e.lte=(t,n)=>e.check(Ra(t,n)),e.max=(t,n)=>e.check(Ra(t,n)),e.positive=t=>e.check(Na(BigInt(0),t)),e.negative=t=>e.check(Ea(BigInt(0),t)),e.nonpositive=t=>e.check(Ra(BigInt(0),t)),e.nonnegative=t=>e.check(Aa(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(za(t,n));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null}));const _l=Mt("ZodBigIntFormat",((e,t)=>{Do.init(e,t),ml.init(e,t)}));const hl=Mt("ZodSymbol",((e,t)=>{Mo.init(e,t),ju.init(e,t)}));const gl=Mt("ZodUndefined",((e,t)=>{Lo.init(e,t),ju.init(e,t)}));const fl=Mt("ZodNull",((e,t)=>{qo.init(e,t),ju.init(e,t)}));function vl(e){return ka(fl,e)}const yl=Mt("ZodAny",((e,t)=>{Zo.init(e,t),ju.init(e,t)}));function bl(){return wa(yl)}const kl=Mt("ZodUnknown",((e,t)=>{Fo.init(e,t),ju.init(e,t)}));function wl(){return xa(kl)}const xl=Mt("ZodNever",((e,t)=>{Ho.init(e,t),ju.init(e,t)}));function Il(e){return Ia(xl,e)}const Sl=Mt("ZodVoid",((e,t)=>{Bo.init(e,t),ju.init(e,t)}));const $l=Mt("ZodDate",((e,t)=>{Wo.init(e,t),ju.init(e,t),e.min=(t,n)=>e.check(Aa(t,n)),e.max=(t,n)=>e.check(Ra(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}));const Ol=Mt("ZodArray",((e,t)=>{Vo.init(e,t),ju.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Za(t,n)),e.nonempty=t=>e.check(Za(1,t)),e.max=(t,n)=>e.check(qa(t,n)),e.length=(t,n)=>e.check(Fa(t,n)),e.unwrap=()=>e.element}));function Tl(e,t){return ru(Ol,e,t)}const El=Mt("ZodObject",((e,t)=>{Go.init(e,t),ju.init(e,t),Xt(e,"shape",(()=>t.shape)),e.keyof=()=>Wl(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wl()}),e.loose=()=>e.clone({...e._zod.def,catchall:wl()}),e.strict=()=>e.clone({...e._zod.def,catchall:Il()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>bn(e,t),e.merge=t=>kn(e,t),e.pick=t=>vn(e,t),e.omit=t=>yn(e,t),e.partial=(...t)=>wn(Xl,e,t[0]),e.required=(...t)=>xn(sc,e,t[0])}));function Rl(e,t){const n={type:"object",get shape(){return en(this,"shape",e?Qt(e):{}),this.shape},...mn(t)};return new El(n)}function Nl(e,t){return new El({type:"object",get shape(){return en(this,"shape",Qt(e)),this.shape},catchall:Il(),...mn(t)})}function Al(e,t){return new El({type:"object",get shape(){return en(this,"shape",Qt(e)),this.shape},catchall:wl(),...mn(t)})}const Cl=Mt("ZodUnion",((e,t)=>{Xo.init(e,t),ju.init(e,t),e.options=t.options}));function Pl(e,t){return new Cl({type:"union",options:e,...mn(t)})}const jl=Mt("ZodDiscriminatedUnion",((e,t)=>{Cl.init(e,t),Qo.init(e,t)}));function Ul(e,t,n){return new jl({type:"union",options:t,discriminator:e,...mn(n)})}const zl=Mt("ZodIntersection",((e,t)=>{ei.init(e,t),ju.init(e,t)}));function Dl(e,t){return new zl({type:"intersection",left:e,right:t})}const Ml=Mt("ZodTuple",((e,t)=>{ri.init(e,t),ju.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})}));function Ll(e,t,n){const r=t instanceof ro;return new Ml({type:"tuple",items:e,rest:r?t:null,...mn(r?n:t)})}const ql=Mt("ZodRecord",((e,t)=>{ii.init(e,t),ju.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));function Zl(e,t,n){return new ql({type:"record",keyType:e,valueType:t,...mn(n)})}const Fl=Mt("ZodMap",((e,t)=>{si.init(e,t),ju.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));const Hl=Mt("ZodSet",((e,t)=>{ui.init(e,t),ju.init(e,t),e.min=(...t)=>e.check(Ma(...t)),e.nonempty=t=>e.check(Ma(1,t)),e.max=(...t)=>e.check(Da(...t)),e.size=(...t)=>e.check(La(...t))}));const Bl=Mt("ZodEnum",((e,t)=>{ci.init(e,t),ju.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new Bl({...t,checks:[],...mn(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Bl({...t,checks:[],...mn(r),entries:o})}}));function Wl(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new Bl({type:"enum",entries:n,...mn(t)})}const Jl=Mt("ZodLiteral",((e,t)=>{di.init(e,t),ju.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}));function Vl(e,t){return new Jl({type:"literal",values:Array.isArray(e)?e:[e],...mn(t)})}const Kl=Mt("ZodFile",((e,t)=>{pi.init(e,t),ju.init(e,t),e.min=(t,n)=>e.check(Ma(t,n)),e.max=(t,n)=>e.check(Da(t,n)),e.mime=(t,n)=>e.check(Ya(Array.isArray(t)?t:[t],n))}));const Gl=Mt("ZodTransform",((e,t)=>{mi.init(e,t),ju.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if("string"==typeof r)n.issues.push(Rn(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Rn(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then((e=>(n.value=e,n))):(n.value=o,n)}}));function Yl(e){return new Gl({type:"transform",transform:e})}const Xl=Mt("ZodOptional",((e,t)=>{hi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function Ql(e){return new Xl({type:"optional",innerType:e})}const ec=Mt("ZodNullable",((e,t)=>{gi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function tc(e){return new ec({type:"nullable",innerType:e})}const nc=Mt("ZodDefault",((e,t)=>{fi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}));function rc(e,t){return new nc({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():un(t)}})}const oc=Mt("ZodPrefault",((e,t)=>{yi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ic(e,t){return new oc({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():un(t)}})}const sc=Mt("ZodNonOptional",((e,t)=>{bi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ac(e,t){return new sc({type:"nonoptional",innerType:e,...mn(t)})}const uc=Mt("ZodSuccess",((e,t)=>{wi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const lc=Mt("ZodCatch",((e,t)=>{xi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));function cc(e,t){return new lc({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const dc=Mt("ZodNaN",((e,t)=>{Ii.init(e,t),ju.init(e,t)}));const pc=Mt("ZodPipe",((e,t)=>{Si.init(e,t),ju.init(e,t),e.in=t.in,e.out=t.out}));function mc(e,t){return new pc({type:"pipe",in:e,out:t})}const _c=Mt("ZodReadonly",((e,t)=>{Oi.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function hc(e){return new _c({type:"readonly",innerType:e})}const gc=Mt("ZodTemplateLiteral",((e,t)=>{Ei.init(e,t),ju.init(e,t)}));const fc=Mt("ZodLazy",((e,t)=>{Ni.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.getter()}));function vc(e){return new fc({type:"lazy",getter:e})}const yc=Mt("ZodPromise",((e,t)=>{Ri.init(e,t),ju.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const bc=Mt("ZodCustom",((e,t)=>{Ai.init(e,t),ju.init(e,t)}));function kc(e,t){return su(bc,e??(()=>!0),t)}function wc(e,t={}){return au(bc,e,t)}function xc(e){return uu(e)}function Ic(e,t={error:`Input not instance of ${e.name}`}){const n=new bc({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...mn(t)});return n._zod.bag.Class=e,n}var Sc;function $c(e){return aa(al,e)}Sc||(Sc={});const Oc=Object.freeze(Object.defineProperty({__proto__:null,bigint:function(e){return ga(ml,e)},boolean:function(e){return _a(dl,e)},date:function(e){return Oa($l,e)},number:$c,string:function(e){return As(zu,e)}},Symbol.toStringTag,{value:"Module"}));Ft(Fi());const Tc=Object.freeze(Object.defineProperty({__proto__:null,$brand:Lt,$input:Os,$output:$s,NEVER:Dt,TimePrecision:ta,ZodAny:yl,ZodArray:Ol,ZodBase64:tl,ZodBase64URL:rl,ZodBigInt:ml,ZodBigIntFormat:_l,ZodBoolean:dl,ZodCIDRv4:Qu,ZodCIDRv6:el,ZodCUID:Wu,ZodCUID2:Ju,ZodCatch:lc,ZodCustom:bc,ZodCustomStringFormat:sl,ZodDate:$l,ZodDefault:nc,ZodDiscriminatedUnion:jl,ZodE164:ol,ZodEmail:Lu,ZodEmoji:Hu,ZodEnum:Bl,ZodError:Eu,ZodFile:Kl,get ZodFirstPartyTypeKind(){return Sc},ZodGUID:qu,ZodIPv4:Yu,ZodIPv6:Xu,ZodISODate:ku,ZodISODateTime:yu,ZodISODuration:Su,ZodISOTime:xu,ZodIntersection:zl,ZodIssueCode:{invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},ZodJWT:il,ZodKSUID:Gu,ZodLazy:fc,ZodLiteral:Jl,ZodMap:Fl,ZodNaN:dc,ZodNanoID:Bu,ZodNever:xl,ZodNonOptional:sc,ZodNull:fl,ZodNullable:ec,ZodNumber:al,ZodNumberFormat:ll,ZodObject:El,ZodOptional:Xl,ZodPipe:pc,ZodPrefault:oc,ZodPromise:yc,ZodReadonly:_c,ZodRealError:Ru,ZodRecord:ql,ZodSet:Hl,ZodString:zu,ZodStringFormat:Mu,ZodSuccess:uc,ZodSymbol:hl,ZodTemplateLiteral:gc,ZodTransform:Gl,ZodTuple:Ml,ZodType:ju,ZodULID:Vu,ZodURL:Fu,ZodUUID:Zu,ZodUndefined:gl,ZodUnion:Cl,ZodUnknown:kl,ZodVoid:Sl,ZodXID:Ku,_ZodString:Uu,_default:rc,any:bl,array:Tl,base64:nl,base64url:function(e){return Xs(rl,e)},bigint:function(e){return ha(ml,e)},boolean:pl,catch:cc,check:function(e){const t=new Nr({check:"custom"});return t._zod.check=e,t},cidrv4:function(e){return Ks(Qu,e)},cidrv6:function(e){return Gs(el,e)},clone:pn,coerce:Oc,config:Ft,core:vu,cuid:function(e){return Zs(Wu,e)},cuid2:function(e){return Fs(Ju,e)},custom:kc,date:function(e){return $a($l,e)},discriminatedUnion:Ul,e164:function(e){return Qs(ol,e)},email:function(e){return Cs(Lu,e)},emoji:function(e){return Ls(Hu,e)},endsWith:Ka,enum:Wl,file:function(e){return iu(Kl,e)},flattenError:jn,float32:function(e){return la(ll,e)},float64:function(e){return ca(ll,e)},formatError:Un,function:mu,getErrorMap:function(){return Ft().customError},globalRegistry:Rs,gt:Na,gte:Aa,guid:function(e){return Ps(qu,e)},hostname:function(e){return du(sl,"hostname",_r,e)},includes:Ja,instanceof:Ic,int:cl,int32:function(e){return da(ll,e)},int64:function(e){return fa(_l,e)},intersection:Dl,ipv4:function(e){return Js(Yu,e)},ipv6:function(e){return Vs(Xu,e)},iso:Ou,json:function(e){const t=vc((()=>Pl([Du(e),ul(),pl(),vl(),Tl(t),Zl(Du(),t)])));return t},jwt:function(e){return ea(il,e)},keyof:function(e){const t=e._zod.def.shape;return Wl(Object.keys(t))},ksuid:function(e){return Ws(Gu,e)},lazy:vc,length:Fa,literal:Vl,locales:Ss,looseObject:Al,lowercase:Ba,lt:Ea,lte:Ra,map:function(e,t,n){return new Fl({type:"map",keyType:e,valueType:t,...mn(n)})},maxLength:qa,maxSize:Da,mime:Ya,minLength:Za,minSize:Ma,multipleOf:za,nan:function(e){return Ta(dc,e)},nanoid:function(e){return qs(Bu,e)},nativeEnum:function(e,t){return new Bl({type:"enum",entries:e,...mn(t)})},negative:Pa,never:Il,nonnegative:Ua,nonoptional:ac,nonpositive:ja,normalize:Qa,null:vl,nullable:tc,nullish:function(e){return Ql(tc(e))},number:ul,object:Rl,optional:Ql,overwrite:Xa,parse:Nu,parseAsync:Au,partialRecord:function(e,t,n){const r=pn(e);return r._zod.values=void 0,new ql({type:"record",keyType:r,valueType:t,...mn(n)})},pipe:mc,positive:Ca,prefault:ic,preprocess:function(e,t){return mc(Yl(e),t)},prettifyError:Mn,promise:function(e){return new yc({type:"promise",innerType:e})},property:Ga,readonly:hc,record:Zl,refine:wc,regex:Ha,regexes:Rr,registry:Es,safeParse:Cu,safeParseAsync:Pu,set:function(e,t){return new Hl({type:"set",valueType:e,...mn(t)})},setErrorMap:function(e){Ft({customError:e})},size:La,startsWith:Va,strictObject:Nl,string:Du,stringFormat:function(e,t,n={}){return du(sl,e,t,n)},stringbool:(...e)=>cu({Pipe:pc,Boolean:dl,String:zu,Transform:Gl},...e),success:function(e){return new uc({type:"success",innerType:e})},superRefine:xc,symbol:function(e){return ya(hl,e)},templateLiteral:function(e,t){return new gc({type:"template_literal",parts:e,...mn(t)})},toJSONSchema:hu,toLowerCase:tu,toUpperCase:nu,transform:Yl,treeifyError:zn,trim:eu,tuple:Ll,uint32:function(e){return pa(ll,e)},uint64:function(e){return va(_l,e)},ulid:function(e){return Hs(Vu,e)},undefined:function(e){return ba(gl,e)},union:Pl,unknown:wl,uppercase:Wa,url:function(e){return Ms(Fu,e)},uuid:function(e){return js(Zu,e)},uuidv4:function(e){return Us(Zu,e)},uuidv6:function(e){return zs(Zu,e)},uuidv7:function(e){return Ds(Zu,e)},void:function(e){return Sa(Sl,e)},xid:function(e){return Bs(Ku,e)}},Symbol.toStringTag,{value:"Module"})),Ec=Symbol("Let zodToJsonSchema decide on which parser to use"),Rc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Nc=e=>{const t=(e=>"string"==typeof e?{...Rc,name:e}:{...Rc,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function Ac(e,t,n,r){(null==r?void 0:r.errorMessages)&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Cc(e,t,n,r,o){e[t]=n,Ac(e,t,r,o)}const Pc=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function jc(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Pc(t,e.currentPath):t.join("/")}}function Uc(e,t){return ld(e.type._def,t)}function zc(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(((n,r)=>zc(e,t,n)))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Dc(e,t)}}const Dc=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Cc(n,"minimum",r.value,r.message,t);break;case"max":Cc(n,"maximum",r.value,r.message,t)}return n};let Mc;const Lc=/^[cC][^\s-]{8,}$/,qc=/^[0-9a-z]+$/,Zc=/^[0-9A-HJKMNP-TV-Z]{26}$/,Fc=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Hc=()=>(void 0===Mc&&(Mc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Mc),Bc=/^(?:(?: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])$/,Wc=/^(([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])$/,Jc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kc=/^[a-zA-Z0-9_-]{21}$/,Gc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Yc(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Cc(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Cc(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ed(n,"email",r.message,t);break;case"format:idn-email":ed(n,"idn-email",r.message,t);break;case"pattern:zod":td(n,Fc,r.message,t)}break;case"url":ed(n,"uri",r.message,t);break;case"uuid":ed(n,"uuid",r.message,t);break;case"regex":td(n,r.regex,r.message,t);break;case"cuid":td(n,Lc,r.message,t);break;case"cuid2":td(n,qc,r.message,t);break;case"startsWith":td(n,RegExp(`^${Xc(r.value,t)}`),r.message,t);break;case"endsWith":td(n,RegExp(`${Xc(r.value,t)}$`),r.message,t);break;case"datetime":ed(n,"date-time",r.message,t);break;case"date":ed(n,"date",r.message,t);break;case"time":ed(n,"time",r.message,t);break;case"duration":ed(n,"duration",r.message,t);break;case"length":Cc(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Cc(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":td(n,RegExp(Xc(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&ed(n,"ipv4",r.message,t),"v4"!==r.version&&ed(n,"ipv6",r.message,t);break;case"base64url":td(n,Vc,r.message,t);break;case"jwt":td(n,Gc,r.message,t);break;case"cidr":"v6"!==r.version&&td(n,Bc,r.message,t),"v4"!==r.version&&td(n,Wc,r.message,t);break;case"emoji":td(n,Hc(),r.message,t);break;case"ulid":td(n,Zc,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":ed(n,"binary",r.message,t);break;case"contentEncoding:base64":Cc(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":td(n,Jc,r.message,t)}break;case"nanoid":td(n,Kc,r.message,t)}return n}function Xc(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)Qc.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const Qc=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ed(e,t,n,r){var o;e.format||(null==(o=e.anyOf)?void 0:o.some((e=>e.format)))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Cc(e,"format",t,n,r)}function td(e,t,n,r){var o;e.pattern||(null==(o=e.allOf)?void 0:o.some((e=>e.pattern)))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:nd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Cc(e,"pattern",nd(t,r),n,r)}function nd(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),o=e.flags.includes("m"),i=e.flags.includes("s"),s=r?e.source.toLowerCase():e.source;let a="",u=!1,l=!1,c=!1;for(let d=0;d<s.length;d++)if(u)a+=s[d],u=!1;else{if(r)if(l){if(s[d].match(/[a-z]/)){c?(a+=s[d],a+=`${s[d-2]}-${s[d]}`.toUpperCase(),c=!1):"-"===s[d+1]&&(null==(n=s[d+2])?void 0:n.match(/[a-z]/))?(a+=s[d],c=!0):a+=`${s[d]}${s[d].toUpperCase()}`;continue}}else if(s[d].match(/[a-z]/)){a+=`[${s[d]}${s[d].toUpperCase()}]`;continue}if(o){if("^"===s[d]){a+="(^|(?<=[\r\n]))";continue}if("$"===s[d]){a+="($|(?=[\r\n]))";continue}}i&&"."===s[d]?a+=l?`${s[d]}\r\n`:`[${s[d]}\r\n]`:(a+=s[d],"\\"===s[d]?u=!0:l&&"]"===s[d]?l=!1:l||"["!==s[d]||(l=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function rd(e,t){var n,r,o,i,s,a;if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&(null==(n=e.keyType)?void 0:n._def.typeName)===Sc.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((n,r)=>({...n,[r]:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??jc(t)})),{}),additionalProperties:t.rejectedAdditionalProperties};const u={type:"object",additionalProperties:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return u;if((null==(r=e.keyType)?void 0:r._def.typeName)===Sc.ZodString&&(null==(o=e.keyType._def.checks)?void 0:o.length)){const{type:n,...r}=Yc(e.keyType._def,t);return{...u,propertyNames:r}}if((null==(i=e.keyType)?void 0:i._def.typeName)===Sc.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if((null==(s=e.keyType)?void 0:s._def.typeName)===Sc.ZodBranded&&e.keyType._def.type._def.typeName===Sc.ZodString&&(null==(a=e.keyType._def.type._def.checks)?void 0:a.length)){const{type:n,...r}=Uc(e.keyType._def,t);return{...u,propertyNames:r}}return u}const od={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const id=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,n)=>ld(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return n.length?{anyOf:n}:void 0};function sd(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},o=[],i=e.shape();for(const a in i){let e=i[a];if(void 0===e||void 0===e._def)continue;let s=ad(e);s&&n&&("ZodOptional"===e._def.typeName&&(e=e._def.innerType),e.isNullable()||(e=e.nullable()),s=!1);const u=ld(e._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});void 0!==u&&(r.properties[a]=u,s||o.push(a))}o.length&&(r.required=o);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ld(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(r.additionalProperties=s),r}function ad(e){try{return e.isOptional()}catch{return!0}}const ud=(e,t,n)=>{switch(t){case Sc.ZodString:return Yc(e,n);case Sc.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Ac(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Cc(n,"minimum",r.value,r.message,t):Cc(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Cc(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Cc(n,"maximum",r.value,r.message,t):Cc(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Cc(n,"maximum",r.value,r.message,t));break;case"multipleOf":Cc(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Sc.ZodObject:return sd(e,n);case Sc.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Cc(n,"minimum",r.value,r.message,t):Cc(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Cc(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Cc(n,"maximum",r.value,r.message,t):Cc(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Cc(n,"maximum",r.value,r.message,t));break;case"multipleOf":Cc(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Sc.ZodBoolean:return{type:"boolean"};case Sc.ZodDate:return zc(e,n);case Sc.ZodUndefined:return function(e){return{not:jc(e)}}(n);case Sc.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case Sc.ZodArray:return function(e,t){var n,r,o;const i={type:"array"};return(null==(n=e.type)?void 0:n._def)&&(null==(o=null==(r=e.type)?void 0:r._def)?void 0:o.typeName)!==Sc.ZodAny&&(i.items=ld(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Cc(i,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Cc(i,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Cc(i,"minItems",e.exactLength.value,e.exactLength.message,t),Cc(i,"maxItems",e.exactLength.value,e.exactLength.message,t)),i}(e,n);case Sc.ZodUnion:case Sc.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return id(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((e=>e._def.typeName in od&&(!e._def.checks||!e._def.checks.length)))){const e=n.reduce(((e,t)=>{const n=od[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e}),[]);return{type:e.length>1?e:e[0]}}if(n.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=n.reduce(((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===n.length){const t=e.filter(((e,t,n)=>n.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:n.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(n.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:n.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return id(e,t)}(e,n);case Sc.ZodIntersection:return function(e,t){const n=[ld(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ld(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;o.push(t)}else o.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t})),o.length?{allOf:o,...r}:void 0}(e,n);case Sc.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,n)=>ld(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:ld(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,n)=>ld(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,n);case Sc.ZodRecord:return rd(e,n);case Sc.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case Sc.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Sc.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),r=Array.from(new Set(n.map((e=>typeof e))));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case Sc.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:od[e.innerType._def.typeName],nullable:!0}:{type:[od[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=ld(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ld(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case Sc.ZodOptional:return((e,t)=>{var n;if(t.currentPath.toString()===(null==(n=t.propertyPath)?void 0:n.toString()))return ld(e.innerType._def,t);const r=ld(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:jc(t)},r]}:jc(t)})(e,n);case Sc.ZodMap:return function(e,t){return"record"===t.mapStrategy?rd(e,t):{type:"array",maxItems:125,items:{type:"array",items:[ld(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||jc(t),ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||jc(t)],minItems:2,maxItems:2}}}(e,n);case Sc.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Cc(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Cc(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case Sc.ZodLazy:return()=>e.getter()._def;case Sc.ZodPromise:return function(e,t){return ld(e.type._def,t)}(e,n);case Sc.ZodNaN:case Sc.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:jc({...e,currentPath:[...e.currentPath,"not"]})}}(n);case Sc.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ld(e.schema._def,t):jc(t)}(e,n);case Sc.ZodAny:return jc(n);case Sc.ZodUnknown:return function(e){return jc(e)}(n);case Sc.ZodDefault:return function(e,t){return{...ld(e.innerType._def,t),default:e.defaultValue()}}(e,n);case Sc.ZodBranded:return Uc(e,n);case Sc.ZodReadonly:case Sc.ZodCatch:return((e,t)=>ld(e.innerType._def,t))(e,n);case Sc.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ld(e.in._def,t);if("output"===t.pipeStrategy)return ld(e.out._def,t);const n=ld(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ld(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter((e=>void 0!==e))}})(e,n);case Sc.ZodFunction:case Sc.ZodVoid:case Sc.ZodSymbol:default:return}};function ld(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const i=null==(r=t.override)?void 0:r.call(t,e,t,o,n);if(i!==Ec)return i}if(o&&!n){const e=cd(o,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const s=ud(e,e.typeName,t),a="function"==typeof s?ld(s(),t):s;if(a&&dd(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return i.jsonSchema=a,n}return i.jsonSchema=a,a}const cd=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Pc(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,n)=>t.currentPath[n]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),jc(t)):"seen"===t.$refStrategy?jc(t):void 0}},dd=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),pd=(e,t)=>{const n=Nc(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,r])=>({...e,[t]:ld(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??jc(n)})),{}):void 0;const o="string"==typeof t?t:"title"===(null==t?void 0:t.nameStrategy)||null==t?void 0:t.name,i=ld(e._def,void 0===o?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??jc(n),s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(i.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=void 0===o?r?{...i,[n.definitionPath]:r}:i:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:i}};return"jsonSchema7"===n.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function md(...e){return e.reduce(((e,t)=>({...e,...null!=t?t:{}})),{})}function _d(e){return Object.fromEntries([...e.headers])}var hd=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const e=n.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n[Math.random()*e|0];return r.join("")};if(null==e)return o;if(n.includes(r))throw new Je({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},gd=hd();function fd(e){return(e instanceof Error||e instanceof DOMException)&&("AbortError"===e.name||"ResponseAborted"===e.name||"TimeoutError"===e.name)}var vd=["fetch failed","failed to fetch"];function yd({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if("string"==typeof e)return e;if(null!=e)throw new mt({message:`${r} API key must be a string.`});if("undefined"==typeof process)throw new mt({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(null==(e=process.env[t]))throw new mt({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if("string"!=typeof e)throw new mt({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var bd=/"__proto__"\s*:/,kd=/"constructor"\s*:/;function wd(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===bd.test(e)&&!1===kd.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}function xd(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return wd(e)}finally{Error.stackTraceLimit=t}}var Id=Symbol.for("vercel.ai.validator");function Sd(e){return function(e){return"object"==typeof e&&null!==e&&Id in e&&!0===e[Id]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Et({value:e,cause:n.issues})}},{[Id]:!0,validate:n});var t,n}async function $d({value:e,schema:t}){const n=Sd(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Et.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Et.wrap({value:e,cause:r}),rawValue:e}}}async function Od({text:e,schema:t}){try{const n=xd(e);return null==t?n:async function({value:e,schema:t}){const n=await $d({value:e,schema:t});if(!n.success)throw Et.wrap({value:e,cause:n.error});return n.value}({value:n,schema:t})}catch(n){if(ut.isInstance(n)||Et.isInstance(n))throw n;throw new ut({text:e,cause:n})}}async function Td({text:e,schema:t}){try{const n=xd(e);return null==t?{success:!0,value:n,rawValue:n}:await $d({value:n,schema:t})}catch(n){return{success:!1,error:ut.isInstance(n)?n:new ut({text:e,cause:n}),rawValue:void 0}}}function Ed(e){try{return xd(e),!0}catch(t){return!1}}function Rd({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new zt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Td({text:e,schema:t}))}}))}async function Nd({provider:e,providerOptions:t,schema:n}){if(null==(null==t?void 0:t[e]))return;const r=await $d({value:t[e],schema:n});if(!r.success)throw new Je({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Ad=()=>globalThis.fetch,Cd=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s})=>Pd({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s}),Pd=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:i,fetch:s=Ad()})=>{try{const l=await s(e,{method:"POST",headers:(a=t,Object.fromEntries(Object.entries(a).filter((([e,t])=>null!=t)))),body:n.content,signal:i}),c=_d(l);if(!l.ok){let t;try{t=await o({response:l,url:e,requestBodyValues:n.values})}catch(u){if(fd(u)||Ue.isInstance(u))throw u;throw new Ue({message:"Failed to process error response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:l,url:e,requestBodyValues:n.values})}catch(u){if(u instanceof Error&&(fd(u)||Ue.isInstance(u)))throw u;throw new Ue({message:"Failed to process successful response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(u){throw function({error:e,url:t,requestBodyValues:n}){if(fd(e))return e;if(e instanceof TypeError&&vd.includes(e.message.toLowerCase())){const r=e.cause;if(null!=r)return new Ue({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}({error:u,url:e,requestBodyValues:n.values})}var a};function jd({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:o,execute:r,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u})}function Ud({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u})}async function zd(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var Dd=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:i})=>{const s=await r.text(),a=_d(r);if(""===s.trim())return{responseHeaders:a,value:new Ue({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})};try{const u=await Od({text:s,schema:e});return{responseHeaders:a,value:new Ue({message:t(u),url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,data:u,isRetryable:null==n?void 0:n(r,u)})}}catch(u){return{responseHeaders:a,value:new Ue({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})}}},Md=e=>async({response:t})=>{const n=_d(t);if(null==t.body)throw new qe({});return{responseHeaders:n,value:Rd({stream:t.body,schema:e})}},Ld=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),i=await Td({text:o,schema:e}),s=_d(t);if(!i.success)throw new Ue({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:s,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:s,value:i.value,rawValue:i.rawValue}};function qd(e,t){return function(e){return"_zod"in e}(e)?function(e){return Fd(hu(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Pu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return Fd(pd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var Zd=Symbol.for("vercel.ai.schema");function Fd(e,{validate:t}={}){return{[Zd]:!0,_type:void 0,[Id]:!0,jsonSchema:e,validate:t}}function Hd(e){return null==e?Fd({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&Zd in t&&!0===t[Zd]&&"jsonSchema"in t&&"validate"in t?e:qd(e);var t}var{btoa:Bd,atob:Wd}=globalThis;function Jd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Wd(t);return Uint8Array.from(n,(e=>e.codePointAt(0)))}function Vd(e){return e instanceof Uint8Array?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Bd(t)}(e):e}function Kd(e){return null==e?void 0:e.replace(/\/$/,"")}var Gd=Dd({errorSchema:Rl({type:Vl("error"),error:Rl({type:Du(),message:Du()})}),errorToMessage:e=>e.error.message}),Yd=Rl({citations:Rl({enabled:pl()}).optional(),title:Du().optional(),context:Du().optional()}),Xd=Rl({sendReasoning:pl().optional(),thinking:Rl({type:Pl([Vl("enabled"),Vl("disabled")]),budgetTokens:ul().optional()}).optional(),disableParallelToolUse:pl().optional()});function Qd(e){var t;const n=null==e?void 0:e.anthropic;return null!=(t=null==n?void 0:n.cacheControl)?t:null==n?void 0:n.cache_control}var ep=Rl({maxUses:ul().optional(),allowedDomains:Tl(Du()).optional(),blockedDomains:Tl(Du()).optional(),userLocation:Rl({type:Vl("approximate"),city:Du().optional(),region:Du().optional(),country:Du().optional(),timezone:Du().optional()}).optional()}),tp=Tl(Rl({url:Du(),title:Du(),pageAge:Du().nullable(),encryptedContent:Du(),type:Du()})),np=Ud({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Rl({query:Du()}),outputSchema:tp});function rp(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var op=Rl({type:Vl("code_execution_result"),stdout:Du(),stderr:Du(),return_code:ul()}),ip=Ud({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Rl({code:Du()}),outputSchema:op});function sp(e){if("string"==typeof e)return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return(new TextDecoder).decode(e);if(e instanceof URL)throw new Ct({functionality:"URL-based text documents are not supported for citations"});throw new Ct({functionality:"unsupported data type for text documents: "+typeof e})}async function ap({prompt:e,sendReasoning:t,warnings:n}){var r,o,i,s,a;const u=new Set,l=function(e){const t=[];let n;for(const r of e){const{role:e}=r;switch(e){case"system":"system"!==(null==n?void 0:n.type)&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break;case"assistant":"assistant"!==(null==n?void 0:n.type)&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break;case"user":case"tool":"user"!==(null==n?void 0:n.type)&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break;default:throw new Error(`Unsupported role: ${e}`)}}return t}(e);let c;const d=[];async function p(e){var t,n;const r=await Nd({provider:"anthropic",providerOptions:e,schema:Yd});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function m(e){const t=await Nd({provider:"anthropic",providerOptions:e,schema:Yd});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let _=0;_<l.length;_++){const e=l[_],h=_===l.length-1,g=e.type;switch(g){case"system":if(null!=c)throw new Ct({functionality:"Multiple system messages that are separated by user/assistant messages"});c=e.messages.map((({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:Qd(t)})));break;case"user":{const t=[];for(const n of e.messages){const{role:e,content:a}=n;switch(e){case"user":for(let e=0;e<a.length;e++){const s=a[e],l=e===a.length-1,c=null!=(r=Qd(s.providerOptions))?r:l?Qd(n.providerOptions):void 0;switch(s.type){case"text":t.push({type:"text",text:s.text,cache_control:c});break;case"file":if(s.mediaType.startsWith("image/"))t.push({type:"image",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"image/*"===s.mediaType?"image/jpeg":s.mediaType,data:Vd(s.data)},cache_control:c});else if("application/pdf"===s.mediaType){u.add("pdfs-2024-09-25");const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"application/pdf",data:Vd(s.data)},title:null!=(o=n.title)?o:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}else{if("text/plain"!==s.mediaType)throw new Ct({functionality:`media type: ${s.mediaType}`});{const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"text",media_type:"text/plain",data:sp(s.data)},title:null!=(i=n.title)?i:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}}}}break;case"tool":for(let e=0;e<a.length;e++){const r=a[e],o=e===a.length-1,i=null!=(s=Qd(r.providerOptions))?s:o?Qd(n.providerOptions):void 0,u=r.output;let l;switch(u.type){case"content":l=u.value.map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,cache_control:void 0};case"media":if(e.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data},cache_control:void 0};throw new Ct({functionality:`media type: ${e.mediaType}`})}}));break;case"text":case"error-text":l=u.value;break;default:l=JSON.stringify(u.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:l,is_error:"error-text"===u.type||"error-json"===u.type||void 0,cache_control:i})}break;default:throw new Error(`Unsupported role: ${e}`)}}d.push({role:"user",content:t});break}case"assistant":{const r=[];for(let o=0;o<e.messages.length;o++){const i=e.messages[o],s=o===e.messages.length-1,{content:u}=i;for(let e=0;e<u.length;e++){const o=u[e],l=e===u.length-1,c=null!=(a=Qd(o.providerOptions))?a:l?Qd(i.providerOptions):void 0;switch(o.type){case"text":r.push({type:"text",text:h&&s&&l?o.text.trim():o.text,cache_control:c});break;case"reasoning":if(t){const e=await Nd({provider:"anthropic",providerOptions:o.providerOptions,schema:hp});null!=e?null!=e.signature?r.push({type:"thinking",thinking:o.text,signature:e.signature,cache_control:c}):null!=e.redactedData?r.push({type:"redacted_thinking",data:e.redactedData,cache_control:c}):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":if(o.providerExecuted){if("web_search"===o.toolName){r.push({type:"server_tool_use",id:o.toolCallId,name:"web_search",input:o.input,cache_control:c});break}if("code_execution"===o.toolName){r.push({type:"server_tool_use",id:o.toolCallId,name:"code_execution",input:o.input,cache_control:c});break}n.push({type:"other",message:`provider executed tool call for tool ${o.toolName} is not supported`});break}r.push({type:"tool_use",id:o.toolCallId,name:o.toolName,input:o.input,cache_control:c});break;case"tool-result":if("web_search"===o.toolName){const e=o.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${o.toolName} is not supported`});break}const t=tp.parse(e.value);r.push({type:"web_search_tool_result",tool_use_id:o.toolCallId,content:t.map((e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type}))),cache_control:c});break}if("code_execution"===o.toolName){const e=o.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${o.toolName} is not supported`});break}const t=op.parse(e.value);r.push({type:"code_execution_tool_result",tool_use_id:o.toolCallId,content:{type:t.type,stdout:t.stdout,stderr:t.stderr,return_code:t.return_code},cache_control:c});break}n.push({type:"other",message:`provider executed tool result for tool ${o.toolName} is not supported`})}}}d.push({role:"assistant",content:r});break}default:throw new Error(`content type: ${g}`)}}return{prompt:{system:c,messages:d},betas:u}}function up({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var lp={webSearchResult:Rl({type:Vl("web_search_result_location"),cited_text:Du(),url:Du(),title:Du(),encrypted_index:Du()}),pageLocation:Rl({type:Vl("page_location"),cited_text:Du(),document_index:ul(),document_title:Du().nullable(),start_page_number:ul(),end_page_number:ul()}),charLocation:Rl({type:Vl("char_location"),cited_text:Du(),document_index:ul(),document_title:Du().nullable(),start_char_index:ul(),end_char_index:ul()})},cp=Ul("type",[lp.webSearchResult,lp.pageLocation,lp.charLocation]);function dp(e,t,n,r){if("page_location"===e.type||"char_location"===e.type){const o=function(e,t,n){var r;const o=t[e.document_index];if(!o)return null;const i="page_location"===e.type?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:"source",sourceType:"document",id:n(),mediaType:o.mediaType,title:null!=(r=e.document_title)?r:o.title,filename:o.filename,providerMetadata:{anthropic:i}}}(e,t,n);o&&r(o)}}Ul("type",[lp.pageLocation,lp.charLocation]);var pp=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:gd}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_,h;const g=[];null!=i&&g.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=s&&g.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=l&&g.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==u?void 0:u.type)&&(null==u.schema?g.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):null!=c&&g.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const f="json"===(null==u?void 0:u.type)&&null!=u.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:u.schema}:void 0,v=await Nd({provider:"anthropic",providerOptions:p,schema:Xd}),{prompt:y,betas:b}=await ap({prompt:e,sendReasoning:null==(m=null==v?void 0:v.sendReasoning)||m,warnings:g}),k="enabled"===(null==(_=null==v?void 0:v.thinking)?void 0:_.type),w=null==(h=null==v?void 0:v.thinking)?void 0:h.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:o,top_p:r,stop_sequences:a,...k&&{thinking:{type:"enabled",budget_tokens:w}},system:y.system,messages:y.messages};if(k){if(null==w)throw new Ct({functionality:"thinking requires a budget"});null!=x.temperature&&(x.temperature=void 0,g.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=o&&(x.top_k=void 0,g.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),null!=r&&(x.top_p=void 0,g.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),x.max_tokens=t+w}const{tools:I,toolChoice:S,toolWarnings:$,betas:O}=function({tools:e,toolChoice:t,disableParallelToolUse:n}){e=(null==e?void 0:e.length)?e:void 0;const r=[],o=new Set;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:o};const i=[];for(const a of e)if(rp(a))i.push(a);else switch(a.type){case"function":const e=Qd(a.providerOptions);i.push({name:a.name,description:a.description,input_schema:a.inputSchema,cache_control:e});break;case"provider-defined":switch(a.id){case"anthropic.computer_20250124":o.add("computer-use-2025-01-24"),i.push({name:"computer",type:"computer_20250124",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.computer_20241022":o.add("computer-use-2024-10-22"),i.push({name:"computer",type:"computer_20241022",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),i.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":o.add("computer-use-2025-01-24"),i.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":o.add("computer-use-2024-10-22"),i.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{const e=ep.parse(a.args);i.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case"anthropic.code_execution_20250522":o.add("code-execution-2025-05-22"),i.push({type:"code_execution_20250522",name:"code_execution"});break;default:r.push({type:"unsupported-tool",tool:a})}break;default:r.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:i,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:o};const s=t.type;switch(s){case"auto":return{tools:i,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:r,betas:o};case"required":return{tools:i,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:r,betas:o};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:o};case"tool":return{tools:i,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:o};default:throw new Ct({functionality:`tool choice type: ${s}`})}}(null!=f?{tools:[f],toolChoice:{type:"tool",toolName:f.name},disableParallelToolUse:null==v?void 0:v.disableParallelToolUse}:{tools:null!=c?c:[],toolChoice:d,disableParallelToolUse:null==v?void 0:v.disableParallelToolUse});return{args:{...x,tools:I,tool_choice:S},warnings:[...g,...$],betas:new Set([...b,...O]),usesJsonResponseTool:null!=f}}async getHeaders({betas:e,headers:t}){return md(await zd(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{},t)}buildRequestUrl(e){var t,n,r;return null!=(r=null==(n=(t=this.config).buildRequestUrl)?void 0:n.call(t,this.config.baseURL,e))?r:`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return null!=(r=null==(n=(t=this.config).transformRequestBody)?void 0:n.call(t,e))?r:e}extractCitationDocuments(e){return e.filter((e=>"user"===e.role)).flatMap((e=>e.content)).filter((e=>{var t,n;if("file"!==e.type)return!1;if("application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;const r=null==(t=e.providerOptions)?void 0:t.anthropic,o=null==r?void 0:r.citations;return null!=(n=null==o?void 0:o.enabled)&&n})).map((e=>{var t;const n=e;return{title:null!=(t=n.filename)?t:"Untitled Document",filename:n.filename,mediaType:n.mediaType}}))}async doGenerate(e){var t,n,r,o,i;const{args:s,warnings:a,betas:u,usesJsonResponseTool:l}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:m}=await Cd({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:u,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Gd,successfulResponseHandler:Ld(mp),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=[];for(const h of p.content)switch(h.type){case"text":if(!l&&(_.push({type:"text",text:h.text}),h.citations))for(const e of h.citations)dp(e,c,this.generateId,(e=>_.push(e)));break;case"thinking":_.push({type:"reasoning",text:h.thinking,providerMetadata:{anthropic:{signature:h.signature}}});break;case"redacted_thinking":_.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:h.data}}});break;case"tool_use":_.push(l?{type:"text",text:JSON.stringify(h.input)}:{type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input)});break;case"server_tool_use":"web_search"!==h.name&&"code_execution"!==h.name||_.push({type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input),providerExecuted:!0});break;case"web_search_tool_result":if(Array.isArray(h.content)){_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",result:h.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const e of h.content)_.push({type:"source",sourceType:"url",id:this.generateId(),url:e.url,title:e.title,providerMetadata:{anthropic:{pageAge:null!=(t=e.page_age)?t:null}}})}else _.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0});break;case"code_execution_tool_result":"code_execution_result"===h.content.type?_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",result:{type:h.content.type,stdout:h.content.stdout,stderr:h.content.stderr,return_code:h.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===h.content.type&&_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0})}return{content:_,finishReason:up({finishReason:p.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:null!=(n=p.usage.cache_read_input_tokens)?n:void 0},request:{body:s},response:{id:null!=(r=p.id)?r:void 0,modelId:null!=(o=p.model)?o:void 0,headers:d,body:m},warnings:a,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:null!=(i=p.usage.cache_creation_input_tokens)?i:null}}}}async doStream(e){const{args:t,warnings:n,betas:r,usesJsonResponseTool:o}=await this.getArgs(e),i=this.extractCitationDocuments(e.prompt),s={...t,stream:!0},{responseHeaders:a,value:u}=await Cd({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Gd,successfulResponseHandler:Md(_p),abortSignal:e.abortSignal,fetch:this.config.fetch});let l="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,m;const _=this.generateId;return{stream:u.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,u,h,g,f;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const v=t.value;switch(v.type){case"ping":return;case"content_block_start":{const e=v.content_block.type;switch(m=e,e){case"text":return d[v.index]={type:"text"},void n.enqueue({type:"text-start",id:String(v.index)});case"thinking":return d[v.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(v.index)});case"redacted_thinking":return d[v.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(v.index),providerMetadata:{anthropic:{redactedData:v.content_block.data}}});case"tool_use":return d[v.index]=o?{type:"text"}:{type:"tool-call",toolCallId:v.content_block.id,toolName:v.content_block.name,input:""},void n.enqueue(o?{type:"text-start",id:String(v.index)}:{type:"tool-input-start",id:v.content_block.id,toolName:v.content_block.name});case"server_tool_use":return void("web_search"!==v.content_block.name&&"code_execution"!==v.content_block.name||(d[v.index]={type:"tool-call",toolCallId:v.content_block.id,toolName:v.content_block.name,input:"",providerExecuted:!0},n.enqueue({type:"tool-input-start",id:v.content_block.id,toolName:v.content_block.name,providerExecuted:!0})));case"web_search_tool_result":{const e=v.content_block;if(Array.isArray(e.content)){n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",result:e.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const t of e.content)n.enqueue({type:"source",sourceType:"url",id:_(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}})}else n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const e=v.content_block;return void("code_execution_result"===e.content.type?n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===e.content.type&&n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0}))}default:throw new Error(`Unsupported content block type: ${e}`)}}case"content_block_stop":if(null!=d[v.index]){const e=d[v.index];switch(e.type){case"text":n.enqueue({type:"text-end",id:String(v.index)});break;case"reasoning":n.enqueue({type:"reasoning-end",id:String(v.index)});break;case"tool-call":o||(n.enqueue({type:"tool-input-end",id:e.toolCallId}),n.enqueue(e))}delete d[v.index]}return void(m=void 0);case"content_block_delta":{const e=v.delta.type;switch(e){case"text_delta":if(o)return;return void n.enqueue({type:"text-delta",id:String(v.index),delta:v.delta.text});case"thinking_delta":return void n.enqueue({type:"reasoning-delta",id:String(v.index),delta:v.delta.thinking});case"signature_delta":return void("thinking"===m&&n.enqueue({type:"reasoning-delta",id:String(v.index),delta:"",providerMetadata:{anthropic:{signature:v.delta.signature}}}));case"input_json_delta":{const e=d[v.index],t=v.delta.partial_json;if(o){if("text"!==(null==e?void 0:e.type))return;n.enqueue({type:"text-delta",id:String(v.index),delta:t})}else{if("tool-call"!==(null==e?void 0:e.type))return;n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t}return}case"citations_delta":return void dp(v.delta.citation,i,_,(e=>n.enqueue(e)));default:throw new Error(`Unsupported delta type: ${e}`)}}case"message_start":return c.inputTokens=v.message.usage.input_tokens,c.cachedInputTokens=null!=(s=v.message.usage.cache_read_input_tokens)?s:void 0,p={anthropic:{usage:v.message.usage,cacheCreationInputTokens:null!=(a=v.message.usage.cache_creation_input_tokens)?a:null}},void n.enqueue({type:"response-metadata",id:null!=(u=v.message.id)?u:void 0,modelId:null!=(h=v.message.model)?h:void 0});case"message_delta":return c.outputTokens=v.usage.output_tokens,c.totalTokens=(null!=(g=c.inputTokens)?g:0)+(null!=(f=v.usage.output_tokens)?f:0),void(l=up({finishReason:v.delta.stop_reason,isJsonResponseFromTool:o}));case"message_stop":return void n.enqueue({type:"finish",finishReason:l,usage:c,providerMetadata:p});case"error":return void n.enqueue({type:"error",error:v.error});default:throw new Error(`Unsupported chunk type: ${v}`)}}})),request:{body:s},response:{headers:a}}}},mp=Rl({type:Vl("message"),id:Du().nullish(),model:Du().nullish(),content:Tl(Ul("type",[Rl({type:Vl("text"),text:Du(),citations:Tl(cp).optional()}),Rl({type:Vl("thinking"),thinking:Du(),signature:Du()}),Rl({type:Vl("redacted_thinking"),data:Du()}),Rl({type:Vl("tool_use"),id:Du(),name:Du(),input:wl()}),Rl({type:Vl("server_tool_use"),id:Du(),name:Du(),input:Zl(Du(),wl()).nullish()}),Rl({type:Vl("web_search_tool_result"),tool_use_id:Du(),content:Pl([Tl(Rl({type:Vl("web_search_result"),url:Du(),title:Du(),encrypted_content:Du(),page_age:Du().nullish()})),Rl({type:Vl("web_search_tool_result_error"),error_code:Du()})])}),Rl({type:Vl("code_execution_tool_result"),tool_use_id:Du(),content:Pl([Rl({type:Vl("code_execution_result"),stdout:Du(),stderr:Du(),return_code:ul()}),Rl({type:Vl("code_execution_tool_result_error"),error_code:Du()})])})])),stop_reason:Du().nullish(),usage:Al({input_tokens:ul(),output_tokens:ul(),cache_creation_input_tokens:ul().nullish(),cache_read_input_tokens:ul().nullish()})}),_p=Ul("type",[Rl({type:Vl("message_start"),message:Rl({id:Du().nullish(),model:Du().nullish(),usage:Al({input_tokens:ul(),output_tokens:ul(),cache_creation_input_tokens:ul().nullish(),cache_read_input_tokens:ul().nullish()})})}),Rl({type:Vl("content_block_start"),index:ul(),content_block:Ul("type",[Rl({type:Vl("text"),text:Du()}),Rl({type:Vl("thinking"),thinking:Du()}),Rl({type:Vl("tool_use"),id:Du(),name:Du()}),Rl({type:Vl("redacted_thinking"),data:Du()}),Rl({type:Vl("server_tool_use"),id:Du(),name:Du(),input:Zl(Du(),wl()).nullish()}),Rl({type:Vl("web_search_tool_result"),tool_use_id:Du(),content:Pl([Tl(Rl({type:Vl("web_search_result"),url:Du(),title:Du(),encrypted_content:Du(),page_age:Du().nullish()})),Rl({type:Vl("web_search_tool_result_error"),error_code:Du()})])}),Rl({type:Vl("code_execution_tool_result"),tool_use_id:Du(),content:Pl([Rl({type:Vl("code_execution_result"),stdout:Du(),stderr:Du(),return_code:ul()}),Rl({type:Vl("code_execution_tool_result_error"),error_code:Du()})])})])}),Rl({type:Vl("content_block_delta"),index:ul(),delta:Ul("type",[Rl({type:Vl("input_json_delta"),partial_json:Du()}),Rl({type:Vl("text_delta"),text:Du()}),Rl({type:Vl("thinking_delta"),thinking:Du()}),Rl({type:Vl("signature_delta"),signature:Du()}),Rl({type:Vl("citations_delta"),citation:cp})])}),Rl({type:Vl("content_block_stop"),index:ul()}),Rl({type:Vl("error"),error:Rl({type:Du(),message:Du()})}),Rl({type:Vl("message_delta"),delta:Rl({stop_reason:Du().nullish()}),usage:Rl({output_tokens:ul()})}),Rl({type:Vl("message_stop")}),Rl({type:Vl("ping")})]),hp=Rl({signature:Du().optional(),redactedData:Du().optional()}),gp=jd({id:"anthropic.bash_20241022",name:"bash",inputSchema:Tc.object({command:Tc.string(),restart:Tc.boolean().optional()})}),fp=jd({id:"anthropic.bash_20250124",name:"bash",inputSchema:Tc.object({command:Tc.string(),restart:Tc.boolean().optional()})}),vp=jd({id:"anthropic.computer_20241022",name:"computer",inputSchema:Rl({action:Wl(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:Tl(ul().int()).optional(),text:Du().optional()})}),yp=jd({id:"anthropic.computer_20250124",name:"computer",inputSchema:Rl({action:Wl(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ll([ul().int(),ul().int()]).optional(),duration:ul().optional(),scroll_amount:ul().optional(),scroll_direction:Wl(["up","down","left","right"]).optional(),start_coordinate:Ll([ul().int(),ul().int()]).optional(),text:Du().optional()})}),bp={bash_20241022:gp,bash_20250124:fp,textEditor_20241022:jd({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Rl({command:Wl(["view","create","str_replace","insert","undo_edit"]),path:Du(),file_text:Du().optional(),insert_line:ul().int().optional(),new_str:Du().optional(),old_str:Du().optional(),view_range:Tl(ul().int()).optional()})}),textEditor_20250124:jd({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:Rl({command:Wl(["view","create","str_replace","insert","undo_edit"]),path:Du(),file_text:Du().optional(),insert_line:ul().int().optional(),new_str:Du().optional(),old_str:Du().optional(),view_range:Tl(ul().int()).optional()})}),textEditor_20250429:jd({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Rl({command:Wl(["view","create","str_replace","insert"]),path:Du(),file_text:Du().optional(),insert_line:ul().int().optional(),new_str:Du().optional(),old_str:Du().optional(),view_range:Tl(ul().int()).optional()})}),computer_20241022:vp,computer_20250124:yp,webSearch_20250305:(e={})=>np(e),codeExecution_20250522:(e={})=>ip(e)};function kp(e={}){var t;const n=null!=(t=Kd(e.baseURL))?t:"https://api.anthropic.com/v1",r=()=>({"anthropic-version":"2023-06-01","x-api-key":yd({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers}),o=t=>{var o;return new pp(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(o=e.generateId)?o:gd,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},i=function(e){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(e)};return i.languageModel=o,i.chat=o,i.messages=o,i.textEmbeddingModel=e=>{throw new vt({modelId:e,modelType:"textEmbeddingModel"})},i.imageModel=e=>{throw new vt({modelId:e,modelType:"imageModel"})},i.tools=bp,i}kp();var wp=Dd({errorSchema:Rl({error:Rl({code:ul().nullable(),message:Du(),status:Du()})}),errorToMessage:e=>e.error.message}),xp=Rl({outputDimensionality:ul().optional(),taskType:Wl(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),Ip=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){const o=await Nd({provider:"google",providerOptions:r,schema:xp});if(e.length>this.maxEmbeddingsPerCall)throw new xt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=md(await zd(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await Cd({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:i,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:null==o?void 0:o.outputDimensionality,taskType:null==o?void 0:o.taskType},failedResponseHandler:wp,successfulResponseHandler:Ld($p),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:s}}}const{responseHeaders:s,value:a,rawValue:u}=await Cd({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:i,body:{requests:e.map((e=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:e}]},outputDimensionality:null==o?void 0:o.outputDimensionality,taskType:null==o?void 0:o.taskType})))},failedResponseHandler:wp,successfulResponseHandler:Ld(Sp),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map((e=>e.values)),usage:void 0,response:{headers:s,body:u}}}},Sp=Rl({embeddings:Tl(Rl({values:Tl(ul())}))}),$p=Rl({embedding:Rl({values:Tl(ul())})});function Op(e){if(null==e||function(e){return null!=e&&"object"==typeof e&&"object"===e.type&&(null==e.properties||0===Object.keys(e.properties).length)&&!e.additionalProperties}(e))return;if("boolean"==typeof e)return{type:"boolean",properties:{}};const{type:t,description:n,required:r,properties:o,items:i,allOf:s,anyOf:a,oneOf:u,format:l,const:c,minLength:d,enum:p}=e,m={};if(n&&(m.description=n),r&&(m.required=r),l&&(m.format=l),void 0!==c&&(m.enum=[c]),t&&(Array.isArray(t)?t.includes("null")?(m.type=t.filter((e=>"null"!==e))[0],m.nullable=!0):m.type=t:m.type="null"===t?"null":t),void 0!==p&&(m.enum=p),null!=o&&(m.properties=Object.entries(o).reduce(((e,[t,n])=>(e[t]=Op(n),e)),{})),i&&(m.items=Array.isArray(i)?i.map(Op):Op(i)),s&&(m.allOf=s.map(Op)),a)if(a.some((e=>"object"==typeof e&&"null"===(null==e?void 0:e.type)))){const e=a.filter((e=>!("object"==typeof e&&"null"===(null==e?void 0:e.type))));if(1===e.length){const t=Op(e[0]);"object"==typeof t&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(Op),m.nullable=!0}else m.anyOf=a.map(Op);return u&&(m.oneOf=u.map(Op)),void 0!==d&&(m.minLength=d),m}function Tp(e){return e.includes("/")?e:`models/${e}`}var Ep=Rl({responseModalities:Tl(Wl(["TEXT","IMAGE"])).optional(),thinkingConfig:Rl({thinkingBudget:ul().optional(),includeThoughts:pl().optional()}).optional(),cachedContent:Du().optional(),structuredOutputs:pl().optional(),safetySettings:Tl(Rl({category:Wl(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Wl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Wl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:pl().optional(),labels:Zl(Du(),Du()).optional()});function Rp({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var Np=Rl({web:Rl({uri:Du(),title:Du()}).nullish(),retrievedContext:Rl({uri:Du(),title:Du()}).nullish()}),Ap=Rl({webSearchQueries:Tl(Du()).nullish(),retrievalQueries:Tl(Du()).nullish(),searchEntryPoint:Rl({renderedContent:Du()}).nullish(),groundingChunks:Tl(Np).nullish(),groundingSupports:Tl(Rl({segment:Rl({startIndex:ul().nullish(),endIndex:ul().nullish(),text:Du().nullish()}),segment_text:Du().nullish(),groundingChunkIndices:Tl(ul()).nullish(),supportChunkIndices:Tl(ul()).nullish(),confidenceScores:Tl(ul()).nullish(),confidenceScore:Tl(ul()).nullish()})).nullish(),retrievalMetadata:Pl([Rl({webDynamicRetrievalScore:ul()}),Rl({})]).nullish()}),Cp=jd({id:"google.google_search",name:"google_search",inputSchema:Rl({mode:Wl(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:ul().default(1)})}),Pp=Rl({retrievedUrl:Du(),urlRetrievalStatus:Du()}),jp=Rl({urlMetadata:Tl(Pp)}),Up=jd({id:"google.url_context",name:"url_context",inputSchema:Rl({})}),zp=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:gd}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_;const h=[],g=await Nd({provider:"google",providerOptions:p,schema:Ep});!0!==(null==(m=null==g?void 0:g.thinkingConfig)?void 0:m.includeThoughts)||this.config.provider.startsWith("google.vertex.")||h.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});const f=this.modelId.toLowerCase().startsWith("gemma-"),{contents:v,systemInstruction:y}=function(e,t){var n;const r=[],o=[];let i=!0;const s=null!=(n=null==t?void 0:t.isGemmaModel)&&n;for(const{role:a,content:u}of e)switch(a){case"system":if(!i)throw new Ct({functionality:"system messages are only supported at the beginning of the conversation"});r.push({text:u});break;case"user":{i=!1;const e=[];for(const t of u)switch(t.type){case"text":e.push({text:t.text});break;case"file":{const n="image/*"===t.mediaType?"image/jpeg":t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:Vd(t.data)}});break}}o.push({role:"user",parts:e});break}case"assistant":i=!1,o.push({role:"model",parts:u.map((e=>{var t,n,r,o,i,s;switch(e.type){case"text":return 0===e.text.length?void 0:{text:e.text,thoughtSignature:null==(n=null==(t=e.providerOptions)?void 0:t.google)?void 0:n.thoughtSignature};case"reasoning":return 0===e.text.length?void 0:{text:e.text,thought:!0,thoughtSignature:null==(o=null==(r=e.providerOptions)?void 0:r.google)?void 0:o.thoughtSignature};case"file":if("image/png"!==e.mediaType)throw new Ct({functionality:"Only PNG images are supported in assistant messages"});if(e.data instanceof URL)throw new Ct({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:e.mediaType,data:Vd(e.data)}};case"tool-call":return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:null==(s=null==(i=e.providerOptions)?void 0:i.google)?void 0:s.thoughtSignature}}})).filter((e=>void 0!==e))});break;case"tool":i=!1,o.push({role:"user",parts:u.map((e=>({functionResponse:{name:e.toolName,response:{name:e.toolName,content:e.output.value}}})))})}if(s&&r.length>0&&o.length>0&&"user"===o[0].role){const e=r.map((e=>e.text)).join("\n\n");o[0].parts.unshift({text:e+"\n\n"})}return{systemInstruction:r.length>0&&!s?{parts:r}:void 0,contents:o}}(e,{isGemmaModel:f}),{tools:b,toolConfig:k,toolWarnings:w}=function({tools:e,toolChoice:t,modelId:n}){var r;e=(null==e?void 0:e.length)?e:void 0;const o=[],i=n.includes("gemini-2"),s=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(null==e)return{tools:void 0,toolConfig:void 0,toolWarnings:o};const a=e.some((e=>"function"===e.type)),u=e.some((e=>"provider-defined"===e.type));if(a&&u&&o.push({type:"unsupported-tool",tool:e.find((e=>"function"===e.type)),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."}),u){const t={};return e.filter((e=>"provider-defined"===e.type)).forEach((e=>{switch(e.id){case"google.google_search":i?t.googleSearch={}:t.googleSearchRetrieval=s?{dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:{};break;case"google.url_context":i?t.urlContext={}:o.push({type:"unsupported-tool",tool:e,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?t.codeExecution={}:o.push({type:"unsupported-tool",tool:e,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:o.push({type:"unsupported-tool",tool:e})}})),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:o}}const l=[];for(const d of e)"function"===d.type?l.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:Op(d.inputSchema)}):o.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:o};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:o};default:throw new Ct({functionality:`tool choice type: ${c}`})}}({tools:c,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:o,topP:r,frequencyPenalty:i,presencePenalty:s,stopSequences:a,seed:l,responseMimeType:"json"===(null==u?void 0:u.type)?"application/json":void 0,responseSchema:"json"!==(null==u?void 0:u.type)||null==u.schema||null!=(_=null==g?void 0:g.structuredOutputs)&&!_?void 0:Op(u.schema),...(null==g?void 0:g.audioTimestamp)&&{audioTimestamp:g.audioTimestamp},responseModalities:null==g?void 0:g.responseModalities,thinkingConfig:null==g?void 0:g.thinkingConfig},contents:v,systemInstruction:f?void 0:y,safetySettings:null==g?void 0:g.safetySettings,tools:b,toolConfig:k,cachedContent:null==g?void 0:g.cachedContent,labels:null==g?void 0:g.labels},warnings:[...h,...w]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p;const{args:m,warnings:_}=await this.getArgs(e),h=JSON.stringify(m),g=md(await zd(this.config.headers),e.headers),{responseHeaders:f,value:v,rawValue:y}=await Cd({url:`${this.config.baseURL}/${Tp(this.modelId)}:generateContent`,headers:g,body:m,failedResponseHandler:wp,successfulResponseHandler:Ld(Zp),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.candidates[0],k=[],w=null!=(n=null==(t=b.content)?void 0:t.parts)?n:[],x=v.usageMetadata;let I;for(const $ of w)if("executableCode"in $&&(null==(r=$.executableCode)?void 0:r.code)){const e=this.config.generateId();I=e,k.push({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify($.executableCode),providerExecuted:!0})}else"codeExecutionResult"in $&&$.codeExecutionResult?(k.push({type:"tool-result",toolCallId:I,toolName:"code_execution",result:{outcome:$.codeExecutionResult.outcome,output:$.codeExecutionResult.output},providerExecuted:!0}),I=void 0):"text"in $&&null!=$.text&&$.text.length>0?k.push({type:!0===$.thought?"reasoning":"text",text:$.text,providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"functionCall"in $?k.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:$.functionCall.name,input:JSON.stringify($.functionCall.args),providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"inlineData"in $&&k.push({type:"file",data:$.inlineData.data,mediaType:$.inlineData.mimeType});const S=null!=(o=Dp({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))?o:[];for(const $ of S)k.push($);return{content:k,finishReason:Rp({finishReason:b.finishReason,hasToolCalls:k.some((e=>"tool-call"===e.type))}),usage:{inputTokens:null!=(i=null==x?void 0:x.promptTokenCount)?i:void 0,outputTokens:null!=(s=null==x?void 0:x.candidatesTokenCount)?s:void 0,totalTokens:null!=(a=null==x?void 0:x.totalTokenCount)?a:void 0,reasoningTokens:null!=(u=null==x?void 0:x.thoughtsTokenCount)?u:void 0,cachedInputTokens:null!=(l=null==x?void 0:x.cachedContentTokenCount)?l:void 0},warnings:_,providerMetadata:{google:{groundingMetadata:null!=(c=b.groundingMetadata)?c:null,urlContextMetadata:null!=(d=b.urlContextMetadata)?d:null,safetyRatings:null!=(p=b.safetyRatings)?p:null,usageMetadata:null!=x?x:null}},request:{body:h},response:{headers:f,body:y}}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),o=md(await zd(this.config.headers),e.headers),{responseHeaders:i,value:s}=await Cd({url:`${this.config.baseURL}/${Tp(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:t,failedResponseHandler:wp,successfulResponseHandler:Md(Fp),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l;const c=this.config.generateId;let d=!1,p=null,m=null,_=0;const h=new Set;let g;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,i,s,f,v,y,b,k,w,x;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const I=t.value,S=I.usageMetadata;null!=S&&(u.inputTokens=null!=(r=S.promptTokenCount)?r:void 0,u.outputTokens=null!=(o=S.candidatesTokenCount)?o:void 0,u.totalTokens=null!=(i=S.totalTokenCount)?i:void 0,u.reasoningTokens=null!=(s=S.thoughtsTokenCount)?s:void 0,u.cachedInputTokens=null!=(f=S.cachedContentTokenCount)?f:void 0);const $=null==(v=I.candidates)?void 0:v[0];if(null==$)return;const O=$.content,T=Dp({groundingMetadata:$.groundingMetadata,generateId:c});if(null!=T)for(const e of T)"url"!==e.sourceType||h.has(e.url)||(h.add(e.url),n.enqueue(e));if(null!=O){const e=null!=(y=O.parts)?y:[];for(const o of e)if("executableCode"in o&&(null==(b=o.executableCode)?void 0:b.code)){const e=c();g=e,n.enqueue({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(o.executableCode),providerExecuted:!0}),d=!0}else if("codeExecutionResult"in o&&o.codeExecutionResult){const e=g;e&&(n.enqueue({type:"tool-result",toolCallId:e,toolName:"code_execution",result:{outcome:o.codeExecutionResult.outcome,output:o.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else"text"in o&&null!=o.text&&o.text.length>0&&(!0===o.thought?(null!==p&&(n.enqueue({type:"text-end",id:p}),p=null),null===m&&(m=String(_++),n.enqueue({type:"reasoning-start",id:m,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})),n.enqueue({type:"reasoning-delta",id:m,delta:o.text,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})):(null!==m&&(n.enqueue({type:"reasoning-end",id:m}),m=null),null===p&&(p=String(_++),n.enqueue({type:"text-start",id:p,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})),n.enqueue({type:"text-delta",id:p,delta:o.text,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})));const t=function(e){return null==e?void 0:e.filter((e=>"inlineData"in e))}(O.parts);if(null!=t)for(const o of t)n.enqueue({type:"file",mediaType:o.inlineData.mimeType,data:o.inlineData.data});const r=function({parts:e,generateId:t}){const n=null==e?void 0:e.filter((e=>"functionCall"in e));return null==n||0===n.length?void 0:n.map((e=>({type:"tool-call",toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0})))}({parts:O.parts,generateId:c});if(null!=r)for(const o of r)n.enqueue({type:"tool-input-start",id:o.toolCallId,toolName:o.toolName,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-input-delta",id:o.toolCallId,delta:o.args,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-input-end",id:o.toolCallId,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.args,providerMetadata:o.providerMetadata}),d=!0}null!=$.finishReason&&(a=Rp({finishReason:$.finishReason,hasToolCalls:d}),l={google:{groundingMetadata:null!=(k=$.groundingMetadata)?k:null,urlContextMetadata:null!=(w=$.urlContextMetadata)?w:null,safetyRatings:null!=(x=$.safetyRatings)?x:null}},null!=S&&(l.google.usageMetadata=S))},flush(e){null!==p&&e.enqueue({type:"text-end",id:p}),null!==m&&e.enqueue({type:"reasoning-end",id:m}),e.enqueue({type:"finish",finishReason:a,usage:u,providerMetadata:l})}})),response:{headers:i},request:{body:r}}}};function Dp({groundingMetadata:e,generateId:t}){var n;return null==(n=null==e?void 0:e.groundingChunks)?void 0:n.filter((e=>null!=e.web)).map((e=>({type:"source",sourceType:"url",id:t(),url:e.web.uri,title:e.web.title})))}var Mp=Rl({parts:Tl(Pl([Rl({functionCall:Rl({name:Du(),args:wl()}),thoughtSignature:Du().nullish()}),Rl({inlineData:Rl({mimeType:Du(),data:Du()})}),Rl({executableCode:Rl({language:Du(),code:Du()}).nullish(),codeExecutionResult:Rl({outcome:Du(),output:Du()}).nullish(),text:Du().nullish(),thought:pl().nullish(),thoughtSignature:Du().nullish()})])).nullish()}),Lp=Rl({category:Du().nullish(),probability:Du().nullish(),probabilityScore:ul().nullish(),severity:Du().nullish(),severityScore:ul().nullish(),blocked:pl().nullish()}),qp=Rl({cachedContentTokenCount:ul().nullish(),thoughtsTokenCount:ul().nullish(),promptTokenCount:ul().nullish(),candidatesTokenCount:ul().nullish(),totalTokenCount:ul().nullish()}),Zp=Rl({candidates:Tl(Rl({content:Mp.nullish().or(Rl({}).strict()),finishReason:Du().nullish(),safetyRatings:Tl(Lp).nullish(),groundingMetadata:Ap.nullish(),urlContextMetadata:jp.nullish()})),usageMetadata:qp.nullish()}),Fp=Rl({candidates:Tl(Rl({content:Mp.nullish(),finishReason:Du().nullish(),safetyRatings:Tl(Lp).nullish(),groundingMetadata:Ap.nullish(),urlContextMetadata:jp.nullish()})).nullish(),usageMetadata:qp.nullish()}),Hp={googleSearch:Cp,urlContext:Up,codeExecution:Ud({id:"google.code_execution",name:"code_execution",inputSchema:Rl({language:Du().describe("The programming language of the code."),code:Du().describe("The code to be executed.")}),outputSchema:Rl({outcome:Du().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:Du().describe("The output from the code execution.")})})},Bp=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=this.settings.maxImagesPerCall)?e:4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;const{prompt:o,n:i=1,size:s="1024x1024",aspectRatio:a="1:1",seed:u,providerOptions:l,headers:c,abortSignal:d}=e,p=[];null!=s&&p.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=u&&p.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});const m=await Nd({provider:"google",providerOptions:l,schema:Jp}),_=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,h={sampleCount:i};null!=a&&(h.aspectRatio=a),m&&Object.assign(h,m);const g={instances:[{prompt:o}],parameters:h},{responseHeaders:f,value:v}=await Cd({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:md(await zd(this.config.headers),c),body:g,failedResponseHandler:wp,successfulResponseHandler:Ld(Wp),abortSignal:d,fetch:this.config.fetch});return{images:v.predictions.map((e=>e.bytesBase64Encoded)),warnings:null!=p?p:[],providerMetadata:{google:{images:v.predictions.map((e=>({})))}},response:{timestamp:_,modelId:this.modelId,headers:f}}}},Wp=Rl({predictions:Tl(Rl({bytesBase64Encoded:Du()})).default([])}),Jp=Rl({personGeneration:Wl(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Wl(["1:1","3:4","4:3","9:16","16:9"]).nullish()});function Vp(e={}){var t;const n=null!=(t=Kd(e.baseURL))?t:"https://generativelanguage.googleapis.com/v1beta",r=()=>({"x-goog-api-key":yd({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers}),o=t=>{var o;return new zp(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(o=e.generateId)?o:gd,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:e.fetch})},i=t=>new Ip(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,o={})=>new Bp(t,o,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),a=function(e){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return o(e)};return a.languageModel=o,a.chat=o,a.generativeAI=o,a.embedding=i,a.textEmbedding=i,a.textEmbeddingModel=i,a.image=s,a.imageModel=s,a.tools=Hp,a}Vp();var Kp=Rl({error:Rl({message:Du(),type:Du().nullish(),param:bl().nullish(),code:Pl([Du(),ul()]).nullish()})}),Gp=Dd({errorSchema:Kp,errorToMessage:e=>e.error.message});function Yp({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function Xp(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Qp=Rl({logitBias:Zl($c(),ul()).optional(),logprobs:Pl([pl(),ul()]).optional(),parallelToolCalls:pl().optional(),user:Du().optional(),reasoningEffort:Wl(["minimal","low","medium","high"]).optional(),maxCompletionTokens:ul().optional(),store:pl().optional(),metadata:Zl(Du().max(64),Du().max(512)).optional(),prediction:Zl(Du(),bl()).optional(),structuredOutputs:pl().optional(),serviceTier:Wl(["auto","flex","priority"]).optional(),strictJsonSchema:pl().optional(),textVerbosity:Wl(["low","medium","high"]).optional(),promptCacheKey:Du().optional(),safetyIdentifier:Du().optional()}),em=Rl({key:Du(),type:Wl(["eq","ne","gt","gte","lt","lte"]),value:Pl([Du(),ul(),pl()])}),tm=Rl({type:Wl(["and","or"]),filters:Tl(Pl([em,vc((()=>tm))]))}),nm=Pl([em,tm]),rm=Rl({vectorStoreIds:Tl(Du()).optional(),maxNumResults:ul().optional(),ranking:Rl({ranker:Wl(["auto","default-2024-08-21"]).optional()}).optional(),filters:nm.optional()}),om=jd({id:"openai.file_search",name:"file_search",inputSchema:Rl({query:Du()})}),im=Rl({searchContextSize:Wl(["low","medium","high"]).optional(),userLocation:Rl({type:Vl("approximate"),country:Du().optional(),city:Du().optional(),region:Du().optional(),timezone:Du().optional()}).optional()}),sm=jd({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:Rl({action:Ul("type",[Rl({type:Vl("search"),query:Du()}),Rl({type:Vl("open_page"),url:Du()}),Rl({type:Vl("find"),url:Du(),pattern:Du()})]).nullish()})});var am=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_,h,g;const f=[],v=null!=(m=await Nd({provider:"openai",providerOptions:p,schema:Qp}))?m:{},y=null==(_=v.structuredOutputs)||_;null!=o&&f.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==u?void 0:u.type)||null==u.schema||y||f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:k}=function({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:i}of e)switch(o){case"system":switch(t){case"system":n.push({role:"system",content:i});break;case"developer":n.push({role:"developer",content:i});break;case"remove":r.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===i.length&&"text"===i[0].type){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map(((e,t)=>{var n,r,o;switch(e.type){case"text":return{type:"text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"image_url",image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Vd(e.data)}`,detail:null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.imageDetail}}}if(!e.mediaType.startsWith("audio/")){if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new Ct({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(o=e.filename)?o:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vd(e.data)}`}}}throw new Ct({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new Ct({functionality:"audio file parts with URLs"});switch(e.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Vd(e.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Vd(e.data),format:"mp3"}};default:throw new Ct({functionality:`audio content parts with media type ${e.mediaType}`})}}}))});break;case"assistant":{let e="";const t=[];for(const n of i)switch(n.type){case"text":e+=n.text;break;case"tool-call":t.push({id:n.toolCallId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.input)}})}n.push({role:"assistant",content:e,tool_calls:t.length>0?t:void 0});break}case"tool":for(const e of i){const t=e.output;let r;switch(t.type){case"text":case"error-text":r=t.value;break;case"content":case"json":case"error-json":r=JSON.stringify(t.value)}n.push({role:"tool",tool_call_id:e.toolCallId,content:r})}break;default:throw new Error(`Unsupported role: ${o}`)}return{messages:n,warnings:r}}({prompt:e,systemMessageMode:pm(this.modelId)});f.push(...k);const w=null!=(h=v.strictJsonSchema)&&h,x={model:this.modelId,logit_bias:v.logitBias,logprobs:!0===v.logprobs||"number"==typeof v.logprobs||void 0,top_logprobs:"number"==typeof v.logprobs?v.logprobs:"boolean"==typeof v.logprobs&&v.logprobs?0:void 0,user:v.user,parallel_tool_calls:v.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:s,response_format:"json"===(null==u?void 0:u.type)?y&&null!=u.schema?{type:"json_schema",json_schema:{schema:u.schema,strict:w,name:null!=(g=u.name)?g:"response",description:u.description}}:{type:"json_object"}:void 0,stop:a,seed:l,verbosity:v.textVerbosity,max_completion_tokens:v.maxCompletionTokens,store:v.store,metadata:v.metadata,prediction:v.prediction,reasoning_effort:v.reasoningEffort,service_tier:v.serviceTier,prompt_cache_key:v.promptCacheKey,safety_identifier:v.safetyIdentifier,messages:b};var I;dm(this.modelId)?(null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=x.frequency_penalty&&(x.frequency_penalty=void 0,f.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=x.presence_penalty&&(x.presence_penalty=void 0,f.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=x.logit_bias&&(x.logit_bias=void 0,f.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=x.logprobs&&(x.logprobs=void 0,f.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=x.top_logprobs&&(x.top_logprobs=void 0,f.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=x.max_tokens&&(null==x.max_completion_tokens&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==v.serviceTier||((I=this.modelId).startsWith("o3")||I.startsWith("o4-mini")||I.startsWith("gpt-5")&&!I.startsWith("gpt-5-chat"))||(f.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),"priority"!==v.serviceTier||function(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}(this.modelId)||(f.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:S,toolChoice:$,toolWarnings:O}=function({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){const o=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:o};const i=[];for(const a of e)switch(a.type){case"function":i.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:n?r:void 0}});break;case"provider-defined":switch(a.id){case"openai.file_search":{const e=rm.parse(a.args);i.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=im.parse(a.args);i.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}default:o.push({type:"unsupported-tool",tool:a})}break;default:o.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:i,toolChoice:void 0,toolWarnings:o};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:i,toolChoice:s,toolWarnings:o};case"tool":return{tools:i,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:throw new Ct({functionality:`tool choice type: ${s}`})}}({tools:c,toolChoice:d,structuredOutputs:y,strictJsonSchema:w});return{args:{...x,tools:S,tool_choice:$},warnings:[...f,...O]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_;const{args:h,warnings:g}=await this.getArgs(e),{responseHeaders:f,value:v,rawValue:y}=await Cd({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:h,failedResponseHandler:Gp,successfulResponseHandler:Ld(lm),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.choices[0],k=[],w=b.message.content;null!=w&&w.length>0&&k.push({type:"text",text:w});for(const $ of null!=(t=b.message.tool_calls)?t:[])k.push({type:"tool-call",toolCallId:null!=(n=$.id)?n:gd(),toolName:$.function.name,input:$.function.arguments});for(const $ of null!=(r=b.message.annotations)?r:[])k.push({type:"source",sourceType:"url",id:gd(),url:$.url,title:$.title});const x=null==(o=v.usage)?void 0:o.completion_tokens_details,I=null==(i=v.usage)?void 0:i.prompt_tokens_details,S={openai:{}};return null!=(null==x?void 0:x.accepted_prediction_tokens)&&(S.openai.acceptedPredictionTokens=null==x?void 0:x.accepted_prediction_tokens),null!=(null==x?void 0:x.rejected_prediction_tokens)&&(S.openai.rejectedPredictionTokens=null==x?void 0:x.rejected_prediction_tokens),null!=(null==(s=b.logprobs)?void 0:s.content)&&(S.openai.logprobs=b.logprobs.content),{content:k,finishReason:Xp(b.finish_reason),usage:{inputTokens:null!=(u=null==(a=v.usage)?void 0:a.prompt_tokens)?u:void 0,outputTokens:null!=(c=null==(l=v.usage)?void 0:l.completion_tokens)?c:void 0,totalTokens:null!=(p=null==(d=v.usage)?void 0:d.total_tokens)?p:void 0,reasoningTokens:null!=(m=null==x?void 0:x.reasoning_tokens)?m:void 0,cachedInputTokens:null!=(_=null==I?void 0:I.cached_tokens)?_:void 0},request:{body:h},response:{...Yp(v),headers:f,body:y},warnings:g,providerMetadata:S}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Cd({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:r,failedResponseHandler:Gp,successfulResponseHandler:Md(cm),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0,c=!1;const d={openai:{}};return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,i,p,m,_,h,g,f,v,y,b,k,w,x,I,S,$,O,T,E,R,N,A;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const C=t.value;if("error"in C)return a="error",void n.enqueue({type:"error",error:C.error});l&&(l=!1,n.enqueue({type:"response-metadata",...Yp(C)})),null!=C.usage&&(u.inputTokens=null!=(r=C.usage.prompt_tokens)?r:void 0,u.outputTokens=null!=(o=C.usage.completion_tokens)?o:void 0,u.totalTokens=null!=(i=C.usage.total_tokens)?i:void 0,u.reasoningTokens=null!=(m=null==(p=C.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?m:void 0,u.cachedInputTokens=null!=(h=null==(_=C.usage.prompt_tokens_details)?void 0:_.cached_tokens)?h:void 0,null!=(null==(g=C.usage.completion_tokens_details)?void 0:g.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(f=C.usage.completion_tokens_details)?void 0:f.accepted_prediction_tokens),null!=(null==(v=C.usage.completion_tokens_details)?void 0:v.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(y=C.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens));const P=C.choices[0];if(null!=(null==P?void 0:P.finish_reason)&&(a=Xp(P.finish_reason)),null!=(null==(b=null==P?void 0:P.logprobs)?void 0:b.content)&&(d.openai.logprobs=P.logprobs.content),null==(null==P?void 0:P.delta))return;const j=P.delta;if(null!=j.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:j.content})),null!=j.tool_calls)for(const e of j.tool_calls){const t=e.index;if(null==s[t]){if("function"!==e.type)throw new rt({data:e,message:"Expected 'function' type."});if(null==e.id)throw new rt({data:e,message:"Expected 'id' to be a string."});if(null==(null==(k=e.function)?void 0:k.name))throw new rt({data:e,message:"Expected 'function.name' to be a string."});n.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),s[t]={id:e.id,type:"function",function:{name:e.function.name,arguments:null!=(w=e.function.arguments)?w:""},hasFinished:!1};const r=s[t];null!=(null==(x=r.function)?void 0:x.name)&&null!=(null==(I=r.function)?void 0:I.arguments)&&(r.function.arguments.length>0&&n.enqueue({type:"tool-input-delta",id:r.id,delta:r.function.arguments}),Ed(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(S=r.id)?S:gd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}const r=s[t];r.hasFinished||(null!=(null==($=e.function)?void 0:$.arguments)&&(r.function.arguments+=null!=(T=null==(O=e.function)?void 0:O.arguments)?T:""),n.enqueue({type:"tool-input-delta",id:r.id,delta:null!=(E=e.function.arguments)?E:""}),null!=(null==(R=r.function)?void 0:R.name)&&null!=(null==(N=r.function)?void 0:N.arguments)&&Ed(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(A=r.id)?A:gd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(null!=j.annotations)for(const e of j.annotations)n.enqueue({type:"source",sourceType:"url",id:gd(),url:e.url,title:e.title})},flush(e){c&&e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:a,usage:u,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:o}}}},um=Rl({prompt_tokens:ul().nullish(),completion_tokens:ul().nullish(),total_tokens:ul().nullish(),prompt_tokens_details:Rl({cached_tokens:ul().nullish()}).nullish(),completion_tokens_details:Rl({reasoning_tokens:ul().nullish(),accepted_prediction_tokens:ul().nullish(),rejected_prediction_tokens:ul().nullish()}).nullish()}).nullish(),lm=Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:Tl(Rl({message:Rl({role:Vl("assistant").nullish(),content:Du().nullish(),tool_calls:Tl(Rl({id:Du().nullish(),type:Vl("function"),function:Rl({name:Du(),arguments:Du()})})).nullish(),annotations:Tl(Rl({type:Vl("url_citation"),start_index:ul(),end_index:ul(),url:Du(),title:Du()})).nullish()}),index:ul(),logprobs:Rl({content:Tl(Rl({token:Du(),logprob:ul(),top_logprobs:Tl(Rl({token:Du(),logprob:ul()}))})).nullish()}).nullish(),finish_reason:Du().nullish()})),usage:um}),cm=Pl([Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:Tl(Rl({delta:Rl({role:Wl(["assistant"]).nullish(),content:Du().nullish(),tool_calls:Tl(Rl({index:ul(),id:Du().nullish(),type:Vl("function").nullish(),function:Rl({name:Du().nullish(),arguments:Du().nullish()})})).nullish(),annotations:Tl(Rl({type:Vl("url_citation"),start_index:ul(),end_index:ul(),url:Du(),title:Du()})).nullish()}).nullish(),logprobs:Rl({content:Tl(Rl({token:Du(),logprob:ul(),top_logprobs:Tl(Rl({token:Du(),logprob:ul()}))})).nullish()}).nullish(),finish_reason:Du().nullish(),index:ul()})),usage:um}),Kp]);function dm(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function pm(e){var t,n;return dm(e)?null!=(n=null==(t=mm[e])?void 0:t.systemMessageMode)?n:"developer":"system"}var mm={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function _m({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function hm(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var gm=Rl({echo:pl().optional(),logitBias:Zl(Du(),ul()).optional(),suffix:Du().optional(),user:Du().optional(),logprobs:Pl([pl(),ul()]).optional()}),fm=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,tools:l,toolChoice:c,seed:d,providerOptions:p}){const m=[],_={...await Nd({provider:"openai",providerOptions:p,schema:gm}),...await Nd({provider:this.providerOptionsName,providerOptions:p,schema:gm})};null!=o&&m.push({type:"unsupported-setting",setting:"topK"}),(null==l?void 0:l.length)&&m.push({type:"unsupported-setting",setting:"tools"}),null!=c&&m.push({type:"unsupported-setting",setting:"toolChoice"}),null!=u&&"text"!==u.type&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:h,stopSequences:g}=function({prompt:e,user:t="user",assistant:n="assistant"}){let r="";"system"===e[0].role&&(r+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:o,content:i}of e)switch(o){case"system":throw new Xe({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":r+=`${t}:\n${i.map((e=>{if("text"===e.type)return e.text})).filter(Boolean).join("")}\n\n`;break;case"assistant":r+=`${n}:\n${i.map((e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new Ct({functionality:"tool-call messages"})}})).join("")}\n\n`;break;case"tool":throw new Ct({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${o}`)}return r+=`${n}:\n`,{prompt:r,stopSequences:[`\n${t}:`]}}({prompt:e}),f=[...null!=g?g:[],...null!=a?a:[]];return{args:{model:this.modelId,echo:_.echo,logit_bias:_.logitBias,logprobs:!0===(null==_?void 0:_.logprobs)?0:!1===(null==_?void 0:_.logprobs)||null==_?void 0:_.logprobs,suffix:_.suffix,user:_.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:s,seed:d,prompt:h,stop:f.length>0?f:void 0},warnings:m}}async doGenerate(e){var t,n,r;const{args:o,warnings:i}=await this.getArgs(e),{responseHeaders:s,value:a,rawValue:u}=await Cd({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:o,failedResponseHandler:Gp,successfulResponseHandler:Ld(ym),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return null!=l.logprobs&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:null==(t=a.usage)?void 0:t.prompt_tokens,outputTokens:null==(n=a.usage)?void 0:n.completion_tokens,totalTokens:null==(r=a.usage)?void 0:r.total_tokens},finishReason:hm(l.finish_reason),request:{body:o},response:{..._m(a),headers:s,body:u},providerMetadata:c,warnings:i}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Cd({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:r,failedResponseHandler:Gp,successfulResponseHandler:Md(bm),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0;return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const r=t.value;if("error"in r)return s="error",void n.enqueue({type:"error",error:r.error});l&&(l=!1,n.enqueue({type:"response-metadata",..._m(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(u.inputTokens=r.usage.prompt_tokens,u.outputTokens=r.usage.completion_tokens,u.totalTokens=r.usage.total_tokens);const o=r.choices[0];null!=(null==o?void 0:o.finish_reason)&&(s=hm(o.finish_reason)),null!=(null==o?void 0:o.logprobs)&&(a.openai.logprobs=o.logprobs),null!=(null==o?void 0:o.text)&&o.text.length>0&&n.enqueue({type:"text-delta",id:"0",delta:o.text})},flush(e){l||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:u})}})),request:{body:r},response:{headers:o}}}},vm=Rl({prompt_tokens:ul(),completion_tokens:ul(),total_tokens:ul()}),ym=Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:Tl(Rl({text:Du(),finish_reason:Du(),logprobs:Rl({tokens:Tl(Du()),token_logprobs:Tl(ul()),top_logprobs:Tl(Zl(Du(),ul())).nullish()}).nullish()})),usage:vm.nullish()}),bm=Pl([Rl({id:Du().nullish(),created:ul().nullish(),model:Du().nullish(),choices:Tl(Rl({text:Du(),finish_reason:Du().nullish(),index:ul(),logprobs:Rl({tokens:Tl(Du()),token_logprobs:Tl(ul()),top_logprobs:Tl(Zl(Du(),ul())).nullish()}).nullish()})),usage:vm.nullish()}),Kp]),km=Rl({dimensions:ul().optional(),user:Du().optional()}),wm=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new xt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=null!=(o=await Nd({provider:"openai",providerOptions:r,schema:km}))?o:{},{responseHeaders:s,value:a,rawValue:u}=await Cd({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:md(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:i.dimensions,user:i.user},failedResponseHandler:Gp,successfulResponseHandler:Ld(xm),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.data.map((e=>e.embedding)),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:s,body:u}}}},xm=Rl({data:Tl(Rl({embedding:Tl(ul())})),usage:Rl({prompt_tokens:ul()}).nullish()}),Im={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Sm=new Set(["gpt-image-1"]),$m=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=Im[this.modelId])?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:i,headers:s,abortSignal:a}){var u,l,c,d;const p=[];null!=r&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),null!=o&&p.push({type:"unsupported-setting",setting:"seed"});const m=null!=(c=null==(l=null==(u=this.config._internal)?void 0:u.currentDate)?void 0:l.call(u))?c:new Date,{value:_,responseHeaders:h}=await Cd({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:md(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...null!=(d=i.openai)?d:{},...Sm.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Gp,successfulResponseHandler:Ld(Om),abortSignal:a,fetch:this.config.fetch});return{images:_.data.map((e=>e.b64_json)),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:_.data.map((e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null))}}}}},Om=Rl({data:Tl(Rl({b64_json:Du(),revised_prompt:Du().optional()}))}),Tm=Rl({container:Pl([Du(),Rl({fileIds:Tl(Du()).optional()})]).optional()}),Em={codeInterpreter:jd({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:Rl({})}),fileSearch:om,webSearchPreview:sm};function Rm(e,t){return!!t&&t.some((t=>e.startsWith(t)))}var Nm=Rl({itemId:Du().nullish(),reasoningEncryptedContent:Du().nullish()});function Am({finishReason:e,hasToolCalls:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var Cm=Rl({type:Vl("web_search_call"),id:Du(),status:Du(),action:Ul("type",[Rl({type:Vl("search"),query:Du()}),Rl({type:Vl("open_page"),url:Du()}),Rl({type:Vl("find"),url:Du(),pattern:Du()})]).nullish()}),Pm=Tl(Rl({token:Du(),logprob:ul(),top_logprobs:Tl(Rl({token:Du(),logprob:ul()}))})),jm=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:i,frequencyPenalty:s,seed:a,prompt:u,providerOptions:l,tools:c,toolChoice:d,responseFormat:p}){var m,_;const h=[],g=function(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};if(e.startsWith("gpt-5-chat"))return{...r,isReasoningModel:!1};if(e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use"))return e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"};return{...r,isReasoningModel:!1}}(this.modelId);null!=o&&h.push({type:"unsupported-setting",setting:"topK"}),null!=a&&h.push({type:"unsupported-setting",setting:"seed"}),null!=i&&h.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=s&&h.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=n&&h.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:f,warnings:v}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,o,i,s,a,u;const l=[],c=[];for(const{role:d,content:p}of e)switch(d){case"system":switch(t){case"system":l.push({role:"system",content:p});break;case"developer":l.push({role:"developer",content:p});break;case"remove":c.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":l.push({role:"user",content:p.map(((e,t)=>{var r,o,i;switch(e.type){case"text":return{type:"input_text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"input_image",...e.data instanceof URL?{image_url:e.data.toString()}:"string"==typeof e.data&&Rm(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Vd(e.data)}`},detail:null==(o=null==(r=e.providerOptions)?void 0:r.openai)?void 0:o.imageDetail}}if("application/pdf"===e.mediaType)return e.data instanceof URL?{type:"input_file",file_url:e.data.toString()}:{type:"input_file",..."string"==typeof e.data&&Rm(e.data,n)?{file_id:e.data}:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vd(e.data)}`}};throw new Ct({functionality:`file part media type ${e.mediaType}`})}}))});break;case"assistant":{const e={};for(const t of p)switch(t.type){case"text":l.push({role:"assistant",content:[{type:"output_text",text:t.text}],id:null!=(i=null==(o=null==(r=t.providerOptions)?void 0:r.openai)?void 0:o.itemId)?i:void 0});break;case"tool-call":if(t.providerExecuted)break;l.push({type:"function_call",call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:null!=(u=null==(a=null==(s=t.providerOptions)?void 0:s.openai)?void 0:a.itemId)?u:void 0});break;case"tool-result":c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break;case"reasoning":{const n=await Nd({provider:"openai",providerOptions:t.providerOptions,schema:Nm}),r=null==n?void 0:n.itemId;if(null!=r){const o=e[r],i=[];t.text.length>0?i.push({type:"summary_text",text:t.text}):void 0!==o&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),void 0===o?(e[r]={type:"reasoning",id:r,encrypted_content:null==n?void 0:n.reasoningEncryptedContent,summary:i},l.push(e[r])):o.summary.push(...i)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case"tool":for(const e of p){const t=e.output;let n;switch(t.type){case"text":case"error-text":n=t.value;break;case"content":case"json":case"error-json":n=JSON.stringify(t.value)}l.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${d}`)}return{messages:l,warnings:c}}({prompt:u,systemMessageMode:g.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});h.push(...v);const y=await Nd({provider:"openai",providerOptions:l,schema:Zm}),b=null!=(m=null==y?void 0:y.strictJsonSchema)&&m,k="number"==typeof(null==y?void 0:y.logprobs)?null==y?void 0:y.logprobs:!0===(null==y?void 0:y.logprobs)?20:void 0,w=k?Array.isArray(null==y?void 0:y.include)?[...null==y?void 0:y.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:null==y?void 0:y.include,x={model:this.modelId,input:f,temperature:t,top_p:r,max_output_tokens:e,...("json"===(null==p?void 0:p.type)||(null==y?void 0:y.textVerbosity))&&{text:{..."json"===(null==p?void 0:p.type)&&{format:null!=p.schema?{type:"json_schema",strict:b,name:null!=(_=p.name)?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(null==y?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},metadata:null==y?void 0:y.metadata,parallel_tool_calls:null==y?void 0:y.parallelToolCalls,previous_response_id:null==y?void 0:y.previousResponseId,store:null==y?void 0:y.store,user:null==y?void 0:y.user,instructions:null==y?void 0:y.instructions,service_tier:null==y?void 0:y.serviceTier,include:w,prompt_cache_key:null==y?void 0:y.promptCacheKey,safety_identifier:null==y?void 0:y.safetyIdentifier,top_logprobs:k,...g.isReasoningModel&&(null!=(null==y?void 0:y.reasoningEffort)||null!=(null==y?void 0:y.reasoningSummary))&&{reasoning:{...null!=(null==y?void 0:y.reasoningEffort)&&{effort:y.reasoningEffort},...null!=(null==y?void 0:y.reasoningSummary)&&{summary:y.reasoningSummary}}},...g.requiredAutoTruncation&&{truncation:"auto"}};g.isReasoningModel?(null!=x.temperature&&(x.temperature=void 0,h.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,h.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==y?void 0:y.reasoningEffort)&&h.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==y?void 0:y.reasoningSummary)&&h.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==y?void 0:y.serviceTier)||g.supportsFlexProcessing||(h.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete x.service_tier),"priority"!==(null==y?void 0:y.serviceTier)||g.supportsPriorityProcessing||(h.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete x.service_tier);const{tools:I,toolChoice:S,toolWarnings:$}=function({tools:e,toolChoice:t,strictJsonSchema:n}){const r=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const s of e)switch(s.type){case"function":o.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,strict:n});break;case"provider-defined":switch(s.id){case"openai.file_search":{const e=rm.parse(s.args);o.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=im.parse(s.args);o.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=Tm.parse(s.args);o.push({type:"code_interpreter",container:null==e.container?{type:"auto",file_ids:void 0}:"string"==typeof e.container?e.container:{type:"auto",file_ids:e.container.fileIds}});break}default:r.push({type:"unsupported-tool",tool:s})}break;default:r.push({type:"unsupported-tool",tool:s})}if(null==t)return{tools:o,toolChoice:void 0,toolWarnings:r};const i=t.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:r};case"tool":return{tools:o,toolChoice:"code_interpreter"===t.toolName||"file_search"===t.toolName||"web_search_preview"===t.toolName?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:throw new Ct({functionality:`tool choice type: ${i}`})}}({tools:c,toolChoice:d,strictJsonSchema:b});return{args:{...x,tools:I,tool_choice:S},warnings:[...h,...$]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_;const{args:h,warnings:g}=await this.getArgs(e),f=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:v,value:y,rawValue:b}=await Cd({url:f,headers:md(this.config.headers(),e.headers),body:h,failedResponseHandler:Gp,successfulResponseHandler:Ld(Rl({id:Du(),created_at:ul(),error:Rl({code:Du(),message:Du()}).nullish(),model:Du(),output:Tl(Ul("type",[Rl({type:Vl("message"),role:Vl("assistant"),id:Du(),content:Tl(Rl({type:Vl("output_text"),text:Du(),logprobs:Pm.nullish(),annotations:Tl(Ul("type",[Rl({type:Vl("url_citation"),start_index:ul(),end_index:ul(),url:Du(),title:Du()}),Rl({type:Vl("file_citation"),start_index:ul(),end_index:ul(),file_id:Du(),quote:Du()})]))}))}),Rl({type:Vl("function_call"),call_id:Du(),name:Du(),arguments:Du(),id:Du()}),Cm,Rl({type:Vl("computer_call"),id:Du(),status:Du().optional()}),Rl({type:Vl("file_search_call"),id:Du(),status:Du().optional(),queries:Tl(Du()).nullish(),results:Tl(Rl({attributes:Rl({file_id:Du(),filename:Du(),score:ul(),text:Du()})})).nullish()}),Rl({type:Vl("reasoning"),id:Du(),encrypted_content:Du().nullish(),summary:Tl(Rl({type:Vl("summary_text"),text:Du()}))})])),incomplete_details:Rl({reason:Du()}).nullable(),usage:Um})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(y.error)throw new Ue({message:y.error.message,url:f,requestBodyValues:h,statusCode:400,responseHeaders:v,responseBody:b,isRetryable:!1});const k=[],w=[];for(const I of y.output)switch(I.type){case"reasoning":0===I.summary.length&&I.summary.push({type:"summary_text",text:""});for(const e of I.summary)k.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:I.id,reasoningEncryptedContent:null!=(t=I.encrypted_content)?t:null}}});break;case"message":for(const t of I.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&w.push(t.logprobs),k.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:I.id}}});for(const e of t.annotations)"url_citation"===e.type?k.push({type:"source",sourceType:"url",id:null!=(s=null==(i=(o=this.config).generateId)?void 0:i.call(o))?s:gd(),url:e.url,title:e.title}):"file_citation"===e.type&&k.push({type:"source",sourceType:"document",id:null!=(l=null==(u=(a=this.config).generateId)?void 0:u.call(a))?l:gd(),mediaType:"text/plain",title:e.quote,filename:e.file_id})}break;case"function_call":k.push({type:"tool-call",toolCallId:I.call_id,toolName:I.name,input:I.arguments,providerMetadata:{openai:{itemId:I.id}}});break;case"web_search_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"web_search_preview",input:JSON.stringify({action:I.action}),providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"web_search_preview",result:{status:I.status},providerExecuted:!0});break;case"computer_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"computer_use",input:"",providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.status||"completed"},providerExecuted:!0});break;case"file_search_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"file_search",input:"",providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.status||"completed",...I.queries&&{queries:I.queries},...I.results&&{results:I.results}},providerExecuted:!0})}const x={openai:{responseId:y.id}};return w.length>0&&(x.openai.logprobs=w),{content:k,finishReason:Am({finishReason:null==(c=y.incomplete_details)?void 0:c.reason,hasToolCalls:k.some((e=>"tool-call"===e.type))}),usage:{inputTokens:y.usage.input_tokens,outputTokens:y.usage.output_tokens,totalTokens:y.usage.input_tokens+y.usage.output_tokens,reasoningTokens:null!=(p=null==(d=y.usage.output_tokens_details)?void 0:d.reasoning_tokens)?p:void 0,cachedInputTokens:null!=(_=null==(m=y.usage.input_tokens_details)?void 0:m.cached_tokens)?_:void 0},request:{body:h},response:{id:y.id,timestamp:new Date(1e3*y.created_at),modelId:y.model,headers:v,body:b},providerMetadata:x,warnings:g}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:o}=await Cd({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Gp,successfulResponseHandler:Md(Mm),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=this;let s="unknown";const a={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let l=null;const c={};let d=!1;const p={};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,m,_,h,g,f,v,y,b,k,w,x,I,S,$;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const O=t.value;if(qm(O))"function_call"===O.item.type?(c[O.output_index]={toolName:O.item.name,toolCallId:O.item.call_id},n.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:O.item.name})):"web_search_call"===O.item.type?(c[O.output_index]={toolName:"web_search_preview",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"web_search_preview"})):"computer_call"===O.item.type?(c[O.output_index]={toolName:"computer_use",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"computer_use"})):"file_search_call"===O.item.type?(c[O.output_index]={toolName:"file_search",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"file_search"})):"message"===O.item.type?n.enqueue({type:"text-start",id:O.item.id,providerMetadata:{openai:{itemId:O.item.id}}}):function(e){return qm(e)&&"reasoning"===e.item.type}(O)&&(p[O.item.id]={encryptedContent:O.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${O.item.id}:0`,providerMetadata:{openai:{itemId:O.item.id,reasoningEncryptedContent:null!=(r=O.item.encrypted_content)?r:null}}}));else if(Lm(O)){if("function_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.call_id}),n.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:O.item.name,input:O.item.arguments,providerMetadata:{openai:{itemId:O.item.id}}});else if("web_search_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"web_search_preview",input:JSON.stringify({action:O.item.action}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"web_search_preview",result:{status:O.item.status},providerExecuted:!0});else if("computer_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:O.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"file_search",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:O.item.status||"completed",...O.item.queries&&{queries:O.item.queries},...O.item.results&&{results:O.item.results}},providerExecuted:!0});else if("message"===O.item.type)n.enqueue({type:"text-end",id:O.item.id});else if(function(e){return Lm(e)&&"reasoning"===e.item.type}(O)){const e=p[O.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${O.item.id}:${t}`,providerMetadata:{openai:{itemId:O.item.id,reasoningEncryptedContent:null!=(o=O.item.encrypted_content)?o:null}}});delete p[O.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(O)){const e=c[O.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:O.delta})}else!function(e){return"response.created"===e.type}(O)?!function(e){return"response.output_text.delta"===e.type}(O)?!function(e){return"response.reasoning_summary_part.added"===e.type}(O)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(O)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(O)?!function(e){return"response.output_text.annotation.added"===e.type}(O)?function(e){return"error"===e.type}(O)&&n.enqueue({type:"error",error:O}):"url_citation"===O.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=(x=null==(w=(k=i.config).generateId)?void 0:w.call(k))?x:gd(),url:O.annotation.url,title:O.annotation.title}):"file_citation"===O.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=($=null==(S=(I=i.config).generateId)?void 0:S.call(I))?$:gd(),mediaType:"text/plain",title:O.annotation.quote,filename:O.annotation.file_id}):(s=Am({finishReason:null==(g=O.response.incomplete_details)?void 0:g.reason,hasToolCalls:d}),a.inputTokens=O.response.usage.input_tokens,a.outputTokens=O.response.usage.output_tokens,a.totalTokens=O.response.usage.input_tokens+O.response.usage.output_tokens,a.reasoningTokens=null!=(v=null==(f=O.response.usage.output_tokens_details)?void 0:f.reasoning_tokens)?v:void 0,a.cachedInputTokens=null!=(b=null==(y=O.response.usage.input_tokens_details)?void 0:y.cached_tokens)?b:void 0):n.enqueue({type:"reasoning-delta",id:`${O.item_id}:${O.summary_index}`,delta:O.delta,providerMetadata:{openai:{itemId:O.item_id}}}):O.summary_index>0&&(null==(m=p[O.item_id])||m.summaryParts.push(O.summary_index),n.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{openai:{itemId:O.item_id,reasoningEncryptedContent:null!=(h=null==(_=p[O.item_id])?void 0:_.encryptedContent)?h:null}}})):(n.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),O.logprobs&&u.push(O.logprobs)):(l=O.response.id,n.enqueue({type:"response-metadata",id:O.response.id,timestamp:new Date(1e3*O.response.created_at),modelId:O.response.model}))},flush(e){const t={openai:{responseId:l}};u.length>0&&(t.openai.logprobs=u),e.enqueue({type:"finish",finishReason:s,usage:a,providerMetadata:t})}})),request:{body:t},response:{headers:r}}}},Um=Rl({input_tokens:ul(),input_tokens_details:Rl({cached_tokens:ul().nullish()}).nullish(),output_tokens:ul(),output_tokens_details:Rl({reasoning_tokens:ul().nullish()}).nullish()}),zm=Rl({type:Vl("response.output_text.delta"),item_id:Du(),delta:Du(),logprobs:Pm.nullish()}),Dm=Rl({type:Vl("error"),code:Du(),message:Du(),param:Du().nullish(),sequence_number:ul()}),Mm=Pl([zm,Rl({type:Wl(["response.completed","response.incomplete"]),response:Rl({incomplete_details:Rl({reason:Du()}).nullish(),usage:Um})}),Rl({type:Vl("response.created"),response:Rl({id:Du(),created_at:ul(),model:Du()})}),Rl({type:Vl("response.output_item.added"),output_index:ul(),item:Ul("type",[Rl({type:Vl("message"),id:Du()}),Rl({type:Vl("reasoning"),id:Du(),encrypted_content:Du().nullish()}),Rl({type:Vl("function_call"),id:Du(),call_id:Du(),name:Du(),arguments:Du()}),Rl({type:Vl("web_search_call"),id:Du(),status:Du(),action:Rl({type:Vl("search"),query:Du().optional()}).nullish()}),Rl({type:Vl("computer_call"),id:Du(),status:Du()}),Rl({type:Vl("file_search_call"),id:Du(),status:Du(),queries:Tl(Du()).nullish(),results:Tl(Rl({attributes:Rl({file_id:Du(),filename:Du(),score:ul(),text:Du()})})).optional()})])}),Rl({type:Vl("response.output_item.done"),output_index:ul(),item:Ul("type",[Rl({type:Vl("message"),id:Du()}),Rl({type:Vl("reasoning"),id:Du(),encrypted_content:Du().nullish()}),Rl({type:Vl("function_call"),id:Du(),call_id:Du(),name:Du(),arguments:Du(),status:Vl("completed")}),Cm,Rl({type:Vl("computer_call"),id:Du(),status:Vl("completed")}),Rl({type:Vl("file_search_call"),id:Du(),status:Vl("completed"),queries:Tl(Du()).nullish(),results:Tl(Rl({attributes:Rl({file_id:Du(),filename:Du(),score:ul(),text:Du()})})).nullish()})])}),Rl({type:Vl("response.function_call_arguments.delta"),item_id:Du(),output_index:ul(),delta:Du()}),Rl({type:Vl("response.output_text.annotation.added"),annotation:Ul("type",[Rl({type:Vl("url_citation"),url:Du(),title:Du()}),Rl({type:Vl("file_citation"),file_id:Du(),quote:Du()})])}),Rl({type:Vl("response.reasoning_summary_part.added"),item_id:Du(),summary_index:ul()}),Rl({type:Vl("response.reasoning_summary_text.delta"),item_id:Du(),summary_index:ul(),delta:Du()}),Dm,Rl({type:Du()}).loose()]);function Lm(e){return"response.output_item.done"===e.type}function qm(e){return"response.output_item.added"===e.type}var Zm=Rl({metadata:bl().nullish(),parallelToolCalls:pl().nullish(),previousResponseId:Du().nullish(),store:pl().nullish(),user:Du().nullish(),reasoningEffort:Du().nullish(),strictJsonSchema:pl().nullish(),instructions:Du().nullish(),reasoningSummary:Du().nullish(),serviceTier:Wl(["auto","flex","priority"]).nullish(),include:Tl(Wl(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:Wl(["low","medium","high"]).nullish(),promptCacheKey:Du().nullish(),safetyIdentifier:Du().nullish(),logprobs:Pl([pl(),ul().min(1).max(20)]).optional()}),Fm=Rl({instructions:Du().nullish(),speed:ul().min(.25).max(4).default(1).nullish()}),Hm=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:i,providerOptions:s}){const a=[],u=await Nd({provider:"openai",providerOptions:s,schema:Fm}),l={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?l.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),u){const e={};for(const t in e){const n=e[t];void 0!==n&&(l[t]=n)}}return i&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${i}" was ignored.`}),{requestBody:l,warnings:a}}async doGenerate(e){var t,n,r;const o=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{requestBody:i,warnings:s}=await this.getArgs(e),{value:a,responseHeaders:u,rawValue:l}=await Cd({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),body:i,failedResponseHandler:Gp,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=_d(e);if(!e.body)throw new Ue({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(o){throw new Ue({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:s,request:{body:JSON.stringify(i)},response:{timestamp:o,modelId:this.modelId,headers:u,body:l}}}},Bm=Rl({include:Tl(Du()).optional(),language:Du().optional(),prompt:Du().optional(),temperature:ul().min(0).max(1).default(0).optional(),timestampGranularities:Tl(Wl(["word","segment"])).default(["segment"]).optional()}),Wm={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Jm=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=await Nd({provider:"openai",providerOptions:n,schema:Bm}),o=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([Jd(e)]);if(o.append("model",this.modelId),o.append("file",new File([i],"audio",{type:t})),r){const e={include:r.include,language:r.language,prompt:r.prompt,response_format:"verbose_json",temperature:r.temperature,timestamp_granularities:r.timestampGranularities};for(const[t,n]of Object.entries(e))null!=n&&o.append(t,String(n))}return{formData:o,warnings:[]}}async doGenerate(e){var t,n,r,o,i,s,a,u;const l=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{formData:c,warnings:d}=await this.getArgs(e),{value:p,responseHeaders:m,rawValue:_}=await(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s})=>Pd({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s}))({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:md(this.config.headers(),e.headers),formData:c,failedResponseHandler:Gp,successfulResponseHandler:Ld(Vm),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=null!=p.language&&p.language in Wm?Wm[p.language]:void 0;return{text:p.text,segments:null!=(a=null!=(s=null==(o=p.segments)?void 0:o.map((e=>({text:e.text,startSecond:e.start,endSecond:e.end}))))?s:null==(i=p.words)?void 0:i.map((e=>({text:e.word,startSecond:e.start,endSecond:e.end}))))?a:[],language:h,durationInSeconds:null!=(u=p.duration)?u:void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:m,body:_}}}},Vm=Rl({text:Du(),language:Du().nullish(),duration:ul().nullish(),words:Tl(Rl({word:Du(),start:ul(),end:ul()})).nullish(),segments:Tl(Rl({id:ul(),seek:ul(),start:ul(),end:ul(),text:Du(),tokens:Tl(ul()),temperature:ul(),avg_logprob:ul(),compression_ratio:ul(),no_speech_prob:ul()})).nullish()});function Km(e={}){var t,n;const r=null!=(t=Kd(e.baseURL))?t:"https://api.openai.com/v1",o=null!=(n=e.name)?n:"openai",i=()=>({Authorization:`Bearer ${yd({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),s=t=>new wm(t,{provider:`${o}.embedding`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),a=t=>new $m(t,{provider:`${o}.image`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),u=t=>new Jm(t,{provider:`${o}.transcription`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),l=t=>new Hm(t,{provider:`${o}.speech`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),c=e=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(e)},d=t=>new jm(t,{provider:`${o}.responses`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(e){return c(e)};return p.languageModel=c,p.chat=t=>new am(t,{provider:`${o}.chat`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),p.completion=t=>new fm(t,{provider:`${o}.completion`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),p.responses=d,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=a,p.imageModel=a,p.transcription=u,p.transcriptionModel=u,p.speech=l,p.speechModel=l,p.tools=Em,p}Km();var Gm,Ym=Object.defineProperty,Xm=Object.defineProperties,Qm=Object.getOwnPropertyDescriptors,e_=Object.getOwnPropertySymbols,t_=Object.prototype.hasOwnProperty,n_=Object.prototype.propertyIsEnumerable,r_=(e,t,n)=>t in e?Ym(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,o_=(e,t)=>{for(var n in t||(t={}))t_.call(t,n)&&r_(e,n,t[n]);if(e_)for(var n of e_(t))n_.call(t,n)&&r_(e,n,t[n]);return e},i_=(e,t)=>Xm(e,Qm(t)),s_="vercel.ai.error",a_=Symbol.for(s_),u_=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Gm]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,s_)}static hasMarker(e,t){const n=Symbol.for(t);return null!=e&&"object"==typeof e&&n in e&&"boolean"==typeof e[n]&&!0===e[n]}};Gm=a_;var l_,c_=u_,d_="AI_APICallError",p_=`vercel.ai.error.${d_}`,m_=Symbol.for(p_),__=class extends c_{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:i,cause:s,isRetryable:a=null!=r&&(408===r||409===r||429===r||r>=500),data:u}){super({name:d_,message:e,cause:s}),this[l_]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=i,this.isRetryable=a,this.data=u}static isInstance(e){return c_.hasMarker(e,p_)}};l_=m_;var h_,g_="AI_EmptyResponseBodyError",f_=`vercel.ai.error.${g_}`,v_=Symbol.for(f_),y_=class extends c_{constructor({message:e="Empty response body"}={}){super({name:g_,message:e}),this[h_]=!0}static isInstance(e){return c_.hasMarker(e,f_)}};function b_(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.message:JSON.stringify(e)}h_=v_;var k_,w_="AI_InvalidArgumentError",x_=`vercel.ai.error.${w_}`,I_=Symbol.for(x_),S_=class extends c_{constructor({message:e,cause:t,argument:n}){super({name:w_,message:e,cause:t}),this[k_]=!0,this.argument=n}static isInstance(e){return c_.hasMarker(e,x_)}};k_=I_;var $_,O_="AI_InvalidPromptError",T_=`vercel.ai.error.${O_}`,E_=Symbol.for(T_),R_=class extends c_{constructor({prompt:e,message:t,cause:n}){super({name:O_,message:`Invalid prompt: ${t}`,cause:n}),this[$_]=!0,this.prompt=e}static isInstance(e){return c_.hasMarker(e,T_)}};$_=E_;var N_,A_="AI_InvalidResponseDataError",C_=`vercel.ai.error.${A_}`,P_=Symbol.for(C_),j_=class extends c_{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:A_,message:t}),this[N_]=!0,this.data=e}static isInstance(e){return c_.hasMarker(e,C_)}};N_=P_;var U_,z_="AI_JSONParseError",D_=`vercel.ai.error.${z_}`,M_=Symbol.for(D_),L_=class extends c_{constructor({text:e,cause:t}){super({name:z_,message:`JSON parsing failed: Text: ${e}.\nError message: ${b_(t)}`,cause:t}),this[U_]=!0,this.text=e}static isInstance(e){return c_.hasMarker(e,D_)}};U_=M_;var q_,Z_="AI_LoadAPIKeyError",F_=`vercel.ai.error.${Z_}`,H_=Symbol.for(F_),B_=class extends c_{constructor({message:e}){super({name:Z_,message:e}),this[q_]=!0}static isInstance(e){return c_.hasMarker(e,F_)}};q_=H_;var W_,J_="AI_TypeValidationError",V_=`vercel.ai.error.${J_}`,K_=Symbol.for(V_);W_=K_;var G_,Y_=class e extends c_{constructor({value:e,cause:t}){super({name:J_,message:`Type validation failed: Value: ${JSON.stringify(e)}.\nError message: ${b_(t)}`,cause:t}),this[W_]=!0,this.value=e}static isInstance(e){return c_.hasMarker(e,V_)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}},X_="AI_UnsupportedFunctionalityError",Q_=`vercel.ai.error.${X_}`,eh=Symbol.for(Q_),th=class extends c_{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:X_,message:t}),this[G_]=!0,this.functionality=e}static isInstance(e){return c_.hasMarker(e,Q_)}};G_=eh;var nh=class 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 rh(e){}function oh(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=rh,onError:n=rh,onRetry:r=rh,onComment:o}=e;let i,s="",a=!0,u="",l="";function c(e){if(""===e)return u.length>0&&t({id:i,event:l||void 0,data:u.endsWith("\n")?u.slice(0,-1):u}),i=void 0,u="",void(l="");if(e.startsWith(":"))return void(o&&o(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1===n)d(e,"",e);else{const t=e.slice(0,n),r=" "===e[n+1]?2:1;d(t,e.slice(n+r),e)}}function d(e,t,o){switch(e){case"event":l=t;break;case"data":u=`${u}${t}\n`;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new nh(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new nh(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:o}))}}return{feed:function(e){const t=a?e.replace(/^\xEF\xBB\xBF/,""):e,[n,r]=function(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),i=e.indexOf("\n",r);let s=-1;if(-1!==o&&-1!==i?s=Math.min(o,i):-1!==o?s=o:-1!==i&&(s=i),-1===s){n=e.slice(r);break}{const n=e.slice(r,s);t.push(n),r=s+1,"\r"===e[r-1]&&"\n"===e[r]&&r++}}return[t,n]}(`${s}${t}`);for(const o of n)c(o);s=r,a=!1},reset:function(e={}){s&&e.consume&&c(s),a=!0,i=void 0,u="",l="",s=""}}}var ih=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(o){r=oh({onEvent:e=>{o.enqueue(e)},onError(t){"terminate"===e?o.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};function sh(...e){return e.reduce(((e,t)=>o_(o_({},e),null!=t?t:{})),{})}function ah(e){return Object.fromEntries([...e.headers])}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var uh=(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const e=n.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n[Math.random()*e|0];return r.join("")};if(null==e)return o;if(n.includes(r))throw new S_({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`})();function lh(e){return(e instanceof Error||e instanceof DOMException)&&("AbortError"===e.name||"ResponseAborted"===e.name||"TimeoutError"===e.name)}var ch=["fetch failed","failed to fetch"];function dh({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if("string"==typeof e)return e;if(null!=e)throw new B_({message:`${r} API key must be a string.`});if("undefined"==typeof process)throw new B_({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(null==(e=process.env[t]))throw new B_({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if("string"!=typeof e)throw new B_({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var ph=/"__proto__"\s*:/,mh=/"constructor"\s*:/;function _h(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===ph.test(e)&&!1===mh.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}function hh(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return _h(e)}finally{Error.stackTraceLimit=t}}var gh=Symbol.for("vercel.ai.validator");function fh(e){return function(e){return"object"==typeof e&&null!==e&&gh in e&&!0===e[gh]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Y_({value:e,cause:n.issues})}},{[gh]:!0,validate:n});var t,n}async function vh({value:e,schema:t}){const n=fh(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Y_.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Y_.wrap({value:e,cause:r}),rawValue:e}}}async function yh({text:e,schema:t}){try{const n=hh(e);return null==t?n:async function({value:e,schema:t}){const n=await vh({value:e,schema:t});if(!n.success)throw Y_.wrap({value:e,cause:n.error});return n.value}({value:n,schema:t})}catch(n){if(L_.isInstance(n)||Y_.isInstance(n))throw n;throw new L_({text:e,cause:n})}}async function bh({text:e,schema:t}){try{const n=hh(e);return null==t?{success:!0,value:n,rawValue:n}:await vh({value:n,schema:t})}catch(n){return{success:!1,error:L_.isInstance(n)?n:new L_({text:e,cause:n}),rawValue:void 0}}}function kh(e){try{return hh(e),!0}catch(t){return!1}}function wh({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ih).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await bh({text:e,schema:t}))}}))}var xh=()=>globalThis.fetch,Ih=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s})=>Sh({url:e,headers:o_({"Content-Type":"application/json"},t),body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s}),Sh=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:i,fetch:s=xh()})=>{try{const l=await s(e,{method:"POST",headers:(a=t,Object.fromEntries(Object.entries(a).filter((([e,t])=>null!=t)))),body:n.content,signal:i}),c=ah(l);if(!l.ok){let t;try{t=await o({response:l,url:e,requestBodyValues:n.values})}catch(u){if(lh(u)||__.isInstance(u))throw u;throw new __({message:"Failed to process error response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:l,url:e,requestBodyValues:n.values})}catch(u){if(u instanceof Error&&(lh(u)||__.isInstance(u)))throw u;throw new __({message:"Failed to process successful response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(u){throw function({error:e,url:t,requestBodyValues:n}){if(lh(e))return e;if(e instanceof TypeError&&ch.includes(e.message.toLowerCase())){const r=e.cause;if(null!=r)return new __({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}({error:u,url:e,requestBodyValues:n.values})}var a},$h=e=>async({response:t})=>{const n=ah(t);if(null==t.body)throw new y_({});return{responseHeaders:n,value:wh({stream:t.body,schema:e})}},Oh=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),i=await bh({text:o,schema:e}),s=ah(t);if(!i.success)throw new __({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:s,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:s,value:i.value,rawValue:i.rawValue}},{btoa:Th}=globalThis;var Eh=Pl([Rl({type:Vl("reasoning.summary"),summary:Du()}),Rl({type:Vl("reasoning.encrypted"),data:Du()}),Rl({type:Vl("reasoning.text"),text:Du().nullish(),signature:Du().nullish()})]),Rh=Tl(Pl([Eh,wl().transform((()=>null))])).transform((e=>e.filter((e=>!!e)))),Nh=Rl({error:Rl({code:Pl([Du(),ul()]).nullable().optional().default(null),message:Du(),type:Du().nullable().optional().default(null),param:bl().nullable().optional().default(null)})}),Ah=(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:i})=>{const s=await r.text(),a=ah(r);if(""===s.trim())return{responseHeaders:a,value:new __({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})};try{const u=await yh({text:s,schema:e});return{responseHeaders:a,value:new __({message:t(u),url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,data:u,isRetryable:null==n?void 0:n(r,u)})}}catch(u){return{responseHeaders:a,value:new __({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})}}})({errorSchema:Nh,errorToMessage:e=>e.error.message});function Ch(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}function Ph({url:e,protocols:t}){try{const n=new URL(e);return t.has(n.protocol)}catch(n){return!1}}function jh({part:e,defaultMediaType:t}){var n,r;if(e.data instanceof Uint8Array){const r=function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Th(t)}(e.data);return`data:${null!=(n=e.mediaType)?n:t};base64,${r}`}const o=e.data.toString();return Ph({url:o,protocols:new Set(["http:","https:"])})||o.startsWith("data:")?o:`data:${null!=(r=e.mediaType)?r:t};base64,${o}`}function Uh(e,t){var n;const r=e.match(/^data:([^;]+)/);return r&&null!=(n=r[1])?n:t}function zh(e){const t=e.match(/^data:[^;]*;base64,(.+)$/);return t?t[1]:e}function Dh(e){var t,n,r;const o=null==e?void 0:e.anthropic,i=null==e?void 0:e.openrouter;return null!=(r=null!=(n=null!=(t=null==i?void 0:i.cacheControl)?t:null==i?void 0:i.cache_control)?n:null==o?void 0:o.cacheControl)?r:null==o?void 0:o.cache_control}function Mh(e){var t,n,r;const o=[];for(const{role:s,content:a,providerOptions:u}of e)switch(s){case"system":o.push({role:"system",content:a,cache_control:Dh(u)});break;case"user":{if(1===a.length&&"text"===(null==(t=a[0])?void 0:t.type)){const e=null!=(n=Dh(u))?n:Dh(a[0].providerOptions),t=e?[{type:"text",text:a[0].text,cache_control:e}]:a[0].text;o.push({role:"user",content:t});break}const e=Dh(u),r=a.map((t=>{var n,r,o,i,s,a;const u=null!=(n=Dh(t.providerOptions))?n:e;switch(t.type){case"text":return{type:"text",text:t.text,cache_control:u};case"file":{if(null==(r=t.mediaType)?void 0:r.startsWith("image/")){return{type:"image_url",image_url:{url:jh({part:t,defaultMediaType:"image/jpeg"})},cache_control:u}}const e=String(null!=(a=null!=(s=null==(i=null==(o=t.providerOptions)?void 0:o.openrouter)?void 0:i.filename)?s:t.filename)?a:""),n=jh({part:t,defaultMediaType:"application/pdf"});return Ph({url:n,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:e,file_data:n}}:{type:"file",file:{filename:e,file_data:n},cache_control:u}}default:return{type:"text",text:"",cache_control:u}}}));o.push({role:"user",content:r});break}case"assistant":{let e="",t="";const n=[],r=[];for(const o of a)switch(o.type){case"text":e+=o.text;break;case"tool-call":r.push({id:o.toolCallId,type:"function",function:{name:o.toolName,arguments:JSON.stringify(o.input)}});break;case"reasoning":t+=o.text,n.push({type:"reasoning.text",text:o.text})}o.push({role:"assistant",content:e,tool_calls:r.length>0?r:void 0,reasoning:t||void 0,reasoning_details:n.length>0?n:void 0,cache_control:Dh(u)});break}case"tool":for(const e of a){const t="text"===(i=e).output.type?i.output.value:JSON.stringify(i.output.value);o.push({role:"tool",tool_call_id:e.toolCallId,content:t,cache_control:null!=(r=Dh(u))?r:Dh(e.providerOptions)})}}var i;return o}function Lh(e){switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:e.toolName}};default:throw new Error(`Invalid tool choice type: ${e}`)}}Pl([Vl("auto"),Vl("none"),Vl("required"),Rl({type:Vl("function"),function:Rl({name:Du()})})]);var qh=Tl(Pl([Rl({type:Vl("image_url"),image_url:Rl({url:Du()})}),wl().transform((()=>null))])).transform((e=>e.filter((e=>!!e)))),Zh=Rl({id:Du().optional(),model:Du().optional(),provider:Du().optional(),usage:Rl({prompt_tokens:ul(),prompt_tokens_details:Rl({cached_tokens:ul()}).nullish(),completion_tokens:ul(),completion_tokens_details:Rl({reasoning_tokens:ul()}).nullish(),total_tokens:ul(),cost:ul().optional(),cost_details:Rl({upstream_inference_cost:ul().nullish()}).nullish()}).nullish()}),Fh=Zh.extend({choices:Tl(Rl({message:Rl({role:Vl("assistant"),content:Du().nullable().optional(),reasoning:Du().nullable().optional(),reasoning_details:Rh.nullish(),images:qh.nullish(),tool_calls:Tl(Rl({id:Du().optional().nullable(),type:Vl("function"),function:Rl({name:Du(),arguments:Du()})})).optional(),annotations:Tl(Rl({type:Wl(["url_citation"]),url_citation:Rl({end_index:ul(),start_index:ul(),title:Du(),url:Du(),content:Du().optional()})})).nullish()}),index:ul().nullish(),logprobs:Rl({content:Tl(Rl({token:Du(),logprob:ul(),top_logprobs:Tl(Rl({token:Du(),logprob:ul()}))})).nullable()}).nullable().optional(),finish_reason:Du().optional().nullable()}))}),Hh=Pl([Zh.extend({choices:Tl(Rl({delta:Rl({role:Wl(["assistant"]).optional(),content:Du().nullish(),reasoning:Du().nullish().optional(),reasoning_details:Rh.nullish(),images:qh.nullish(),tool_calls:Tl(Rl({index:ul().nullish(),id:Du().nullish(),type:Vl("function").optional(),function:Rl({name:Du().nullish(),arguments:Du().nullish()})})).nullish(),annotations:Tl(Rl({type:Wl(["url_citation"]),url_citation:Rl({end_index:ul(),start_index:ul(),title:Du(),url:Du(),content:Du().optional()})})).nullish()}).nullish(),logprobs:Rl({content:Tl(Rl({token:Du(),logprob:ul(),top_logprobs:Tl(Rl({token:Du(),logprob:ul()}))})).nullable()}).nullish(),finish_reason:Du().nullable().optional(),index:ul().nullish()}))}),Nh]),Bh=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=e,this.settings=t,this.config=n}getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,frequencyPenalty:o,presencePenalty:i,seed:s,stopSequences:a,responseFormat:u,topK:l,tools:c,toolChoice:d}){var p;const m=o_(o_({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:!0===this.settings.logprobs||"number"==typeof this.settings.logprobs||void 0,top_logprobs:"number"==typeof this.settings.logprobs?this.settings.logprobs:"boolean"==typeof this.settings.logprobs&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:i,seed:s,stop:a,response_format:u,top_k:l,messages:Mh(e),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody);if("json"===(null==u?void 0:u.type)&&null!=u.schema)return i_(o_({},m),{response_format:{type:"json_schema",json_schema:o_({schema:u.schema,strict:!0,name:null!=(p=u.name)?p:"response"},u.description&&{description:u.description})}});if(c&&c.length>0){const e=c.filter((e=>"function"===e.type)).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.inputSchema}})));return i_(o_({},m),{tools:e,tool_choice:d?Lh(d):void 0})}return m}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_,h,g,f,v,y,b,k,w,x,I;const S=(e.providerOptions||{}).openrouter||{},$=o_(o_({},this.getArgs(e)),S),{value:O,responseHeaders:T}=await Ih({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:sh(this.config.headers(),e.headers),body:$,failedResponseHandler:Ah,successfulResponseHandler:Oh(Fh),abortSignal:e.abortSignal,fetch:this.config.fetch}),E=O.choices[0];if(!E)throw new Error("No choice in response");const R=O.usage?{inputTokens:null!=(t=O.usage.prompt_tokens)?t:0,outputTokens:null!=(n=O.usage.completion_tokens)?n:0,totalTokens:(null!=(r=O.usage.prompt_tokens)?r:0)+(null!=(o=O.usage.completion_tokens)?o:0),reasoningTokens:null!=(s=null==(i=O.usage.completion_tokens_details)?void 0:i.reasoning_tokens)?s:0,cachedInputTokens:null!=(u=null==(a=O.usage.prompt_tokens_details)?void 0:a.cached_tokens)?u:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},N=null!=(l=E.message.reasoning_details)?l:[],A=N.length>0?N.map((e=>{switch(e.type){case"reasoning.text":if(e.text)return{type:"reasoning",text:e.text};break;case"reasoning.summary":if(e.summary)return{type:"reasoning",text:e.summary};break;case"reasoning.encrypted":if(e.data)return{type:"reasoning",text:"[REDACTED]"}}return null})).filter((e=>null!==e)):E.message.reasoning?[{type:"reasoning",text:E.message.reasoning}]:[],C=[];if(C.push(...A),E.message.content&&C.push({type:"text",text:E.message.content}),E.message.tool_calls)for(const P of E.message.tool_calls)C.push({type:"tool-call",toolCallId:null!=(c=P.id)?c:uh(),toolName:P.function.name,input:P.function.arguments});if(E.message.images)for(const P of E.message.images)C.push({type:"file",mediaType:Uh(P.image_url.url,"image/jpeg"),data:zh(P.image_url.url)});if(E.message.annotations)for(const P of E.message.annotations)"url_citation"===P.type&&C.push({type:"source",sourceType:"url",id:P.url_citation.url,url:P.url_citation.url,title:P.url_citation.title,providerMetadata:{openrouter:{content:P.url_citation.content||""}}});return{content:C,finishReason:Ch(E.finish_reason),usage:R,warnings:[],providerMetadata:{openrouter:{provider:null!=(d=O.provider)?d:"",usage:{promptTokens:null!=(p=R.inputTokens)?p:0,completionTokens:null!=(m=R.outputTokens)?m:0,totalTokens:null!=(_=R.totalTokens)?_:0,cost:null==(h=O.usage)?void 0:h.cost,promptTokensDetails:{cachedTokens:null!=(v=null==(f=null==(g=O.usage)?void 0:g.prompt_tokens_details)?void 0:f.cached_tokens)?v:0},completionTokensDetails:{reasoningTokens:null!=(k=null==(b=null==(y=O.usage)?void 0:y.completion_tokens_details)?void 0:b.reasoning_tokens)?k:0},costDetails:{upstreamInferenceCost:null!=(I=null==(x=null==(w=O.usage)?void 0:w.cost_details)?void 0:x.upstream_inference_cost)?I:0}}}},request:{body:$},response:{id:O.id,modelId:O.model,headers:T}}}async doStream(e){var t;const n=(e.providerOptions||{}).openrouter||{},r=o_(o_({},this.getArgs(e)),n),{value:o,responseHeaders:i}=await Ih({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:sh(this.config.headers(),e.headers),body:i_(o_({},r),{stream:!0,stream_options:"strict"===this.config.compatibility?o_({include_usage:!0},(null==(t=this.settings.usage)?void 0:t.include)?{include_usage:!0}:{}):void 0}),failedResponseHandler:Ah,successfulResponseHandler:$h(Hh),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="other";const u={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},l={};let c,d,p,m,_=!1,h=!1;return{stream:o.pipeThrough(new TransformStream({transform(e,t){var n,r,o,i,g,f,v,y,b,k,w,x,I,S;if(!e.success)return a="error",void t.enqueue({type:"error",error:e.error});const $=e.value;if("error"in $)return a="error",void t.enqueue({type:"error",error:$.error});if($.provider&&(m=$.provider),$.id&&(p=$.id,t.enqueue({type:"response-metadata",id:$.id})),$.model&&t.enqueue({type:"response-metadata",modelId:$.model}),null!=$.usage){if(u.inputTokens=$.usage.prompt_tokens,u.outputTokens=$.usage.completion_tokens,u.totalTokens=$.usage.prompt_tokens+$.usage.completion_tokens,l.promptTokens=$.usage.prompt_tokens,$.usage.prompt_tokens_details){const e=null!=(n=$.usage.prompt_tokens_details.cached_tokens)?n:0;u.cachedInputTokens=e,l.promptTokensDetails={cachedTokens:e}}if(l.completionTokens=$.usage.completion_tokens,$.usage.completion_tokens_details){const e=null!=(r=$.usage.completion_tokens_details.reasoning_tokens)?r:0;u.reasoningTokens=e,l.completionTokensDetails={reasoningTokens:e}}l.cost=$.usage.cost,l.totalTokens=$.usage.total_tokens}const O=$.choices[0];if(null!=(null==O?void 0:O.finish_reason)&&(a=Ch(O.finish_reason)),null==(null==O?void 0:O.delta))return;const T=O.delta,E=e=>{h||(d=p||uh(),t.enqueue({type:"reasoning-start",id:d}),h=!0),t.enqueue({type:"reasoning-delta",delta:e,id:d||uh()})};if(T.reasoning_details&&T.reasoning_details.length>0)for(const s of T.reasoning_details)switch(s.type){case"reasoning.text":s.text&&E(s.text);break;case"reasoning.encrypted":s.data&&E("[REDACTED]");break;case"reasoning.summary":s.summary&&E(s.summary)}else T.reasoning&&E(T.reasoning);if(T.content&&(h&&!_&&(t.enqueue({type:"reasoning-end",id:d||uh()}),h=!1),_||(c=p||uh(),t.enqueue({type:"text-start",id:c}),_=!0),t.enqueue({type:"text-delta",delta:T.content,id:c||uh()})),T.annotations)for(const s of T.annotations)"url_citation"===s.type&&t.enqueue({type:"source",sourceType:"url",id:s.url_citation.url,url:s.url_citation.url,title:s.url_citation.title,providerMetadata:{openrouter:{content:s.url_citation.content||""}}});if(null!=T.tool_calls)for(const a of T.tool_calls){const e=null!=(o=a.index)?o:s.length-1;if(null==s[e]){if("function"!==a.type)throw new j_({data:a,message:"Expected 'function' type."});if(null==a.id)throw new j_({data:a,message:"Expected 'id' to be a string."});if(null==(null==(i=a.function)?void 0:i.name))throw new j_({data:a,message:"Expected 'function.name' to be a string."});s[e]={id:a.id,type:"function",function:{name:a.function.name,arguments:null!=(g=a.function.arguments)?g:""},inputStarted:!1,sent:!1};const n=s[e];if(null==n)throw new Error("Tool call is missing");null!=(null==(f=n.function)?void 0:f.name)&&null!=(null==(v=n.function)?void 0:v.arguments)&&kh(n.function.arguments)&&(n.inputStarted=!0,t.enqueue({type:"tool-input-start",id:n.id,toolName:n.function.name}),t.enqueue({type:"tool-input-delta",id:n.id,delta:n.function.arguments}),t.enqueue({type:"tool-input-end",id:n.id}),t.enqueue({type:"tool-call",toolCallId:n.id,toolName:n.function.name,input:n.function.arguments}),n.sent=!0);continue}const n=s[e];if(null==n)throw new Error("Tool call is missing");n.inputStarted||(n.inputStarted=!0,t.enqueue({type:"tool-input-start",id:n.id,toolName:n.function.name})),null!=(null==(y=a.function)?void 0:y.arguments)&&(n.function.arguments+=null!=(k=null==(b=a.function)?void 0:b.arguments)?k:""),t.enqueue({type:"tool-input-delta",id:n.id,delta:null!=(w=a.function.arguments)?w:""}),null!=(null==(x=n.function)?void 0:x.name)&&null!=(null==(I=n.function)?void 0:I.arguments)&&kh(n.function.arguments)&&(t.enqueue({type:"tool-call",toolCallId:null!=(S=n.id)?S:uh(),toolName:n.function.name,input:n.function.arguments}),n.sent=!0)}if(null!=T.images)for(const s of T.images)t.enqueue({type:"file",mediaType:Uh(s.image_url.url,"image/jpeg"),data:zh(s.image_url.url)})},flush(e){var t;if("tool-calls"===a)for(const r of s)r&&!r.sent&&(e.enqueue({type:"tool-call",toolCallId:null!=(t=r.id)?t:uh(),toolName:r.function.name,input:kh(r.function.arguments)?r.function.arguments:"{}"}),r.sent=!0);h&&e.enqueue({type:"reasoning-end",id:d||uh()}),_&&e.enqueue({type:"text-end",id:c||uh()});const n={usage:l};void 0!==m&&(n.provider=m),e.enqueue({type:"finish",finishReason:a,usage:u,providerMetadata:{openrouter:n}})}})),warnings:[],request:{body:r},response:{headers:i}}}};var Wh=Pl([Rl({id:Du().optional(),model:Du().optional(),choices:Tl(Rl({text:Du(),reasoning:Du().nullish().optional(),reasoning_details:Rh.nullish(),finish_reason:Du().nullish(),index:ul().nullish(),logprobs:Rl({tokens:Tl(Du()),token_logprobs:Tl(ul()),top_logprobs:Tl(Zl(Du(),ul())).nullable()}).nullable().optional()})),usage:Rl({prompt_tokens:ul(),prompt_tokens_details:Rl({cached_tokens:ul()}).nullish(),completion_tokens:ul(),completion_tokens_details:Rl({reasoning_tokens:ul()}).nullish(),total_tokens:ul(),cost:ul().optional()}).nullish()}),Nh]),Jh=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=e,this.settings=t,this.config=n}getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,frequencyPenalty:o,presencePenalty:i,seed:s,responseFormat:a,topK:u,stopSequences:l,tools:c,toolChoice:d}){const{prompt:p}=function({prompt:e,inputFormat:t,user:n="user",assistant:r="assistant"}){if(1===e.length&&e[0]&&"user"===e[0].role&&1===e[0].content.length&&e[0].content[0]&&"text"===e[0].content[0].type)return{prompt:e[0].content[0].text};let o="";e[0]&&"system"===e[0].role&&(o+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:i,content:s}of e)switch(i){case"system":throw new R_({message:`Unexpected system message in prompt: ${s}`,prompt:e});case"user":o+=`${n}:\n${s.map((e=>{switch(e.type){case"text":return e.text;case"file":throw new th({functionality:"file attachments"});default:return""}})).join("")}\n\n`;break;case"assistant":o+=`${r}:\n${s.map((e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new th({functionality:"tool-call messages"});case"tool-result":throw new th({functionality:"tool-result messages"});case"reasoning":throw new th({functionality:"reasoning messages"});case"file":throw new th({functionality:"file attachments"});default:return""}})).join("")}\n\n`;break;case"tool":throw new th({functionality:"tool messages"})}return o+=`${r}:\n`,{prompt:o}}({prompt:e,inputFormat:"prompt"});if(null==c?void 0:c.length)throw new th({functionality:"tools"});if(d)throw new th({functionality:"toolChoice"});return o_(o_({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:"number"==typeof this.settings.logprobs?this.settings.logprobs:"boolean"==typeof this.settings.logprobs&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:i,seed:s,stop:l,response_format:a,top_k:u,prompt:p,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_,h;const g=(e.providerOptions||{}).openrouter||{},f=o_(o_({},this.getArgs(e)),g),{value:v,responseHeaders:y}=await Ih({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:sh(this.config.headers(),e.headers),body:f,failedResponseHandler:Ah,successfulResponseHandler:Oh(Wh),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in v)throw new Error(`${v.error.message}`);const b=v.choices[0];if(!b)throw new Error("No choice in OpenRouter completion response");return{content:[{type:"text",text:null!=(t=b.text)?t:""}],finishReason:Ch(b.finish_reason),usage:{inputTokens:null!=(r=null==(n=v.usage)?void 0:n.prompt_tokens)?r:0,outputTokens:null!=(i=null==(o=v.usage)?void 0:o.completion_tokens)?i:0,totalTokens:(null!=(a=null==(s=v.usage)?void 0:s.prompt_tokens)?a:0)+(null!=(l=null==(u=v.usage)?void 0:u.completion_tokens)?l:0),reasoningTokens:null!=(p=null==(d=null==(c=v.usage)?void 0:c.completion_tokens_details)?void 0:d.reasoning_tokens)?p:0,cachedInputTokens:null!=(h=null==(_=null==(m=v.usage)?void 0:m.prompt_tokens_details)?void 0:_.cached_tokens)?h:0},warnings:[],response:{headers:y}}}async doStream(e){const t=(e.providerOptions||{}).openrouter||{},n=o_(o_({},this.getArgs(e)),t),{value:r,responseHeaders:o}=await Ih({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:sh(this.config.headers(),e.headers),body:i_(o_({},n),{stream:!0,stream_options:"strict"===this.config.compatibility?{include_usage:!0}:void 0}),failedResponseHandler:Ah,successfulResponseHandler:$h(Wh),abortSignal:e.abortSignal,fetch:this.config.fetch});let i="other";const s={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},a={};return{stream:r.pipeThrough(new TransformStream({transform(e,t){var n,r;if(!e.success)return i="error",void t.enqueue({type:"error",error:e.error});const o=e.value;if("error"in o)return i="error",void t.enqueue({type:"error",error:o.error});if(null!=o.usage){if(s.inputTokens=o.usage.prompt_tokens,s.outputTokens=o.usage.completion_tokens,s.totalTokens=o.usage.prompt_tokens+o.usage.completion_tokens,a.promptTokens=o.usage.prompt_tokens,o.usage.prompt_tokens_details){const e=null!=(n=o.usage.prompt_tokens_details.cached_tokens)?n:0;s.cachedInputTokens=e,a.promptTokensDetails={cachedTokens:e}}if(a.completionTokens=o.usage.completion_tokens,o.usage.completion_tokens_details){const e=null!=(r=o.usage.completion_tokens_details.reasoning_tokens)?r:0;s.reasoningTokens=e,a.completionTokensDetails={reasoningTokens:e}}a.cost=o.usage.cost,a.totalTokens=o.usage.total_tokens}const u=o.choices[0];null!=(null==u?void 0:u.finish_reason)&&(i=Ch(u.finish_reason)),null!=(null==u?void 0:u.text)&&t.enqueue({type:"text-delta",delta:u.text,id:uh()})},flush(e){e.enqueue({type:"finish",finishReason:i,usage:s,providerMetadata:{openrouter:{usage:a}}})}})),response:{headers:o}}}};function Vh(e={}){var t,n,r;const o=null!=(n=null==(i=null!=(t=e.baseURL)?t:e.baseUrl)?void 0:i.replace(/\/$/,""))?n:"https://openrouter.ai/api/v1";var i;const s=null!=(r=e.compatibility)?r:"compatible",a=()=>o_({Authorization:`Bearer ${dh({apiKey:e.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},e.headers),u=(t,n={})=>new Bh(t,n,{provider:"openrouter.chat",url:({path:e})=>`${o}${e}`,headers:a,compatibility:s,fetch:e.fetch,extraBody:e.extraBody}),l=(t,n={})=>new Jh(t,n,{provider:"openrouter.completion",url:({path:e})=>`${o}${e}`,headers:a,compatibility:s,fetch:e.fetch,extraBody:e.extraBody}),c=(e,t)=>{if(new.target)throw new Error("The OpenRouter model function cannot be called with the new keyword.");return"openai/gpt-3.5-turbo-instruct"===e?l(e,t):u(e,t)},d=(e,t)=>c(e,t);return d.languageModel=c,d.chat=u,d.completion=l,d}Vh({compatibility:"strict"});var Kh=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},Gh=class{constructor(e){i(this,"getTokenFn"),i(this,"refreshTokenFn"),i(this,"onRefreshErrorFn"),this.getTokenFn=e.getTokenFn,this.refreshTokenFn=e.refreshTokenFn,this.onRefreshErrorFn=e.onRefreshErrorFn}async getAccessToken(){return this.getTokenFn()}async refreshToken(){return this.refreshTokenFn()}onRefreshError(e){this.onRefreshErrorFn&&this.onRefreshErrorFn(e)}},Yh={baseUrl:"undefined"!=typeof process&&(null==(r=process.env)?void 0:r.ECHO_BASE_URL)||"https://echo.merit.systems"};var Xh="https://echo.router.merit.systems",Qh=class{constructor(e,t){i(this,"isRefreshing",!1),i(this,"refreshPromise",null),this.baseUrl=e,this.tokenProvider=t}async request(e,t={}){var n;const r=await this.tokenProvider.getAccessToken(),o=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...r&&{Authorization:`Bearer ${r}`}}});if(401===o.status&&!(null==(n=t.headers)?void 0:n["X-Retry"])){await this.handleTokenRefresh();const n=await this.tokenProvider.getAccessToken();return fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...n&&{Authorization:`Bearer ${n}`},"X-Retry":"true"}})}return o}async handleTokenRefresh(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.performRefresh();try{await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async performRefresh(){try{await this.tokenProvider.refreshToken()}catch(e){throw this.tokenProvider.onRefreshError&&this.tokenProvider.onRefreshError(e),e}}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,n){return this.request(e,{...n,method:"POST",body:t?JSON.stringify(t):null})}async put(e,t,n){return this.request(e,{...n,method:"PUT",body:t?JSON.stringify(t):null})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}},eg=class extends Error{constructor(e,t,n){super(t),i(this,"code"),i(this,"statusCode"),i(this,"endpoint"),this.name="EchoError",this.code=e,void 0!==(null==n?void 0:n.statusCode)&&(this.statusCode=n.statusCode),void 0!==(null==n?void 0:n.endpoint)&&(this.endpoint=n.endpoint)}};function tg(e,t,n){if("TypeError"===e.name)return new eg("NETWORK_ERROR","Network error"+(t?` while ${t}`:""),n?{endpoint:n}:void 0);const r=e.message.match(/^HTTP (\d+): (.*)$/);if(r&&r[1]&&r[2]){const e=parseInt(r[1]),o=r[2];return new eg(`HTTP_${e}`,`${o}${t?` while ${t}`:""}`,n?{statusCode:e,endpoint:n}:{statusCode:e})}return new eg("UNKNOWN_ERROR",`${e.message}${t?` while ${t}`:""}`,n?{endpoint:n}:void 0)}var ng=class{constructor(e){this.http=e}async handleRequest(e,t,n){try{const t=await e();if(!t.ok){const e=await t.text();throw new Error(`HTTP ${t.status}: ${e}`)}return await t.json()}catch(r){if(r instanceof Error)throw tg(r,t,n);throw new eg("UNKNOWN_ERROR","Unknown error occurred",n?{endpoint:n}:void 0)}}},rg=class extends ng{constructor(e,t){super(e),this.baseUrl=t}async listEchoApps(){return(await this.handleRequest((()=>this.http.get("/api/v1/apps")),"listing Echo apps","/api/v1/apps")).apps}async getEchoApp(e){return this.handleRequest((()=>this.http.get(`/api/v1/apps/${e}`)),"fetching Echo app",`/api/v1/apps/${e}`)}getAppUrl(e){return`${this.baseUrl}/apps/${e}`}},og=class extends ng{constructor(e){super(e)}async getBalance(){return this.handleRequest((()=>this.http.get("/api/v1/balance")),"fetching balance","/api/v1/balance")}async getFreeBalance(e){const t={echoAppId:e};return this.handleRequest((()=>this.http.post("/api/v1/balance/free",t)),"fetching free tier balance","/api/v1/balance/free")}},ig=[{model_id:"claude-3-5-haiku-20241022",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"Anthropic"},{model_id:"claude-3-5-sonnet-20240620",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-5-sonnet-20241022",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-7-sonnet-20250219",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-haiku-20240307",input_cost_per_token:25e-8,output_cost_per_token:125e-8,provider:"Anthropic"},{model_id:"claude-3-opus-20240229",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-opus-4-1-20250805",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-opus-4-20250514",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-sonnet-4-20250514",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"}],sg=[{model_id:"gemini-2.0-flash",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-001",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-exp",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-exp-image-generation",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-001",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-preview",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-preview-02-05",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-preview-image-generation",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp-01-21",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp-1219",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-image-preview",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-lite",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-lite-preview-06-17",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-preview-05-20",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-preview-tts",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-pro",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-03-25",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-05-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-06-05",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-tts",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"}],ag=[{model_id:"gpt-3.5-turbo",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-3.5-turbo-0125",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-3.5-turbo-1106",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-4",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-0125-preview",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-0613",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-1106-preview",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-turbo",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4-turbo-2024-04-09",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4-turbo-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4.1",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"gpt-4.1-2025-04-14",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"gpt-4.1-mini",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4.1-mini-2025-04-14",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4.1-nano",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-4.1-nano-2025-04-14",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-4o",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-05-13",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-08-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-11-20",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-mini",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenAI"},{model_id:"gpt-4o-mini-2024-07-18",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenAI"},{model_id:"gpt-5",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-2025-08-07",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-chat-latest",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-mini",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenAI"},{model_id:"gpt-5-mini-2025-08-07",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenAI"},{model_id:"gpt-5-nano",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-5-nano-2025-08-07",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"o1",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-2024-12-17",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-pro",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-pro-2025-03-19",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o3",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-2025-04-16",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-deep-research",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-deep-research-2025-06-26",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenAI"},{model_id:"o3-mini-2025-01-31",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenAI"},{model_id:"o3-pro",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-pro-2025-06-10",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"}],ug=[{model_id:"agentica-org/deepcoder-14b-preview",input_cost_per_token:15e-9,output_cost_per_token:15e-9,provider:"OpenRouter"},{model_id:"agentica-org/deepcoder-14b-preview:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"ai21/jamba-large-1.7",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"ai21/jamba-mini-1.7",input_cost_per_token:2e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"aion-labs/aion-1.0",input_cost_per_token:4e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"aion-labs/aion-1.0-mini",input_cost_per_token:7e-7,output_cost_per_token:14e-7,provider:"OpenRouter"},{model_id:"aion-labs/aion-rp-llama-3.1-8b",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"alfredpros/codellama-7b-instruct-solidity",input_cost_per_token:7e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"alpindale/goliath-120b",input_cost_per_token:4e-6,output_cost_per_token:55e-7,provider:"OpenRouter"},{model_id:"amazon/nova-lite-v1",input_cost_per_token:6e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"amazon/nova-micro-v1",input_cost_per_token:35e-9,output_cost_per_token:14e-8,provider:"OpenRouter"},{model_id:"amazon/nova-pro-v1",input_cost_per_token:8e-7,output_cost_per_token:32e-7,provider:"OpenRouter"},{model_id:"anthracite-org/magnum-v2-72b",input_cost_per_token:3e-6,output_cost_per_token:3e-6,provider:"OpenRouter"},{model_id:"anthracite-org/magnum-v4-72b",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3-haiku",input_cost_per_token:25e-8,output_cost_per_token:125e-8,provider:"OpenRouter"},{model_id:"anthropic/claude-3-opus",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-haiku",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-haiku-20241022",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-sonnet",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-sonnet-20240620",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.7-sonnet",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.7-sonnet:thinking",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-opus-4",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-opus-4.1",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-sonnet-4",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"arcee-ai/coder-large",input_cost_per_token:5e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"arcee-ai/maestro-reasoning",input_cost_per_token:9e-7,output_cost_per_token:33e-7,provider:"OpenRouter"},{model_id:"arcee-ai/spotlight",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"arcee-ai/virtuoso-large",input_cost_per_token:75e-8,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"arliai/qwq-32b-arliai-rpr-v1",input_cost_per_token:1e-8,output_cost_per_token:4.00032e-8,provider:"OpenRouter"},{model_id:"arliai/qwq-32b-arliai-rpr-v1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-21b-a3b",input_cost_per_token:7e-8,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-300b-a47b",input_cost_per_token:28e-8,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-vl-28b-a3b",input_cost_per_token:14e-8,output_cost_per_token:56e-8,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-vl-424b-a47b",input_cost_per_token:42e-8,output_cost_per_token:125e-8,provider:"OpenRouter"},{model_id:"bytedance/ui-tars-1.5-7b",input_cost_per_token:1e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin-mistral-24b-venice-edition:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin-mixtral-8x22b",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-mistral-24b",input_cost_per_token:3.7022e-8,output_cost_per_token:1.4816e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-mistral-24b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-r1-mistral-24b",input_cost_per_token:1e-8,output_cost_per_token:3.40768e-8,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-r1-mistral-24b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cohere/command",input_cost_per_token:1e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"cohere/command-a",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"cohere/command-r",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-03-2024",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-08-2024",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-plus",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"cohere/command-r-plus-04-2024",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"cohere/command-r-plus-08-2024",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"cohere/command-r7b-12-2024",input_cost_per_token:3.75e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3-0324",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3-0324:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3.1",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-prover-v2",input_cost_per_token:5e-7,output_cost_per_token:218e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528-qwen3-8b",input_cost_per_token:1e-8,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528-qwen3-8b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-70b",input_cost_per_token:2.59154e-8,output_cost_per_token:1.03712e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-70b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-8b",input_cost_per_token:4e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-1.5b",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-14b",input_cost_per_token:15e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-14b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-32b",input_cost_per_token:75e-9,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-v3.1-base",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"eleutherai/llemma_7b",input_cost_per_token:8e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-001",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-exp:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-lite-001",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash-lite",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash-lite-preview-06-17",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-exp-03-25",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-preview",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-preview-05-06",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-flash-1.5",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"google/gemini-flash-1.5-8b",input_cost_per_token:3.75e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"google/gemini-pro-1.5",input_cost_per_token:125e-8,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"google/gemma-2-27b-it",input_cost_per_token:65e-8,output_cost_per_token:65e-8,provider:"OpenRouter"},{model_id:"google/gemma-2-9b-it",input_cost_per_token:1e-8,output_cost_per_token:1.00008e-8,provider:"OpenRouter"},{model_id:"google/gemma-2-9b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-12b-it",input_cost_per_token:4.81286e-8,output_cost_per_token:1.92608e-7,provider:"OpenRouter"},{model_id:"google/gemma-3-12b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-27b-it",input_cost_per_token:6.66396e-8,output_cost_per_token:2.66688e-7,provider:"OpenRouter"},{model_id:"google/gemma-3-27b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-4b-it",input_cost_per_token:2e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"google/gemma-3-4b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3n-e2b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3n-e4b-it",input_cost_per_token:2e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"google/gemma-3n-e4b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"gryphe/mythomax-l2-13b",input_cost_per_token:6e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"inception/mercury",input_cost_per_token:25e-8,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"inception/mercury-coder",input_cost_per_token:25e-8,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"infermatic/mn-inferor-12b",input_cost_per_token:6e-7,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"inflection/inflection-3-pi",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"inflection/inflection-3-productivity",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"liquid/lfm-3b",input_cost_per_token:2e-8,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"liquid/lfm-7b",input_cost_per_token:1e-8,output_cost_per_token:1e-8,provider:"OpenRouter"},{model_id:"mancer/weaver",input_cost_per_token:1125e-9,output_cost_per_token:1125e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3-70b-instruct",input_cost_per_token:3e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3-8b-instruct",input_cost_per_token:3e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b",input_cost_per_token:2e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b-instruct",input_cost_per_token:8e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-70b-instruct",input_cost_per_token:1e-7,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-8b-instruct",input_cost_per_token:15e-9,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-11b-vision-instruct",input_cost_per_token:49e-9,output_cost_per_token:49e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-11b-vision-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-1b-instruct",input_cost_per_token:5e-9,output_cost_per_token:1e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-3b-instruct",input_cost_per_token:3e-9,output_cost_per_token:6e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-3b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-90b-vision-instruct",input_cost_per_token:12e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-70b-instruct",input_cost_per_token:38e-9,output_cost_per_token:12e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-70b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-8b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-maverick",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-maverick:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-scout",input_cost_per_token:8e-8,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-scout:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-2-8b",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-3-8b",input_cost_per_token:2e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-4-12b",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"microsoft/mai-ds-r1",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"microsoft/mai-ds-r1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"microsoft/phi-3-medium-128k-instruct",input_cost_per_token:1e-6,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"microsoft/phi-3-mini-128k-instruct",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-3.5-mini-128k-instruct",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-4",input_cost_per_token:6e-8,output_cost_per_token:14e-8,provider:"OpenRouter"},{model_id:"microsoft/phi-4-multimodal-instruct",input_cost_per_token:5e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-4-reasoning-plus",input_cost_per_token:7e-8,output_cost_per_token:35e-8,provider:"OpenRouter"},{model_id:"microsoft/wizardlm-2-8x22b",input_cost_per_token:48e-8,output_cost_per_token:48e-8,provider:"OpenRouter"},{model_id:"minimax/minimax-01",input_cost_per_token:2e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"minimax/minimax-m1",input_cost_per_token:3e-7,output_cost_per_token:165e-8,provider:"OpenRouter"},{model_id:"mistralai/codestral-2501",input_cost_per_token:3e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/codestral-2508",input_cost_per_token:3e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/devstral-medium",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/devstral-small",input_cost_per_token:7e-8,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"mistralai/devstral-small-2505",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/devstral-small-2505:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/magistral-medium-2506",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"mistralai/magistral-medium-2506:thinking",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"mistralai/magistral-small-2506",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"mistralai/ministral-3b",input_cost_per_token:4e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"mistralai/ministral-8b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct",input_cost_per_token:28e-9,output_cost_per_token:54e-9,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct-v0.1",input_cost_per_token:11e-8,output_cost_per_token:19e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct-v0.3",input_cost_per_token:28e-9,output_cost_per_token:54e-9,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-large",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-large-2407",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-large-2411",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-medium-3",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-medium-3.1",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-nemo",input_cost_per_token:7.5e-9,output_cost_per_token:5e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-nemo:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-saba",input_cost_per_token:2e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small",input_cost_per_token:2e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-24b-instruct-2501",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-24b-instruct-2501:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.1-24b-instruct",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.1-24b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.2-24b-instruct",input_cost_per_token:5e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.2-24b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-tiny",input_cost_per_token:25e-8,output_cost_per_token:25e-8,provider:"OpenRouter"},{model_id:"mistralai/mixtral-8x22b-instruct",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/mixtral-8x7b-instruct",input_cost_per_token:8e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"mistralai/pixtral-12b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/pixtral-large-2411",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"moonshotai/kimi-dev-72b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"moonshotai/kimi-k2",input_cost_per_token:14e-8,output_cost_per_token:249e-8,provider:"OpenRouter"},{model_id:"moonshotai/kimi-k2:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"moonshotai/kimi-vl-a3b-thinking",input_cost_per_token:2.498985e-8,output_cost_per_token:1.00008e-7,provider:"OpenRouter"},{model_id:"moonshotai/kimi-vl-a3b-thinking:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"morph/morph-v3-fast",input_cost_per_token:9e-7,output_cost_per_token:19e-7,provider:"OpenRouter"},{model_id:"morph/morph-v3-large",input_cost_per_token:9e-7,output_cost_per_token:19e-7,provider:"OpenRouter"},{model_id:"neversleep/llama-3-lumimaid-70b",input_cost_per_token:4e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"neversleep/llama-3.1-lumimaid-8b",input_cost_per_token:9e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"neversleep/noromaid-20b",input_cost_per_token:1e-6,output_cost_per_token:175e-8,provider:"OpenRouter"},{model_id:"nousresearch/deephermes-3-llama-3-8b-preview:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"nousresearch/deephermes-3-mistral-24b-preview",input_cost_per_token:9.329544e-8,output_cost_per_token:3.733632e-7,provider:"OpenRouter"},{model_id:"nousresearch/hermes-2-pro-llama-3-8b",input_cost_per_token:25e-9,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"nousresearch/hermes-3-llama-3.1-405b",input_cost_per_token:7e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"nousresearch/hermes-3-llama-3.1-70b",input_cost_per_token:1e-7,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"nousresearch/hermes-4-405b",input_cost_per_token:1e-6,output_cost_per_token:3e-6,provider:"OpenRouter"},{model_id:"nousresearch/hermes-4-70b",input_cost_per_token:13e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"nousresearch/nous-hermes-2-mixtral-8x7b-dpo",input_cost_per_token:6e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-70b-instruct",input_cost_per_token:12e-8,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-ultra-253b-v1",input_cost_per_token:6e-7,output_cost_per_token:18e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-ultra-253b-v1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"nvidia/llama-3.3-nemotron-super-49b-v1",input_cost_per_token:13e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/chatgpt-4o-latest",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"openai/codex-mini",input_cost_per_token:15e-7,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-0613",input_cost_per_token:1e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-16k",input_cost_per_token:3e-6,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-instruct",input_cost_per_token:15e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4",input_cost_per_token:3e-5,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-0314",input_cost_per_token:3e-5,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-1106-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-turbo",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-turbo-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4.1",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4.1-mini",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4.1-nano",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-05-13",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-08-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-11-20",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-audio-preview",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini-2024-07-18",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini-search-preview",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-search-preview",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o:extended",input_cost_per_token:6e-6,output_cost_per_token:18e-6,provider:"OpenRouter"},{model_id:"openai/gpt-5",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-5-chat",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-5-mini",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-5-nano",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/gpt-oss-120b",input_cost_per_token:72e-9,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"openai/gpt-oss-20b",input_cost_per_token:4e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"openai/gpt-oss-20b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"openai/o1",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/o1-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o1-mini-2024-09-12",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o1-pro",input_cost_per_token:15e-5,output_cost_per_token:6e-4,provider:"OpenRouter"},{model_id:"openai/o3",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"openai/o3-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o3-mini-high",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o3-pro",input_cost_per_token:2e-5,output_cost_per_token:8e-5,provider:"OpenRouter"},{model_id:"openai/o4-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o4-mini-high",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"opengvlab/internvl3-14b",input_cost_per_token:2e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openrouter/auto",input_cost_per_token:-1,output_cost_per_token:-1,provider:"OpenRouter"},{model_id:"perplexity/r1-1776",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar",input_cost_per_token:1e-6,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-deep-research",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-pro",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-reasoning",input_cost_per_token:1e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-reasoning-pro",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"pygmalionai/mythalion-13b",input_cost_per_token:7e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2-72b-instruct",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-72b-instruct",input_cost_per_token:5.18308e-8,output_cost_per_token:2.07424e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-72b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-7b-instruct",input_cost_per_token:4e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-coder-32b-instruct",input_cost_per_token:4.99797e-8,output_cost_per_token:2.00016e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-coder-32b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-vl-7b-instruct",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-max",input_cost_per_token:16e-7,output_cost_per_token:64e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-plus",input_cost_per_token:4e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-turbo",input_cost_per_token:5e-8,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-vl-max",input_cost_per_token:8e-7,output_cost_per_token:32e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-vl-plus",input_cost_per_token:21e-8,output_cost_per_token:63e-8,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-32b-instruct",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-32b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-72b-instruct",input_cost_per_token:9.99594e-8,output_cost_per_token:4.00032e-7,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-72b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-14b",input_cost_per_token:6e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-14b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b",input_cost_per_token:13e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b-2507",input_cost_per_token:7.7968332e-8,output_cost_per_token:3.1202496e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b-thinking-2507",input_cost_per_token:7.7968332e-8,output_cost_per_token:3.1202496e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b-instruct-2507",input_cost_per_token:1e-7,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-32b",input_cost_per_token:1.7992692e-8,output_cost_per_token:7.200576e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-4b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-8b",input_cost_per_token:35e-9,output_cost_per_token:138e-9,provider:"OpenRouter"},{model_id:"qwen/qwen3-8b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-coder",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-coder:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwq-32b",input_cost_per_token:75e-9,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"qwen/qwq-32b-preview",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwq-32b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"raifle/sorcererlm-8x22b",input_cost_per_token:45e-7,output_cost_per_token:45e-7,provider:"OpenRouter"},{model_id:"rekaai/reka-flash-3:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"sao10k/l3-euryale-70b",input_cost_per_token:148e-8,output_cost_per_token:148e-8,provider:"OpenRouter"},{model_id:"sao10k/l3-lunaris-8b",input_cost_per_token:2e-8,output_cost_per_token:5e-8,provider:"OpenRouter"},{model_id:"sao10k/l3.1-euryale-70b",input_cost_per_token:65e-8,output_cost_per_token:75e-8,provider:"OpenRouter"},{model_id:"sao10k/l3.3-euryale-70b",input_cost_per_token:65e-8,output_cost_per_token:75e-8,provider:"OpenRouter"},{model_id:"sarvamai/sarvam-m:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"scb10x/llama3.1-typhoon2-70b-instruct",input_cost_per_token:88e-8,output_cost_per_token:88e-8,provider:"OpenRouter"},{model_id:"shisa-ai/shisa-v2-llama3.3-70b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"shisa-ai/shisa-v2-llama3.3-70b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"sophosympatheia/midnight-rose-70b",input_cost_per_token:8e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"switchpoint/router",input_cost_per_token:85e-8,output_cost_per_token:34e-7,provider:"OpenRouter"},{model_id:"tencent/hunyuan-a13b-instruct",input_cost_per_token:3e-8,output_cost_per_token:3e-8,provider:"OpenRouter"},{model_id:"tencent/hunyuan-a13b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"thedrummer/anubis-70b-v1.1",input_cost_per_token:4e-7,output_cost_per_token:7e-7,provider:"OpenRouter"},{model_id:"thedrummer/anubis-pro-105b-v1",input_cost_per_token:5e-7,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"thedrummer/rocinante-12b",input_cost_per_token:17e-8,output_cost_per_token:43e-8,provider:"OpenRouter"},{model_id:"thedrummer/skyfall-36b-v2",input_cost_per_token:4.81286e-8,output_cost_per_token:1.92608e-7,provider:"OpenRouter"},{model_id:"thedrummer/unslopnemo-12b",input_cost_per_token:4e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"thudm/glm-4-32b",input_cost_per_token:55e-8,output_cost_per_token:166e-8,provider:"OpenRouter"},{model_id:"thudm/glm-4.1v-9b-thinking",input_cost_per_token:35e-9,output_cost_per_token:138e-9,provider:"OpenRouter"},{model_id:"thudm/glm-z1-32b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t-chimera",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t-chimera:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t2-chimera:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"undi95/remm-slerp-l2-13b",input_cost_per_token:45e-8,output_cost_per_token:65e-8,provider:"OpenRouter"},{model_id:"x-ai/grok-2-1212",input_cost_per_token:2e-6,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"x-ai/grok-2-vision-1212",input_cost_per_token:2e-6,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"x-ai/grok-3",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-3-beta",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-3-mini",input_cost_per_token:3e-7,output_cost_per_token:5e-7,provider:"OpenRouter"},{model_id:"x-ai/grok-3-mini-beta",input_cost_per_token:3e-7,output_cost_per_token:5e-7,provider:"OpenRouter"},{model_id:"x-ai/grok-4",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-code-fast-1",input_cost_per_token:2e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"x-ai/grok-vision-beta",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"z-ai/glm-4-32b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5-air",input_cost_per_token:2e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5-air:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5v",input_cost_per_token:5e-7,output_cost_per_token:18e-7,provider:"OpenRouter"}],lg=[{model_id:"gpt-image-1",image_input_cost_per_token:1e-5,image_output_cost_per_token:4e-5,text_input_cost_per_token:5e-6,provider:"OpenAI"}],cg=class extends ng{constructor(e){super(e)}async listSupportedChatModels(){return[...ag,...ig,...sg,...ug]}async listSupportedImageModels(){return lg}},dg=class extends ng{constructor(e){super(e)}async createPaymentLink(e){return this.handleRequest((()=>this.http.post("/api/v1/stripe/payment-link",e)),"creating payment link","/api/v1/stripe/payment-link")}async getPaymentUrl(e,t,n){const r={amount:e,description:t||"Echo Credits"};n&&(r.successUrl=n);try{return(await this.createPaymentLink(r)).paymentLink.url}catch(o){throw o}}},pg=class extends ng{constructor(e){super(e)}async getUserInfo(){return this.handleRequest((()=>this.http.get("/api/v1/user")),"fetching user info","/api/v1/user")}async registerReferralCode(e,t){const n={echoAppId:e,code:t};return this.handleRequest((()=>this.http.post("/api/v1/user/referral",n)),"registering referral code","/api/v1/user/referral")}},mg=class{constructor(e){var t;if(i(this,"http"),i(this,"config"),i(this,"tokenProvider"),i(this,"balance"),i(this,"payments"),i(this,"apps"),i(this,"users"),i(this,"models"),this.config=(t=e,{...Yh,...t}),null==e?void 0:e.tokenProvider)this.tokenProvider=e.tokenProvider;else{const e=this.config.apiKey||process.env.ECHO_API_KEY;if(!e)throw new Error("No API key or token provider provided");this.tokenProvider=new Kh(e)}this.http=new Qh(this.config.baseUrl,this.tokenProvider),this.balance=new og(this.http),this.payments=new dg(this.http),this.apps=new rg(this.http,this.config.baseUrl),this.users=new pg(this.http),this.models=new cg(this.http)}};function _g({appId:e,baseRouterUrl:t=Xh},n,r){return kp({baseURL:t,apiKey:"placeholder_replaced_by_echoFetch",headers:{"anthropic-dangerous-direct-browser-access":"true"},fetch:vg(fetch,(async()=>await n(e)),r)})}function hg({appId:e,baseRouterUrl:t=Xh},n,r){return Vp({baseURL:t,apiKey:"placeholder_replaced_by_echoFetch",fetch:vg(fetch,(async()=>await n(e)),r)})}function gg({appId:e,baseRouterUrl:t=Xh},n,r){return Km({baseURL:t,apiKey:"placeholder_replaced_by_echoFetch",fetch:vg(fetch,(async()=>await n(e)),r)})}function fg({appId:e,baseRouterUrl:t=Xh},n,r){return Vh({baseURL:t,apiKey:"placeholder_replaced_by_echoFetch",fetch:vg(fetch,(async()=>await n(e)),r)})}function vg(e,t,n){return async(r,o)=>{const i=await t();o&&(o.headers={...o.headers,Authorization:`Bearer ${i}`});const s=await e(r,o);return 402===s.status&&(null==n||n()),s.status,s}}function yg({apiUrl:e}){var t,r;const o=Oe(),[i,s]=n.useState(null);return n.useEffect((()=>{if(!o.user)return void s(null);const t=new Gh({getTokenFn:()=>{var e;return Promise.resolve((null==(e=o.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{const e=await o.signinSilent();if(!e)throw new Error("Silent renew did not yield a new access token");return e.access_token},onRefreshErrorFn:async e=>{console.error("Token refresh failed:",e),await o.removeUser(),await o.clearStaleState()}}),n=new mg({baseUrl:e,tokenProvider:t});return s(n),()=>{s(null)}}),[e,o.user,null==(r=null==(t=o.user)?void 0:t.profile)?void 0:r.sub,o.signinSilent,o.signoutSilent]),i}const bg=n.createContext(null),kg=n.createContext(null);function wg({config:e,children:r}){var o,i,s;const a=Oe(),u=a.user,l=e.baseEchoUrl||"https://echo.merit.systems",c=(null==(o=a.user)?void 0:o.access_token)||null,d=yg({apiUrl:l}),[p,m]=n.useState(!1),{balance:_,freeTierBalance:h,refreshBalance:g,error:f,isLoading:v}=function(e,t){const[r,o]=n.useState(null),[i,s]=n.useState(null),[a,u]=n.useState(null),[l,c]=n.useState(!1),d=n.useCallback((async()=>{if(!e)throw new Error("Not authenticated");c(!0);try{const[n,r]=await Promise.all([e.balance.getBalance(),e.balance.getFreeBalance(t)]);o(n),s(r),u(null)}catch(n){const e=tg(n instanceof Error?n:new Error(String(n)),"refreshing balance");throw u(e.message),e}finally{c(!1)}}),[e,t]);return n.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(o(null),s(null),u(null))}),[e,t,d]),{balance:r,freeTierBalance:i,error:a,isLoading:l,refreshBalance:d}}(d,e.appId),{user:y,error:b,isLoading:k}=function(e){const[t,r]=n.useState(null),[o,i]=n.useState(null),[s,a]=n.useState(!1),u=n.useCallback((async()=>{if(!e)throw new Error("Not authenticated");a(!0);try{const t=await e.users.getUserInfo();r(t),i(null)}catch(t){const e=tg(t instanceof Error?t:new Error(String(t)),"refreshing user");throw i(e.message),e}finally{a(!1)}}),[e]);return n.useEffect((()=>{e?u().catch((e=>{console.error("Error loading initial user:",e)})):(r(null),i(null))}),[e,u]),{user:t,error:o,isLoading:s,refreshUser:u}}(d),{createPaymentLink:w,error:x,isLoading:I}=function(e){const[t,r]=n.useState(null),[o,i]=n.useState(!1);return{createPaymentLink:n.useCallback((async(t,n,o)=>{if(!e)throw new Error("Not authenticated");i(!0);try{const i=await e.payments.createPaymentLink({amount:t,description:n||"Echo Credits",successUrl:o||window.location.origin});return r(null),i.paymentLink.url}catch(s){const e=tg(s instanceof Error?s:new Error(String(s)),"creating payment link");throw r(e.message),e}finally{i(!1)}}),[e]),error:t,isLoading:o}}(d),S=n.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),$=n.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(i=a.user)?void 0:i.access_token]),O=(null==(s=a.error)?void 0:s.message)||f||x||b||null,T=a.isLoading&&!a.isAuthenticated,E=a.isLoading&&a.isAuthenticated,R=T||v||I||k,N=n.useMemo((()=>({user:y,rawUser:u,balance:_,freeTierBalance:h,isAuthenticated:a.isAuthenticated,isLoading:R,error:O,token:c,echoClient:d,signIn:a.signinRedirect,signOut:S,refreshBalance:g,createPaymentLink:w,getToken:$,clearAuth:S,config:e,isInsufficientFunds:p,setIsInsufficientFunds:m})),[y,u,_,h,a.isAuthenticated,R,O,c,d,a.signinRedirect,S,g,w,$,e,p]),A=n.useMemo((()=>({isRefreshing:E})),[E]);return t.jsx(bg.Provider,{value:N,children:t.jsx(kg.Provider,{value:A,children:r})})}function xg(){const e=n.useContext(bg);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}
2
+ /*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:Ig,setPrototypeOf:Sg,isFrozen:$g,getPrototypeOf:Og,getOwnPropertyDescriptor:Tg}=Object;let{freeze:Eg,seal:Rg,create:Ng}=Object,{apply:Ag,construct:Cg}="undefined"!=typeof Reflect&&Reflect;Eg||(Eg=function(e){return e}),Rg||(Rg=function(e){return e}),Ag||(Ag=function(e,t,n){return e.apply(t,n)}),Cg||(Cg=function(e,t){return new e(...t)});const Pg=Kg(Array.prototype.forEach),jg=Kg(Array.prototype.lastIndexOf),Ug=Kg(Array.prototype.pop),zg=Kg(Array.prototype.push),Dg=Kg(Array.prototype.splice),Mg=Kg(String.prototype.toLowerCase),Lg=Kg(String.prototype.toString),qg=Kg(String.prototype.match),Zg=Kg(String.prototype.replace),Fg=Kg(String.prototype.indexOf),Hg=Kg(String.prototype.trim),Bg=Kg(Object.prototype.hasOwnProperty),Wg=Kg(RegExp.prototype.test),Jg=(Vg=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Cg(Vg,t)});var Vg;function Kg(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Ag(e,t,r)}}function Gg(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Mg;Sg&&Sg(e,null);let r=t.length;for(;r--;){let o=t[r];if("string"==typeof o){const e=n(o);e!==o&&($g(t)||(t[r]=e),o=e)}e[o]=!0}return e}function Yg(e){for(let t=0;t<e.length;t++){Bg(e,t)||(e[t]=null)}return e}function Xg(e){const t=Ng(null);for(const[n,r]of Ig(e)){Bg(e,n)&&(Array.isArray(r)?t[n]=Yg(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=Xg(r):t[n]=r)}return t}function Qg(e,t){for(;null!==e;){const n=Tg(e,t);if(n){if(n.get)return Kg(n.get);if("function"==typeof n.value)return Kg(n.value)}e=Og(e)}return function(){return null}}const ef=Eg(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),tf=Eg(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),nf=Eg(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),rf=Eg(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),of=Eg(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),sf=Eg(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),af=Eg(["#text"]),uf=Eg(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),lf=Eg(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),cf=Eg(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),df=Eg(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),pf=Rg(/\{\{[\w\W]*|[\w\W]*\}\}/gm),mf=Rg(/<%[\w\W]*|[\w\W]*%>/gm),_f=Rg(/\$\{[\w\W]*/gm),hf=Rg(/^data-[\-\w.\u00B7-\uFFFF]+$/),gf=Rg(/^aria-[\-\w]+$/),ff=Rg(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),vf=Rg(/^(?:\w+script|data):/i),yf=Rg(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),bf=Rg(/^html$/i),kf=Rg(/^[a-z][.\w]*(-[.\w]+)+$/i);var wf=Object.freeze({__proto__:null,ARIA_ATTR:gf,ATTR_WHITESPACE:yf,CUSTOM_ELEMENT:kf,DATA_ATTR:hf,DOCTYPE_NAME:bf,ERB_EXPR:mf,IS_ALLOWED_URI:ff,IS_SCRIPT_OR_DATA:vf,MUSTACHE_EXPR:pf,TMPLIT_EXPR:_f});const xf=1,If=3,Sf=7,$f=8,Of=9;var Tf=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const n=t=>e(t);if(n.version="3.2.6",n.removed=[],!t||!t.document||t.document.nodeType!==Of||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const o=r,i=o.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:u,Element:l,NodeFilter:c,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:_}=t,h=l.prototype,g=Qg(h,"cloneNode"),f=Qg(h,"remove"),v=Qg(h,"nextSibling"),y=Qg(h,"childNodes"),b=Qg(h,"parentNode");if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let k,w="";const{implementation:x,createNodeIterator:I,createDocumentFragment:S,getElementsByTagName:$}=r,{importNode:O}=o;let T={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof Ig&&"function"==typeof b&&x&&void 0!==x.createHTMLDocument;const{MUSTACHE_EXPR:E,ERB_EXPR:R,TMPLIT_EXPR:N,DATA_ATTR:A,ARIA_ATTR:C,IS_SCRIPT_OR_DATA:P,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:U}=wf;let{IS_ALLOWED_URI:z}=wf,D=null;const M=Gg({},[...ef,...tf,...nf,...of,...af]);let L=null;const q=Gg({},[...uf,...lf,...cf,...df]);let Z=Object.seal(Ng(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),F=null,H=null,B=!0,W=!0,J=!1,V=!0,K=!1,G=!0,Y=!1,X=!1,Q=!1,ee=!1,te=!1,ne=!1,re=!0,oe=!1,ie=!0,se=!1,ae={},ue=null;const le=Gg({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ce=null;const de=Gg({},["audio","video","img","source","image","track"]);let pe=null;const me=Gg({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_e="http://www.w3.org/1998/Math/MathML",he="http://www.w3.org/2000/svg",ge="http://www.w3.org/1999/xhtml";let fe=ge,ve=!1,ye=null;const be=Gg({},[_e,he,ge],Lg);let ke=Gg({},["mi","mo","mn","ms","mtext"]),we=Gg({},["annotation-xml"]);const xe=Gg({},["title","style","font","a","script"]);let Ie=null;const Se=["application/xhtml+xml","text/html"];let $e=null,Oe=null;const Te=r.createElement("form"),Ee=function(e){return e instanceof RegExp||e instanceof Function},Re=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Oe||Oe!==e){if(e&&"object"==typeof e||(e={}),e=Xg(e),Ie=-1===Se.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,$e="application/xhtml+xml"===Ie?Lg:Mg,D=Bg(e,"ALLOWED_TAGS")?Gg({},e.ALLOWED_TAGS,$e):M,L=Bg(e,"ALLOWED_ATTR")?Gg({},e.ALLOWED_ATTR,$e):q,ye=Bg(e,"ALLOWED_NAMESPACES")?Gg({},e.ALLOWED_NAMESPACES,Lg):be,pe=Bg(e,"ADD_URI_SAFE_ATTR")?Gg(Xg(me),e.ADD_URI_SAFE_ATTR,$e):me,ce=Bg(e,"ADD_DATA_URI_TAGS")?Gg(Xg(de),e.ADD_DATA_URI_TAGS,$e):de,ue=Bg(e,"FORBID_CONTENTS")?Gg({},e.FORBID_CONTENTS,$e):le,F=Bg(e,"FORBID_TAGS")?Gg({},e.FORBID_TAGS,$e):Xg({}),H=Bg(e,"FORBID_ATTR")?Gg({},e.FORBID_ATTR,$e):Xg({}),ae=!!Bg(e,"USE_PROFILES")&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,W=!1!==e.ALLOW_DATA_ATTR,J=e.ALLOW_UNKNOWN_PROTOCOLS||!1,V=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,K=e.SAFE_FOR_TEMPLATES||!1,G=!1!==e.SAFE_FOR_XML,Y=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,ne=e.RETURN_TRUSTED_TYPE||!1,Q=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,oe=e.SANITIZE_NAMED_PROPS||!1,ie=!1!==e.KEEP_CONTENT,se=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||ff,fe=e.NAMESPACE||ge,ke=e.MATHML_TEXT_INTEGRATION_POINTS||ke,we=e.HTML_INTEGRATION_POINTS||we,Z=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Ee(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Ee(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Z.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),K&&(W=!1),te&&(ee=!0),ae&&(D=Gg({},af),L=[],!0===ae.html&&(Gg(D,ef),Gg(L,uf)),!0===ae.svg&&(Gg(D,tf),Gg(L,lf),Gg(L,df)),!0===ae.svgFilters&&(Gg(D,nf),Gg(L,lf),Gg(L,df)),!0===ae.mathMl&&(Gg(D,of),Gg(L,cf),Gg(L,df))),e.ADD_TAGS&&(D===M&&(D=Xg(D)),Gg(D,e.ADD_TAGS,$e)),e.ADD_ATTR&&(L===q&&(L=Xg(L)),Gg(L,e.ADD_ATTR,$e)),e.ADD_URI_SAFE_ATTR&&Gg(pe,e.ADD_URI_SAFE_ATTR,$e),e.FORBID_CONTENTS&&(ue===le&&(ue=Xg(ue)),Gg(ue,e.FORBID_CONTENTS,$e)),ie&&(D["#text"]=!0),Y&&Gg(D,["html","head","body"]),D.table&&(Gg(D,["tbody"]),delete F.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Jg('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Jg('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');k=e.TRUSTED_TYPES_POLICY,w=k.createHTML("")}else void 0===k&&(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(i){return console.warn("TrustedTypes policy "+o+" could not be created."),null}}(_,i)),null!==k&&"string"==typeof w&&(w=k.createHTML(""));Eg&&Eg(e),Oe=e}},Ne=Gg({},[...tf,...nf,...rf]),Ae=Gg({},[...of,...sf]),Ce=function(e){zg(n.removed,{element:e});try{b(e).removeChild(e)}catch(t){f(e)}},Pe=function(e,t){try{zg(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){zg(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Ce(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},je=function(e){let t=null,n=null;if(Q)e="<remove></remove>"+e;else{const t=qg(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Ie&&fe===ge&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=k?k.createHTML(e):e;if(fe===ge)try{t=(new m).parseFromString(o,Ie)}catch(s){}if(!t||!t.documentElement){t=x.createDocument(fe,"template",null);try{t.documentElement.innerHTML=ve?w:o}catch(s){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),fe===ge?$.call(t,Y?"html":"body")[0]:Y?t.documentElement:i},Ue=function(e){return I.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ze=function(e){return e instanceof p&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},De=function(e){return"function"==typeof u&&e instanceof u};function Me(e,t,r){Pg(e,(e=>{e.call(n,t,r,Oe)}))}const Le=function(e){let t=null;if(Me(T.beforeSanitizeElements,e,null),ze(e))return Ce(e),!0;const r=$e(e.nodeName);if(Me(T.uponSanitizeElement,e,{tagName:r,allowedTags:D}),G&&e.hasChildNodes()&&!De(e.firstElementChild)&&Wg(/<[/\w!]/g,e.innerHTML)&&Wg(/<[/\w!]/g,e.textContent))return Ce(e),!0;if(e.nodeType===Sf)return Ce(e),!0;if(G&&e.nodeType===$f&&Wg(/<[/\w]/g,e.data))return Ce(e),!0;if(!D[r]||F[r]){if(!F[r]&&Ze(r)){if(Z.tagNameCheck instanceof RegExp&&Wg(Z.tagNameCheck,r))return!1;if(Z.tagNameCheck instanceof Function&&Z.tagNameCheck(r))return!1}if(ie&&!ue[r]){const t=b(e)||e.parentNode,n=y(e)||e.childNodes;if(n&&t){for(let r=n.length-1;r>=0;--r){const o=g(n[r],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,v(e))}}}return Ce(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:fe,tagName:"template"});const n=Mg(e.tagName),r=Mg(t.tagName);return!!ye[e.namespaceURI]&&(e.namespaceURI===he?t.namespaceURI===ge?"svg"===n:t.namespaceURI===_e?"svg"===n&&("annotation-xml"===r||ke[r]):Boolean(Ne[n]):e.namespaceURI===_e?t.namespaceURI===ge?"math"===n:t.namespaceURI===he?"math"===n&&we[r]:Boolean(Ae[n]):e.namespaceURI===ge?!(t.namespaceURI===he&&!we[r])&&!(t.namespaceURI===_e&&!ke[r])&&!Ae[n]&&(xe[n]||!Ne[n]):!("application/xhtml+xml"!==Ie||!ye[e.namespaceURI]))}(e)?(Ce(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!Wg(/<\/no(script|embed|frames)/i,e.innerHTML)?(K&&e.nodeType===If&&(t=e.textContent,Pg([E,R,N],(e=>{t=Zg(t,e," ")})),e.textContent!==t&&(zg(n.removed,{element:e.cloneNode()}),e.textContent=t)),Me(T.afterSanitizeElements,e,null),!1):(Ce(e),!0)},qe=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in r||n in Te))return!1;if(W&&!H[t]&&Wg(A,t));else if(B&&Wg(C,t));else if(!L[t]||H[t]){if(!(Ze(e)&&(Z.tagNameCheck instanceof RegExp&&Wg(Z.tagNameCheck,e)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(e))&&(Z.attributeNameCheck instanceof RegExp&&Wg(Z.attributeNameCheck,t)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(t))||"is"===t&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&Wg(Z.tagNameCheck,n)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(n))))return!1}else if(pe[t]);else if(Wg(z,Zg(n,j,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Fg(n,"data:")||!ce[e]){if(J&&!Wg(P,Zg(n,j,"")));else if(n)return!1}else;return!0},Ze=function(e){return"annotation-xml"!==e&&qg(e,U)},Fe=function(e){Me(T.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||ze(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0};let o=t.length;for(;o--;){const s=t[o],{name:a,namespaceURI:u,value:l}=s,c=$e(a),d=l;let p="value"===a?d:Hg(d);if(r.attrName=c,r.attrValue=p,r.keepAttr=!0,r.forceKeepAttr=void 0,Me(T.uponSanitizeAttribute,e,r),p=r.attrValue,!oe||"id"!==c&&"name"!==c||(Pe(a,e),p="user-content-"+p),G&&Wg(/((--!?|])>)|<\/(style|title)/i,p)){Pe(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Pe(a,e);continue}if(!V&&Wg(/\/>/i,p)){Pe(a,e);continue}K&&Pg([E,R,N],(e=>{p=Zg(p,e," ")}));const m=$e(e.nodeName);if(qe(m,c,p)){if(k&&"object"==typeof _&&"function"==typeof _.getAttributeType)if(u);else switch(_.getAttributeType(m,c)){case"TrustedHTML":p=k.createHTML(p);break;case"TrustedScriptURL":p=k.createScriptURL(p)}if(p!==d)try{u?e.setAttributeNS(u,a,p):e.setAttribute(a,p),ze(e)?Ce(e):Ug(n.removed)}catch(i){Pe(a,e)}}else Pe(a,e)}Me(T.afterSanitizeAttributes,e,null)},He=function e(t){let n=null;const r=Ue(t);for(Me(T.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Me(T.uponSanitizeShadowNode,n,null),Le(n),Fe(n),n.content instanceof s&&e(n.content);Me(T.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,i=null,a=null,l=null;if(ve=!e,ve&&(e="\x3c!--\x3e"),"string"!=typeof e&&!De(e)){if("function"!=typeof e.toString)throw Jg("toString is not a function");if("string"!=typeof(e=e.toString()))throw Jg("dirty is not a string, aborting")}if(!n.isSupported)return e;if(X||Re(t),n.removed=[],"string"==typeof e&&(se=!1),se){if(e.nodeName){const t=$e(e.nodeName);if(!D[t]||F[t])throw Jg("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof u)r=je("\x3c!----\x3e"),i=r.ownerDocument.importNode(e,!0),i.nodeType===xf&&"BODY"===i.nodeName||"HTML"===i.nodeName?r=i:r.appendChild(i);else{if(!ee&&!K&&!Y&&-1===e.indexOf("<"))return k&&ne?k.createHTML(e):e;if(r=je(e),!r)return ee?null:ne?w:""}r&&Q&&Ce(r.firstChild);const c=Ue(se?e:r);for(;a=c.nextNode();)Le(a),Fe(a),a.content instanceof s&&He(a.content);if(se)return e;if(ee){if(te)for(l=S.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(L.shadowroot||L.shadowrootmode)&&(l=O.call(o,l,!0)),l}let d=Y?r.outerHTML:r.innerHTML;return Y&&D["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Wg(bf,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),K&&Pg([E,R,N],(e=>{d=Zg(d,e," ")})),k&&ne?k.createHTML(d):d},n.setConfig=function(){Re(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),X=!0},n.clearConfig=function(){Oe=null,X=!1},n.isValidAttribute=function(e,t,n){Oe||Re({});const r=$e(e),o=$e(t);return qe(r,o,n)},n.addHook=function(e,t){"function"==typeof t&&zg(T[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=jg(T[e],t);return-1===n?void 0:Dg(T[e],n,1)[0]}return Ug(T[e])},n.removeHooks=function(e){T[e]=[]},n.removeAllHooks=function(){T={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Ef=(()=>{if("undefined"!=typeof window)return Tf;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return Tf(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Rf(e){if(!e)return"";const t=String(e);try{let e=Ef.sanitize(t,{ALLOWED_TAGS:[],ALLOWED_ATTR:[],KEEP_CONTENT:!0,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,FORCE_BODY:!0});if(!e.trim()&&t){t.replace(/<[^>]*>/g,"").trim()&&(e=t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim())}return e.trim().slice(0,1e3)}catch{return t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim().slice(0,1e3)}}async function Nf(e,t={}){const{onComplete:n,onError:r}=t,o=function(e){if(!e)return"";const t=Rf(e);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol?t:""}catch{return""}}(e);if(!o){const e=new Error("Invalid payment URL provided");throw null==r||r(e),e}try{window.location.href=o}catch(i){const e=i instanceof Error?i:new Error("Payment flow failed");throw null==r||r(e),e}}const Af=({className:e="",width:n=16,height:r=16,variant:o="light"})=>{const i="dark"===o?"#DFE2D9":"#232323";return t.jsxs("svg",{id:"Layer_1","data-name":"Layer 1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 226.03 261",className:e,width:n,height:r,"aria-label":"Echo Logo",children:[t.jsx("defs",{children:t.jsx("style",{children:`\n .cls-1 {\n fill: none;\n }\n .cls-3 {\n fill: #7f0404;\n }\n .cls-4 {\n fill: ${i};\n }\n .cls-5 {\n fill: #a50404;\n }\n .cls-6 {\n fill: #cd0202;\n opacity: .9;\n }\n `})}),t.jsx("polygon",{className:"cls-6",points:"59.23 99.45 59.23 161.55 113.02 192.61 113.02 130.5 59.23 99.45"}),t.jsx("polygon",{className:"cls-5",points:"113.02 68.39 113.02 68.39 59.23 99.45 113.02 130.5 166.8 99.45 113.02 68.39"}),t.jsx("polygon",{className:"cls-3",points:"166.8 99.45 113.02 130.5 113.02 192.61 113.02 192.61 166.8 161.55 166.8 99.45"}),t.jsxs("g",{children:[t.jsx("path",{className:"cls-4",d:"m113.02,196.41l-57.08-32.95v-65.91l57.08-32.95,57.08,32.95v65.91l-57.08,32.95Zm-52.53-35.58l52.53,30.33,52.53-30.33v-60.66l-52.53-30.33-52.53,30.33v60.66Z"}),t.jsx("path",{className:"cls-4",d:"m113.02,261L0,195.75V65.25L113.02,0l113.02,65.25v130.5l-113.02,65.25ZM6.82,191.81l106.2,61.31,106.2-61.31v-122.62L113.02,7.88,6.82,69.19v122.62Z"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"3.94",width:"2.27",height:"63.28"}),t.jsx("rect",{className:"cls-4",x:"-.83",y:"176.82",width:"63.28",height:"2.27",transform:"translate(-84.84 39.24) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"194.08",y:"146.32",width:"2.27",height:"63.28",transform:"translate(-56.51 258.05) rotate(-60)"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"130.5",width:"2.27",height:"126.56"}),t.jsx("rect",{className:"cls-4",x:"104.54",y:"97.72",width:"126.56",height:"2.27",transform:"translate(-26.95 97.14) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"57.08",y:"35.58",width:"2.27",height:"126.56",transform:"translate(-56.51 99.84) rotate(-60)"})]})]})};function Cf({onSuccess:e,onError:r,className:o="",children:i}){const{signIn:s,isLoading:a,user:u,error:l}=xg(),[c,d]=n.useState(!1);n.useEffect((()=>{u&&e&&e(u)}),[u,e]),n.useEffect((()=>{l&&r&&r(new Error(l))}),[l,r]);const p=async()=>{try{await s()}catch(e){r&&r(e instanceof Error?e:new Error("Sign in failed"))}};return u?t.jsx("div",{className:`echo-signin-success ${o}`,children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[t.jsx(Af,{width:16,height:16,variant:"light"}),t.jsxs("span",{children:["Signed in as ",Rf((null==u?void 0:u.name)||(null==u?void 0:u.email))]})]})}):t.jsx("div",{className:`echo-signin ${o}`,children:i?t.jsx("div",{onClick:p,style:{cursor:"pointer"},children:i}):t.jsxs("button",{onClick:p,disabled:a,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:a?"#f3f4f6":c?"#f1f5f9":"#ffffff",color:a?"#9ca3af":"#09090b",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:a?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[t.jsx(Af,{width:16,height:16,variant:"light"}),t.jsx("span",{children:a?"Signing in...":"Sign in"})]})})}function Pf({onSuccess:e,onError:r,className:o="",children:i}){const{signOut:s,isLoading:a,user:u,error:l}=xg(),[c,d]=n.useState(!1),[p,m]=n.useState(!1);n.useEffect((()=>{!u&&e&&p&&(e(),m(!1))}),[u,e,p]),n.useEffect((()=>{l&&r&&r(new Error(l))}),[l,r]);const _=async()=>{try{m(!0),await s()}catch(e){m(!1),r&&r(e instanceof Error?e:new Error("Sign out failed"))}};return u?t.jsx("div",{className:`echo-signout ${o}`,children:i?t.jsx("div",{onClick:_,style:{cursor:"pointer"},children:i}):t.jsxs("button",{onClick:_,disabled:a||p,className:"echo-signout-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:a||p?"#f3f4f6":c?"#fef2f2":"#ffffff",color:a||p?"#9ca3af":c?"#dc2626":"#374151",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:a||p?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[t.jsx(Af,{width:16,height:16,variant:"light"}),t.jsx("span",{children:a||p?"Signing out...":"Sign out"})]})}):t.jsx("div",{className:`echo-signout-success ${o}`,children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[t.jsx(Af,{width:16,height:16,variant:"light"}),t.jsx("span",{children:"Signed out"})]})})}const jf=({onAddCredits:e,onCancel:r,isProcessing:o})=>{const[i,s]=n.useState(""),a=n.useRef(null);n.useEffect((()=>{a.current&&a.current.focus()}),[]);const u=()=>{const t=Number(i);t>0&&e(t)},l=""!==i&&Number(i)>0;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),t.jsx("input",{ref:a,type:"number",value:i,onChange:e=>s(e.target.value),placeholder:"0.00",min:"1",step:"0.01",style:{flex:1,padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none"},onKeyDown:e=>{"Enter"===e.key&&l&&!o?u():"Escape"===e.key&&r()}})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsx("button",{onClick:r,style:{flex:1,padding:"8px 16px",backgroundColor:"transparent",color:"#6b7280",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Cancel"}),t.jsx("button",{onClick:u,disabled:!l||o,style:{flex:1,padding:"8px 16px",backgroundColor:l&&!o?"#dc2626":"#9ca3af",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:l&&!o?"pointer":"not-allowed",fontFamily:"HelveticaNowDisplay, sans-serif"},children:o?"Processing...":"Add Credits"})]})]})};function Uf({isOpen:e,onClose:r,onPurchaseComplete:o,onError:i}){const{createPaymentLink:s,user:a,refreshBalance:u}=xg(),[l,c]=n.useState(!1),[d,p]=n.useState(null),[m,_]=n.useState(!1),h=async e=>{if(!a){const e=new Error("Please sign in to purchase tokens");return p(e.message),void(null==i||i(e))}try{c(!0),p(null);const t=await s(e);await Nf(t,{onComplete:async()=>{try{await u(),null==o||o(),r()}catch(e){console.error("Failed to refresh balance:",e)}},onError:e=>{p(e.message),null==i||i(e)}})}catch(t){const e=t instanceof Error?t.message:"Purchase failed";p(e),null==i||i(t instanceof Error?t:new Error(e))}finally{c(!1)}};return e?t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px",margin:0,boxSizing:"border-box",border:"none",outline:"none",textDecoration:"none",listStyle:"none"},onClick:e=>{e.target===e.currentTarget&&r()},children:t.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",margin:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px",boxSizing:"border-box"},children:[t.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx(Af,{width:20,height:20,variant:"light"}),t.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Insufficient Balance"})]})}),t.jsx("div",{style:{padding:"0 16px 16px 16px"},children:t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"You don't have enough credits to complete this request. Please add credits to your account."})}),t.jsx("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:m?t.jsx(jf,{onAddCredits:h,onCancel:()=>_(!1),isProcessing:l}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsx("button",{onClick:()=>h(10),disabled:l,style:{width:"100%",padding:"12px 16px",backgroundColor:l?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:l?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{l||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{l||(e.currentTarget.style.backgroundColor="#dc2626")},children:l?"Processing...":"Add $10.00"}),t.jsx("button",{onClick:()=>_(!0),disabled:l,style:{width:"100%",padding:"8px 16px",backgroundColor:"transparent",color:"#dc2626",border:"1px solid #dc2626",borderRadius:"6px",fontSize:"14px",cursor:l?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease"},onMouseEnter:e=>{l||(e.currentTarget.style.backgroundColor="#fef2f2",e.currentTarget.style.borderColor="#b91c1c")},onMouseLeave:e=>{l||(e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.borderColor="#dc2626")},children:"Custom Amount"})]})}),d&&t.jsx("div",{style:{padding:"0 16px 16px 16px"},children:t.jsx("div",{style:{padding:"8px 12px",backgroundColor:"#fef2f2",borderRadius:"6px",border:"1px solid #fecaca"},children:t.jsx("p",{style:{color:"#dc2626",margin:0,fontSize:"12px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:d})})}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",padding:"12px 16px",borderTop:"1px solid #f3f4f6",gap:"8px"},children:t.jsx("button",{onClick:r,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})})]})}):null}const zf=({onAddCredits:e,onCancel:r,isProcessing:o})=>{const[i,s]=n.useState(""),a=n.useRef(null);n.useEffect((()=>{a.current&&a.current.focus()}),[]);const u=""!==i&&Number(i)>0;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),t.jsx("input",{ref:a,type:"number",placeholder:"0.00",value:i,onChange:e=>s(e.target.value),style:{width:"96px",textAlign:"right",padding:"8px 12px",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none",backgroundColor:"#ffffff"},min:"1",step:"0.01"})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("button",{onClick:r,style:{padding:"8px 12px",backgroundColor:"transparent",color:"#6b7280",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",textDecoration:"none"},onMouseEnter:e=>{e.currentTarget.style.color="#111827"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280"},children:"Cancel"}),t.jsx("button",{onClick:()=>{const t=Number(i);t>0&&e(t)},disabled:o||!u,style:{padding:"8px 16px",backgroundColor:o||!u?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:o||!u?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!o&&u&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!o&&u&&(e.currentTarget.style.backgroundColor="#dc2626")},children:o?"Processing...":"Add Credits"})]})]})};const Df=n.createContext(null);var Mf=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const e=n.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n[Math.random()*e|0];return r.join("")};if(null==e)return o;if(n.includes(r))throw new Je({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},Lf=Mf(),qf=/"__proto__"\s*:/,Zf=/"constructor"\s*:/;function Ff(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===qf.test(e)&&!1===Zf.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}var Hf=Symbol.for("vercel.ai.validator");function Bf(e){return function(e){return"object"==typeof e&&null!==e&&Hf in e&&!0===e[Hf]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Et({value:e,cause:n.issues})}},{[Hf]:!0,validate:n});var t,n}async function Wf({value:e,schema:t}){const n=await Jf({value:e,schema:t});if(!n.success)throw Et.wrap({value:e,cause:n.error});return n.value}async function Jf({value:e,schema:t}){const n=Bf(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Et.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Et.wrap({value:e,cause:r}),rawValue:e}}}async function Vf({text:e,schema:t}){try{const n=function(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ff(e)}finally{Error.stackTraceLimit=t}}(e);return null==t?{success:!0,value:n,rawValue:n}:await Jf({value:n,schema:t})}catch(n){return{success:!1,error:ut.isInstance(n)?n:new ut({text:e,cause:n}),rawValue:void 0}}}async function Kf(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}function Gf(e,t){return function(e){return"_zod"in e}(e)?function(e){return Xf(hu(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Pu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return Xf(pd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var Yf=Symbol.for("vercel.ai.schema");function Xf(e,{validate:t}={}){return{[Yf]:!0,_type:void 0,[Hf]:!0,jsonSchema:e,validate:t}}function Qf(e){return null==e?Xf({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&Yf in t&&!0===t[Yf]&&"jsonSchema"in t&&"validate"in t?e:Gf(e);var t}var ev,tv=Object.defineProperty,nv="AI_NoObjectGeneratedError",rv=`vercel.ai.error.${nv}`,ov=Symbol.for(rv),iv=class extends Ae{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:nv,message:e,cause:t}),this[ev]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return Ae.hasMarker(e,rv)}};ev=ov;var sv=Pl([Du(),Ic(Uint8Array),Ic(ArrayBuffer),kc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),av=vc((()=>Pl([vl(),Du(),ul(),pl(),Zl(Du(),av),Tl(av)]))),uv=Zl(Du(),Zl(Du(),av)),lv=Rl({type:Vl("text"),text:Du(),providerOptions:uv.optional()}),cv=Rl({type:Vl("image"),image:Pl([sv,Ic(URL)]),mediaType:Du().optional(),providerOptions:uv.optional()}),dv=Rl({type:Vl("file"),data:Pl([sv,Ic(URL)]),filename:Du().optional(),mediaType:Du(),providerOptions:uv.optional()}),pv=Rl({type:Vl("reasoning"),text:Du(),providerOptions:uv.optional()}),mv=Rl({type:Vl("tool-call"),toolCallId:Du(),toolName:Du(),input:wl(),providerOptions:uv.optional(),providerExecuted:pl().optional()}),_v=Ul("type",[Rl({type:Vl("text"),value:Du()}),Rl({type:Vl("json"),value:av}),Rl({type:Vl("error-text"),value:Du()}),Rl({type:Vl("error-json"),value:av}),Rl({type:Vl("content"),value:Tl(Pl([Rl({type:Vl("text"),text:Du()}),Rl({type:Vl("media"),data:Du(),mediaType:Du()})]))})]),hv=Rl({type:Vl("tool-result"),toolCallId:Du(),toolName:Du(),output:_v,providerOptions:uv.optional()}),gv=Rl({role:Vl("system"),content:Du(),providerOptions:uv.optional()}),fv=Rl({role:Vl("user"),content:Pl([Du(),Tl(Pl([lv,cv,dv]))]),providerOptions:uv.optional()}),vv=Rl({role:Vl("assistant"),content:Pl([Du(),Tl(Pl([lv,dv,pv,mv,hv]))]),providerOptions:uv.optional()});Pl([gv,fv,vv,Rl({role:Vl("tool"),content:Tl(hv),providerOptions:uv.optional()})]),Mf({prefix:"aitxt",size:24}),TransformStream;var yv=Pl([Nl({type:Vl("text-start"),id:Du(),providerMetadata:uv.optional()}),Nl({type:Vl("text-delta"),id:Du(),delta:Du(),providerMetadata:uv.optional()}),Nl({type:Vl("text-end"),id:Du(),providerMetadata:uv.optional()}),Nl({type:Vl("error"),errorText:Du()}),Nl({type:Vl("tool-input-start"),toolCallId:Du(),toolName:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-delta"),toolCallId:Du(),inputTextDelta:Du()}),Nl({type:Vl("tool-input-available"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:uv.optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-error"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:uv.optional(),dynamic:pl().optional(),errorText:Du()}),Nl({type:Vl("tool-output-available"),toolCallId:Du(),output:wl(),providerExecuted:pl().optional(),dynamic:pl().optional(),preliminary:pl().optional()}),Nl({type:Vl("tool-output-error"),toolCallId:Du(),errorText:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("reasoning"),text:Du(),providerMetadata:uv.optional()}),Nl({type:Vl("reasoning-start"),id:Du(),providerMetadata:uv.optional()}),Nl({type:Vl("reasoning-delta"),id:Du(),delta:Du(),providerMetadata:uv.optional()}),Nl({type:Vl("reasoning-end"),id:Du(),providerMetadata:uv.optional()}),Nl({type:Vl("reasoning-part-finish")}),Nl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:uv.optional()}),Nl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:uv.optional()}),Nl({type:Vl("file"),url:Du(),mediaType:Du(),providerMetadata:uv.optional()}),Nl({type:Du().startsWith("data-"),id:Du().optional(),data:wl(),transient:pl().optional()}),Nl({type:Vl("start-step")}),Nl({type:Vl("finish-step")}),Nl({type:Vl("start"),messageId:Du().optional(),messageMetadata:wl().optional()}),Nl({type:Vl("finish"),messageMetadata:wl().optional()}),Nl({type:Vl("abort")}),Nl({type:Vl("message-metadata"),messageMetadata:wl()})]);function bv(e,t){if(void 0===e&&void 0===t)return;if(void 0===e)return t;if(void 0===t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(void 0===o)continue;const i=r in e?e[r]:void 0,s=!(null===o||"object"!=typeof o||Array.isArray(o)||o instanceof Date||o instanceof RegExp),a=!(null==i||"object"!=typeof i||Array.isArray(i)||i instanceof Date||i instanceof RegExp);n[r]=s&&a?bv(i,o):o}return n}function kv(e){const t=["ROOT"];let n=-1,r=null;function o(e,o,i){switch(e){case'"':n=o,t.pop(),t.push(i),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=o,r=o,t.pop(),t.push(i),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=o,t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"{":n=o,t.pop(),t.push(i),t.push("INSIDE_OBJECT_START");break;case"[":n=o,t.pop(),t.push(i),t.push("INSIDE_ARRAY_START")}}function i(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":o(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":o(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":i(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const o=e.substring(r,u+1);"false".startsWith(o)||"true".startsWith(o)||"null".startsWith(o)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?i(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}async function wv(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Vf({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Vf({text:kv(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function xv(e){return e.type.startsWith("tool-")}function Iv(e){return e.type.split("-").slice(1).join("-")}function Sv({lastMessage:e,messageId:t}){return{message:"assistant"===(null==e?void 0:e.role)?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function $v({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:i,onData:s}){return e.pipeThrough(new TransformStream({async transform(e,a){await r((async({state:r,write:u})=>{var l,c,d,p;function m(e){const t=r.message.parts.filter(xv).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function _(e){const t=r.message.parts.filter((e=>"dynamic-tool"===e.type)).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function h(e){var t;const n=r.message.parts.find((t=>xv(t)&&t.toolCallId===e.toolCallId)),o=e,i=n;null!=n?(n.state=e.state,i.input=o.input,i.output=o.output,i.errorText=o.errorText,i.rawInput=o.rawInput,i.preliminary=o.preliminary,i.providerExecuted=null!=(t=o.providerExecuted)?t:n.providerExecuted,null!=o.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=o.providerMetadata)):r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,input:o.input,output:o.output,rawInput:o.rawInput,errorText:o.errorText,providerExecuted:o.providerExecuted,preliminary:o.preliminary,...null!=o.providerMetadata?{callProviderMetadata:o.providerMetadata}:{}})}function g(e){var t;const n=r.message.parts.find((t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId)),o=e,i=n;null!=n?(n.state=e.state,i.toolName=e.toolName,i.input=o.input,i.output=o.output,i.errorText=o.errorText,i.rawInput=null!=(t=o.rawInput)?t:i.rawInput,i.preliminary=o.preliminary,null!=o.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=o.providerMetadata)):r.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:o.input,output:o.output,errorText:o.errorText,preliminary:o.preliminary,...null!=o.providerMetadata?{callProviderMetadata:o.providerMetadata}:{}})}async function f(e){if(null!=e){const n=null!=r.message.metadata?bv(r.message.metadata,e):e;null!=t&&await Wf({value:n,schema:t}),r.message.metadata=n}}switch(e.type){case"text-start":{const t={type:"text",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeTextParts[e.id]=t,r.message.parts.push(t),u();break}case"text-delta":{const t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(l=e.providerMetadata)?l:t.providerMetadata,u();break}case"text-end":{const t=r.activeTextParts[e.id];t.state="done",t.providerMetadata=null!=(c=e.providerMetadata)?c:t.providerMetadata,delete r.activeTextParts[e.id],u();break}case"reasoning-start":{const t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),u();break}case"reasoning-delta":{const t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,u();break}case"reasoning-end":{const t=r.activeReasoningParts[e.id];t.providerMetadata=null!=(p=e.providerMetadata)?p:t.providerMetadata,t.state="done",delete r.activeReasoningParts[e.id],u();break}case"file":r.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url}),u();break;case"source-url":r.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),u();break;case"source-document":r.message.parts.push({type:"source-document",sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),u();break;case"tool-input-start":{const t=r.message.parts.filter(xv);r.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic},e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted}),u();break}case"tool-input-delta":{const t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;const{value:n}=await wv(t.text);t.dynamic?g({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}):h({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}),u();break}case"tool-input-available":e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u(),i&&!e.providerExecuted&&await i({toolCall:e});break;case"tool-input-error":e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u();break;case"tool-output-available":if(e.dynamic){const t=_(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary})}else{const t=m(e.toolCallId);h({toolCallId:e.toolCallId,toolName:Iv(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}u();break;case"tool-output-error":if(e.dynamic){const t=_(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText})}else{const t=m(e.toolCallId);h({toolCallId:e.toolCallId,toolName:Iv(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText})}u();break;case"start-step":r.message.parts.push({type:"step-start"});break;case"finish-step":r.activeTextParts={},r.activeReasoningParts={};break;case"start":null!=e.messageId&&(r.message.id=e.messageId),await f(e.messageMetadata),null==e.messageId&&null==e.messageMetadata||u();break;case"finish":case"message-metadata":await f(e.messageMetadata),null!=e.messageMetadata&&u();break;case"error":null==o||o(new Error(e.errorText));break;default:if(function(e){return e.type.startsWith("data-")}(e)){null!=(null==n?void 0:n[e.type])&&await Wf({value:e.data,schema:n[e.type]});const t=e;if(t.transient){null==s||s(t);break}const o=null!=t.id?r.message.parts.find((e=>t.type===e.type&&t.id===e.id)):void 0;null!=o?o.data=t.data:r.message.parts.push(t),null==s||s(t),u()}}a.enqueue(e)}))}}))}Mf({prefix:"aitxt",size:24}),Mf({prefix:"aiobj",size:24});var Ov=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise(((t,n)=>{this.queue.push((async()=>{try{await e(),t()}catch(r){n(r)}})),this.processQueue()}))}};Mf({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)tv(e,n,{get:t[n],enumerable:!0})})({},{object:()=>Ev,text:()=>Tv});var Tv=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),Ev=({schema:e})=>{const t=Qf(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await wv(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Vf({text:e});if(!r.success)throw new iv({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Jf({value:r.value,schema:t});if(!o.success)throw new iv({message:"No object generated: response did not match schema.",cause:o.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},Rv=Al({name:Du(),version:Du()}),Nv=Al({_meta:Ql(Rl({}).loose())}),Av=Nv,Cv=Rl({method:Du(),params:Ql(Nv)}),Pv=Al({experimental:Ql(Rl({}).loose()),logging:Ql(Rl({}).loose()),prompts:Ql(Al({listChanged:Ql(pl())})),resources:Ql(Al({subscribe:Ql(pl()),listChanged:Ql(pl())})),tools:Ql(Al({listChanged:Ql(pl())}))});Av.extend({protocolVersion:Du(),capabilities:Pv,serverInfo:Rv,instructions:Ql(Du())});var jv=Av.extend({nextCursor:Ql(Du())}),Uv=Rl({name:Du(),description:Ql(Du()),inputSchema:Rl({type:Vl("object"),properties:Ql(Rl({}).loose())}).loose()}).loose();jv.extend({tools:Tl(Uv)});var zv=Rl({type:Vl("text"),text:Du()}).loose(),Dv=Rl({type:Vl("image"),data:nl(),mimeType:Du()}).loose(),Mv=Rl({uri:Du(),mimeType:Ql(Du())}).loose(),Lv=Mv.extend({text:Du()}),qv=Mv.extend({blob:nl()}),Zv=Rl({type:Vl("resource"),resource:Pl([Lv,qv])}).loose();Av.extend({content:Tl(Pl([zv,Dv,Zv])),isError:pl().default(!1).optional()}).or(Av.extend({toolResult:wl()}));var Fv="2.0",Hv=Rl({jsonrpc:Vl(Fv),id:Pl([Du(),ul().int()])}).merge(Cv).strict(),Bv=Rl({jsonrpc:Vl(Fv),id:Pl([Du(),ul().int()]),result:Av}).strict(),Wv=Rl({jsonrpc:Vl(Fv),id:Pl([Du(),ul().int()]),error:Rl({code:ul().int(),message:Du(),data:Ql(wl())})}).strict();Pl([Hv,Rl({jsonrpc:Vl(Fv)}).merge(Rl({method:Du(),params:Ql(Nv)})).strict(),Bv,Wv]);var Jv,Vv,Kv=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:o,prepareSendMessagesRequest:i,prepareReconnectToStreamRequest:s}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=o,this.prepareSendMessagesRequest=i,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:e,...t}){var n,r,o,i,s;const a=await Kf(this.body),u=await Kf(this.headers),l=await Kf(this.credentials),c=await(null==(n=this.prepareSendMessagesRequest)?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...u,...t.headers},credentials:l,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),d=null!=(r=null==c?void 0:c.api)?r:this.api,p=void 0!==(null==c?void 0:c.headers)?c.headers:{...u,...t.headers},m=void 0!==(null==c?void 0:c.body)?c.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},_=null!=(o=null==c?void 0:c.credentials)?o:l,h=null!=(i=this.fetch)?i:globalThis.fetch,g=await h(d,{method:"POST",headers:{"Content-Type":"application/json",...p},body:JSON.stringify(m),credentials:_,signal:e});if(!g.ok)throw new Error(null!=(s=await g.text())?s:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}async reconnectToStream(e){var t,n,r,o,i;const s=await Kf(this.body),a=await Kf(this.headers),u=await Kf(this.credentials),l=await(null==(t=this.prepareReconnectToStreamRequest)?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...s,...e.body},headers:{...a,...e.headers},credentials:u,requestMetadata:e.metadata})),c=null!=(n=null==l?void 0:l.api)?n:`${this.api}/${e.chatId}/stream`,d=void 0!==(null==l?void 0:l.headers)?l.headers:{...a,...e.headers},p=null!=(r=null==l?void 0:l.credentials)?r:u,m=null!=(o=this.fetch)?o:globalThis.fetch,_=await m(c,{method:"GET",headers:d,credentials:p});if(204===_.status)return null;if(!_.ok)throw new Error(null!=(i=await _.text())?i:"Failed to fetch the chat response.");if(!_.body)throw new Error("The response body is empty.");return this.processResponseStream(_.body)}},Gv=class extends Kv{constructor(e={}){super(e)}processResponseStream(e){return function({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new zt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Vf({text:e,schema:t}))}}))}({stream:e,schema:yv}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Yv=class{constructor({generateId:e=Lf,id:t=e(),transport:n=new Gv,messageMetadataSchema:r,dataPartSchemas:o,state:i,onError:s,onToolCall:a,onFinish:u,onData:l,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new Ov,this.sendMessage=async(e,t)=>{var n,r,o,i;if(null==e)return void(await this.makeRequest({trigger:"submit-message",messageId:null==(n=this.lastMessage)?void 0:n.id,...t}));let s;if("text"in e||"files"in e){const t=Array.isArray(e.files)?e.files:await async function(e){if(null==e)return[];if(!(globalThis.FileList&&e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map((async e=>{const{name:t,type:n}=e;return{type:"file",mediaType:n,filename:t,url:await new Promise(((t,n)=>{const r=new FileReader;r.onload=e=>{var n;t(null==(n=e.target)?void 0:n.result)},r.onerror=e=>n(e),r.readAsDataURL(e)}))}})))}(e.files);s={parts:[...t,..."text"in e&&null!=e.text?[{type:"text",text:e.text}]:[]]}}else s=e;if(null!=e.messageId){const t=this.state.messages.findIndex((t=>t.id===e.messageId));if(-1===t)throw new Error(`message with id ${e.messageId} not found`);if("user"!==this.state.messages[t].role)throw new Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...s,id:e.messageId,role:null!=(r=s.role)?r:"user",metadata:e.metadata})}else this.state.pushMessage({...s,id:null!=(o=s.id)?o:this.generateId(),role:null!=(i=s.role)?i:"user",metadata:e.metadata});await this.makeRequest({trigger:"submit-message",messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{const n=null==e?this.state.messages.length-1:this.state.messages.findIndex((t=>t.id===e));if(-1===n)throw new Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,"assistant"===this.messages[n].role?n:n+1),await this.makeRequest({trigger:"regenerate-message",messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:"resume-stream",...e})},this.clearError=()=>{"error"===this.status&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({tool:e,toolCallId:t,output:n})=>this.jobExecutor.run((async()=>{var e,r;const o=this.state.messages,i=o[o.length-1];this.state.replaceMessage(o.length-1,{...i,parts:i.parts.map((e=>xv(e)&&e.toolCallId===t?{...e,state:"output-available",output:n}:e))}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map((e=>xv(e)&&e.toolCallId===t?{...e,state:"output-available",output:n,errorText:void 0}:e))),"streaming"!==this.status&&"submitted"!==this.status&&(null==(e=this.sendAutomaticallyWhen)?void 0:e.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:null==(r=this.lastMessage)?void 0:r.id})})),this.stop=async()=>{var e;"streaming"!==this.status&&"submitted"!==this.status||(null==(e=this.activeResponse)?void 0:e.abortController)&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=o,this.state=i,this.onError=s,this.onToolCall=a,this.onFinish=u,this.onData=l,this.sendAutomaticallyWhen=c}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:o}){var i,s,a;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;try{const s={state:Sv({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};let a;if(this.activeResponse=s,"resume-stream"===e){const e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(null==e)return void this.setStatus({status:"ready"});a=e}else a=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:s.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:o});const l=e=>this.jobExecutor.run((()=>e({state:s.state,write:()=>{var e;this.setStatus({status:"streaming"});s.state.message.id===(null==(e=this.lastMessage)?void 0:e.id)?this.state.replaceMessage(this.state.messages.length-1,s.state.message):this.state.pushMessage(s.state.message)}})));await async function({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:e}=await n.read();if(e)break}}catch(r){null==t||t(r)}finally{n.releaseLock()}}({stream:$v({stream:a,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:l,onError:e=>{throw e}}),onError:e=>{throw e}}),null==(i=this.onFinish)||i.call(this,{message:s.state.message}),this.setStatus({status:"ready"})}catch(l){if("AbortError"===l.name)return this.setStatus({status:"ready"}),null;this.onError&&l instanceof Error&&this.onError(l),this.setStatus({status:"error",error:l})}finally{this.activeResponse=void 0}(null==(s=this.sendAutomaticallyWhen)?void 0:s.call(this,{messages:this.state.messages}))&&await this.makeRequest({trigger:"submit-message",messageId:null==(a=this.lastMessage)?void 0:a.id,metadata:t,headers:n,body:r})}},Xv=Rl({type:Vl("text"),text:Du(),state:Wl(["streaming","done"]).optional(),providerMetadata:uv.optional()}),Qv=Rl({type:Vl("reasoning"),text:Du(),state:Wl(["streaming","done"]).optional(),providerMetadata:uv.optional()}),ey=Rl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:uv.optional()}),ty=Rl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:uv.optional()}),ny=Rl({type:Vl("file"),mediaType:Du(),filename:Du().optional(),url:Du(),providerMetadata:uv.optional()}),ry=Rl({type:Vl("step-start")}),oy=Rl({type:Du().startsWith("data-"),id:Du().optional(),data:wl()}),iy=[Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:uv.optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:uv.optional(),preliminary:pl().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:uv.optional()})],sy=[Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:uv.optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:uv.optional(),preliminary:pl().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:uv.optional()})];function ay(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function uy(){if(Vv)return Jv;return Vv=1,Jv=function(e,t){if("function"!=typeof e)throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),s=t-(i-r);s<=0?(r=i,e.apply(this,o)):n=setTimeout((()=>{r=Date.now(),e.apply(this,o)}),s)}}}Rl({id:Du(),role:Wl(["system","user","assistant"]),metadata:wl().optional(),parts:Tl(Pl([Xv,Qv,ey,ty,ny,ry,oy,...iy,...sy]))});const ly=ay(uy());var cy,dy,py,my,_y,hy,gy,fy,vy,yy=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},by=(e,t,n)=>(yy(e,t,"read from private field"),n?n.call(e):t.get(e)),ky=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},wy=(e,t,n,r)=>(yy(e,t,"write to private field"),t.set(e,n),n);var xy,Iy=class{constructor(e=[]){ky(this,cy,void 0),ky(this,dy,"ready"),ky(this,py,void 0),ky(this,my,new Set),ky(this,_y,new Set),ky(this,hy,new Set),this.pushMessage=e=>{wy(this,cy,by(this,cy).concat(e)),by(this,gy).call(this)},this.popMessage=()=>{wy(this,cy,by(this,cy).slice(0,-1)),by(this,gy).call(this)},this.replaceMessage=(e,t)=>{wy(this,cy,[...by(this,cy).slice(0,e),this.snapshot(t),...by(this,cy).slice(e+1)]),by(this,gy).call(this)},this.snapshot=e=>structuredClone(e),this["~registerMessagesCallback"]=(e,t)=>{const n=t?(r=e,null!=(o=t)?ly(r,o):r):e;var r,o;return by(this,my).add(n),()=>{by(this,my).delete(n)}},this["~registerStatusCallback"]=e=>(by(this,_y).add(e),()=>{by(this,_y).delete(e)}),this["~registerErrorCallback"]=e=>(by(this,hy).add(e),()=>{by(this,hy).delete(e)}),ky(this,gy,(()=>{by(this,my).forEach((e=>e()))})),ky(this,fy,(()=>{by(this,_y).forEach((e=>e()))})),ky(this,vy,(()=>{by(this,hy).forEach((e=>e()))})),wy(this,cy,e)}get status(){return by(this,dy)}set status(e){wy(this,dy,e),by(this,fy).call(this)}get error(){return by(this,py)}set error(e){wy(this,py,e),by(this,vy).call(this)}get messages(){return by(this,cy)}set messages(e){wy(this,cy,[...e]),by(this,gy).call(this)}};cy=new WeakMap,dy=new WeakMap,py=new WeakMap,my=new WeakMap,_y=new WeakMap,hy=new WeakMap,gy=new WeakMap,fy=new WeakMap,vy=new WeakMap;var Sy=class extends Yv{constructor({messages:e,...t}){const n=new Iy(e);super({...t,state:n}),ky(this,xy,void 0),this["~registerMessagesCallback"]=(e,t)=>by(this,xy)["~registerMessagesCallback"](e,t),this["~registerStatusCallback"]=e=>by(this,xy)["~registerStatusCallback"](e),this["~registerErrorCallback"]=e=>by(this,xy)["~registerErrorCallback"](e),wy(this,xy,n)}};xy=new WeakMap;var $y,Oy=Object.defineProperty,Ty="AI_NoObjectGeneratedError",Ey=`vercel.ai.error.${Ty}`,Ry=Symbol.for(Ey),Ny=class extends Ae{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:Ty,message:e,cause:t}),this[$y]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return Ae.hasMarker(e,Ey)}};$y=Ry;var Ay,Cy="AI_MessageConversionError",Py=`vercel.ai.error.${Cy}`,jy=Symbol.for(Py),Uy=class extends Ae{constructor({originalMessage:e,message:t}){super({name:Cy,message:t}),this[Ay]=!0,this.originalMessage=e}static isInstance(e){return Ae.hasMarker(e,Py)}};Ay=jy;var zy=Pl([Du(),Ic(Uint8Array),Ic(ArrayBuffer),kc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),Dy=vc((()=>Pl([vl(),Du(),ul(),pl(),Zl(Du(),Dy),Tl(Dy)]))),My=Zl(Du(),Zl(Du(),Dy)),Ly=Rl({type:Vl("text"),text:Du(),providerOptions:My.optional()}),qy=Rl({type:Vl("image"),image:Pl([zy,Ic(URL)]),mediaType:Du().optional(),providerOptions:My.optional()}),Zy=Rl({type:Vl("file"),data:Pl([zy,Ic(URL)]),filename:Du().optional(),mediaType:Du(),providerOptions:My.optional()}),Fy=Rl({type:Vl("reasoning"),text:Du(),providerOptions:My.optional()}),Hy=Rl({type:Vl("tool-call"),toolCallId:Du(),toolName:Du(),input:wl(),providerOptions:My.optional(),providerExecuted:pl().optional()}),By=Ul("type",[Rl({type:Vl("text"),value:Du()}),Rl({type:Vl("json"),value:Dy}),Rl({type:Vl("error-text"),value:Du()}),Rl({type:Vl("error-json"),value:Dy}),Rl({type:Vl("content"),value:Tl(Pl([Rl({type:Vl("text"),text:Du()}),Rl({type:Vl("media"),data:Du(),mediaType:Du()})]))})]),Wy=Rl({type:Vl("tool-result"),toolCallId:Du(),toolName:Du(),output:By,providerOptions:My.optional()}),Jy=Rl({role:Vl("system"),content:Du(),providerOptions:My.optional()}),Vy=Rl({role:Vl("user"),content:Pl([Du(),Tl(Pl([Ly,qy,Zy]))]),providerOptions:My.optional()}),Ky=Rl({role:Vl("assistant"),content:Pl([Du(),Tl(Pl([Ly,Zy,Fy,Hy,Wy]))]),providerOptions:My.optional()});function Gy({output:e,tool:t,errorMode:n}){return"text"===n?{type:"error-text",value:Ze(e)}:"json"===n?{type:"error-json",value:Yy(e)}:(null==t?void 0:t.toModelOutput)?t.toModelOutput(e):"string"==typeof e?{type:"text",value:e}:{type:"json",value:Yy(e)}}function Yy(e){return void 0===e?null:e}function Xy(e){const t=["ROOT"];let n=-1,r=null;function o(e,o,i){switch(e){case'"':n=o,t.pop(),t.push(i),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=o,r=o,t.pop(),t.push(i),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=o,t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"{":n=o,t.pop(),t.push(i),t.push("INSIDE_OBJECT_START");break;case"[":n=o,t.pop(),t.push(i),t.push("INSIDE_ARRAY_START")}}function i(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":o(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":o(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":i(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const o=e.substring(r,u+1);"false".startsWith(o)||"true".startsWith(o)||"null".startsWith(o)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?i(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}function Qy(e){return e.type.startsWith("tool-")}function eb(e){return e.type.split("-").slice(1).join("-")}Pl([Jy,Vy,Ky,Rl({role:Vl("tool"),content:Tl(Wy),providerOptions:My.optional()})]),hd({prefix:"aitxt",size:24}),TransformStream,Pl([Nl({type:Vl("text-start"),id:Du(),providerMetadata:My.optional()}),Nl({type:Vl("text-delta"),id:Du(),delta:Du(),providerMetadata:My.optional()}),Nl({type:Vl("text-end"),id:Du(),providerMetadata:My.optional()}),Nl({type:Vl("error"),errorText:Du()}),Nl({type:Vl("tool-input-start"),toolCallId:Du(),toolName:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-delta"),toolCallId:Du(),inputTextDelta:Du()}),Nl({type:Vl("tool-input-available"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:My.optional(),dynamic:pl().optional()}),Nl({type:Vl("tool-input-error"),toolCallId:Du(),toolName:Du(),input:wl(),providerExecuted:pl().optional(),providerMetadata:My.optional(),dynamic:pl().optional(),errorText:Du()}),Nl({type:Vl("tool-output-available"),toolCallId:Du(),output:wl(),providerExecuted:pl().optional(),dynamic:pl().optional(),preliminary:pl().optional()}),Nl({type:Vl("tool-output-error"),toolCallId:Du(),errorText:Du(),providerExecuted:pl().optional(),dynamic:pl().optional()}),Nl({type:Vl("reasoning"),text:Du(),providerMetadata:My.optional()}),Nl({type:Vl("reasoning-start"),id:Du(),providerMetadata:My.optional()}),Nl({type:Vl("reasoning-delta"),id:Du(),delta:Du(),providerMetadata:My.optional()}),Nl({type:Vl("reasoning-end"),id:Du(),providerMetadata:My.optional()}),Nl({type:Vl("reasoning-part-finish")}),Nl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:My.optional()}),Nl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:My.optional()}),Nl({type:Vl("file"),url:Du(),mediaType:Du(),providerMetadata:My.optional()}),Nl({type:Du().startsWith("data-"),id:Du().optional(),data:wl(),transient:pl().optional()}),Nl({type:Vl("start-step")}),Nl({type:Vl("finish-step")}),Nl({type:Vl("start"),messageId:Du().optional(),messageMetadata:wl().optional()}),Nl({type:Vl("finish"),messageMetadata:wl().optional()}),Nl({type:Vl("abort")}),Nl({type:Vl("message-metadata"),messageMetadata:wl()})]),hd({prefix:"aitxt",size:24}),hd({prefix:"aiobj",size:24}),hd({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)Oy(e,n,{get:t[n],enumerable:!0})})({},{object:()=>nb,text:()=>tb});var tb=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),nb=({schema:e})=>{const t=Hd(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await async function(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Td({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Td({text:Xy(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Td({text:e});if(!r.success)throw new Ny({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await $d({value:r.value,schema:t});if(!o.success)throw new Ny({message:"No object generated: response did not match schema.",cause:o.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},rb=Al({name:Du(),version:Du()}),ob=Al({_meta:Ql(Rl({}).loose())}),ib=ob,sb=Rl({method:Du(),params:Ql(ob)}),ab=Al({experimental:Ql(Rl({}).loose()),logging:Ql(Rl({}).loose()),prompts:Ql(Al({listChanged:Ql(pl())})),resources:Ql(Al({subscribe:Ql(pl()),listChanged:Ql(pl())})),tools:Ql(Al({listChanged:Ql(pl())}))});ib.extend({protocolVersion:Du(),capabilities:ab,serverInfo:rb,instructions:Ql(Du())});var ub=ib.extend({nextCursor:Ql(Du())}),lb=Rl({name:Du(),description:Ql(Du()),inputSchema:Rl({type:Vl("object"),properties:Ql(Rl({}).loose())}).loose()}).loose();ub.extend({tools:Tl(lb)});var cb=Rl({type:Vl("text"),text:Du()}).loose(),db=Rl({type:Vl("image"),data:nl(),mimeType:Du()}).loose(),pb=Rl({uri:Du(),mimeType:Ql(Du())}).loose(),mb=pb.extend({text:Du()}),_b=pb.extend({blob:nl()}),hb=Rl({type:Vl("resource"),resource:Pl([mb,_b])}).loose();ib.extend({content:Tl(Pl([cb,db,hb])),isError:pl().default(!1).optional()}).or(ib.extend({toolResult:wl()}));var gb="2.0",fb=Rl({jsonrpc:Vl(gb),id:Pl([Du(),ul().int()])}).merge(sb).strict(),vb=Rl({jsonrpc:Vl(gb),id:Pl([Du(),ul().int()]),result:ib}).strict(),yb=Rl({jsonrpc:Vl(gb),id:Pl([Du(),ul().int()]),error:Rl({code:ul().int(),message:Du(),data:Ql(wl())})}).strict();Pl([fb,Rl({jsonrpc:Vl(gb)}).merge(Rl({method:Du(),params:Ql(ob)})).strict(),vb,yb]);var bb=Rl({type:Vl("text"),text:Du(),state:Wl(["streaming","done"]).optional(),providerMetadata:My.optional()}),kb=Rl({type:Vl("reasoning"),text:Du(),state:Wl(["streaming","done"]).optional(),providerMetadata:My.optional()}),wb=Rl({type:Vl("source-url"),sourceId:Du(),url:Du(),title:Du().optional(),providerMetadata:My.optional()}),xb=Rl({type:Vl("source-document"),sourceId:Du(),mediaType:Du(),title:Du(),filename:Du().optional(),providerMetadata:My.optional()}),Ib=Rl({type:Vl("file"),mediaType:Du(),filename:Du().optional(),url:Du(),providerMetadata:My.optional()}),Sb=Rl({type:Vl("step-start")}),$b=Rl({type:Du().startsWith("data-"),id:Du().optional(),data:wl()}),Ob=[Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:My.optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:My.optional(),preliminary:pl().optional()}),Rl({type:Vl("dynamic-tool"),toolName:Du(),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:My.optional()})],Tb=[Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-streaming"),input:wl().optional(),output:Il().optional(),errorText:Il().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("input-available"),input:wl(),output:Il().optional(),errorText:Il().optional(),callProviderMetadata:My.optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-available"),input:wl(),output:wl(),errorText:Il().optional(),callProviderMetadata:My.optional(),preliminary:pl().optional()}),Rl({type:Du().startsWith("tool-"),toolCallId:Du(),state:Vl("output-error"),input:wl(),output:Il().optional(),errorText:Du(),callProviderMetadata:My.optional()})];function Eb(){const e=function(){const e=n.useContext(Df);if(!e)throw new Error("useChat must be used within an EchoChatProvider");return e}();return{async sendMessages(t){const{messages:n,abortSignal:r,...o}=t,i=function(e,t){const n=[];(null==t?void 0:t.ignoreIncompleteToolCalls)&&(e=e.map((e=>({...e,parts:e.parts.filter((e=>!Qy(e)||"input-streaming"!==e.state&&"input-available"!==e.state))}))));for(const r of e)switch(r.role){case"system":{const e=r.parts.filter((e=>"text"===e.type)),t=e.reduce(((e,t)=>null!=t.providerMetadata?{...e,...t.providerMetadata}:e),{});n.push({role:"system",content:e.map((e=>e.text)).join(""),...Object.keys(t).length>0?{providerOptions:t}:{}});break}case"user":n.push({role:"user",content:r.parts.filter((e=>"text"===e.type||"file"===e.type)).map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};case"file":return{type:"file",mediaType:e.mediaType,filename:e.filename,data:e.url,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};default:return e}}))});break;case"assistant":if(null!=r.parts){let e=function(){var e,i;if(0===o.length)return;const s=[];for(const n of o)if("text"===n.type)s.push({type:"text",text:n.text,...null!=n.providerMetadata?{providerOptions:n.providerMetadata}:{}});else if("file"===n.type)s.push({type:"file",mediaType:n.mediaType,filename:n.filename,data:n.url});else if("reasoning"===n.type)s.push({type:"reasoning",text:n.text,providerOptions:n.providerMetadata});else if("dynamic-tool"===n.type){const e=n.toolName;if("input-streaming"===n.state)throw new Uy({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:e,input:n.input,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}})}else{if(!Qy(n))throw new Error(`Unsupported part: ${n}`);{const o=eb(n);if("input-streaming"===n.state)throw new Uy({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:o,input:"output-error"===n.state?null!=(e=n.input)?e:n.rawInput:n.input,providerExecuted:n.providerExecuted,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}}),!0!==n.providerExecuted||"output-available"!==n.state&&"output-error"!==n.state||s.push({type:"tool-result",toolCallId:n.toolCallId,toolName:o,output:Gy({output:"output-error"===n.state?n.errorText:n.output,tool:null==(i=null==t?void 0:t.tools)?void 0:i[o],errorMode:"output-error"===n.state?"json":"none"})})}}n.push({role:"assistant",content:s});const a=o.filter((e=>Qy(e)&&!0!==e.providerExecuted||"dynamic-tool"===e.type));a.length>0&&n.push({role:"tool",content:a.map((e=>{var n;switch(e.state){case"output-error":case"output-available":{const r="dynamic-tool"===e.type?e.toolName:eb(e);return{type:"tool-result",toolCallId:e.toolCallId,toolName:r,output:Gy({output:"output-error"===e.state?e.errorText:e.output,tool:null==(n=null==t?void 0:t.tools)?void 0:n[r],errorMode:"output-error"===e.state?"text":"none"})}}default:throw new Uy({originalMessage:r,message:`Unsupported tool part state: ${e.state}`})}}))}),o=[]},o=[];for(const t of r.parts)"text"===t.type||"reasoning"===t.type||"file"===t.type||"dynamic-tool"===t.type||Qy(t)?o.push(t):"step-start"===t.type&&e();e();break}break;default:{const e=r.role;throw new Uy({originalMessage:r,message:`Unsupported role: ${e}`})}}return n}(n.map((({role:e,parts:t,metadata:n})=>({role:e,parts:t,metadata:n}))));return await e({uiMessages:n,modelMessages:i,abortSignal:r,...o})},reconnectToStream:async()=>null}}Rl({id:Du(),role:Wl(["system","user","assistant"]),metadata:wl().optional(),parts:Tl(Pl([bb,kb,wb,xb,Ib,Sb,$b,...Ob,...Tb]))}),e.EchoChatProvider=function({chatFn:e,children:n}){return t.jsx(Df.Provider,{value:e,children:n})},e.EchoProvider=function({config:e,children:r}){const[o,i]=n.useState(!1);if(n.useEffect((()=>{i(!0)}),[]),!o)return null;const s=e.baseEchoUrl||"https://echo.merit.systems",a={userManager:"undefined"!=typeof window&&window.__echoUserManager||new de({authority:s,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",silentRequestTimeoutInSeconds:10,automaticSilentRenew:!0,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${s}/api/oauth/authorize`,token_endpoint:`${s}/api/oauth/token`,userinfo_endpoint:`${s}/api/oauth/userinfo`,issuer:s,jwks_uri:`${s}/.well-known/jwks.json`,end_session_endpoint:`${s}/api/oauth/logout`},userStore:new N({store:window.localStorage})}),onSigninCallback:()=>{window.location.search.includes("code=")&&window.history.replaceState({},document.title,window.location.pathname)}};return t.jsx($e,{...a,children:t.jsx(wg,{config:e,children:r})})},e.EchoSignIn=Cf,e.EchoSignOut=Pf,e.EchoTokens=function({onPurchaseComplete:e,onError:r,className:o="",children:i,showAvatar:s=!1}){const{createPaymentLink:a,user:u,balance:l,freeTierBalance:c,refreshBalance:d,isInsufficientFunds:p,setIsInsufficientFunds:m}=xg(),[_,h]=n.useState(!1),[g,f]=n.useState(null),[v,y]=n.useState(!1),[b,k]=n.useState(!1),w=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),x=()=>{var e,t;return(((null==(e=null==c?void 0:c.userSpendInfo)?void 0:e.amountLeft)||0)<0?0:(null==(t=null==c?void 0:c.userSpendInfo)?void 0:t.amountLeft)||0)+((null==l?void 0:l.balance)||0)},I=async t=>{if(!u){const e=new Error("Please sign in to purchase tokens");return f(e.message),void(r&&r(e))}try{h(!0),f(null);const n=await a(t);await Nf(n,{onComplete:async()=>{try{await d(),y(!1),k(!1),e&&l&&e(l)}catch(t){const e=t instanceof Error?t:new Error("Failed to refresh balance");f(e.message),r&&r(e)}finally{h(!1)}},onCancel:()=>{h(!1)},onError:e=>{f(e.message),r&&r(e),h(!1)}})}catch(n){const e=n instanceof Error?n:new Error("Failed to create payment link");f(e.message),r&&r(e),h(!1)}},S=()=>{y(!1),k(!1),f(null)};if(!u)return t.jsx("div",{className:`echo-token-purchase ${o}`,children:i?t.jsxs("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px",textAlign:"center"},children:[t.jsx("p",{style:{margin:"0 0 12px 0"},children:"Please sign in to purchase tokens"}),t.jsx(Cf,{})]}):t.jsx(Cf,{})});const $=()=>{const[e,r]=n.useState(!1);return t.jsxs("button",{onClick:()=>y(!0),className:`echo-token-purchase-compact ${o}`,style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 12px",borderRadius:"8px",backgroundColor:e?"#f1f5f9":"#ffffff",border:"1px solid #e5e7eb",color:"#09090b",fontSize:"14px",fontWeight:"800",cursor:"pointer",backdropFilter:"blur(8px)",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",height:"40px",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[s&&(null==u?void 0:u.picture)?t.jsx("img",{src:u.picture,alt:u.name||u.email||"User avatar",style:{width:"24px",height:"24px",borderRadius:"50%",objectFit:"cover",flexShrink:0},onError:e=>{e.currentTarget.style.display="none"}}):t.jsx(Af,{width:20,height:20,variant:"light"}),t.jsx("span",{children:w(x())}),t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:e?"#dc2626":"#6b7280",transition:"color 0.2s ease"},children:[t.jsx("path",{d:"M7 7h10v10"}),t.jsx("path",{d:"M7 17 17 7"})]})]})},O=()=>t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px"},onClick:e=>{e.target===e.currentTarget&&S()},children:t.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px"},children:[t.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx(Af,{width:20,height:20,variant:"light"}),t.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Credits"})]})}),t.jsxs("div",{style:{padding:"0 16px",marginBottom:"16px"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Total Available"}),t.jsx("p",{style:{fontSize:"28px",fontWeight:"700",color:"#111827",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:w(x())}),t.jsxs("div",{style:{marginBottom:"8px"},children:[c&&x()>0&&t.jsxs("div",{style:{marginBottom:"8px"},children:[t.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[t.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#3b82f6"}}),t.jsxs("span",{children:[w(c.userSpendInfo.amountLeft<0?0:c.userSpendInfo.amountLeft)," ","Free Tier",c.userSpendInfo&&c.userSpendInfo.spendLimit&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",w(c.userSpendInfo.amountSpent>c.userSpendInfo.spendLimit?c.userSpendInfo.spendLimit:c.userSpendInfo.amountSpent)," ","of"," ",w(c.userSpendInfo.spendLimit)," ","spent)"]})]})]}),c.userSpendInfo&&c.userSpendInfo.spendLimit&&t.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",marginBottom:"4px",border:"1px solid #d1d5db"},children:t.jsx("div",{style:{width:`${Math.max(0,Math.min(100,Math.max(0,c.userSpendInfo.amountLeft)/(c.userSpendInfo.spendLimit||1)*100))}%`,height:"100%",backgroundColor:"#3b82f6"}})})]}),l&&l.balance>0&&t.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[t.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#dc2626"}}),t.jsxs("span",{children:[w(l.balance)," Paid Credits",l.totalPaid>0&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",w(l.totalSpent)," of"," ",w(l.totalPaid)," spent)"]})]})]}),l.totalPaid>0&&t.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",border:"1px solid #d1d5db"},children:t.jsx("div",{style:{width:`${Math.max(0,Math.min(100,l.balance/l.totalPaid*100))}%`,height:"100%",backgroundColor:"#dc2626"}})})]})]})]}),t.jsxs("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Add Credits"}),b?t.jsx(zf,{onAddCredits:I,onCancel:()=>k(!1),isProcessing:_}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsx("button",{onClick:()=>I(10),disabled:_,style:{width:"100%",padding:"12px 16px",backgroundColor:_?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:_?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{_||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{_||(e.currentTarget.style.backgroundColor="#dc2626")},children:_?"Processing...":"Add $10 Credits"}),t.jsx("button",{onClick:()=>k(!0),style:{width:"100%",padding:"8px 16px",fontSize:"14px",color:"#6b7280",backgroundColor:"transparent",border:"1px solid #e5e7eb",borderRadius:"6px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.color="#111827",e.currentTarget.style.borderColor="#d1d5db"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280",e.currentTarget.style.borderColor="#e5e7eb"},children:"Choose different amount"})]})]}),g&&t.jsx("div",{style:{margin:"0 16px 12px 16px",padding:"8px 12px",backgroundColor:"#fee2e2",color:"#dc2626",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:g}),t.jsxs("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"space-between",alignItems:"center",borderTop:"1px solid #f3f4f6"},children:[t.jsx(Pf,{onSuccess:()=>{console.log("Signed out from credits modal"),S()},onError:e=>{console.error("Sign out error from credits modal:",e)},children:t.jsx("button",{style:{padding:"8px 16px",backgroundColor:"transparent",color:"#dc2626",border:"1px solid #dc2626",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#fef2f2",e.currentTarget.style.borderColor="#b91c1c"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.borderColor="#dc2626"},children:"Sign Out"})}),t.jsx("button",{onClick:S,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})]})]})});return t.jsxs(t.Fragment,{children:[i?t.jsx("div",{onClick:()=>y(!0),style:{cursor:"pointer"},children:i}):t.jsx($,{}),v&&t.jsx(O,{}),t.jsx(Uf,{isOpen:p,onClose:()=>m(!1),onPurchaseComplete:()=>{null==e||e(l),m(!1)},onError:r})]})},e.InsufficientFundsModal=Uf,e.Logo=Af,e.useChat=function(){return function({experimental_throttle:e,resume:t=!1,...r}={}){const o=n.useRef("chat"in r?r.chat:new Sy(r));("chat"in r&&r.chat!==o.current||"id"in r&&o.current.id!==r.id)&&(o.current="chat"in r?r.chat:new Sy(r));const i="id"in r?r.id:null,s=n.useCallback((t=>o.current["~registerMessagesCallback"](t,e)),[e,i]),a=n.useSyncExternalStore(s,(()=>o.current.messages),(()=>o.current.messages)),u=n.useSyncExternalStore(o.current["~registerStatusCallback"],(()=>o.current.status),(()=>o.current.status)),l=n.useSyncExternalStore(o.current["~registerErrorCallback"],(()=>o.current.error),(()=>o.current.error)),c=n.useCallback((e=>{"function"==typeof e&&(e=e(o.current.messages)),o.current.messages=e}),[o]);return n.useEffect((()=>{t&&o.current.resumeStream()}),[t,o]),{id:o.current.id,messages:a,setMessages:c,sendMessage:o.current.sendMessage,regenerate:o.current.regenerate,clearError:o.current.clearError,stop:o.current.stop,error:l,resumeStream:o.current.resumeStream,status:u,addToolResult:o.current.addToolResult}}({transport:Eb()})},e.useEcho=xg,e.useEchoClient=yg,e.useEchoModelProviders=()=>{const{token:e,config:t,setIsInsufficientFunds:r}=xg(),o=()=>r(!0);return n.useMemo((()=>{const n={appId:t.appId,baseRouterUrl:t.baseRouterUrl},r=async()=>e;return{openai:gg(n,r,o),anthropic:_g(n,r,o),google:hg(n,r,o),openrouter:fg(n,r,o)}}),[e,t.appId,t.baseRouterUrl,r])},e.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:r=!0}=e,{token:o,user:i}=xg(),[s,a]=n.useState(void 0),[u,l]=n.useState(null),[c,d]=n.useState(!1),p=n.useRef(null);return n.useEffect((()=>{if(p.current&&p.current.abort(),!r||!o)return a(void 0),l(null),void d(!1);return(async()=>{const e=new AbortController;p.current=e,d(!0),l(null);try{if(e.signal.aborted)return;const{default:n}=await import("openai");if(e.signal.aborted)return;const r=new n({apiKey:o,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(r)}catch(n){if(!e.signal.aborted){const e=n instanceof Error?n.message:"Failed to load OpenAI";e.includes("Cannot resolve module")||e.includes("Module not found")||e.includes("openai")?l("OpenAI package not found. Please install it with: pnpm add openai"):l(`Failed to initialize OpenAI client: ${e}`),console.error("Error loading OpenAI:",n),a(void 0)}}finally{e.signal.aborted||d(!1)}})(),()=>{p.current&&p.current.abort()}}),[o,i,t,r]),{openai:s,isReady:void 0!==s&&!c,error:u,isLoading:c}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
3
3
  //# sourceMappingURL=echo-react-sdk.umd.js.map