@merit-systems/echo-react-sdk 1.0.10 → 1.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/echo-react-sdk.umd.js +2 -3
- package/dist/echo-react-sdk.umd.js.map +1 -1
- package/dist/index.cjs +2 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +34 -0
- package/dist/index.js +26426 -7019
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
|
@@ -1,4 +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,r){"use strict";var n,s=Object.defineProperty,i=(e,t,r)=>((e,t,r)=>t in e?s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class o 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 r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(r){return atob(t)}}o.prototype.name="InvalidTokenError";var c,l,u,d={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},h=(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))(h||{});(u=h||(h={})).reset=function(){c=3,l=d},u.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");c=e},u.setLogger=function(e){l=e};var p=class e{constructor(e){this._name=e}debug(...t){c>=4&&l.debug(e._format(this._name,this._method),...t)}info(...t){c>=3&&l.info(e._format(this._name,this._method),...t)}warn(...t){c>=2&&l.warn(e._format(this._name,this._method),...t)}error(...t){c>=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,r){const n=new e(`${t}.${r}`);return n.debug("begin"),n}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(t,...r){c>=4&&l.debug(e._format(t),...r)}static info(t,...r){c>=3&&l.info(e._format(t),...r)}static warn(t,...r){c>=2&&l.warn(e._format(t),...r)}static error(t,...r){c>=1&&l.error(e._format(t),...r)}};h.reset();var f=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new o("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new o(`Invalid token specified: missing part #${r+1}`);let s;try{s=a(n)}catch(tn){throw new o(`Invalid token specified: invalid base64 for part #${r+1} (${tn.message})`)}try{return JSON.parse(s)}catch(tn){throw new o(`Invalid token specified: invalid json for part #${r+1} (${tn.message})`)}}(e)}catch(t){throw p.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,r){const n=`${_.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${_.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${_.encodeBase64Url(new Uint8Array(s))}`}},g=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),m=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),r=await crypto.subtle.digest("SHA-256",t);return g(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw p.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return g(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(t){let r;switch(t.kty){case"RSA":r={e:t.e,kty:t.kty,n:t.n};break;case"EC":r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":r={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":r={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const n=await e.hash("SHA-256",JSON.stringify(r));return e.encodeBase64Url(n)}static async generateDPoPProof({url:t,accessToken:r,httpMethod:n,keyPair:s,nonce:i}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=n?n:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};r&&(o=await e.hash("SHA-256",r),a=e.encodeBase64Url(o),c.ath=a),i&&(c.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await f.generateSignedJwt(t,c,s.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const r=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(r)}catch(r){throw r instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${r.message}`):r}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};m.encodeBase64Url=e=>g(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var _=m,w=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new p(`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 w{constructor(){super(...arguments),this._logger=new p(`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 r=this._logger.create("init");t=Math.max(Math.floor(t),1);const n=e.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void r.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),r.debug("using duration",t),this._expiration=n;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},S=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},v=";",E=class extends Error{constructor(e,t){var r,n,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw p.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},k=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},R=class{constructor(e){this._logger=new p("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 r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let e=r-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 n=r+1;t.debug("registering expired timer, raising in",n,"seconds"),this._expiredTimer.init(n)}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)}},x=class{constructor(e,t,r,n,s){this._callback=e,this._client_id=t,this._intervalInSeconds=n,this._stopOnError=s,this._logger=new p("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(r);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)}},T=class{constructor(){this._logger=new p("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]}},O=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},A=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new p("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const s=new AbortController,i=setTimeout((()=>s.abort()),1e3*r);try{return await fetch(e,{...t,signal:s.signal})}catch(o){if(o instanceof DOMException&&"AbortError"===o.name)throw new k("Network timed out");throw o}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let o;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:n,credentials:r})}catch(l){throw s.error("Network Error"),l}s.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(l){if(s.error("Error parsing JSON response",l),o.ok)throw l;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(s.error("Error from server:",c),c.error)throw new E(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:s,extraHeaders:i}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let c;void 0!==r&&(a.Authorization="Basic "+r),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:n,credentials:s})}catch(h){throw o.error("Network error"),h}o.debug("HTTP response received, status",c.status);const l=c.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 u=await c.text();let d={};if(u)try{d=JSON.parse(u)}catch(h){if(o.error("Error parsing JSON response",h),c.ok)throw h;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",d),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new O(e,`${JSON.stringify(d)}`)}if(d.error)throw new E(d,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],s=["authorization"];0!==r.length&&r.forEach((r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(s.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,s);const i="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];i&&""!==i&&(e[r]=i)}))}},C=class{constructor(e){this._settings=e,this._logger=new p("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new A(["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 r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[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 r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},N=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new p("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 r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},P=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:s,client_id:i,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:u,client_authentication:d="client_secret_post",prompt:h,display:p,max_age:f,ui_locales:g,acr_values:m,resource:_,response_mode:w,filterProtocolClaims:y=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:v=900,mergeClaimsStrategy:E={array:"replace"},disablePKCE:k=!1,stateStore:R,revokeTokenAdditionalContentTypes:x,fetchRequestCredentials:O,refreshTokenAllowedScope:A,extraQueryParams:C={},extraTokenParams:P={},extraHeaders:I={},dpop:U,omitScopeWhenRequesting:j=!1}){var L;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=r,this.metadataSeed=s,this.signingKeys=n,this.client_id=i,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=u,this.client_authentication=d,this.prompt=h,this.display=p,this.max_age=f,this.ui_locales=g,this.acr_values=m,this.resource=_,this.response_mode=w,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.mergeClaimsStrategy=E,this.omitScopeWhenRequesting=j,this.disablePKCE=!!k,this.revokeTokenAdditionalContentTypes=x,this.fetchRequestCredentials=O||"same-origin",this.requestTimeoutInSeconds=S,R)this.stateStore=R;else{const e="undefined"!=typeof window?window.localStorage:new T;this.stateStore=new N({store:e})}if(this.refreshTokenAllowedScope=A,this.extraQueryParams=C,this.extraTokenParams=P,this.extraHeaders=I,this.dpop=U,this.dpop&&!(null==(L=this.dpop)?void 0:L.store))throw new Error("A DPoPStore is required when dpop is enabled")}},I=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=f.decode(e);return t.debug("JWT decoding successful"),r}catch(r){throw t.error("Error parsing JWT response"),r}},this._jsonService=new A(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 r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},U=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("TokenClient"),this._jsonService=new A(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:s,...i}){const o=this._logger.create("exchangeCode");r||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),i.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,h]of Object.entries(i))null!=h&&a.set(d,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;c=_.generateBasicAuth(r,n);break;case"client_secret_post":a.append("client_id",r),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),u}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...s}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",n);for(const[u,d]of Object.entries(s))null!=d&&o.set(u,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw i.throw(new Error("A client_secret is required")),null;a=_.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r)}const c=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,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:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:s,...i}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),i.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[d,h]of Object.entries(i))Array.isArray(h)?h.forEach((e=>a.append(d,e))):null!=h&&a.set(d,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw o.throw(new Error("A client_secret is required")),null;c=_.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),u}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[i,o]of Object.entries(e))null!=o&&s.set(i,o);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},j=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new p("ResponseValidator"),this._userInfoService=new I(this._settings,this._metadataService),this._tokenClient=new U(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=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),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new E(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new E(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&s.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const s=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:r,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var r;const n=this._logger.create("_validateIdTokenAttributes");n.debug("decoding ID Token JWT");const s=f.decode(null!=(r=e.id_token)?r:"");if(s.sub||n.throw(new Error("ID Token is missing a subject claim")),t){const e=f.decode(t);s.sub!==e.sub&&n.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&n.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&n.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&n.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},L=class e{constructor(e){this.id=e.id||_.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 p("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 p.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const n=p.createStatic("State","clearStaleState"),s=b.getEpochTime()-r,i=await t.getAllKeys();n.debug("got keys",i);for(let a=0;a<i.length;a++){const r=i[a],c=await t.get(r);let l=!1;if(c)try{const t=await e.fromStorageString(c);n.debug("got item from key:",r,t.created),t.created<=s&&(l=!0)}catch(o){n.error("Error parsing state for key:",r,o),l=!0}else n.debug("no item in storage for key:",r),l=!0;l&&(n.debug("removed item for key:",r),t.remove(r))}}},D=class e extends L{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 r=!0===t.code_verifier?_.generateCodeVerifier():t.code_verifier||void 0,n=r?await _.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:n})}toStorageString(){return new p("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){p.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},F=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:r,client_id:n,redirect_uri:s,response_type:i,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:u,nonce:d,url_state:h,resource:p,skipUserInfo:f,extraQueryParams:g,extraTokenParams:m,disablePKCE:_,dpopJkt:w,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)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(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!r)throw this._logger.error("create: No authority passed"),new Error("authority");const S=await D.create({data:a,request_type:l,url_state:h,code_verifier:!_,client_id:n,authority:r,redirect_uri:s,response_mode:c,client_secret:u,scope:o,extraTokenParams:m,skipUserInfo:f}),E=new URL(t);E.searchParams.append("client_id",n),E.searchParams.append("redirect_uri",s),E.searchParams.append("response_type",i),y||E.searchParams.append("scope",o),d&&E.searchParams.append("nonce",d),w&&E.searchParams.append("dpop_jkt",w);let k=S.id;if(h&&(k=`${k}${v}${h}`),E.searchParams.append("state",k),S.code_challenge&&(E.searchParams.append("code_challenge",S.code_challenge),E.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach((e=>E.searchParams.append("resource",e)))}for(const[e,v]of Object.entries({response_mode:c,...b,...g}))null!=v&&E.searchParams.append(e,v.toString());return new e({url:E.href,state:S})}};F._logger=new p("SigninRequest");var M=F,q=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(v);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(v))}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}},B=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:s,request_type:i,client_id:o,url_state:a}){if(this._logger=new p("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||a)){this.state=new L({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${v}${a}`),c.searchParams.append("state",e)}for(const[l,u]of Object.entries({...s}))null!=u&&c.searchParams.append(l,u.toString());this.url=c.href}},H=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(v);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(v))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},z=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],W=["sub","iss","aud","exp","iat"],$=class{constructor(e){this._settings=e,this._logger=new p("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:z;for(const r of e)W.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[n,s]of Object.entries(t))if(r[n]!==s)if(Array.isArray(r[n])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)r[n]=s;else{const e=Array.isArray(r[n])?r[n]:[r[n]];for(const t of Array.isArray(s)?s:[s])e.includes(t)||e.push(t);r[n]=e}else"object"==typeof r[n]&&"object"==typeof s?r[n]=this.mergeClaims(r[n],s):r[n]=s;return r}},K=class{constructor(e,t){this.keys=e,this.nonce=t}},J=class{constructor(e,t){this._logger=new p("OidcClient"),this.settings=e instanceof P?e:new P(e),this.metadataService=null!=t?t:new C(this.settings),this._claimsService=new $(this.settings),this._validator=new j(this.settings,this.metadataService,this._claimsService),this._tokenClient=new U(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:s,login_hint:i,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:f=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:_=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:S,omitScopeWhenRequesting:v=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const R=await M.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:u,state_data:e,url_state:c,prompt:h,display:p,max_age:f,ui_locales:g,id_token_hint:s,login_hint:i,acr_values:m,dpopJkt:S,resource:_,request:t,request_uri:r,extraQueryParams:y,extraTokenParams:b,request_type:n,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:v});await this.clearStaleState();const x=R.state;return await this.settings.stateStore.set(x.id,x.toStorageString()),R}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new q(S.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await D.fromStorageString(s),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:s,response:i}=await this.readSigninResponseState(e,r);if(n.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,s,t)}catch(o){if(!(o instanceof O&&this.settings.dpop))throw o;{const e=await this.getDpopProof(this.settings.dpop.store,o.nonce);t.DPoP=e,await this._validator.validateSigninResponse(i,s,t)}}return i}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await _.generateDPoPKeys(),n=new K(r,t),await e.set(this.settings.client_id,n)),await _.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),i=new q(new URLSearchParams);return Object.assign(i,s),await this._validator.validateCredentialsResponse(i,r),i}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,extraTokenParams:i}){var o;const a=this._logger.create("useRefreshToken");let c,l;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);s={...s,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}catch(d){if(!(d instanceof O&&this.settings.dpop))throw d;s.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}const u=new q(new URLSearchParams);return Object.assign(u,l),a.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...e,scope:c}),u}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),r||!i||t||(r=this.settings.client_id);const l=new B({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:i,state_data:e,extraQueryParams:o,request_type:n,url_state:s});await this.clearStaleState();const u=l.state;return u&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),l}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new H(S.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new E(n);return{state:void 0,response:n}}const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await L.fromStorageString(s),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),L.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 p("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){r.debug("initializing check session iframe");const n=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,o=new x(this._callback,n,e,s,i);await o.load(),this._checkSessionIFrame=o,o.start(t)}else r.warn("no check session iframe found in the metadata")}catch(n){r.error("Error from getCheckSessionIframe:",n instanceof Error?n.message:n)}},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(r){e.error("error from querySessionStatus",r instanceof Error?r.message:r)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!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"),r?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 p("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 p.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},X="oidc-client",Q=class{constructor(){this._abort=new w("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:r,keepOpen:n}=await new Promise(((r,n)=>{const s=s=>{var i;const o=s.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(s.origin===a&&(null==o?void 0:o.source)===X){try{const r=S.readParams(o.url,e.response_mode).get("state");if(r||t.warn("no state found in response url"),s.source!==this._window&&r!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}r(o)}};window.addEventListener("message",s,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",s,!1)));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",s,!1),this._disposeHandlers.add((()=>i.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),n(e)})))}));return t.debug("got response from window"),this._dispose(),n||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,n=window.location.origin){const s={source:X,url:t,keepOpen:r},i=new p("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(s,n);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 r=new BroadcastChannel(`oidc-client-popup-${e}`);r.postMessage(s),r.close()}}},Y={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Z="_blank",ee=60,te=2,re=class extends P{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:n=Y,popupWindowTarget:s=Z,redirectMethod:i="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:u=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:f=!1,monitorSession:g=!1,monitorAnonymousSession:m=!1,checkSessionIntervalInSeconds:_=te,query_status_response_type:w="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:S=!1,includeIdTokenInSilentSignout:v=!1,accessTokenExpiringNotificationTimeInSeconds:E=ee,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=n,this.popupWindowTarget=s,this.redirectMethod=i,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=u,this.silentRequestTimeoutInSeconds=d||l||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=f,this.monitorSession=g,this.monitorAnonymousSession=m,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=y,this.query_status_response_type=w,this.revokeTokenTypes=b,this.revokeTokensOnSignout=S,this.includeIdTokenInSilentSignout=v,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new T;this.userStore=new N({store:e})}}},ne=class e extends Q{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new p("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 k("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 r=e.target;null==(t=r.parentNode)||t.removeChild(r),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)}},se=class{constructor(e){this._settings=e,this._logger=new p("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ne({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ne.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ie=class extends Q{constructor({popupWindowTarget:e=Z,popupWindowFeatures:t={},popupSignal:r}){super(),this._logger=new p("PopupWindow");const n=y.center({...Y,...t});this._window=window.open(void 0,e,y.serialize(n)),r&&r.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=r.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 r=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),n(),this._disposeHandlers.delete(n))}),500),n=()=>clearInterval(r);return this._disposeHandlers.add(n),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()}},oe=class{constructor(e){this._settings=e,this._logger=new p("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:r}){return new ie({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:r})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ie.notifyOpener(e,t)}},ae=class{constructor(e){this._settings=e,this._logger=new p("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var r;this._logger.create("prepare");let n=window.self;"top"===t&&(n=null!=(r=window.top)?r:window.self);const s=n.location[e].bind(n.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return s(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),n.stop()}}}async callback(){}},ce=class extends R{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new p("UserManagerEvents"),this._userLoaded=new w("User loaded"),this._userUnloaded=new w("User unloaded"),this._silentRenewError=new w("Silent renew error"),this._userSignedIn=new w("User signed in"),this._userSignedOut=new w("User signed out"),this._userSessionChanged=new w("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 p("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 k)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)}},ue=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,r,n){this._logger=new p("UserManager"),this.settings=new re(e),this._client=new J(e),this._redirectNavigator=null!=t?t:new ae(this.settings),this._popupNavigator=null!=r?r:new oe(this.settings),this._iframeNavigator=null!=n?n:new se(this.settings),this._events=new ce(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"),r=await this._loadUser();return r?(t.info("user loaded"),await this._events.load(r,e),r):(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:r,...n}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:r});await this._signinStart({request_type:"si:r",dpopJkt:s,...n},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){const n=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});n.debug("got signin response");const i=await this._buildUser(s);return i.profile&&i.profile.sub?n.info("success, signed in subject",i.profile.sub):n.info("no subject"),i}async signinPopup(e={}){var t;const r=this._logger.create("signinPopup");let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o,...a}=e,c=this.settings.popup_redirect_uri;c||r.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o}),u=await this._signin({request_type:"si:p",redirect_uri:c,display:"popup",dpopJkt:n,...a},l);return u&&(u.profile&&u.profile.sub?r.info("success, signed in subject",u.profile.sub):r.info("no subject")),u}async signinPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var t,r;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...i}=e;let o,a=await this._loadUser();if(null==a?void 0:a.refresh_token){n.debug("using refresh token");const e=new ue(a);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:s})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let l;c||n.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const u=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...i},u,l),a&&((null==(r=a.profile)?void 0:r.sub)?n.info("success, signed in subject",a.profile.sub):n.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),r=new G({...e.state,...t});return await this.storeUser(r),await this._events.load(r),r}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:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.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:r,...n}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),a=await this._signinStart({request_type:"si:s",redirect_uri:s,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,...n},o);try{const e={},r=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),r.session_state&&r.profile.sub?(t.info("success for subject",r.profile.sub),{session_state:r.session_state,sub:r.profile.sub}):(t.info("success, user not authenticated"),null)}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof E)switch(c.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:c.session_state}}throw c}}async _signin(e,t,r){const n=await this._signinStart(e,t);return await this._signinEnd(n.url,r)}async _signinStart(e,t){const r=this._logger.create("_signinStart");try{const n=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:n.url,state:n.state.id,response_mode:n.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(n){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),n}}async _signinEnd(e,t){const r=this._logger.create("_signinEnd"),n=await this._client.processSigninResponse(e,{});r.debug("got signin response");return await this._buildUser(n,t)}async _buildUser(e,t){const r=this._logger.create("_buildUser"),n=new G(e);if(t){if(t!==n.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",n.profile.sub),new E({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(n),r.debug("user stored"),await this._events.load(n),n}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:r,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...n},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s,...i}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){const r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var r;const n=this._logger.create("_signoutStart");try{const s=await this._loadUser();n.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const i=e.id_token_hint||s&&s.id_token;i&&(n.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),n.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return n.debug("got signout request"),await t.navigate({url:o.url,state:null==(r=o.state)?void 0:r.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var t;const r=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:n,...s}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:i,...s},a),r.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 r=this._logger.create("_revokeInternal");if(!e)return;const n=t.filter((t=>"string"==typeof e[t]));if(n.length){for(const t of n)await this._client.revokeToken(e[t],t),r.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),r.debug("user stored"),await this._events.load(e)}else r.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 r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}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,r,n){var s,i;const o=await(null==(i=null==(s=this.settings.dpop)?void 0:s.store)?void 0:i.get(this.settings.client_id));if(o)return await _.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:r,keyPair:o.keys,nonce:n})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const r=await _.generateDPoPKeys();t=new K(r),await e.store.set(this.settings.client_id,t)}return await _.generateDPoPJkt(t.keys)}},he=r.createContext(void 0);he.displayName="AuthContext";var pe={isLoading:!0,isAuthenticated:!1},fe=(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 r=t.error;return r.toString=()=>`${r.name}: ${r.message}`,{...e,isLoading:!1,error:r}}default:{const r=new TypeError(`unknown type ${t.type}`),n={name:r.name,message:r.message,innerError:r,stack:r.stack,source:"unknown",toString:()=>`${n.name}: ${n.message}`};return{...e,isLoading:!1,error:n}}}},ge=ye("signinCallback","Sign-in failed"),me=ye("signoutCallback","Sign-out failed"),_e=ye("renewSilent","Renew silent failed");function we(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 r=>({...we(r,t),source:e})}function be(e,t,r){if(e&&"object"==typeof e){const r=e[t];if("string"==typeof r)return r}return r()}var Se=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],ve=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],Ee=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.`)},ke="undefined"==typeof window?null:de,Re=e=>{const{children:t,onSigninCallback:n,skipSigninCallback:s,matchSignoutCallback:i,onSignoutCallback:o,onRemoveUser:a,userManager:c=null,...l}=e,[u]=r.useState((()=>null!=c?c:ke?new ke(l):{settings:l})),[d,h]=r.useReducer(fe,pe),p=r.useMemo((()=>Object.assign({settings:u.settings,events:u.events},Object.fromEntries(Se.map((e=>{var t,r;return[e,null!=(r=null==(t=u[e])?void 0:t.bind(u))?r:Ee(e)]}))),Object.fromEntries(ve.map((e=>[e,u[e]?async t=>{h({type:"NAVIGATOR_INIT",method:e});try{return await u[e](t)}catch(r){return h({type:"ERROR",error:{...we(r,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{h({type:"NAVIGATOR_CLOSE"})}}:Ee(e)]))))),[u]),f=r.useRef(!1);r.useEffect((()=>{u&&!f.current&&(f.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")))})()&&!s&&(e=await u.signinCallback(),n&&await n(e)),e=e||await u.getUser(),h({type:"INITIALISED",user:e})}catch(e){h({type:"ERROR",error:ge(e)})}try{if(i&&i(u.settings)){const e=await u.signoutCallback();o&&await o(e)}}catch(e){h({type:"ERROR",error:me(e)})}})())}),[u,s,n,o,i]),r.useEffect((()=>{if(!u)return;const e=e=>{h({type:"USER_LOADED",user:e})};u.events.addUserLoaded(e);const t=()=>{h({type:"USER_UNLOADED"})};u.events.addUserUnloaded(t);const r=()=>{h({type:"USER_SIGNED_OUT"})};u.events.addUserSignedOut(r);const n=e=>{h({type:"ERROR",error:_e(e)})};return u.events.addSilentRenewError(n),()=>{u.events.removeUserLoaded(e),u.events.removeUserUnloaded(t),u.events.removeUserSignedOut(r),u.events.removeSilentRenewError(n)}}),[u]);const g=r.useCallback((async()=>{await u.removeUser(),a&&await a()}),[u,a]),m=r.useMemo((()=>({...d,...p,removeUser:g})),[d,p,g]);return r.createElement(he.Provider,{value:m},t)},xe=()=>{const e=r.useContext(he);return e||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component."),e};function Te(e,t){return function(){return e.apply(t,arguments)}}const{toString:Oe}=Object.prototype,{getPrototypeOf:Ae}=Object,{iterator:Ce,toStringTag:Ne}=Symbol,Pe=(e=>t=>{const r=Oe.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ie=e=>(e=e.toLowerCase(),t=>Pe(t)===e),Ue=e=>t=>typeof t===e,{isArray:je}=Array,Le=Ue("undefined");const De=Ie("ArrayBuffer");const Fe=Ue("string"),Me=Ue("function"),qe=Ue("number"),Be=e=>null!==e&&"object"==typeof e,He=e=>{if("object"!==Pe(e))return!1;const t=Ae(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Ne in e||Ce in e)},ze=Ie("Date"),We=Ie("File"),$e=Ie("Blob"),Ke=Ie("FileList"),Je=Ie("URLSearchParams"),[Ve,Ge,Xe,Qe]=["ReadableStream","Request","Response","Headers"].map(Ie);function Ye(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),je(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(n=0;n<i;n++)o=s[n],t.call(null,e[o],o,e)}}function Ze(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const et="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,tt=e=>!Le(e)&&e!==et;const rt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Ae(Uint8Array)),nt=Ie("HTMLFormElement"),st=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),it=Ie("RegExp"),ot=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};Ye(r,((r,s)=>{let i;!1!==(i=t(r,s,e))&&(n[s]=i||r)})),Object.defineProperties(e,n)};const at=Ie("AsyncFunction"),ct=(lt="function"==typeof setImmediate,ut=Me(et.postMessage),lt?setImmediate:ut?(dt=`axios@${Math.random()}`,ht=[],et.addEventListener("message",(({source:e,data:t})=>{e===et&&t===dt&&ht.length&&ht.shift()()}),!1),e=>{ht.push(e),et.postMessage(dt,"*")}):e=>setTimeout(e));var lt,ut,dt,ht;const pt="undefined"!=typeof queueMicrotask?queueMicrotask.bind(et):"undefined"!=typeof process&&process.nextTick||ct,ft={isArray:je,isArrayBuffer:De,isBuffer:function(e){return null!==e&&!Le(e)&&null!==e.constructor&&!Le(e.constructor)&&Me(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Me(e.append)&&("formdata"===(t=Pe(e))||"object"===t&&Me(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&De(e.buffer),t},isString:Fe,isNumber:qe,isBoolean:e=>!0===e||!1===e,isObject:Be,isPlainObject:He,isReadableStream:Ve,isRequest:Ge,isResponse:Xe,isHeaders:Qe,isUndefined:Le,isDate:ze,isFile:We,isBlob:$e,isRegExp:it,isFunction:Me,isStream:e=>Be(e)&&Me(e.pipe),isURLSearchParams:Je,isTypedArray:rt,isFileList:Ke,forEach:Ye,merge:function e(){const{caseless:t}=tt(this)&&this||{},r={},n=(n,s)=>{const i=t&&Ze(r,s)||s;He(r[i])&&He(n)?r[i]=e(r[i],n):He(n)?r[i]=e({},n):je(n)?r[i]=n.slice():r[i]=n};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&Ye(arguments[s],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(Ye(t,((t,n)=>{r&&Me(t)?e[n]=Te(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let s,i,o;const a={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)o=s[i],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Ae(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Pe,kindOfTest:Ie,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(je(e))return e;let t=e.length;if(!qe(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Ce]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:nt,hasOwnProperty:st,hasOwnProp:st,reduceDescriptors:ot,freezeMethods:e=>{ot(e,((t,r)=>{if(Me(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Me(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return je(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Ze,global:et,isContextDefined:tt,isSpecCompliantForm:function(e){return!!(e&&Me(e.append)&&"FormData"===e[Ne]&&e[Ce])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(Be(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=je(e)?[]:{};return Ye(e,((e,t)=>{const i=r(e,n+1);!Le(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)},isAsyncFn:at,isThenable:e=>e&&(Be(e)||Me(e))&&Me(e.then)&&Me(e.catch),setImmediate:ct,asap:pt,isIterable:e=>null!=e&&Me(e[Ce])};function gt(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}ft.inherits(gt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ft.toJSONObject(this.config),code:this.code,status:this.status}}});const mt=gt.prototype,_t={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{_t[e]={value:e}})),Object.defineProperties(gt,_t),Object.defineProperty(mt,"isAxiosError",{value:!0}),gt.from=(e,t,r,n,s,i)=>{const o=Object.create(mt);return ft.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),gt.call(o,e.message,t,r,n,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};function wt(e){return ft.isPlainObject(e)||ft.isArray(e)}function yt(e){return ft.endsWith(e,"[]")?e.slice(0,-2):e}function bt(e,t,r){return e?e.concat(t).map((function(e,t){return e=yt(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const St=ft.toFlatObject(ft,{},null,(function(e){return/^is[A-Z]/.test(e)}));function vt(e,t,r){if(!ft.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=ft.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ft.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,i=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ft.isSpecCompliantForm(t);if(!ft.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ft.isDate(e))return e.toISOString();if(ft.isBoolean(e))return e.toString();if(!a&&ft.isBlob(e))throw new gt("Blob is not supported. Use a Buffer instead.");return ft.isArrayBuffer(e)||ft.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,s){let a=e;if(e&&!s&&"object"==typeof e)if(ft.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ft.isArray(e)&&function(e){return ft.isArray(e)&&!e.some(wt)}(e)||(ft.isFileList(e)||ft.endsWith(r,"[]"))&&(a=ft.toArray(e)))return r=yt(r),a.forEach((function(e,n){!ft.isUndefined(e)&&null!==e&&t.append(!0===o?bt([r],n,i):null===o?r:r+"[]",c(e))})),!1;return!!wt(e)||(t.append(bt(s,r,i),c(e)),!1)}const u=[],d=Object.assign(St,{defaultVisitor:l,convertValue:c,isVisitable:wt});if(!ft.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ft.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),ft.forEach(r,(function(r,i){!0===(!(ft.isUndefined(r)||null===r)&&s.call(t,r,ft.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function Et(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function kt(e,t){this._pairs=[],e&&vt(e,this,t)}const Rt=kt.prototype;function xt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Tt(e,t,r){if(!t)return e;const n=r&&r.encode||xt;ft.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let i;if(i=s?s(t,r):ft.isURLSearchParams(t)?t.toString():new kt(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}Rt.append=function(e,t){this._pairs.push([e,t])},Rt.toString=function(e){const t=e?function(t){return e.call(this,t,Et)}:Et;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Ot{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ft.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const At={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ct={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:kt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Nt="undefined"!=typeof window&&"undefined"!=typeof document,Pt="object"==typeof navigator&&navigator||void 0,It=Nt&&(!Pt||["ReactNative","NativeScript","NS"].indexOf(Pt.product)<0),Ut="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,jt=Nt&&window.location.href||"http://localhost",Lt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Nt,hasStandardBrowserEnv:It,hasStandardBrowserWebWorkerEnv:Ut,navigator:Pt,origin:jt},Symbol.toStringTag,{value:"Module"})),...Ct};function Dt(e){function t(e,r,n,s){let i=e[s++];if("__proto__"===i)return!0;const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&ft.isArray(n)?n.length:i,a)return ft.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!o;n[i]&&ft.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&ft.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!o}if(ft.isFormData(e)&&ft.isFunction(e.entries)){const r={};return ft.forEachEntry(e,((e,n)=>{t(function(e){return ft.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Ft={transitional:At,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=ft.isObject(e);s&&ft.isHTMLForm(e)&&(e=new FormData(e));if(ft.isFormData(e))return n?JSON.stringify(Dt(e)):e;if(ft.isArrayBuffer(e)||ft.isBuffer(e)||ft.isStream(e)||ft.isFile(e)||ft.isBlob(e)||ft.isReadableStream(e))return e;if(ft.isArrayBufferView(e))return e.buffer;if(ft.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return vt(e,new Lt.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Lt.isNode&&ft.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=ft.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return vt(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(ft.isString(e))try{return(t||JSON.parse)(e),ft.trim(e)}catch(tn){if("SyntaxError"!==tn.name)throw tn}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ft.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(ft.isResponse(e)||ft.isReadableStream(e))return e;if(e&&ft.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(tn){if(r){if("SyntaxError"===tn.name)throw gt.from(tn,gt.ERR_BAD_RESPONSE,this,null,this.response);throw tn}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Lt.classes.FormData,Blob:Lt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ft.forEach(["delete","get","head","post","put","patch"],(e=>{Ft.headers[e]={}}));const Mt=ft.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),qt=Symbol("internals");function Bt(e){return e&&String(e).trim().toLowerCase()}function Ht(e){return!1===e||null==e?e:ft.isArray(e)?e.map(Ht):String(e)}function zt(e,t,r,n,s){return ft.isFunction(n)?n.call(this,t,r):(s&&(t=r),ft.isString(t)?ft.isString(n)?-1!==t.indexOf(n):ft.isRegExp(n)?n.test(t):void 0:void 0)}let Wt=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=Bt(t);if(!s)throw new Error("header name must be a non-empty string");const i=ft.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Ht(e))}const i=(e,t)=>ft.forEach(e,((e,r)=>s(e,r,t)));if(ft.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(ft.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&Mt[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(ft.isObject(e)&&ft.isIterable(e)){let r,n,s={};for(const t of e){if(!ft.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[n=t[0]]=(r=s[n])?ft.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(s,t)}else null!=e&&s(t,e,r);return this}get(e,t){if(e=Bt(e)){const r=ft.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(ft.isFunction(t))return t.call(this,e,r);if(ft.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Bt(e)){const r=ft.findKey(this,e);return!(!r||void 0===this[r]||t&&!zt(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=Bt(e)){const s=ft.findKey(r,e);!s||t&&!zt(0,r[s],s,t)||(delete r[s],n=!0)}}return ft.isArray(e)?e.forEach(s):s(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const s=t[r];e&&!zt(0,this[s],s,e,!0)||(delete this[s],n=!0)}return n}normalize(e){const t=this,r={};return ft.forEach(this,((n,s)=>{const i=ft.findKey(r,s);if(i)return t[i]=Ht(n),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();o!==s&&delete t[s],t[o]=Ht(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ft.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&ft.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[qt]=this[qt]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=Bt(e);t[n]||(!function(e,t){const r=ft.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return ft.isArray(e)?e.forEach(n):n(e),this}};function $t(e,t){const r=this||Ft,n=t||r,s=Wt.from(n.headers);let i=n.data;return ft.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function Kt(e){return!(!e||!e.__CANCEL__)}function Jt(e,t,r){gt.call(this,null==e?"canceled":e,gt.ERR_CANCELED,t,r),this.name="CanceledError"}function Vt(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new gt("Request failed with status code "+r.status,[gt.ERR_BAD_REQUEST,gt.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Wt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ft.reduceDescriptors(Wt.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),ft.freezeMethods(Wt),ft.inherits(Jt,gt,{__CANCEL__:!0});const Gt=(e,t,r=3)=>{let n=0;const s=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[o];s||(s=c),r[i]=a,n[i]=c;let u=o,d=0;for(;u!==i;)d+=r[u++],u%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),c-s<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}(50,250);return function(e,t){let r,n,s=0,i=1e3/t;const o=(t,i=Date.now())=>{s=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-s;a>=i?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),i-a)))},()=>r&&o(r)]}((r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,c=s(a);n=i;e({loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&i<=o?(o-i)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},Xt=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Qt=e=>(...t)=>ft.asap((()=>e(...t))),Yt=Lt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Lt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Lt.origin),Lt.navigator&&/(msie|trident)/i.test(Lt.navigator.userAgent)):()=>!0,Zt=Lt.hasStandardBrowserEnv?{write(e,t,r,n,s,i){const o=[e+"="+encodeURIComponent(t)];ft.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ft.isString(n)&&o.push("path="+n),ft.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function er(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const tr=e=>e instanceof Wt?{...e}:e;function rr(e,t){t=t||{};const r={};function n(e,t,r,n){return ft.isPlainObject(e)&&ft.isPlainObject(t)?ft.merge.call({caseless:n},e,t):ft.isPlainObject(t)?ft.merge({},t):ft.isArray(t)?t.slice():t}function s(e,t,r,s){return ft.isUndefined(t)?ft.isUndefined(e)?void 0:n(void 0,e,0,s):n(e,t,0,s)}function i(e,t){if(!ft.isUndefined(t))return n(void 0,t)}function o(e,t){return ft.isUndefined(t)?ft.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>s(tr(e),tr(t),0,!0)};return ft.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||s,o=i(e[n],t[n],n);ft.isUndefined(o)&&i!==a||(r[n]=o)})),r}const nr=e=>{const t=rr({},e);let r,{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Wt.from(a),t.url=Tt(er(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ft.isFormData(n))if(Lt.hasStandardBrowserEnv||Lt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Lt.hasStandardBrowserEnv&&(s&&ft.isFunction(s)&&(s=s(t)),s||!1!==s&&Yt(t.url))){const e=i&&o&&Zt.read(o);e&&a.set(i,e)}return t},sr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=nr(e);let s=n.data;const i=Wt.from(n.headers).normalize();let o,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const n=Wt.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Vt((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:n,config:e,request:g}),g=null}g.open(n.method.toUpperCase(),n.url,!0),g.timeout=n.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new gt("Request aborted",gt.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new gt("Network Error",gt.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const s=n.transitional||At;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new gt(t,s.clarifyTimeoutError?gt.ETIMEDOUT:gt.ECONNABORTED,e,g)),g=null},void 0===s&&i.setContentType(null),"setRequestHeader"in g&&ft.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),ft.isUndefined(n.withCredentials)||(g.withCredentials=!!n.withCredentials),d&&"json"!==d&&(g.responseType=n.responseType),p&&([c,u]=Gt(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,l]=Gt(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(o=t=>{g&&(r(!t||t.type?new Jt(null,e,g):t),g.abort(),g=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const _=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);_&&-1===Lt.protocols.indexOf(_)?r(new gt("Unsupported protocol "+_+":",gt.ERR_BAD_REQUEST,e)):g.send(s||null)}))},ir=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const s=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof gt?t:new Jt(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,s(new gt(`timeout ${t} of ms exceeded`,gt.ETIMEDOUT))}),t);const o=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(s):e.removeEventListener("abort",s)})),e=null)};e.forEach((e=>e.addEventListener("abort",s)));const{signal:a}=n;return a.unsubscribe=()=>ft.asap(o),a}},or=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,s=0;for(;s<r;)n=s+t,yield e.slice(s,n),s=n},ar=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},cr=(e,t,r,n)=>{const s=async function*(e,t){for await(const r of ar(e))yield*or(r,t)}(e,t);let i,o=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await s.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw a(t),t}},cancel:e=>(a(e),s.return())},{highWaterMark:2})},lr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,ur=lr&&"function"==typeof ReadableStream,dr=lr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),hr=(e,...t)=>{try{return!!e(...t)}catch(tn){return!1}},pr=ur&&hr((()=>{let e=!1;const t=new Request(Lt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),fr=ur&&hr((()=>ft.isReadableStream(new Response("").body))),gr={stream:fr&&(e=>e.body)};var mr;lr&&(mr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!gr[e]&&(gr[e]=ft.isFunction(mr[e])?t=>t[e]():(t,r)=>{throw new gt(`Response type '${e}' is not supported`,gt.ERR_NOT_SUPPORT,r)})})));const _r=async(e,t)=>{const r=ft.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(ft.isBlob(e))return e.size;if(ft.isSpecCompliantForm(e)){const t=new Request(Lt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ft.isArrayBufferView(e)||ft.isArrayBuffer(e)?e.byteLength:(ft.isURLSearchParams(e)&&(e+=""),ft.isString(e)?(await dr(e)).byteLength:void 0)})(t):r},wr={http:null,xhr:sr,fetch:lr&&(async e=>{let{url:t,method:r,data:n,signal:s,cancelToken:i,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:h}=nr(e);l=l?(l+"").toLowerCase():"text";let p,f=ir([s,i&&i.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&pr&&"get"!==r&&"head"!==r&&0!==(m=await _r(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(ft.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Xt(m,Gt(Qt(c)));n=cr(r.body,65536,e,t)}}ft.isString(d)||(d=d?"include":"omit");const s="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:s?d:void 0});let i=await fetch(p,h);const o=fr&&("stream"===l||"response"===l);if(fr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=ft.toFiniteNumber(i.headers.get("content-length")),[r,n]=a&&Xt(t,Gt(Qt(a),!0))||[];i=new Response(cr(i.body,65536,r,(()=>{n&&n(),g&&g()})),e)}l=l||"text";let _=await gr[ft.findKey(gr,l)||"text"](i,e);return!o&&g&&g(),await new Promise(((t,r)=>{Vt(t,r,{data:_,headers:Wt.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(_){if(g&&g(),_&&"TypeError"===_.name&&/Load failed|fetch/i.test(_.message))throw Object.assign(new gt("Network Error",gt.ERR_NETWORK,e,p),{cause:_.cause||_});throw gt.from(_,_&&_.code,e,p)}})};ft.forEach(wr,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(tn){}Object.defineProperty(e,"adapterName",{value:t})}}));const yr=e=>`- ${e}`,br=e=>ft.isFunction(e)||null===e||!1===e,Sr=e=>{e=ft.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!br(r)&&(n=wr[(t=String(r)).toLowerCase()],void 0===n))throw new gt(`Unknown adapter '${t}'`);if(n)break;s[t||"#"+i]=n}if(!n){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new gt("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(yr).join("\n"):" "+yr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function vr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Jt(null,e)}function Er(e){vr(e),e.headers=Wt.from(e.headers),e.data=$t.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Sr(e.adapter||Ft.adapter)(e).then((function(t){return vr(e),t.data=$t.call(e,e.transformResponse,t),t.headers=Wt.from(t.headers),t}),(function(t){return Kt(t)||(vr(e),t&&t.response&&(t.response.data=$t.call(e,e.transformResponse,t.response),t.response.headers=Wt.from(t.response.headers))),Promise.reject(t)}))}const kr="1.10.0",Rr={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Rr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const xr={};Rr.transitional=function(e,t,r){function n(e,t){return"[Axios v"+kr+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new gt(n(s," has been removed"+(t?" in "+t:"")),gt.ERR_DEPRECATED);return t&&!xr[s]&&(xr[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}},Rr.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Tr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new gt("options must be an object",gt.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],o=t[i];if(o){const t=e[i],r=void 0===t||o(t,i,e);if(!0!==r)throw new gt("option "+i+" must be "+r,gt.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new gt("Unknown option "+i,gt.ERR_BAD_OPTION)}},validators:Rr},Or=Tr.validators;let Ar=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ot,response:new Ot}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(tn){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=rr(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;void 0!==r&&Tr.assertOptions(r,{silentJSONParsing:Or.transitional(Or.boolean),forcedJSONParsing:Or.transitional(Or.boolean),clarifyTimeoutError:Or.transitional(Or.boolean)},!1),null!=n&&(ft.isFunction(n)?t.paramsSerializer={serialize:n}:Tr.assertOptions(n,{encode:Or.function,serialize:Or.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Tr.assertOptions(t,{baseUrl:Or.spelling("baseURL"),withXsrfToken:Or.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&ft.merge(s.common,s[t.method]);s&&ft.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=Wt.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,d=0;if(!a){const e=[Er.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=o.length;let h=t;for(d=0;d<u;){const e=o[d++],t=o[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{l=Er.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return Tt(er((e=rr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};ft.forEach(["delete","get","head","options"],(function(e){Ar.prototype[e]=function(t,r){return this.request(rr(r||{},{method:e,url:t,data:(r||{}).data}))}})),ft.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(rr(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Ar.prototype[e]=t(),Ar.prototype[e+"Form"]=t(!0)}));const Cr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Cr).forEach((([e,t])=>{Cr[t]=e}));const Nr=function e(t){const r=new Ar(t),n=Te(Ar.prototype.request,r);return ft.extend(n,Ar.prototype,r,{allOwnKeys:!0}),ft.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(rr(t,r))},n}(Ft);Nr.Axios=Ar,Nr.CanceledError=Jt,Nr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new Jt(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e((function(e){t=e})),cancel:t}}},Nr.isCancel=Kt,Nr.VERSION=kr,Nr.toFormData=vt,Nr.AxiosError=gt,Nr.Cancel=Nr.CanceledError,Nr.all=function(e){return Promise.all(e)},Nr.spread=function(e){return function(t){return e.apply(null,t)}},Nr.isAxiosError=function(e){return ft.isObject(e)&&!0===e.isAxiosError},Nr.mergeConfig=rr,Nr.AxiosHeaders=Wt,Nr.formToJSON=e=>Dt(ft.isHTMLForm(e)?new FormData(e):e),Nr.getAdapter=Sr,Nr.HttpStatusCode=Cr,Nr.default=Nr;const{Axios:Pr,AxiosError:Ir,CanceledError:Ur,isCancel:jr,CancelToken:Lr,VERSION:Dr,all:Fr,Cancel:Mr,isAxiosError:qr,spread:Br,toFormData:Hr,AxiosHeaders:zr,HttpStatusCode:Wr,formToJSON:$r,getAdapter:Kr,mergeConfig:Jr}=Nr;var Vr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Gr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Xr,Qr,Yr={exports:{}};
|
|
2
|
-
/*! Axios v1.10.0 Copyright (c) 2025 Matt Zabriskie and contributors */function Zr(){if(Qr)return Xr;function e(e,t){return function(){return e.apply(t,arguments)}}Qr=1;const{toString:t}=Object.prototype,{getPrototypeOf:r}=Object,{iterator:n,toStringTag:s}=Symbol,i=(e=>r=>{const n=t.call(r);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),o=e=>(e=e.toLowerCase(),t=>i(t)===e),a=e=>t=>typeof t===e,{isArray:c}=Array,l=a("undefined");const u=o("ArrayBuffer");const d=a("string"),h=a("function"),p=a("number"),f=e=>null!==e&&"object"==typeof e,g=e=>{if("object"!==i(e))return!1;const t=r(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||s in e||n in e)},m=o("Date"),_=o("File"),w=o("Blob"),y=o("FileList"),b=o("URLSearchParams"),[S,v,E,k]=["ReadableStream","Request","Response","Headers"].map(o);function R(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),c(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(n=0;n<i;n++)o=s[n],t.call(null,e[o],o,e)}}function x(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const T="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:Vr,O=e=>!l(e)&&e!==T;const A=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&r(Uint8Array)),C=o("HTMLFormElement"),N=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),P=o("RegExp"),I=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};R(r,((r,s)=>{let i;!1!==(i=t(r,s,e))&&(n[s]=i||r)})),Object.defineProperties(e,n)};const U=o("AsyncFunction"),j=((e,t)=>e?setImmediate:t?((e,t)=>(T.addEventListener("message",(({source:r,data:n})=>{r===T&&n===e&&t.length&&t.shift()()}),!1),r=>{t.push(r),T.postMessage(e,"*")}))(`axios@${Math.random()}`,[]):e=>setTimeout(e))("function"==typeof setImmediate,h(T.postMessage)),L="undefined"!=typeof queueMicrotask?queueMicrotask.bind(T):"undefined"!=typeof process&&process.nextTick||j;var D={isArray:c,isArrayBuffer:u,isBuffer:function(e){return null!==e&&!l(e)&&null!==e.constructor&&!l(e.constructor)&&h(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||h(e.append)&&("formdata"===(t=i(e))||"object"===t&&h(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&u(e.buffer),t},isString:d,isNumber:p,isBoolean:e=>!0===e||!1===e,isObject:f,isPlainObject:g,isReadableStream:S,isRequest:v,isResponse:E,isHeaders:k,isUndefined:l,isDate:m,isFile:_,isBlob:w,isRegExp:P,isFunction:h,isStream:e=>f(e)&&h(e.pipe),isURLSearchParams:b,isTypedArray:A,isFileList:y,forEach:R,merge:function e(){const{caseless:t}=O(this)&&this||{},r={},n=(n,s)=>{const i=t&&x(r,s)||s;g(r[i])&&g(n)?r[i]=e(r[i],n):g(n)?r[i]=e({},n):c(n)?r[i]=n.slice():r[i]=n};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&R(arguments[s],n);return r},extend:(t,r,n,{allOwnKeys:s}={})=>(R(r,((r,s)=>{n&&h(r)?t[s]=e(r,n):t[s]=r}),{allOwnKeys:s}),t),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,n,s)=>{let i,o,a;const c={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)a=i[o],s&&!s(a,e,t)||c[a]||(t[a]=e[a],c[a]=!0);e=!1!==n&&r(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:i,kindOfTest:o,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(c(e))return e;let t=e.length;if(!p(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[n]).call(e);let s;for(;(s=r.next())&&!s.done;){const r=s.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:C,hasOwnProperty:N,hasOwnProp:N,reduceDescriptors:I,freezeMethods:e=>{I(e,((t,r)=>{if(h(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];h(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return c(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:x,global:T,isContextDefined:O,isSpecCompliantForm:function(e){return!!(e&&h(e.append)&&"FormData"===e[s]&&e[n])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(f(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=c(e)?[]:{};return R(e,((e,t)=>{const i=r(e,n+1);!l(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)},isAsyncFn:U,isThenable:e=>e&&(f(e)||h(e))&&h(e.then)&&h(e.catch),setImmediate:j,asap:L,isIterable:e=>null!=e&&h(e[n])};function F(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}D.inherits(F,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:D.toJSONObject(this.config),code:this.code,status:this.status}}});const M=F.prototype,q={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{q[e]={value:e}})),Object.defineProperties(F,q),Object.defineProperty(M,"isAxiosError",{value:!0}),F.from=(e,t,r,n,s,i)=>{const o=Object.create(M);return D.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),F.call(o,e.message,t,r,n,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};function B(e){return D.isPlainObject(e)||D.isArray(e)}function H(e){return D.endsWith(e,"[]")?e.slice(0,-2):e}function z(e,t,r){return e?e.concat(t).map((function(e,t){return e=H(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const W=D.toFlatObject(D,{},null,(function(e){return/^is[A-Z]/.test(e)}));function $(e,t,r){if(!D.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=D.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!D.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,i=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&D.isSpecCompliantForm(t);if(!D.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(D.isDate(e))return e.toISOString();if(D.isBoolean(e))return e.toString();if(!a&&D.isBlob(e))throw new F("Blob is not supported. Use a Buffer instead.");return D.isArrayBuffer(e)||D.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,s){let a=e;if(e&&!s&&"object"==typeof e)if(D.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(D.isArray(e)&&function(e){return D.isArray(e)&&!e.some(B)}(e)||(D.isFileList(e)||D.endsWith(r,"[]"))&&(a=D.toArray(e)))return r=H(r),a.forEach((function(e,n){!D.isUndefined(e)&&null!==e&&t.append(!0===o?z([r],n,i):null===o?r:r+"[]",c(e))})),!1;return!!B(e)||(t.append(z(s,r,i),c(e)),!1)}const u=[],d=Object.assign(W,{defaultVisitor:l,convertValue:c,isVisitable:B});if(!D.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!D.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),D.forEach(r,(function(r,i){!0===(!(D.isUndefined(r)||null===r)&&s.call(t,r,D.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function K(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function J(e,t){this._pairs=[],e&&$(e,this,t)}const V=J.prototype;function G(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function X(e,t,r){if(!t)return e;const n=r&&r.encode||G;D.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let i;if(i=s?s(t,r):D.isURLSearchParams(t)?t.toString():new J(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}V.append=function(e,t){this._pairs.push([e,t])},V.toString=function(e){const t=e?function(t){return e.call(this,t,K)}:K;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Q=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){D.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},Y={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Z={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:J,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const ee="undefined"!=typeof window&&"undefined"!=typeof document,te="object"==typeof navigator&&navigator||void 0,re=ee&&(!te||["ReactNative","NativeScript","NS"].indexOf(te.product)<0),ne="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,se=ee&&window.location.href||"http://localhost";var ie={...Object.freeze({__proto__:null,hasBrowserEnv:ee,hasStandardBrowserWebWorkerEnv:ne,hasStandardBrowserEnv:re,navigator:te,origin:se}),...Z};function oe(e){function t(e,r,n,s){let i=e[s++];if("__proto__"===i)return!0;const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&D.isArray(n)?n.length:i,a)return D.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!o;n[i]&&D.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&D.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!o}if(D.isFormData(e)&&D.isFunction(e.entries)){const r={};return D.forEachEntry(e,((e,n)=>{t(function(e){return D.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const ae={transitional:Y,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=D.isObject(e);s&&D.isHTMLForm(e)&&(e=new FormData(e));if(D.isFormData(e))return n?JSON.stringify(oe(e)):e;if(D.isArrayBuffer(e)||D.isBuffer(e)||D.isStream(e)||D.isFile(e)||D.isBlob(e)||D.isReadableStream(e))return e;if(D.isArrayBufferView(e))return e.buffer;if(D.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return $(e,new ie.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return ie.isNode&&D.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=D.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return $(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(D.isString(e))try{return(t||JSON.parse)(e),D.trim(e)}catch(tn){if("SyntaxError"!==tn.name)throw tn}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||ae.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(D.isResponse(e)||D.isReadableStream(e))return e;if(e&&D.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(tn){if(r){if("SyntaxError"===tn.name)throw F.from(tn,F.ERR_BAD_RESPONSE,this,null,this.response);throw tn}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ie.classes.FormData,Blob:ie.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};D.forEach(["delete","get","head","post","put","patch"],(e=>{ae.headers[e]={}}));var ce=ae;const le=D.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const ue=Symbol("internals");function de(e){return e&&String(e).trim().toLowerCase()}function he(e){return!1===e||null==e?e:D.isArray(e)?e.map(he):String(e)}function pe(e,t,r,n,s){return D.isFunction(n)?n.call(this,t,r):(s&&(t=r),D.isString(t)?D.isString(n)?-1!==t.indexOf(n):D.isRegExp(n)?n.test(t):void 0:void 0)}class fe{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=de(t);if(!s)throw new Error("header name must be a non-empty string");const i=D.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=he(e))}const i=(e,t)=>D.forEach(e,((e,r)=>s(e,r,t)));if(D.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(D.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&le[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(D.isObject(e)&&D.isIterable(e)){let r,n,s={};for(const t of e){if(!D.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[n=t[0]]=(r=s[n])?D.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(s,t)}else null!=e&&s(t,e,r);return this}get(e,t){if(e=de(e)){const r=D.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(D.isFunction(t))return t.call(this,e,r);if(D.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=de(e)){const r=D.findKey(this,e);return!(!r||void 0===this[r]||t&&!pe(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=de(e)){const s=D.findKey(r,e);!s||t&&!pe(0,r[s],s,t)||(delete r[s],n=!0)}}return D.isArray(e)?e.forEach(s):s(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const s=t[r];e&&!pe(0,this[s],s,e,!0)||(delete this[s],n=!0)}return n}normalize(e){const t=this,r={};return D.forEach(this,((n,s)=>{const i=D.findKey(r,s);if(i)return t[i]=he(n),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();o!==s&&delete t[s],t[o]=he(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return D.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&D.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[ue]=this[ue]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=de(e);t[n]||(!function(e,t){const r=D.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return D.isArray(e)?e.forEach(n):n(e),this}}fe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),D.reduceDescriptors(fe.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),D.freezeMethods(fe);var ge=fe;function me(e,t){const r=this||ce,n=t||r,s=ge.from(n.headers);let i=n.data;return D.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function _e(e){return!(!e||!e.__CANCEL__)}function we(e,t,r){F.call(this,null==e?"canceled":e,F.ERR_CANCELED,t,r),this.name="CanceledError"}function ye(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new F("Request failed with status code "+r.status,[F.ERR_BAD_REQUEST,F.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}D.inherits(we,F,{__CANCEL__:!0});const be=(e,t,r=3)=>{let n=0;const s=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[o];s||(s=c),r[i]=a,n[i]=c;let u=o,d=0;for(;u!==i;)d+=r[u++],u%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),c-s<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}(50,250);return function(e,t){let r,n,s=0,i=1e3/t;const o=(t,i=Date.now())=>{s=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-s;a>=i?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),i-a)))},()=>r&&o(r)]}((r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,c=s(a);n=i;e({loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&i<=o?(o-i)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},Se=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},ve=e=>(...t)=>D.asap((()=>e(...t)));var Ee=ie.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ie.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ie.origin),ie.navigator&&/(msie|trident)/i.test(ie.navigator.userAgent)):()=>!0,ke=ie.hasStandardBrowserEnv?{write(e,t,r,n,s,i){const o=[e+"="+encodeURIComponent(t)];D.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),D.isString(n)&&o.push("path="+n),D.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Re(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const xe=e=>e instanceof ge?{...e}:e;function Te(e,t){t=t||{};const r={};function n(e,t,r,n){return D.isPlainObject(e)&&D.isPlainObject(t)?D.merge.call({caseless:n},e,t):D.isPlainObject(t)?D.merge({},t):D.isArray(t)?t.slice():t}function s(e,t,r,s){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e,0,s):n(e,t,0,s)}function i(e,t){if(!D.isUndefined(t))return n(void 0,t)}function o(e,t){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>s(xe(e),xe(t),0,!0)};return D.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||s,o=i(e[n],t[n],n);D.isUndefined(o)&&i!==a||(r[n]=o)})),r}var Oe=e=>{const t=Te({},e);let r,{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=ge.from(a),t.url=X(Re(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),D.isFormData(n))if(ie.hasStandardBrowserEnv||ie.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(ie.hasStandardBrowserEnv&&(s&&D.isFunction(s)&&(s=s(t)),s||!1!==s&&Ee(t.url))){const e=i&&o&&ke.read(o);e&&a.set(i,e)}return t};var Ae="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=Oe(e);let s=n.data;const i=ge.from(n.headers).normalize();let o,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const n=ge.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());ye((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:n,config:e,request:g}),g=null}g.open(n.method.toUpperCase(),n.url,!0),g.timeout=n.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new F("Request aborted",F.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new F("Network Error",F.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const s=n.transitional||Y;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new F(t,s.clarifyTimeoutError?F.ETIMEDOUT:F.ECONNABORTED,e,g)),g=null},void 0===s&&i.setContentType(null),"setRequestHeader"in g&&D.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),D.isUndefined(n.withCredentials)||(g.withCredentials=!!n.withCredentials),d&&"json"!==d&&(g.responseType=n.responseType),p&&([c,u]=be(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,l]=be(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(o=t=>{g&&(r(!t||t.type?new we(null,e,g):t),g.abort(),g=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const _=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);_&&-1===ie.protocols.indexOf(_)?r(new F("Unsupported protocol "+_+":",F.ERR_BAD_REQUEST,e)):g.send(s||null)}))};var Ce=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const s=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof F?t:new we(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,s(new F(`timeout ${t} of ms exceeded`,F.ETIMEDOUT))}),t);const o=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(s):e.removeEventListener("abort",s)})),e=null)};e.forEach((e=>e.addEventListener("abort",s)));const{signal:a}=n;return a.unsubscribe=()=>D.asap(o),a}};const Ne=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,s=0;for(;s<r;)n=s+t,yield e.slice(s,n),s=n},Pe=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Ie=(e,t,r,n)=>{const s=async function*(e,t){for await(const r of Pe(e))yield*Ne(r,t)}(e,t);let i,o=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await s.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw a(t),t}},cancel:e=>(a(e),s.return())},{highWaterMark:2})},Ue="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,je=Ue&&"function"==typeof ReadableStream,Le=Ue&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),De=(e,...t)=>{try{return!!e(...t)}catch(tn){return!1}},Fe=je&&De((()=>{let e=!1;const t=new Request(ie.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Me=je&&De((()=>D.isReadableStream(new Response("").body))),qe={stream:Me&&(e=>e.body)};Ue&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach((t=>{!qe[t]&&(qe[t]=D.isFunction(e[t])?e=>e[t]():(e,r)=>{throw new F(`Response type '${t}' is not supported`,F.ERR_NOT_SUPPORT,r)})}))})(new Response);const Be=async(e,t)=>{const r=D.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(D.isBlob(e))return e.size;if(D.isSpecCompliantForm(e)){const t=new Request(ie.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return D.isArrayBufferView(e)||D.isArrayBuffer(e)?e.byteLength:(D.isURLSearchParams(e)&&(e+=""),D.isString(e)?(await Le(e)).byteLength:void 0)})(t):r};const He={http:null,xhr:Ae,fetch:Ue&&(async e=>{let{url:t,method:r,data:n,signal:s,cancelToken:i,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:h}=Oe(e);l=l?(l+"").toLowerCase():"text";let p,f=Ce([s,i&&i.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&Fe&&"get"!==r&&"head"!==r&&0!==(m=await Be(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(D.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Se(m,be(ve(c)));n=Ie(r.body,65536,e,t)}}D.isString(d)||(d=d?"include":"omit");const s="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:s?d:void 0});let i=await fetch(p,h);const o=Me&&("stream"===l||"response"===l);if(Me&&(a||o&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=D.toFiniteNumber(i.headers.get("content-length")),[r,n]=a&&Se(t,be(ve(a),!0))||[];i=new Response(Ie(i.body,65536,r,(()=>{n&&n(),g&&g()})),e)}l=l||"text";let _=await qe[D.findKey(qe,l)||"text"](i,e);return!o&&g&&g(),await new Promise(((t,r)=>{ye(t,r,{data:_,headers:ge.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(_){if(g&&g(),_&&"TypeError"===_.name&&/Load failed|fetch/i.test(_.message))throw Object.assign(new F("Network Error",F.ERR_NETWORK,e,p),{cause:_.cause||_});throw F.from(_,_&&_.code,e,p)}})};D.forEach(He,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(tn){}Object.defineProperty(e,"adapterName",{value:t})}}));const ze=e=>`- ${e}`,We=e=>D.isFunction(e)||null===e||!1===e;var $e=e=>{e=D.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!We(r)&&(n=He[(t=String(r)).toLowerCase()],void 0===n))throw new F(`Unknown adapter '${t}'`);if(n)break;s[t||"#"+i]=n}if(!n){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new F("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(ze).join("\n"):" "+ze(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Ke(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new we(null,e)}function Je(e){Ke(e),e.headers=ge.from(e.headers),e.data=me.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return $e(e.adapter||ce.adapter)(e).then((function(t){return Ke(e),t.data=me.call(e,e.transformResponse,t),t.headers=ge.from(t.headers),t}),(function(t){return _e(t)||(Ke(e),t&&t.response&&(t.response.data=me.call(e,e.transformResponse,t.response),t.response.headers=ge.from(t.response.headers))),Promise.reject(t)}))}const Ve="1.10.0",Ge={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ge[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Xe={};Ge.transitional=function(e,t,r){function n(e,t){return"[Axios v"+Ve+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new F(n(s," has been removed"+(t?" in "+t:"")),F.ERR_DEPRECATED);return t&&!Xe[s]&&(Xe[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}},Ge.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Qe={assertOptions:function(e,t,r){if("object"!=typeof e)throw new F("options must be an object",F.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],o=t[i];if(o){const t=e[i],r=void 0===t||o(t,i,e);if(!0!==r)throw new F("option "+i+" must be "+r,F.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new F("Unknown option "+i,F.ERR_BAD_OPTION)}},validators:Ge};const Ye=Qe.validators;class Ze{constructor(e){this.defaults=e||{},this.interceptors={request:new Q,response:new Q}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(tn){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Te(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;void 0!==r&&Qe.assertOptions(r,{silentJSONParsing:Ye.transitional(Ye.boolean),forcedJSONParsing:Ye.transitional(Ye.boolean),clarifyTimeoutError:Ye.transitional(Ye.boolean)},!1),null!=n&&(D.isFunction(n)?t.paramsSerializer={serialize:n}:Qe.assertOptions(n,{encode:Ye.function,serialize:Ye.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Qe.assertOptions(t,{baseUrl:Ye.spelling("baseURL"),withXsrfToken:Ye.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&D.merge(s.common,s[t.method]);s&&D.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=ge.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,d=0;if(!a){const e=[Je.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=o.length;let h=t;for(d=0;d<u;){const e=o[d++],t=o[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{l=Je.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return X(Re((e=Te(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}D.forEach(["delete","get","head","options"],(function(e){Ze.prototype[e]=function(t,r){return this.request(Te(r||{},{method:e,url:t,data:(r||{}).data}))}})),D.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(Te(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Ze.prototype[e]=t(),Ze.prototype[e+"Form"]=t(!0)}));var et=Ze;class tt{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new we(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new tt((function(t){e=t})),cancel:e}}}var rt=tt;const nt={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(nt).forEach((([e,t])=>{nt[t]=e}));var st=nt;const it=function t(r){const n=new et(r),s=e(et.prototype.request,n);return D.extend(s,et.prototype,n,{allOwnKeys:!0}),D.extend(s,n,null,{allOwnKeys:!0}),s.create=function(e){return t(Te(r,e))},s}(ce);return it.Axios=et,it.CanceledError=we,it.CancelToken=rt,it.isCancel=_e,it.VERSION=Ve,it.toFormData=$,it.AxiosError=F,it.Cancel=it.CanceledError,it.all=function(e){return Promise.all(e)},it.spread=function(e){return function(t){return e.apply(null,t)}},it.isAxiosError=function(e){return D.isObject(e)&&!0===e.isAxiosError},it.mergeConfig=Te,it.AxiosHeaders=ge,it.formToJSON=e=>oe(D.isHTMLForm(e)?new FormData(e):e),it.getAdapter=$e,it.HttpStatusCode=st,it.default=it,Xr=it}var en,tn;const rn=Gr((en||(en=1,Yr.exports=(tn=Zr(),function(){var e={593:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.resendFailedRequest=t.getRetryInstance=t.unsetCache=t.createRequestQueueInterceptor=t.createRefreshCall=t.shouldInterceptError=t.mergeOptions=t.defaultOptions=void 0;const n=r(300);t.defaultOptions={statusCodes:[401],pauseInstanceWhileRefreshing:!1},t.mergeOptions=function(e,t){return Object.assign(Object.assign(Object.assign({},e),{pauseInstanceWhileRefreshing:t.skipWhileRefreshing}),t)},t.shouldInterceptError=function(e,t,r,n){var s,i;return!(!e||(null===(s=e.config)||void 0===s?void 0:s.skipAuthRefresh)||!(t.interceptNetworkError&&!e.response&&0===e.request.status||e.response&&((null==t?void 0:t.shouldRefresh)?t.shouldRefresh(e):null===(i=t.statusCodes)||void 0===i?void 0:i.includes(parseInt(e.response.status))))||(e.response||(e.response={config:e.config}),t.pauseInstanceWhileRefreshing&&n.skipInstances.includes(r)))},t.createRefreshCall=function(e,t,r){return r.refreshCall||(r.refreshCall=t(e),"function"==typeof r.refreshCall.then)?r.refreshCall:(console.warn("axios-auth-refresh requires `refreshTokenCall` to return a promise."),Promise.reject())},t.createRequestQueueInterceptor=function(e,t,r){return void 0===t.requestQueueInterceptorId&&(t.requestQueueInterceptorId=e.interceptors.request.use((e=>t.refreshCall.catch((()=>{throw new n.default.Cancel("Request call failed")})).then((()=>r.onRetry?r.onRetry(e):e))))),t.requestQueueInterceptorId},t.unsetCache=function(e,t){e.interceptors.request.eject(t.requestQueueInterceptorId),t.requestQueueInterceptorId=void 0,t.refreshCall=void 0,t.skipInstances=t.skipInstances.filter((t=>t!==e))},t.getRetryInstance=function(e,t){return t.retryInstance||e},t.resendFailedRequest=function(e,t){return e.config.skipAuthRefresh=!0,t(e.response.config)}},300:function(e){e.exports=tn}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}var n={};return function(){var e=n;Object.defineProperty(e,"__esModule",{value:!0});const t=r(593);e.default=function(e,r,n={}){if("function"!=typeof r)throw new Error("axios-auth-refresh requires `refreshAuthCall` to be a function that returns a promise.");const s={skipInstances:[],refreshCall:void 0,requestQueueInterceptorId:void 0};return e.interceptors.response.use((e=>e),(i=>{if(n=(0,t.mergeOptions)(t.defaultOptions,n),!(0,t.shouldInterceptError)(i,n,e,s))return Promise.reject(i);n.pauseInstanceWhileRefreshing&&s.skipInstances.push(e);const o=(0,t.createRefreshCall)(i,r,s);return(0,t.createRequestQueueInterceptor)(e,s,n),o.catch((e=>Promise.reject(e))).then((()=>(0,t.resendFailedRequest)(i,(0,t.getRetryInstance)(e,n)))).finally((()=>(0,t.unsetCache)(e,s)))}))}}(),n}())),Yr.exports));var nn=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},sn=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)}},on={baseUrl:"undefined"!=typeof process&&(null==(n=process.env)?void 0:n.ECHO_BASE_URL)||"https://echo.merit.systems"};var an=class e extends Error{constructor(t,r,n){super(r),i(this,"code"),i(this,"details"),i(this,"statusCode"),i(this,"endpoint"),i(this,"originalError"),this.name="EchoError",this.code=t,void 0!==(null==n?void 0:n.details)&&(this.details=n.details),void 0!==(null==n?void 0:n.statusCode)&&(this.statusCode=n.statusCode),void 0!==(null==n?void 0:n.endpoint)&&(this.endpoint=n.endpoint),void 0!==(null==n?void 0:n.originalError)&&(this.originalError=n.originalError),Error.captureStackTrace&&Error.captureStackTrace(this,e)}},cn=class extends an{constructor(e,t,r,n,s){const i={};void 0!==n&&(i.details=n),void 0!==r&&(i.statusCode=r),void 0!==s&&(i.endpoint=s),super(e,t,i),this.name="EchoApiError"}},ln=class extends an{constructor(e,t,r){const n={originalError:t};void 0!==r&&(n.endpoint=r),super("NETWORK_ERROR",e,n),this.name="EchoNetworkError"}},un=class extends an{constructor(e,t,r){const n={};void 0!==r&&(n.endpoint=r),super("TIMEOUT_ERROR",e,n),i(this,"timeout"),this.name="EchoTimeoutError",this.timeout=t}},dn="UNAUTHORIZED",hn="TOKEN_EXPIRED",pn="INVALID_TOKEN",fn="BAD_REQUEST",gn="NOT_FOUND",mn="RATE_LIMITED",_n="INSUFFICIENT_BALANCE",wn="VALIDATION_ERROR",yn="NETWORK_ERROR",bn="TIMEOUT_ERROR",Sn="SERVER_ERROR",vn="SERVICE_UNAVAILABLE";function En(e,t,r){if(e&&"object"==typeof e&&"isAxiosError"in e){const n=e;if("ECONNABORTED"===n.code)return new un("Request timeout"+(t?` while ${t}`:""),3e4,r);if(!n.response)return new ln("Network error"+(t?` while ${t}`:""),n,r);const s=n.response.status,i=n.response.data;let o,a;const c=(null==i?void 0:i.error)||(null==i?void 0:i.message);switch(s){case 401:o=dn,a=c||"Authentication required. Please sign in again.";break;case 403:o=pn,a=c||"Access denied. Your session may have expired.";break;case 404:o=gn,a=c||"Resource not found";break;case 429:o=mn,a=c||"Too many requests. Please try again later.";break;case 400:o=fn,a=c||"Invalid request";break;case 402:o=_n,a=c||"Insufficient balance. Please add credits to continue.";break;case 422:o=wn,a=c||"Validation failed";break;case 503:o=vn,a=c||"Service temporarily unavailable. Please try again.";break;default:o=Sn,a=c||"An unexpected error occurred"}return new cn(o,t?`Failed to ${t}: ${a}`:a,s,(null==i?void 0:i.details)||(null==i?void 0:i.error_description),r)}return e instanceof Error?new ln(e.message||"Unknown error"+(t?` while ${t}`:""),e,r):"string"==typeof e?new cn(Sn,e,void 0,void 0,r):new cn(Sn,"Unknown error"+(t?` while ${t}`:""),void 0,String(e),r)}function kn(e){switch(e.code){case dn:case hn:case pn:return"Please sign in to continue";case _n:return"Insufficient balance. Please add credits to your account.";case mn:return"Too many requests. Please wait a moment and try again.";case yn:return"Connection failed. Please check your internet connection.";case bn:return"Request timed out. Please try again.";case vn:return"Service is temporarily unavailable. Please try again later.";case gn:return e.message||"The requested resource was not found.";case wn:return e.message||"Please check your input and try again.";default:return e.message||"An unexpected error occurred. Please try again."}}var Rn=class{constructor(e){this.http=e}async handleRequest(e,t,r){try{return(await e()).data}catch(n){throw En(n,t,r)}}handleError(e,t,r){throw En(e,t,r)}},xn=class extends Rn{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}`}},Tn=class extends Rn{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")}},On=class extends Rn{constructor(e){super(e)}async getSupportedModels(){return this.handleRequest((()=>this.http.get("/api/v1/supported-models")),"fetching supported models","/api/v1/supported-models")}async listSupportedModels(){try{return(await this.getSupportedModels()).models}catch(e){throw this.handleError(e,"listing supported models")}}async getSupportedModelsByProvider(){try{return(await this.getSupportedModels()).models_by_provider}catch(e){throw this.handleError(e,"getting models by provider")}}},An=class extends Rn{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,r){const n={amount:e,description:t||"Echo Credits"};r&&(n.successUrl=r);try{return(await this.createPaymentLink(n)).paymentLink.url}catch(s){throw this.handleError(s,"getting payment URL")}}},Cn=class extends Rn{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 r={echoAppId:e,code:t};return this.handleRequest((()=>this.http.post("/api/v1/user/referral",r)),"registering referral code","/api/v1/user/referral")}},Nn=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,{...on,...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 nn(e)}this.http=Nr.create({baseURL:this.config.baseUrl,timeout:3e4}),this.http.interceptors.request.use((async e=>{const t=await this.tokenProvider.getAccessToken();return t&&(e.headers.Authorization=`Bearer ${t}`),e}));rn(this.http,(async e=>{try{await this.tokenProvider.refreshToken();const t=await this.tokenProvider.getAccessToken();return t&&(e.response.config.headers.Authorization=`Bearer ${t}`),Promise.resolve()}catch(t){return this.tokenProvider.onRefreshError&&this.tokenProvider.onRefreshError(t),Promise.reject(t)}}),{statusCodes:[401],pauseInstanceWhileRefreshing:!0}),this.balance=new Tn(this.http),this.payments=new An(this.http),this.apps=new xn(this.http,this.config.baseUrl),this.users=new Cn(this.http),this.models=new On(this.http)}};function Pn({apiUrl:e}){var t,n;const s=xe(),[i,o]=r.useState(null);return r.useEffect((()=>{if(!s.isAuthenticated||!s.user)return void o(null);const t=new sn({getTokenFn:()=>{var e;return Promise.resolve((null==(e=s.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{await s.signinSilent()},onRefreshErrorFn:e=>{console.error("Token refresh failed:",e),s.signoutSilent()}}),r=new Nn({baseUrl:e,tokenProvider:t});return o(r),()=>{o(null)}}),[e,s.isAuthenticated,null==(n=null==(t=s.user)?void 0:t.profile)?void 0:n.sub,s.signinSilent,s.signoutSilent]),i}const In=r.createContext(null),Un=r.createContext(null);function jn({config:e,children:n}){var s,i,o;const a=xe(),c=a.user,l=c?function(e){return{id:e.profile.sub||"",email:e.profile.email||"",name:e.profile.name||e.profile.preferred_username||"",picture:e.profile.picture||""}}(c):null,u=e.apiUrl||"https://echo.merit.systems",d=(null==(s=a.user)?void 0:s.access_token)||null,h=Pn({apiUrl:u}),{balance:p,freeTierBalance:f,refreshBalance:g,error:m,isLoading:_}=function(e,t){const[n,s]=r.useState(null),[i,o]=r.useState(null),[a,c]=r.useState(null),[l,u]=r.useState(!1),d=r.useCallback((async()=>{if(!e)throw new Error("Not authenticated");u(!0);try{const[r,n]=await Promise.all([e.balance.getBalance(),e.balance.getFreeBalance(t)]);s(r),o(n),c(null)}catch(r){const e=En(r,"refreshing balance"),t=kn(e);throw c(t),e}finally{u(!1)}}),[e,t]);return r.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(s(null),o(null),c(null))}),[e,t,d]),{balance:n,freeTierBalance:i,error:a,isLoading:l,refreshBalance:d}}(h,e.appId),{createPaymentLink:w,error:y,isLoading:b}=function(e){const[t,n]=r.useState(null),[s,i]=r.useState(!1);return{createPaymentLink:r.useCallback((async(t,r,s)=>{if(!e)throw new Error("Not authenticated");i(!0);try{const i=await e.payments.createPaymentLink({amount:t,description:r||"Echo Credits",successUrl:s||window.location.origin});return n(null),i.paymentLink.url}catch(o){const e=En(o,"creating payment link"),t=kn(e);throw n(t),e}finally{i(!1)}}),[e]),error:t,isLoading:s}}(h),S=r.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),v=r.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(i=a.user)?void 0:i.access_token]),E=(null==(o=a.error)?void 0:o.message)||m||y||null,k=a.isLoading&&!a.isAuthenticated,R=a.isLoading&&a.isAuthenticated,x=k||_||b,T=r.useMemo((()=>({user:l||null,rawUser:c,balance:p,freeTierBalance:f,isAuthenticated:a.isAuthenticated,isLoading:x,error:E,token:d,echoClient:h,signIn:a.signinRedirect,signOut:S,refreshBalance:g,createPaymentLink:w,getToken:v,clearAuth:S})),[l,c,p,f,a.isAuthenticated,x,E,d,h,a.signinRedirect,S,g,w,v]),O=r.useMemo((()=>({isRefreshing:R})),[R]);return t.jsx(In.Provider,{value:T,children:t.jsx(Un.Provider,{value:O,children:n})})}function Ln(){const e=r.useContext(In);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}
|
|
3
|
-
/*! @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:Dn,setPrototypeOf:Fn,isFrozen:Mn,getPrototypeOf:qn,getOwnPropertyDescriptor:Bn}=Object;let{freeze:Hn,seal:zn,create:Wn}=Object,{apply:$n,construct:Kn}="undefined"!=typeof Reflect&&Reflect;Hn||(Hn=function(e){return e}),zn||(zn=function(e){return e}),$n||($n=function(e,t,r){return e.apply(t,r)}),Kn||(Kn=function(e,t){return new e(...t)});const Jn=cs(Array.prototype.forEach),Vn=cs(Array.prototype.lastIndexOf),Gn=cs(Array.prototype.pop),Xn=cs(Array.prototype.push),Qn=cs(Array.prototype.splice),Yn=cs(String.prototype.toLowerCase),Zn=cs(String.prototype.toString),es=cs(String.prototype.match),ts=cs(String.prototype.replace),rs=cs(String.prototype.indexOf),ns=cs(String.prototype.trim),ss=cs(Object.prototype.hasOwnProperty),is=cs(RegExp.prototype.test),os=(as=TypeError,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return Kn(as,t)});var as;function cs(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return $n(e,t,n)}}function ls(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Yn;Fn&&Fn(e,null);let n=t.length;for(;n--;){let s=t[n];if("string"==typeof s){const e=r(s);e!==s&&(Mn(t)||(t[n]=e),s=e)}e[s]=!0}return e}function us(e){for(let t=0;t<e.length;t++){ss(e,t)||(e[t]=null)}return e}function ds(e){const t=Wn(null);for(const[r,n]of Dn(e)){ss(e,r)&&(Array.isArray(n)?t[r]=us(n):n&&"object"==typeof n&&n.constructor===Object?t[r]=ds(n):t[r]=n)}return t}function hs(e,t){for(;null!==e;){const r=Bn(e,t);if(r){if(r.get)return cs(r.get);if("function"==typeof r.value)return cs(r.value)}e=qn(e)}return function(){return null}}const ps=Hn(["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"]),fs=Hn(["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"]),gs=Hn(["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"]),ms=Hn(["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"]),_s=Hn(["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"]),ws=Hn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ys=Hn(["#text"]),bs=Hn(["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"]),Ss=Hn(["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"]),vs=Hn(["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"]),Es=Hn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ks=zn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Rs=zn(/<%[\w\W]*|[\w\W]*%>/gm),xs=zn(/\$\{[\w\W]*/gm),Ts=zn(/^data-[\-\w.\u00B7-\uFFFF]+$/),Os=zn(/^aria-[\-\w]+$/),As=zn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Cs=zn(/^(?:\w+script|data):/i),Ns=zn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ps=zn(/^html$/i),Is=zn(/^[a-z][.\w]*(-[.\w]+)+$/i);var Us=Object.freeze({__proto__:null,ARIA_ATTR:Os,ATTR_WHITESPACE:Ns,CUSTOM_ELEMENT:Is,DATA_ATTR:Ts,DOCTYPE_NAME:Ps,ERB_EXPR:Rs,IS_ALLOWED_URI:As,IS_SCRIPT_OR_DATA:Cs,MUSTACHE_EXPR:ks,TMPLIT_EXPR:xs});const js=1,Ls=3,Ds=7,Fs=8,Ms=9;var qs=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const r=t=>e(t);if(r.version="3.2.6",r.removed=[],!t||!t.document||t.document.nodeType!==Ms||!t.Element)return r.isSupported=!1,r;let{document:n}=t;const s=n,i=s.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:c,Element:l,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:f}=t,g=l.prototype,m=hs(g,"cloneNode"),_=hs(g,"remove"),w=hs(g,"nextSibling"),y=hs(g,"childNodes"),b=hs(g,"parentNode");if("function"==typeof a){const e=n.createElement("template");e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let S,v="";const{implementation:E,createNodeIterator:k,createDocumentFragment:R,getElementsByTagName:x}=n,{importNode:T}=s;let O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};r.isSupported="function"==typeof Dn&&"function"==typeof b&&E&&void 0!==E.createHTMLDocument;const{MUSTACHE_EXPR:A,ERB_EXPR:C,TMPLIT_EXPR:N,DATA_ATTR:P,ARIA_ATTR:I,IS_SCRIPT_OR_DATA:U,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:L}=Us;let{IS_ALLOWED_URI:D}=Us,F=null;const M=ls({},[...ps,...fs,...gs,..._s,...ys]);let q=null;const B=ls({},[...bs,...Ss,...vs,...Es]);let H=Object.seal(Wn(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}})),z=null,W=null,$=!0,K=!0,J=!1,V=!0,G=!1,X=!0,Q=!1,Y=!1,Z=!1,ee=!1,te=!1,re=!1,ne=!0,se=!1,ie=!0,oe=!1,ae={},ce=null;const le=ls({},["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 ue=null;const de=ls({},["audio","video","img","source","image","track"]);let he=null;const pe=ls({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fe="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",me="http://www.w3.org/1999/xhtml";let _e=me,we=!1,ye=null;const be=ls({},[fe,ge,me],Zn);let Se=ls({},["mi","mo","mn","ms","mtext"]),ve=ls({},["annotation-xml"]);const Ee=ls({},["title","style","font","a","script"]);let ke=null;const Re=["application/xhtml+xml","text/html"];let xe=null,Te=null;const Oe=n.createElement("form"),Ae=function(e){return e instanceof RegExp||e instanceof Function},Ce=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Te||Te!==e){if(e&&"object"==typeof e||(e={}),e=ds(e),ke=-1===Re.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,xe="application/xhtml+xml"===ke?Zn:Yn,F=ss(e,"ALLOWED_TAGS")?ls({},e.ALLOWED_TAGS,xe):M,q=ss(e,"ALLOWED_ATTR")?ls({},e.ALLOWED_ATTR,xe):B,ye=ss(e,"ALLOWED_NAMESPACES")?ls({},e.ALLOWED_NAMESPACES,Zn):be,he=ss(e,"ADD_URI_SAFE_ATTR")?ls(ds(pe),e.ADD_URI_SAFE_ATTR,xe):pe,ue=ss(e,"ADD_DATA_URI_TAGS")?ls(ds(de),e.ADD_DATA_URI_TAGS,xe):de,ce=ss(e,"FORBID_CONTENTS")?ls({},e.FORBID_CONTENTS,xe):le,z=ss(e,"FORBID_TAGS")?ls({},e.FORBID_TAGS,xe):ds({}),W=ss(e,"FORBID_ATTR")?ls({},e.FORBID_ATTR,xe):ds({}),ae=!!ss(e,"USE_PROFILES")&&e.USE_PROFILES,$=!1!==e.ALLOW_ARIA_ATTR,K=!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,X=!1!==e.SAFE_FOR_XML,Q=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,re=e.RETURN_TRUSTED_TYPE||!1,Z=e.FORCE_BODY||!1,ne=!1!==e.SANITIZE_DOM,se=e.SANITIZE_NAMED_PROPS||!1,ie=!1!==e.KEEP_CONTENT,oe=e.IN_PLACE||!1,D=e.ALLOWED_URI_REGEXP||As,_e=e.NAMESPACE||me,Se=e.MATHML_TEXT_INTEGRATION_POINTS||Se,ve=e.HTML_INTEGRATION_POINTS||ve,H=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Ae(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(H.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Ae(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(H.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(H.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(K=!1),te&&(ee=!0),ae&&(F=ls({},ys),q=[],!0===ae.html&&(ls(F,ps),ls(q,bs)),!0===ae.svg&&(ls(F,fs),ls(q,Ss),ls(q,Es)),!0===ae.svgFilters&&(ls(F,gs),ls(q,Ss),ls(q,Es)),!0===ae.mathMl&&(ls(F,_s),ls(q,vs),ls(q,Es))),e.ADD_TAGS&&(F===M&&(F=ds(F)),ls(F,e.ADD_TAGS,xe)),e.ADD_ATTR&&(q===B&&(q=ds(q)),ls(q,e.ADD_ATTR,xe)),e.ADD_URI_SAFE_ATTR&&ls(he,e.ADD_URI_SAFE_ATTR,xe),e.FORBID_CONTENTS&&(ce===le&&(ce=ds(ce)),ls(ce,e.FORBID_CONTENTS,xe)),ie&&(F["#text"]=!0),Q&&ls(F,["html","head","body"]),F.table&&(ls(F,["tbody"]),delete z.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw os('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw os('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=e.TRUSTED_TYPES_POLICY,v=S.createHTML("")}else void 0===S&&(S=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let r=null;const n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML:e=>e,createScriptURL:e=>e})}catch(i){return console.warn("TrustedTypes policy "+s+" could not be created."),null}}(f,i)),null!==S&&"string"==typeof v&&(v=S.createHTML(""));Hn&&Hn(e),Te=e}},Ne=ls({},[...fs,...gs,...ms]),Pe=ls({},[..._s,...ws]),Ie=function(e){Xn(r.removed,{element:e});try{b(e).removeChild(e)}catch(t){_(e)}},Ue=function(e,t){try{Xn(r.removed,{attribute:t.getAttributeNode(e),from:t})}catch(n){Xn(r.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Ie(t)}catch(n){}else try{t.setAttribute(e,"")}catch(n){}},je=function(e){let t=null,r=null;if(Z)e="<remove></remove>"+e;else{const t=es(e,/^[\r\n\t ]+/);r=t&&t[0]}"application/xhtml+xml"===ke&&_e===me&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const s=S?S.createHTML(e):e;if(_e===me)try{t=(new p).parseFromString(s,ke)}catch(o){}if(!t||!t.documentElement){t=E.createDocument(_e,"template",null);try{t.documentElement.innerHTML=we?v:s}catch(o){}}const i=t.body||t.documentElement;return e&&r&&i.insertBefore(n.createTextNode(r),i.childNodes[0]||null),_e===me?x.call(t,Q?"html":"body")[0]:Q?t.documentElement:i},Le=function(e){return k.call(e.ownerDocument||e,e,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},De=function(e){return e instanceof h&&("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)},Fe=function(e){return"function"==typeof c&&e instanceof c};function Me(e,t,n){Jn(e,(e=>{e.call(r,t,n,Te)}))}const qe=function(e){let t=null;if(Me(O.beforeSanitizeElements,e,null),De(e))return Ie(e),!0;const n=xe(e.nodeName);if(Me(O.uponSanitizeElement,e,{tagName:n,allowedTags:F}),X&&e.hasChildNodes()&&!Fe(e.firstElementChild)&&is(/<[/\w!]/g,e.innerHTML)&&is(/<[/\w!]/g,e.textContent))return Ie(e),!0;if(e.nodeType===Ds)return Ie(e),!0;if(X&&e.nodeType===Fs&&is(/<[/\w]/g,e.data))return Ie(e),!0;if(!F[n]||z[n]){if(!z[n]&&He(n)){if(H.tagNameCheck instanceof RegExp&&is(H.tagNameCheck,n))return!1;if(H.tagNameCheck instanceof Function&&H.tagNameCheck(n))return!1}if(ie&&!ce[n]){const t=b(e)||e.parentNode,r=y(e)||e.childNodes;if(r&&t){for(let n=r.length-1;n>=0;--n){const s=m(r[n],!0);s.__removalCount=(e.__removalCount||0)+1,t.insertBefore(s,w(e))}}}return Ie(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:_e,tagName:"template"});const r=Yn(e.tagName),n=Yn(t.tagName);return!!ye[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===me?"svg"===r:t.namespaceURI===fe?"svg"===r&&("annotation-xml"===n||Se[n]):Boolean(Ne[r]):e.namespaceURI===fe?t.namespaceURI===me?"math"===r:t.namespaceURI===ge?"math"===r&&ve[n]:Boolean(Pe[r]):e.namespaceURI===me?!(t.namespaceURI===ge&&!ve[n])&&!(t.namespaceURI===fe&&!Se[n])&&!Pe[r]&&(Ee[r]||!Ne[r]):!("application/xhtml+xml"!==ke||!ye[e.namespaceURI]))}(e)?(Ie(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!is(/<\/no(script|embed|frames)/i,e.innerHTML)?(G&&e.nodeType===Ls&&(t=e.textContent,Jn([A,C,N],(e=>{t=ts(t,e," ")})),e.textContent!==t&&(Xn(r.removed,{element:e.cloneNode()}),e.textContent=t)),Me(O.afterSanitizeElements,e,null),!1):(Ie(e),!0)},Be=function(e,t,r){if(ne&&("id"===t||"name"===t)&&(r in n||r in Oe))return!1;if(K&&!W[t]&&is(P,t));else if($&&is(I,t));else if(!q[t]||W[t]){if(!(He(e)&&(H.tagNameCheck instanceof RegExp&&is(H.tagNameCheck,e)||H.tagNameCheck instanceof Function&&H.tagNameCheck(e))&&(H.attributeNameCheck instanceof RegExp&&is(H.attributeNameCheck,t)||H.attributeNameCheck instanceof Function&&H.attributeNameCheck(t))||"is"===t&&H.allowCustomizedBuiltInElements&&(H.tagNameCheck instanceof RegExp&&is(H.tagNameCheck,r)||H.tagNameCheck instanceof Function&&H.tagNameCheck(r))))return!1}else if(he[t]);else if(is(D,ts(r,j,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==rs(r,"data:")||!ue[e]){if(J&&!is(U,ts(r,j,"")));else if(r)return!1}else;return!0},He=function(e){return"annotation-xml"!==e&&es(e,L)},ze=function(e){Me(O.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||De(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:q,forceKeepAttr:void 0};let s=t.length;for(;s--;){const o=t[s],{name:a,namespaceURI:c,value:l}=o,u=xe(a),d=l;let h="value"===a?d:ns(d);if(n.attrName=u,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,Me(O.uponSanitizeAttribute,e,n),h=n.attrValue,!se||"id"!==u&&"name"!==u||(Ue(a,e),h="user-content-"+h),X&&is(/((--!?|])>)|<\/(style|title)/i,h)){Ue(a,e);continue}if(n.forceKeepAttr)continue;if(!n.keepAttr){Ue(a,e);continue}if(!V&&is(/\/>/i,h)){Ue(a,e);continue}G&&Jn([A,C,N],(e=>{h=ts(h,e," ")}));const p=xe(e.nodeName);if(Be(p,u,h)){if(S&&"object"==typeof f&&"function"==typeof f.getAttributeType)if(c);else switch(f.getAttributeType(p,u)){case"TrustedHTML":h=S.createHTML(h);break;case"TrustedScriptURL":h=S.createScriptURL(h)}if(h!==d)try{c?e.setAttributeNS(c,a,h):e.setAttribute(a,h),De(e)?Ie(e):Gn(r.removed)}catch(i){Ue(a,e)}}else Ue(a,e)}Me(O.afterSanitizeAttributes,e,null)},We=function e(t){let r=null;const n=Le(t);for(Me(O.beforeSanitizeShadowDOM,t,null);r=n.nextNode();)Me(O.uponSanitizeShadowNode,r,null),qe(r),ze(r),r.content instanceof o&&e(r.content);Me(O.afterSanitizeShadowDOM,t,null)};return r.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,i=null,a=null,l=null;if(we=!e,we&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Fe(e)){if("function"!=typeof e.toString)throw os("toString is not a function");if("string"!=typeof(e=e.toString()))throw os("dirty is not a string, aborting")}if(!r.isSupported)return e;if(Y||Ce(t),r.removed=[],"string"==typeof e&&(oe=!1),oe){if(e.nodeName){const t=xe(e.nodeName);if(!F[t]||z[t])throw os("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)n=je("\x3c!----\x3e"),i=n.ownerDocument.importNode(e,!0),i.nodeType===js&&"BODY"===i.nodeName||"HTML"===i.nodeName?n=i:n.appendChild(i);else{if(!ee&&!G&&!Q&&-1===e.indexOf("<"))return S&&re?S.createHTML(e):e;if(n=je(e),!n)return ee?null:re?v:""}n&&Z&&Ie(n.firstChild);const u=Le(oe?e:n);for(;a=u.nextNode();)qe(a),ze(a),a.content instanceof o&&We(a.content);if(oe)return e;if(ee){if(te)for(l=R.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(q.shadowroot||q.shadowrootmode)&&(l=T.call(s,l,!0)),l}let d=Q?n.outerHTML:n.innerHTML;return Q&&F["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&is(Ps,n.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+d),G&&Jn([A,C,N],(e=>{d=ts(d,e," ")})),S&&re?S.createHTML(d):d},r.setConfig=function(){Ce(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Y=!0},r.clearConfig=function(){Te=null,Y=!1},r.isValidAttribute=function(e,t,r){Te||Ce({});const n=xe(e),s=xe(t);return Be(n,s,r)},r.addHook=function(e,t){"function"==typeof t&&Xn(O[e],t)},r.removeHook=function(e,t){if(void 0!==t){const r=Vn(O[e],t);return-1===r?void 0:Qn(O[e],r,1)[0]}return Gn(O[e])},r.removeHooks=function(e){O[e]=[]},r.removeAllHooks=function(){O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},r}();const Bs=(()=>{if("undefined"!=typeof window)return qs;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return qs(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Hs(e){if(!e)return"";const t=String(e);try{let e=Bs.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 zs(e,t={}){const{onComplete:r,onCancel:n,onError:s}=t,i=function(e){if(!e)return"";const t=Hs(e);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol?t:""}catch{return""}}(e);if(!i){const e=new Error("Invalid payment URL provided");throw null==s||s(e),e}try{const e=window.open(i,"echo-payment","width=600,height=700,scrollbars=yes,resizable=yes");if(e&&!e.closed)return new Promise((t=>{const s=()=>{try{if(e.closed)return null==r||r(),void t();setTimeout(s,1e3)}catch{null==r||r(),t()}};s(),setTimeout((()=>{e.close(),null==n||n(),t()}),6e5)}));return confirm("Payment will open in a new tab. Click OK to continue, or Cancel to abort.")?(sessionStorage.setItem("echo_payment_flow","true"),window.location.href=i,new Promise((e=>{const t=()=>{"completed"===sessionStorage.getItem("echo_payment_flow")&&(sessionStorage.removeItem("echo_payment_flow"),null==r||r(),window.removeEventListener("focus",t),e())};window.addEventListener("focus",t),setTimeout((()=>{window.removeEventListener("focus",t),sessionStorage.removeItem("echo_payment_flow"),null==n||n(),e()}),18e5)}))):(null==n||n(),Promise.resolve())}catch(o){const e=o instanceof Error?o:new Error("Payment flow failed");throw null==s||s(e),e}}const Ws=({className:e="",width:r=16,height:n=16,variant:s="light"})=>{const i="dark"===s?"#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:r,height:n,"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)"})]})]})};const $s=({onAddCredits:e,onCancel:n,isProcessing:s})=>{const[i,o]=r.useState(""),a=r.useRef(null);r.useEffect((()=>{a.current&&a.current.focus()}),[]);const c=""!==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=>o(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:n,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:s||!c,style:{padding:"8px 16px",backgroundColor:s||!c?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:s||!c?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!s&&c&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!s&&c&&(e.currentTarget.style.backgroundColor="#dc2626")},children:s?"Processing...":"Add Credits"})]})]})};e.EchoProvider=function({config:e,children:n}){const[s,i]=r.useState(!1);if(r.useEffect((()=>{i(!0)}),[]),!s)return null;const o=e.apiUrl||"https://echo.merit.systems",a={userManager:"undefined"!=typeof window&&window.__echoUserManager||new de({authority:o,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",silentRequestTimeoutInSeconds:10,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${o}/api/oauth/authorize`,token_endpoint:`${o}/api/oauth/token`,userinfo_endpoint:`${o}/api/oauth/userinfo`,issuer:o,jwks_uri:`${o}/.well-known/jwks.json`,end_session_endpoint:`${o}/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(Re,{...a,children:t.jsx(jn,{config:e,children:n})})},e.EchoSignIn=function({onSuccess:e,onError:n,className:s="",children:i}){const{signIn:o,isAuthenticated:a,isLoading:c,user:l,error:u}=Ln(),[d,h]=r.useState(!1);r.useEffect((()=>{a&&l&&e&&e(l)}),[a,l,e]),r.useEffect((()=>{u&&n&&n(new Error(u))}),[u,n]);const p=async()=>{try{await o()}catch(e){n&&n(e instanceof Error?e:new Error("Sign in failed"))}};return a?t.jsx("div",{className:`echo-signin-success ${s}`,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(Ws,{width:16,height:16,variant:"light"}),t.jsxs("span",{children:["Signed in as ",Hs((null==l?void 0:l.name)||(null==l?void 0:l.email))]})]})}):t.jsx("div",{className:`echo-signin ${s}`,children:i?t.jsx("div",{onClick:p,style:{cursor:"pointer"},children:i}):t.jsxs("button",{onClick:p,disabled:c,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:c?"#f3f4f6":d?"#f1f5f9":"#ffffff",color:c?"#9ca3af":"#09090b",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:c?"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:()=>h(!0),onMouseLeave:()=>h(!1),children:[t.jsx(Ws,{width:16,height:16,variant:"light"}),t.jsx("span",{children:c?"Signing in...":"Sign in"})]})})},e.EchoTokenPurchase=function({onPurchaseComplete:e,onError:n,className:s="",children:i}){const{createPaymentLink:o,isAuthenticated:a,balance:c,freeTierBalance:l,refreshBalance:u}=Ln(),[d,h]=r.useState(!1),[p,f]=r.useState(null),[g,m]=r.useState(!1),[_,w]=r.useState(!1),y=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),b=()=>{var e,t;return(((null==(e=null==l?void 0:l.userSpendInfo)?void 0:e.amountLeft)||0)<0?0:(null==(t=null==l?void 0:l.userSpendInfo)?void 0:t.amountLeft)||0)+((null==c?void 0:c.balance)||0)},S=async t=>{if(!a){const e=new Error("Please sign in to purchase tokens");return f(e.message),void(n&&n(e))}try{h(!0),f(null);const r=await o(t);await zs(r,{onComplete:async()=>{try{await u(),m(!1),w(!1),e&&c&&e(c)}catch(t){const e=t instanceof Error?t:new Error("Failed to refresh balance");f(e.message),n&&n(e)}finally{h(!1)}},onCancel:()=>{h(!1)},onError:e=>{f(e.message),n&&n(e),h(!1)}})}catch(r){const e=r instanceof Error?r:new Error("Failed to create payment link");f(e.message),n&&n(e),h(!1)}},v=()=>{m(!1),w(!1),f(null)};if(!a)return t.jsx("div",{className:`echo-token-purchase ${s}`,children:t.jsx("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px"},children:"Please sign in to purchase tokens"})});const E=()=>{const[e,n]=r.useState(!1);return t.jsxs("button",{onClick:()=>m(!0),className:`echo-token-purchase-compact ${s}`,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:()=>n(!0),onMouseLeave:()=>n(!1),children:[t.jsx(Ws,{width:16,height:16,variant:"light"}),t.jsx("span",{children:y(b())}),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"})]})]})},k=()=>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&&v()},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.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:y(b())}),t.jsxs("div",{style:{marginBottom:"8px"},children:[l&&b()>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:[y(l.userSpendInfo.amountLeft<0?0:l.userSpendInfo.amountLeft)," ","Free Tier",l.userSpendInfo&&l.userSpendInfo.spendLimit&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",y(l.userSpendInfo.amountSpent>l.userSpendInfo.spendLimit?l.userSpendInfo.spendLimit:l.userSpendInfo.amountSpent)," ","of"," ",y(l.userSpendInfo.spendLimit)," ","spent)"]})]})]}),l.userSpendInfo&&l.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,l.userSpendInfo.amountLeft)/(l.userSpendInfo.spendLimit||1)*100))}%`,height:"100%",backgroundColor:"#3b82f6"}})})]}),c&&c.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:[y(c.balance)," Paid Credits",c.totalSpent&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",y(c.totalSpent)," /"," ",y(c.totalPaid)," spent)"]})]})]}),c.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,c.balance/c.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"}),_?t.jsx($s,{onAddCredits:S,onCancel:()=>w(!1),isProcessing:d}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsx("button",{onClick:()=>S(10),disabled:d,style:{width:"100%",padding:"12px 16px",backgroundColor:d?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:d?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{d||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{d||(e.currentTarget.style.backgroundColor="#dc2626")},children:d?"Processing...":"Add $10 Credits"}),t.jsx("button",{onClick:()=>w(!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"})]})]}),p&&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:p}),t.jsx("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"flex-end",borderTop:"1px solid #f3f4f6"},children:t.jsx("button",{onClick:v,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:()=>m(!0),style:{cursor:"pointer"},children:i}):t.jsx(E,{}),g&&t.jsx(k,{})]})},e.Logo=Ws,e.useEcho=Ln,e.useEchoClient=Pn,e.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:n=!0}=e,{token:s,isAuthenticated:i}=Ln(),[o,a]=r.useState(void 0),[c,l]=r.useState(null),[u,d]=r.useState(!1),h=r.useRef(null);return r.useEffect((()=>{if(h.current&&h.current.abort(),!n||!s||!i)return a(void 0),l(null),void d(!1);return(async()=>{const e=new AbortController;h.current=e,d(!0),l(null);try{if(e.signal.aborted)return;const{default:r}=await import("openai");if(e.signal.aborted)return;const n=new r({apiKey:s,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(n)}catch(r){if(!e.signal.aborted){const e=r instanceof Error?r.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:",r),a(void 0)}}finally{e.signal.aborted||d(!1)}})(),()=>{h.current&&h.current.abort()}}),[s,i,t,n]),{openai:o,isReady:void 0!==o&&!u,error:c,isLoading:u}},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,i=Object.defineProperty,o=(e,t,n)=>((e,t,n)=>t in e?i(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 l,u,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(){l=3,u=d},c.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");l=e},c.setLogger=function(e){u=e};var m=class e{constructor(e){this._name=e}debug(...t){l>=4&&u.debug(e._format(this._name,this._method),...t)}info(...t){l>=3&&u.info(e._format(this._name,this._method),...t)}warn(...t){l>=2&&u.warn(e._format(this._name,this._method),...t)}error(...t){l>=1&&u.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){l>=4&&u.debug(e._format(t),...n)}static info(t,...n){l>=3&&u.info(e._format(t),...n)}static warn(t,...n){l>=2&&u.warn(e._format(t),...n)}static error(t,...n){l>=1&&u.error(e._format(t),...n)}};p.reset();var h=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 i;try{i=a(r)}catch(o){throw new s(`Invalid token specified: invalid base64 for part #${n+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new s(`Invalid token specified: invalid json for part #${n+1} (${o.message})`)}}(e)}catch(t){throw m.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,n){const r=`${v.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${v.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,(new TextEncoder).encode(r));return`${r}.${v.encodeBase64Url(new Uint8Array(i))}`}},g=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),f=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 g(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 g(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:i,nonce:o}){let s,a;const l={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),l.ath=a),o&&(l.nonce=o);try{const e=await crypto.subtle.exportKey("jwk",i.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await h.generateSignedJwt(t,l,i.privateKey)}catch(u){throw u instanceof TypeError?new Error(`Error exporting dpop public key: ${u.message}`):u}}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"])}};f.encodeBase64Url=e=>g(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var v=f,y=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)}},_=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 y{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 i=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*i)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},w=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))}},k=";",x=class extends Error{constructor(e,t){var n,r,i;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!=(i=e.session_state)?i: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,i){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=i,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 o=new URL(n);this._frame_origin=o.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=o.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)}},E=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}},O=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 i=new AbortController,o=setTimeout((()=>i.abort()),1e3*n);try{return await fetch(e,{...t,signal:i.signal})}catch(s){if(s instanceof DOMException&&"AbortError"===s.name)throw new I("Network timed out");throw s}finally{clearTimeout(o)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){const i=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};let s;t&&(i.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+t),this._appendExtraHeaders(o);try{i.debug("url:",e),s=await this.fetchWithTimeout(e,{method:"GET",headers:o,timeoutInSeconds:r,credentials:n})}catch(u){throw i.error("Network Error"),u}i.debug("HTTP response received, status",s.status);const a=s.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&i.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 l;try{l=await s.json()}catch(u){if(i.error("Error parsing JSON response",u),s.ok)throw u;throw new Error(`${s.statusText} (${s.status})`)}if(!s.ok){if(i.error("Error from server:",l),l.error)throw new x(l);throw new Error(`${s.statusText} (${s.status}): ${JSON.stringify(l)}`)}return l}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:i,extraHeaders:o}){const s=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...o};let l;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{s.debug("url:",e),l=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:r,credentials:i})}catch(p){throw s.error("Network error"),p}s.debug("HTTP response received, status",l.status);const u=l.headers.get("Content-Type");if(u&&!this._contentTypes.find((e=>u.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=u?u:"undefined"}, from URL: ${e}`);const c=await l.text();let d={};if(c)try{d=JSON.parse(c)}catch(p){if(s.error("Error parsing JSON response",p),l.ok)throw p;throw new Error(`${l.statusText} (${l.status})`)}if(!l.ok){if(s.error("Error from server:",d),l.headers.has("dpop-nonce")){const e=l.headers.get("dpop-nonce");throw new T(e,`${JSON.stringify(d)}`)}if(d.error)throw new x(d,t);throw new Error(`${l.statusText} (${l.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["accept","content-type"],i=["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(i.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n))return void t.warn("Header could not be overridden",n,i);const o="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];o&&""!==o&&(e[n]=o)}))}},N=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 O(["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}},C=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:i,client_id:o,client_secret:s,response_type:a="code",scope:l="openid",redirect_uri:u,post_logout_redirect_uri:c,client_authentication:d="client_secret_post",prompt:p,display:m,max_age:h,ui_locales:g,acr_values:f,resource:v,response_mode:y,filterProtocolClaims:_=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:w,staleStateAgeInSeconds:k=900,mergeClaimsStrategy:x={array:"replace"},disablePKCE:I=!1,stateStore:S,revokeTokenAdditionalContentTypes:$,fetchRequestCredentials:T,refreshTokenAllowedScope:O,extraQueryParams:N={},extraTokenParams:A={},extraHeaders:R={},dpop:U,omitScopeWhenRequesting:P=!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=i,this.signingKeys=r,this.client_id=o,this.client_secret=s,this.response_type=a,this.scope=l,this.redirect_uri=u,this.post_logout_redirect_uri=c,this.client_authentication=d,this.prompt=p,this.display=m,this.max_age=h,this.ui_locales=g,this.acr_values=f,this.resource=v,this.response_mode=y,this.filterProtocolClaims=null==_||_,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=k,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=P,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=$,this.fetchRequestCredentials=T||"same-origin",this.requestTimeoutInSeconds=w,S)this.stateStore=S;else{const e="undefined"!=typeof window?window.localStorage:new E;this.stateStore=new C({store:e})}if(this.refreshTokenAllowedScope=O,this.extraQueryParams=N,this.extraTokenParams=A,this.extraHeaders=R,this.dpop=U,this.dpop&&!(null==(j=this.dpop)?void 0:j.store))throw new Error("A DPoPStore is required when dpop is enabled")}},R=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=h.decode(e);return t.debug("JWT decoding successful"),n}catch(n){throw t.error("Error parsing JWT response"),n}},this._jsonService=new O(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}},U=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new m("TokenClient"),this._jsonService=new O(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:i,...o}){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")),o.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(o))null!=p&&a.set(d,p);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw s.throw(new Error("A client_secret is required")),null;l=v.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r)}const u=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(u,{body:a,basicAuth:l,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});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,...i}){const o=this._logger.create("exchangeCredentials");t||o.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(i))null!=d&&s.set(c,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;a=v.generateBasicAuth(t,n);break;case"client_secret_post":s.append("client_id",t),n&&s.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return o.debug("got response"),u}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:i,...o}){const s=this._logger.create("exchangeRefreshToken");t||s.throw(new Error("A client_id is required")),o.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(o))Array.isArray(p)?p.forEach((e=>a.append(d,e))):null!=p&&a.set(d,p);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw s.throw(new Error("A client_secret is required")),null;l=v.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const u=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(u,{body:a,basicAuth:l,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});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 i=new URLSearchParams;for(const[o,s]of Object.entries(e))null!=s&&i.set(o,s);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),n.debug("got response")}},P=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new m("ResponseValidator"),this._userInfoService=new R(this._settings,this._metadataService),this._tokenClient=new U(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 i=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),n&&i.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(i)),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 i=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,i)}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 i=h.decode(null!=(n=e.id_token)?n:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=h.decode(t);i.sub!==e.sub&&r.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==e.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==e.azp&&r.throw(new Error("azp in id_token does not match original azp")),!i.azp&&e.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}},j=class e{constructor(e){this.id=e.id||v.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"),i=b.getEpochTime()-n,o=await t.getAllKeys();r.debug("got keys",o);for(let a=0;a<o.length;a++){const n=o[a],l=await t.get(n);let u=!1;if(l)try{const t=await e.fromStorageString(l);r.debug("got item from key:",n,t.created),t.created<=i&&(u=!0)}catch(s){r.error("Error parsing state for key:",n,s),u=!0}else r.debug("no item in storage for key:",n),u=!0;u&&(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?v.generateCodeVerifier():t.code_verifier||void 0,r=n?await v.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:i,response_type:o,scope:s,state_data:a,response_mode:l,request_type:u,client_secret:c,nonce:d,url_state:p,resource:m,skipUserInfo:h,extraQueryParams:g,extraTokenParams:f,disablePKCE:v,dpopJkt:y,omitScopeWhenRequesting:_,...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(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!o)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 w=await z.create({data:a,request_type:u,url_state:p,code_verifier:!v,client_id:r,authority:n,redirect_uri:i,response_mode:l,client_secret:c,scope:s,extraTokenParams:f,skipUserInfo:h}),x=new URL(t);x.searchParams.append("client_id",r),x.searchParams.append("redirect_uri",i),x.searchParams.append("response_type",o),_||x.searchParams.append("scope",s),d&&x.searchParams.append("nonce",d),y&&x.searchParams.append("dpop_jkt",y);let I=w.id;if(p&&(I=`${I}${k}${p}`),x.searchParams.append("state",I),w.code_challenge&&(x.searchParams.append("code_challenge",w.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,k]of Object.entries({response_mode:l,...b,...g}))null!=k&&x.searchParams.append(e,k.toString());return new e({url:x.href,state:w})}};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(k);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(k))}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}},Z=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:i,request_type:o,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 l=new URL(e);if(n&&l.searchParams.append("id_token_hint",n),s&&l.searchParams.append("client_id",s),r&&(l.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new j({data:t,request_type:o,url_state:a});let e=this.state.id;a&&(e=`${e}${k}${a}`),l.searchParams.append("state",e)}for(const[u,c]of Object.entries({...i}))null!=c&&l.searchParams.append(u,c.toString());this.url=l.href}},q=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(k);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(k))}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"],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)W.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[r,i]of Object.entries(t))if(n[r]!==i)if(Array.isArray(n[r])||Array.isArray(i))if("replace"==this._settings.mergeClaimsStrategy.array)n[r]=i;else{const e=Array.isArray(n[r])?n[r]:[n[r]];for(const t of Array.isArray(i)?i:[i])e.includes(t)||e.push(t);n[r]=e}else"object"==typeof n[r]&&"object"==typeof i?n[r]=this.mergeClaims(n[r],i):n[r]=i;return n}},J=class{constructor(e,t){this.keys=e,this.nonce=t}},H=class{constructor(e,t){this._logger=new m("OidcClient"),this.settings=e instanceof A?e:new A(e),this.metadataService=null!=t?t:new N(this.settings),this._claimsService=new B(this.settings),this._validator=new P(this.settings,this.metadataService,this._claimsService),this._tokenClient=new U(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:i,login_hint:o,skipUserInfo:s,nonce:a,url_state:l,response_type:u=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:h=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:f=this.settings.acr_values,resource:v=this.settings.resource,response_mode:y=this.settings.response_mode,extraQueryParams:_=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:w,omitScopeWhenRequesting:k=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if("code"!==u)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:u,scope:c,state_data:e,url_state:l,prompt:p,display:m,max_age:h,ui_locales:g,id_token_hint:i,login_hint:o,acr_values:f,dpopJkt:w,resource:v,request:t,request_uri:n,extraQueryParams:_,extraTokenParams:b,request_type:r,response_mode:y,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:k});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(w.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await z.fromStorageString(i),response:r}}async processSigninResponse(e,t,n=!0){const r=this._logger.create("processSigninResponse"),{state:i,response:o}=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(o,i,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(o,i,t)}}return o}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 v.generateDPoPKeys(),r=new J(n,t),await e.set(this.settings.client_id,r)),await v.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 i=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),o=new L(new URLSearchParams);return Object.assign(o,i),await this._validator.validateCredentialsResponse(o,n),o}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:o}){var s;const a=this._logger.create("useRefreshToken");let l,u;if(void 0===this.settings.refreshTokenAllowedScope)l=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");l=((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);i={...i,DPoP:e}}try{u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:l,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...o})}catch(d){if(!(d instanceof T&&this.settings.dpop))throw d;i.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:l,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...o})}const c=new L(new URLSearchParams);return Object.assign(c,u),a.debug("validating response",c),await this._validator.validateRefreshResponse(c,{...e,scope:l}),c}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:i,post_logout_redirect_uri:o=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),l=await this.metadataService.getEndSessionEndpoint();if(!l)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",l),n||!o||t||(n=this.settings.client_id);const u=new Z({url:l,id_token_hint:t,client_id:n,post_logout_redirect_uri:o,state_data:e,extraQueryParams:s,request_type:r,url_state:i});await this.clearStaleState();const c=u.state;return c&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),u}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),r=new q(w.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 i=await this.settings.stateStore[t?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await j.fromStorageString(i),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,i=this._userManager.settings.checkSessionIntervalInSeconds,o=this._userManager.settings.stopCheckSessionOnError,s=new $(this._callback,r,e,i,o);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 y("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 i=i=>{var o;const s=i.data,a=null!=(o=e.scriptOrigin)?o:window.location.origin;if(i.origin===a&&(null==s?void 0:s.source)===G){try{const n=w.readParams(s.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),i.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(new Error("Invalid response from window"))}n(s)}};window.addEventListener("message",i,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",i,!1)));const o=new BroadcastChannel(`oidc-client-popup-${e.state}`);o.addEventListener("message",i,!1),this._disposeHandlers.add((()=>o.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 i={source:G,url:t,keepOpen:n},o=new m("_notifyParent");if(e)o.debug("With parent. Using parent.postMessage."),e.postMessage(i,r);else{o.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(i),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:i=Q,redirectMethod:o="assign",redirectTarget:s="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:l=e.iframeScriptOrigin,requestTimeoutInSeconds:u,silent_redirect_uri:c=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:p=!0,validateSubOnSilentRenew:m=!0,includeIdTokenInSilentRenew:h=!1,monitorSession:g=!1,monitorAnonymousSession:f=!1,checkSessionIntervalInSeconds:v=te,query_status_response_type:y="code",stopCheckSessionOnError:_=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:w=!1,includeIdTokenInSilentSignout:k=!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=i,this.redirectMethod=o,this.redirectTarget=s,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=l,this.silent_redirect_uri=c,this.silentRequestTimeoutInSeconds=d||u||10,this.automaticSilentRenew=p,this.validateSubOnSilentRenew=m,this.includeIdTokenInSilentRenew=h,this.monitorSession=g,this.monitorAnonymousSession=f,this.checkSessionIntervalInSeconds=v,this.stopCheckSessionOnError=_,this.query_status_response_type=y,this.revokeTokenTypes=b,this.revokeTokensOnSignout=w,this.includeIdTokenInSilentSignout=k,this.accessTokenExpiringNotificationTimeInSeconds=x,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new E;this.userStore=new C({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)}},ie=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)}},oe=class extends Y{constructor({popupWindowTarget:e=Q,popupWindowFeatures:t={},popupSignal:n}){super(),this._logger=new m("PopupWindow");const r=_.center({...X,...t});this._window=window.open(void 0,e,_.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 oe({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),oe.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 i=r.location[e].bind(r.location);let o;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{o=t}));return i(e.url),await t},close:()=>{this._logger.create("close"),null==o||o(new Error("Redirect aborted")),r.stop()}}}async callback(){}},le=class extends S{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new m("UserManagerEvents"),this._userLoaded=new y("User loaded"),this._userUnloaded=new y("User unloaded"),this._silentRenewError=new y("Silent renew error"),this._userSignedIn=new y("User signed in"),this._userSignedOut=new y("User signed out"),this._userSessionChanged=new y("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()}},ue=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 H(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 ie(this.settings),this._events=new le(this.settings),this._silentRenewService=new ue(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 i;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(i=await this.generateDPoPJkt(this.settings.dpop));const o=await this._redirectNavigator.prepare({redirectMethod:n});await this._signinStart({request_type:"si:r",dpopJkt:i,...r},o)}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"),i=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug("got signin response");const o=await this._buildUser(i);return o.profile&&o.profile.sub?r.info("success, signed in subject",o.profile.sub):r.info("no subject"),o}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:i,popupWindowTarget:o,popupSignal:s,...a}=e,l=this.settings.popup_redirect_uri;l||n.throw(new Error("No popup_redirect_uri configured"));const u=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:o,popupSignal:s}),c=await this._signin({request_type:"si:p",redirect_uri:l,display:"popup",dpopJkt:r,...a},u);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:i,...o}=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:o.redirect_uri,resource:o.resource,extraTokenParams:o.extraTokenParams,timeoutInSeconds:i})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const l=this.settings.silent_redirect_uri;let u;l||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),u=a.profile.sub);const c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i});return a=await this._signin({request_type:"si:s",redirect_uri:l,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:s,...o},c,u),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,i=this.settings.silent_redirect_uri;i||t.throw(new Error("No silent_redirect_uri configured"));const o=await this._loadUser(),s=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:i,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==o?void 0:o.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(l){if(this.settings.monitorAnonymousSession&&l instanceof x)switch(l.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:l.session_state}}throw l}}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,i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},i),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:i,...o}=e,s=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:i});await this._signout({request_type:"so:p",post_logout_redirect_uri:s,state:null==s?void 0:{},...o},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 i=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(i);const o=e.id_token_hint||i&&i.id_token;o&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=o),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(i){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),i}}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,...i}=e,o=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:o,...i},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 i,o;const s=await(null==(o=null==(i=this.settings.dpop)?void 0:i.store)?void 0:o.get(this.settings.client_id));if(s)return await v.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 v.generateDPoPKeys();t=new J(n),await e.store.set(this.settings.client_id,t)}return await v.generateDPoPJkt(t.keys)}},pe=n.createContext(void 0);pe.displayName="AuthContext";var me={isLoading:!0,isAuthenticated:!1},he=(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}}}},ge=_e("signinCallback","Sign-in failed"),fe=_e("signoutCallback","Sign-out failed"),ve=_e("renewSilent","Renew silent failed");function ye(e,t){return{name:be(e,"name",(()=>"Error")),message:be(e,"message",(()=>t)),stack:be(e,"stack",(()=>(new Error).stack)),innerError:e}}function _e(e,t){return n=>({...ye(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 we,ke=["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:i,matchSignoutCallback:o,onSignoutCallback:s,onRemoveUser:a,userManager:l=null,...u}=e,[c]=n.useState((()=>null!=l?l:Se?new Se(u):{settings:u})),[d,p]=n.useReducer(he,me),m=n.useMemo((()=>Object.assign({settings:c.settings,events:c.events},Object.fromEntries(ke.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:{...ye(n,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{p({type:"NAVIGATOR_CLOSE"})}}:Ie(e)]))))),[c]),h=n.useRef(!1);n.useEffect((()=>{c&&!h.current&&(h.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")))})()&&!i&&(e=await c.signinCallback(),r&&await r(e)),e=e||await c.getUser(),p({type:"INITIALISED",user:e})}catch(e){p({type:"ERROR",error:ge(e)})}try{if(o&&o(c.settings)){const e=await c.signoutCallback();s&&await s(e)}}catch(e){p({type:"ERROR",error:fe(e)})}})())}),[c,i,r,s,o]),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:ve(e)})};return c.events.addSilentRenewError(r),()=>{c.events.removeUserLoaded(e),c.events.removeUserUnloaded(t),c.events.removeUserSignedOut(n),c.events.removeSilentRenewError(r)}}),[c]);const g=n.useCallback((async()=>{await c.removeUser(),a&&await a()}),[c,a]),f=n.useMemo((()=>({...d,...m,removeUser:g})),[d,m,g]);return n.createElement(pe.Provider,{value:f},t)},Ee=()=>{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",Oe=Symbol.for(Te),Ne=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[we]=!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]}};we=Oe;var Ce,Ae=Ne,Re="AI_APICallError",Ue=`vercel.ai.error.${Re}`,Pe=Symbol.for(Ue),je=class extends Ae{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:o,cause:s,isRetryable:a=null!=r&&(408===r||409===r||429===r||r>=500),data:l}){super({name:Re,message:e,cause:s}),this[Ce]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=o,this.isRetryable=a,this.data=l}static isInstance(e){return Ae.hasMarker(e,Ue)}};Ce=Pe;var ze,De="AI_EmptyResponseBodyError",Me=`vercel.ai.error.${De}`,Le=Symbol.for(Me),Ze=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 qe(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",Be=`vercel.ai.error.${We}`,Je=Symbol.for(Be),He=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,Be)}};Fe=Je;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 it,ot="AI_JSONParseError",st=`vercel.ai.error.${ot}`,at=Symbol.for(st),lt=class extends Ae{constructor({text:e,cause:t}){super({name:ot,message:`JSON parsing failed: Text: ${e}.\nError message: ${qe(t)}`,cause:t}),this[it]=!0,this.text=e}static isInstance(e){return Ae.hasMarker(e,st)}};it=at;var ut,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[ut]=!0}static isInstance(e){return Ae.hasMarker(e,dt)}};ut=pt;var ht,gt="AI_NoSuchModelError",ft=`vercel.ai.error.${gt}`,vt=Symbol.for(ft),yt=class extends Ae{constructor({errorName:e=gt,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[ht]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return Ae.hasMarker(e,ft)}};ht=vt;var _t,bt="AI_TooManyEmbeddingValuesForCallError",wt=`vercel.ai.error.${bt}`,kt=Symbol.for(wt),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[_t]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Ae.hasMarker(e,wt)}};_t=kt;var It,St="AI_TypeValidationError",$t=`vercel.ai.error.${St}`,Et=Symbol.for($t);It=Et;var Tt,Ot=class e extends Ae{constructor({value:e,cause:t}){super({name:St,message:`Type validation failed: Value: ${JSON.stringify(e)}.\nError message: ${qe(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})}},Nt="AI_UnsupportedFunctionalityError",Ct=`vercel.ai.error.${Nt}`,At=Symbol.for(Ct),Rt=class extends Ae{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Nt,message:t}),this[Tt]=!0,this.functionality=e}static isInstance(e){return Ae.hasMarker(e,Ct)}};Tt=At;class Ut 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 Pt(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=Pt,onError:n=Pt,onRetry:r=Pt,onComment:i}=e;let o,s="",a=!0,l="",u="";function c(e){if(""===e)return l.length>0&&t({id:o,event:u||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),o=void 0,l="",void(u="");if(e.startsWith(":"))return void(i&&i(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,i){switch(e){case"event":u=t;break;case"data":l=`${l}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new Ut(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:i}));break;default:n(new Ut(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:i}))}}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 i=e.indexOf("\r",r),o=e.indexOf("\n",r);let s=-1;if(-1!==i&&-1!==o?s=Math.min(i,o):-1!==i?s=i===e.length-1?-1:i:-1!==o&&(s=o),-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 i of n)c(i);s=r,a=!1},reset:function(e={}){s&&e.consume&&c(s),a=!0,o=void 0,l="",u="",s=""}}}class zt extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=jt({onEvent:e=>{i.enqueue(e)},onError(t){"terminate"===e?i.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 i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.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 i=(null==n?void 0:n.Parent)??Object;class o extends i{}function s(e){var t;const i=(null==n?void 0:n.Parent)?new o:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const n of i._zod.deferred)n();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>{var r,i;return!!((null==n?void 0:n.Parent)&&t instanceof n.Parent)||(null==(i=null==(r=null==t?void 0:t._zod)?void 0:r.traits)?void 0:i.has(e))}}),Object.defineProperty(s,"name",{value:e}),s}const Lt=Symbol("zod_brand");class Zt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const qt={};function Ft(e){return e&&Object.assign(qt,e),qt}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 Bt(e,t="|"){return e.map((e=>hn(e))).join(t)}function Jt(e,t){return"bigint"==typeof t?t.toString():t}function Ht(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 i=(r.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);(null==e?void 0:e[1])&&(i=Number.parseInt(e[1]))}const o=n>i?n:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}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=Ht((()=>{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 ln(e){return an(e)?{...e}:e}const un=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 hn(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function gn(e){return Object.keys(e).filter((t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout))}const fn={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]},vn={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function yn(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 _n(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 wn(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 kn(e,t,n){const r=tn(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return en(this,"shape",i),i},checks:[]});return pn(t,r)}function xn(e,t,n){const r=tn(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)i[t]=new e({type:"nonoptional",innerType:r[t]});return en(this,"shape",i),i},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 En(e,t,n){var r,i,o,s,a,l;const u={...e,path:e.path??[]};if(!e.message){const c=$n(null==(o=null==(i=null==(r=e.inst)?void 0:r._zod.def)?void 0:i.error)?void 0:o.call(i,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==(l=n.localeError)?void 0:l.call(n,e))??"Invalid input";u.message=c}return delete u.inst,delete u.continue,(null==t?void 0:t.reportInput)||delete u.input,u}function Tn(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function On(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Nn(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Cn=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:vn,Class:class{constructor(...e){}},NUMBER_FORMAT_RANGES:fn,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:Ht,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,i)=>(t??(t=e()),Reflect.get(t,r,i)),set:(n,r,i,o)=>(t??(t=e()),Reflect.set(t,r,i,o)),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,i)=>(t??(t=e()),Reflect.defineProperty(t,r,i))})},defineLazy:Xt,esc:nn,escapeRegex:dn,extend:bn,finalizeIssue:En,floatSafeRemainder:Gt,getElementAtPath:function(e,t){return t?t.reduce(((e,t)=>null==e?void 0:e[t]),e):e},getEnumValues:Wt,getLengthableOrigin:On,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:Nn,joinValues:Bt,jsonStringifyReplacer:Jt,merge:wn,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:_n,optionalKeys:gn,partial:kn,pick:yn,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:un,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:ln,stringifyPrimitive:hn,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,Jt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Rn=Mt("$ZodError",An),Un=Mt("$ZodError",An,{Parent:Error});function Pn(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function jn(e,t){const n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map((e=>i({issues:e})));else if("invalid_key"===t.code)i({issues:t.issues});else if("invalid_element"===t.code)i({issues:t.issues});else if(0===t.path.length)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){const r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}function zn(e,t){const n=t||function(e){return e.message},r={errors:[]},i=(e,t=[])=>{var o,s;for(const a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map((e=>i({issues:e},a.path)));else if("invalid_key"===a.code)i({issues:a.issues},a.path);else if("invalid_element"===a.code)i({issues:a.issues},a.path);else{const e=[...t,...a.path];if(0===e.length){r.errors.push(n(a));continue}let i=r,l=0;for(;l<e.length;){const t=e[l],r=l===e.length-1;"string"==typeof t?(i.properties??(i.properties={}),(o=i.properties)[t]??(o[t]={errors:[]}),i=i.properties[t]):(i.items??(i.items=[]),(s=i.items)[t]??(s[t]={errors:[]}),i=i.items[t]),r&&i.errors.push(n(a)),l++}}};return i(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 i of r)n.push(`✖ ${i.message}`),(null==(t=i.path)?void 0:t.length)&&n.push(` → at ${Dn(i.path)}`);return n.join("\n")}const Ln=e=>(t,n,r,i)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Zt;if(s.issues.length){const t=new((null==i?void 0:i.Err)??e)(s.issues.map((e=>En(e,o,Ft()))));throw rn(t,null==i?void 0:i.callee),t}return s.value},Zn=Ln(Un),qn=e=>async(t,n,r,i)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new((null==i?void 0:i.Err)??e)(s.issues.map((e=>En(e,o,Ft()))));throw rn(t,null==i?void 0:i.callee),t}return s.value},Fn=qn(Un),Wn=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Zt;return o.issues.length?{success:!1,error:new(e??Rn)(o.issues.map((e=>En(e,i,Ft()))))}:{success:!0,data:o.value}},Bn=Wn(Un),Jn=e=>async(t,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map((e=>En(e,i,Ft()))))}:{success:!0,data:o.value}},Hn=Jn(Un),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),ir=nr(6),or=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 lr=/^(?:(?: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])$/,ur=/^(([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_-]*$/,hr=/^(?=.{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])?)*\.?$/,gr=/^\+(?:[0-9]){6,14}[0-9]$/,fr="(?:(?:\\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])))",vr=new RegExp(`^${fr}$`);function yr(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 _r(e){return new RegExp(`^${yr(e)}$`)}function br(e){const t=yr({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(`^${fr}T(?:${r})$`)}const wr=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}$`)},kr=/^\d+n?$/,xr=/^\d+$/,Ir=/^-?\d+(?:\.\d+)?/i,Sr=/true|false/i,$r=/null/i,Er=/undefined/i,Tr=/^[^A-Z]*$/,Or=/^[^a-z]*$/,Nr=Object.freeze(Object.defineProperty({__proto__:null,base64:pr,base64url:mr,bigint:kr,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:vr,datetime:br,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,duration:er,e164:gr,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:hr,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:lr,ipv6:ur,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:wr,time:_r,ulid:Gn,undefined:Er,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,uppercase:Or,uuid:nr,uuid4:rr,uuid6:ir,uuid7:or,xid:Yn},Symbol.toStringTag,{value:"Module"})),Cr=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"},Rr=Mt("$ZodCheckLessThan",((e,t)=>{Cr.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})}})),Ur=Mt("$ZodCheckGreaterThan",((e,t)=>{Cr.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})}})),Pr=Mt("$ZodCheckMultipleOf",((e,t)=>{Cr.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})}})),jr=Mt("$ZodCheckNumberFormat",((e,t)=>{var n;Cr.init(e,t),t.format=t.format||"float64";const r=null==(n=t.format)?void 0:n.includes("int"),i=r?"int":"number",[o,s]=fn[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=o,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:i,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:i,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:i,continue:!t.abort}))}a<o&&n.issues.push({origin:"number",input:a,code:"too_small",minimum:o,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)=>{Cr.init(e,t);const[n,r]=vn[t.format];e._zod.onattach.push((e=>{const i=e._zod.bag;i.format=t.format,i.minimum=n,i.maximum=r})),e._zod.check=i=>{const o=i.value;o<n&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>r&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:r,inst:e})}})),Dr=Mt("$ZodCheckMaxSize",((e,t)=>{var n;Cr.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;Cr.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;Cr.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,i=r.size;if(i===t.size)return;const o=i>t.size;n.issues.push({origin:Tn(r),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),Zr=Mt("$ZodCheckMaxLength",((e,t)=>{var n;Cr.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 i=On(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),qr=Mt("$ZodCheckMinLength",((e,t)=>{var n;Cr.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 i=On(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),Fr=Mt("$ZodCheckLengthEquals",((e,t)=>{var n;Cr.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,i=r.length;if(i===t.length)return;const o=On(r),s=i>t.length;n.issues.push({origin:o,...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;Cr.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)=>{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})}})),Jr=Mt("$ZodCheckLowerCase",((e,t)=>{t.pattern??(t.pattern=Tr),Wr.init(e,t)})),Hr=Mt("$ZodCheckUpperCase",((e,t)=>{t.pattern??(t.pattern=Or),Wr.init(e,t)})),Vr=Mt("$ZodCheckIncludes",((e,t)=>{Cr.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)=>{Cr.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)=>{Cr.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)=>{Cr.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)=>{Cr.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})}})),ei=Mt("$ZodCheckOverwrite",((e,t)=>{Cr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class ti{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 i of r)this.content.push(i)}compile(){return new Function(...null==this?void 0:this.args,[...((null==this?void 0:this.content)??[""]).map((e=>` ${e}`))].join("\n"))}}const ni={major:4,minor:0,patch:17},ri=Mt("$ZodType",((e,t)=>{var n,r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ni;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const o of i)for(const t of o._zod.onattach)t(e);if(0===i.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,i=In(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===(null==n?void 0:n.async))throw new Zt;if(r||s instanceof Promise)r=(r??Promise.resolve()).then((async()=>{await s;e.issues.length!==t&&(i||(i=In(e,t)))}));else{if(e.issues.length===t)continue;i||(i=In(e,t))}}return r?r.then((()=>e)):e};e._zod.run=(n,r)=>{const o=e._zod.parse(n,r);if(o instanceof Promise){if(!1===r.async)throw new Zt;return o.then((e=>t(e,i,r)))}return t(o,i,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 Hn(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}})),ii=Mt("$ZodString",((e,t)=>{var n;ri.init(e,t),e._zod.pattern=[...(null==(n=null==e?void 0:e._zod.bag)?void 0:n.patterns)??[]].pop()??wr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}})),oi=Mt("$ZodStringFormat",((e,t)=>{Wr.init(e,t),ii.init(e,t)})),si=Mt("$ZodGUID",((e,t)=>{t.pattern??(t.pattern=tr),oi.init(e,t)})),ai=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());oi.init(e,t)})),li=Mt("$ZodEmail",((e,t)=>{t.pattern??(t.pattern=sr),oi.init(e,t)})),ui=Mt("$ZodURL",((e,t)=>{oi.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:hr.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.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=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}})),ci=Mt("$ZodEmoji",((e,t)=>{t.pattern??(t.pattern=ar()),oi.init(e,t)})),di=Mt("$ZodNanoID",((e,t)=>{t.pattern??(t.pattern=Qn),oi.init(e,t)})),pi=Mt("$ZodCUID",((e,t)=>{t.pattern??(t.pattern=Vn),oi.init(e,t)})),mi=Mt("$ZodCUID2",((e,t)=>{t.pattern??(t.pattern=Kn),oi.init(e,t)})),hi=Mt("$ZodULID",((e,t)=>{t.pattern??(t.pattern=Gn),oi.init(e,t)})),gi=Mt("$ZodXID",((e,t)=>{t.pattern??(t.pattern=Yn),oi.init(e,t)})),fi=Mt("$ZodKSUID",((e,t)=>{t.pattern??(t.pattern=Xn),oi.init(e,t)})),vi=Mt("$ZodISODateTime",((e,t)=>{t.pattern??(t.pattern=br(t)),oi.init(e,t)})),yi=Mt("$ZodISODate",((e,t)=>{t.pattern??(t.pattern=vr),oi.init(e,t)})),_i=Mt("$ZodISOTime",((e,t)=>{t.pattern??(t.pattern=_r(t)),oi.init(e,t)})),bi=Mt("$ZodISODuration",((e,t)=>{t.pattern??(t.pattern=er),oi.init(e,t)})),wi=Mt("$ZodIPv4",((e,t)=>{t.pattern??(t.pattern=lr),oi.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv4"}))})),ki=Mt("$ZodIPv6",((e,t)=>{t.pattern??(t.pattern=ur),oi.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})}}})),xi=Mt("$ZodCIDRv4",((e,t)=>{t.pattern??(t.pattern=cr),oi.init(e,t)})),Ii=Mt("$ZodCIDRv6",((e,t)=>{t.pattern??(t.pattern=dr),oi.init(e,t),e._zod.check=n=>{const[r,i]=n.value.split("/");try{if(!i)throw new Error;const e=Number(i);if(`${e}`!==i)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 Si(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const $i=Mt("$ZodBase64",((e,t)=>{t.pattern??(t.pattern=pr),oi.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64"})),e._zod.check=n=>{Si(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}));function Ei(e){if(!mr.test(e))return!1;const t=e.replace(/[-_]/g,(e=>"-"===e?"+":"/"));return Si(t.padEnd(4*Math.ceil(t.length/4),"="))}const Ti=Mt("$ZodBase64URL",((e,t)=>{t.pattern??(t.pattern=mr),oi.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64url"})),e._zod.check=n=>{Ei(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}})),Oi=Mt("$ZodE164",((e,t)=>{t.pattern??(t.pattern=gr),oi.init(e,t)}));function Ni(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return(!("typ"in i)||"JWT"===(null==i?void 0:i.typ))&&(!!i.alg&&(!t||"alg"in i&&i.alg===t))}catch{return!1}}const Ci=Mt("$ZodJWT",((e,t)=>{oi.init(e,t),e._zod.check=n=>{Ni(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}})),Ai=Mt("$ZodCustomStringFormat",((e,t)=>{oi.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})}})),Ri=Mt("$ZodNumber",((e,t)=>{ri.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 i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}})),Ui=Mt("$ZodNumber",((e,t)=>{jr.init(e,t),Ri.init(e,t)})),Pi=Mt("$ZodBoolean",((e,t)=>{ri.init(e,t),e._zod.pattern=Sr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}})),ji=Mt("$ZodBigInt",((e,t)=>{ri.init(e,t),e._zod.pattern=kr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(i){}return"bigint"==typeof n.value||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}})),zi=Mt("$ZodBigInt",((e,t)=>{zr.init(e,t),ji.init(e,t)})),Di=Mt("$ZodSymbol",((e,t)=>{ri.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}})),Mi=Mt("$ZodUndefined",((e,t)=>{ri.init(e,t),e._zod.pattern=Er,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}})),Li=Mt("$ZodNull",((e,t)=>{ri.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}})),Zi=Mt("$ZodAny",((e,t)=>{ri.init(e,t),e._zod.parse=e=>e})),qi=Mt("$ZodUnknown",((e,t)=>{ri.init(e,t),e._zod.parse=e=>e})),Fi=Mt("$ZodNever",((e,t)=>{ri.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)})),Wi=Mt("$ZodVoid",((e,t)=>{ri.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}})),Bi=Mt("$ZodDate",((e,t)=>{ri.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}}));function Ji(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues)),t.value[n]=e.value}const Hi=Mt("$ZodArray",((e,t)=>{ri.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const s=i[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?o.push(a.then((t=>Ji(t,n,e)))):Ji(a,n,e)}return o.length?Promise.all(o).then((()=>n)):n}}));function Vi(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 Ki=Mt("$ZodObject",((e,t)=>{ri.init(e,t);const n=Ht((()=>{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=gn(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 i=on,o=!qt.jitless,s=o&&sn.value,a=t.catchall;let l;e._zod.parse=(u,c)=>{l??(l=n.value);const d=u.value;if(!i(d))return u.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),u;const p=[];if(o&&s&&!1===(null==c?void 0:c.async)&&!0!==c.jitless)r||(r=(e=>{const t=new ti(["shape","payload","ctx"]),r=n.value,i=e=>{const t=nn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const n of r.keys)o[n]="key_"+s++;t.write("const newResult = {}");for(const n of r.keys){const e=o[n],r=nn(n);t.write(`const ${e} = ${i(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)),u=r(u,c);else{u.value={};const e=l.shape;for(const t of l.keys){const n=e[t]._zod.run({value:d[t],issues:[]},c);n instanceof Promise?p.push(n.then((e=>Vi(e,u,t,d)))):Vi(n,u,t,d)}}if(!a)return p.length?Promise.all(p).then((()=>u)):u;const m=[],h=l.keySet,g=a._zod,f=g.def.type;for(const e of Object.keys(d)){if(h.has(e))continue;if("never"===f){m.push(e);continue}const t=g.run({value:d[e],issues:[]},c);t instanceof Promise?p.push(t.then((t=>Vi(t,u,e,d)))):Vi(t,u,e,d)}return m.length&&u.issues.push({code:"unrecognized_keys",keys:m,input:d,inst:e}),p.length?Promise.all(p).then((()=>u)):u}}));function Gi(e,t,n,r){for(const o of e)if(0===o.issues.length)return t.value=o.value,t;const i=e.filter((e=>!In(e)));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((e=>e.issues.map((e=>En(e,r,Ft())))))}),t)}const Yi=Mt("$ZodUnion",((e,t)=>{ri.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=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);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=>Gi(t,i,e,o))):Gi(a,i,e,o)}})),Xi=Mt("$ZodDiscriminatedUnion",((e,t)=>{Yi.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=Ht((()=>{var e;const n=t.options,r=new Map;for(const i of n){const n=null==(e=i._zod.propValues)?void 0:e[t.discriminator];if(!n||0===n.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const e of n){if(r.has(e))throw new Error(`Duplicate discriminator value "${String(e)}"`);r.set(e,i)}}return r}));e._zod.parse=(i,o)=>{const s=i.value;if(!on(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=r.value.get(null==s?void 0:s[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}})),Qi=Mt("$ZodIntersection",((e,t)=>{ri.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then((([t,n])=>to(e,t,n))):to(e,i,o)}}));function eo(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))),i={...e,...t};for(const o of r){const n=eo(e[o],t[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};i[o]=n.data}return{valid:!0,data:i}}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 i=eo(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function to(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=eo(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 no=Mt("$ZodTuple",((e,t)=>{ri.init(e,t);const n=t.items,r=n.length-[...n].reverse().findIndex((e=>"optional"!==e._zod.optin));e._zod.parse=(i,o)=>{const s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];const a=[];if(!t.rest){const t=s.length>n.length,o=s.length<r-1;if(t||o)return i.issues.push({...t?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},input:s,inst:e,origin:"array"}),i}let l=-1;for(const e of n){if(l++,l>=s.length&&l>=r)continue;const t=e._zod.run({value:s[l],issues:[]},o);t instanceof Promise?a.push(t.then((e=>ro(e,i,l)))):ro(t,i,l)}if(t.rest){const e=s.slice(n.length);for(const n of e){l++;const e=t.rest._zod.run({value:n,issues:[]},o);e instanceof Promise?a.push(e.then((e=>ro(e,i,l)))):ro(e,i,l)}}return a.length?Promise.all(a).then((()=>i)):i}}));function ro(e,t,n){e.issues.length&&t.issues.push(...Sn(n,e.issues)),t.value[n]=e.value}const io=Mt("$ZodRecord",((e,t)=>{ri.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!an(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const o=[];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:i[e],issues:[]},r);s instanceof Promise?o.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 i)s.has(e)||(a=a??[],a.push(e));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{n.value={};for(const s of Reflect.ownKeys(i)){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=>En(e,r,Ft()))),input:s,path:[s],inst:e}),n.value[a.value]=a.value;continue}const l=t.valueType._zod.run({value:i[s],issues:[]},r);l instanceof Promise?o.push(l.then((e=>{e.issues.length&&n.issues.push(...Sn(s,e.issues)),n.value[a.value]=e.value}))):(l.issues.length&&n.issues.push(...Sn(s,l.issues)),n.value[a.value]=l.value)}}return o.length?Promise.all(o).then((()=>n)):n}})),oo=Mt("$ZodMap",((e,t)=>{ri.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),n;const o=[];n.value=new Map;for(const[s,a]of i){const l=t.keyType._zod.run({value:s,issues:[]},r),u=t.valueType._zod.run({value:a,issues:[]},r);l instanceof Promise||u instanceof Promise?o.push(Promise.all([l,u]).then((([t,o])=>{so(t,o,n,s,i,e,r)}))):so(l,u,n,s,i,e,r)}return o.length?Promise.all(o).then((()=>n)):n}}));function so(e,t,n,r,i,o,s){e.issues.length&&(un.has(typeof r)?n.issues.push(...Sn(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map((e=>En(e,s,Ft())))})),t.issues.length&&(un.has(typeof r)?n.issues.push(...Sn(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:r,issues:t.issues.map((e=>En(e,s,Ft())))})),n.value.set(e.value,t.value)}const ao=Mt("$ZodSet",((e,t)=>{ri.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Set))return n.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),n;const o=[];n.value=new Set;for(const e of i){const i=t.valueType._zod.run({value:e,issues:[]},r);i instanceof Promise?o.push(i.then((e=>lo(e,n)))):lo(i,n)}return o.length?Promise.all(o).then((()=>n)):n}}));function lo(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const uo=Mt("$ZodEnum",((e,t)=>{ri.init(e,t);const n=Wt(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((e=>un.has(typeof e))).map((e=>"string"==typeof e?dn(e):e.toString())).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}})),co=Mt("$ZodLiteral",((e,t)=>{if(ri.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 i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}})),po=Mt("$ZodFile",((e,t)=>{ri.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}})),mo=Mt("$ZodTransform",((e,t)=>{ri.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 Zt;return e.value=r,e}}));function ho(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const go=Mt("$ZodOptional",((e,t)=>{ri.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=>ho(t,e.value))):ho(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}})),fo=Mt("$ZodNullable",((e,t)=>{ri.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)})),vo=Mt("$ZodDefault",((e,t)=>{ri.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=>yo(e,t))):yo(r,t)}}));function yo(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const _o=Mt("$ZodPrefault",((e,t)=>{ri.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))})),bo=Mt("$ZodNonOptional",((e,t)=>{ri.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 i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then((t=>wo(t,e))):wo(i,e)}}));function wo(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 ko=Mt("$ZodSuccess",((e,t)=>{ri.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)}})),xo=Mt("$ZodCatch",((e,t)=>{ri.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=>En(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=>En(e,n,Ft())))},input:e.value}),e.issues=[]),e)}})),Io=Mt("$ZodNaN",((e,t)=>{ri.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)})),So=Mt("$ZodPipe",((e,t)=>{ri.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=>$o(e,t,n))):$o(r,t,n)}}));function $o(e,t,n){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Eo=Mt("$ZodReadonly",((e,t)=>{ri.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(To):To(r)}}));function To(e){return e.value=Object.freeze(e.value),e}const Oo=Mt("$ZodTemplateLiteral",((e,t)=>{ri.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,i=e.endsWith("$")?e.length-1:e.length;n.push(e.slice(t,i))}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)})),No=Mt("$ZodPromise",((e,t)=>{ri.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then((e=>t.innerType._zod.run({value:e,issues:[]},n)))})),Co=Mt("$ZodLazy",((e,t)=>{ri.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)})),Ao=Mt("$ZodCustom",((e,t)=>{Cr.init(e,t),ri.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((t=>Ro(t,n,r,e)));Ro(i,n,r,e)}}));function Ro(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(Nn(e))}}const Uo=()=>{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?`مدخلات غير مقبولة: يفترض إدخال ${hn(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 Po=()=>{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 ${hn(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 jo(e,t,n,r){const i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?r:1===o?t:o>=2&&o<=4?n:r}const zo=()=>{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?`Няправільны ўвод: чакалася ${hn(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${Bt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=jo(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=jo(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 Do=()=>{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 ${hn(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 Mo=()=>{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 ${hn(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 Lo=()=>{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 i={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 ${hn(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${Bt(e.values,"|")}`;case"too_big":{const t=e.inclusive?"<=":"<",i=n(e.origin),o=r(e.origin);return i?`For stor: forventede ${o??"value"} ${i.verb} ${t} ${e.maximum.toString()} ${i.unit??"elementer"}`:`For stor: forventede ${o??"value"} havde ${t} ${e.maximum.toString()}`}case"too_small":{const t=e.inclusive?">=":">",i=n(e.origin),o=r(e.origin);return i?`For lille: forventede ${o} ${i.verb} ${t} ${e.minimum.toString()} ${i.unit}`:`For lille: forventede ${o} 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 ${i[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 Zo=()=>{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 ${hn(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 qo=()=>{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 ${hn(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 Fo(){return{localeError:qo()}}const Wo=()=>{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 ${hn(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 Bo=()=>{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 ${hn(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 Jo=()=>{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?`ورودی نامعتبر: میبایست ${hn(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 Ho=()=>{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 ${hn(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 Vo=()=>{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 : ${hn(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 Ko=()=>{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 ${hn(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 Go=()=>{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?`קלט לא תקין: צריך ${hn(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 Yo=()=>{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 ${hn(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 Xo=()=>{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 ${hn(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 Qo=()=>{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 ${hn(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 ${hn(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?`無効な入力: ${hn(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?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${hn(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?`잘못된 입력: 값은 ${hn(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${Bt(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const n=e.inclusive?"이하":"미만",r="미만"===n?"이어야 합니다":"여야 합니다",i=t(e.origin),o=(null==i?void 0:i.unit)??"요소";return i?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${o} ${n}${r}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${n}${r}`}case"too_small":{const n=e.inclusive?"이상":"초과",r="이상"===n?"이어야 합니다":"여야 합니다",i=t(e.origin),o=(null==i?void 0:i.unit)??"요소";return i?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${o} ${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 is=()=>{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 ${hn(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 os=()=>{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 ${hn(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 ${hn(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 ${hn(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 ls=()=>{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 ${hn(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 us=()=>{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?`ناسم ورودي: باید ${hn(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 ${hn(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 ${hn(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 i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?r:1===o?t:o>=2&&o<=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?`Неверный ввод: ожидалось ${hn(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 hs=()=>{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 ${hn(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 gs=()=>{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 ${hn(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 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:"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?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${hn(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 vs=()=>{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?`ค่าไม่ถูกต้อง: ควรเป็น ${hn(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 ys=()=>{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 ${hn(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 _s=()=>{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?`Неправильні вхідні дані: очікується ${hn(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?`غلط ان پٹ: ${hn(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 ws=()=>{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 ${hn(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 ks=()=>{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?`无效输入:期望 ${hn(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?`無效的輸入值:預期為 ${hn(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 ${hn(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:Uo()}},az:function(){return{localeError:Po()}},be:function(){return{localeError:zo()}},ca:function(){return{localeError:Do()}},cs:function(){return{localeError:Mo()}},da:function(){return{localeError:Lo()}},de:function(){return{localeError:Zo()}},en:Fo,eo:function(){return{localeError:Wo()}},es:function(){return{localeError:Bo()}},fa:function(){return{localeError:Jo()}},fi:function(){return{localeError:Ho()}},fr:function(){return{localeError:Vo()}},frCA:function(){return{localeError:Ko()}},he:function(){return{localeError:Go()}},hu:function(){return{localeError:Yo()}},id:function(){return{localeError:Xo()}},is:function(){return{localeError:Qo()}},it:function(){return{localeError:es()}},ja:function(){return{localeError:ts()}},kh:function(){return{localeError:ns()}},ko:function(){return{localeError:rs()}},mk:function(){return{localeError:is()}},ms:function(){return{localeError:os()}},nl:function(){return{localeError:ss()}},no:function(){return{localeError:as()}},ota:function(){return{localeError:ls()}},pl:function(){return{localeError:cs()}},ps:function(){return{localeError:us()}},pt:function(){return{localeError:ds()}},ru:function(){return{localeError:ms()}},sl:function(){return{localeError:hs()}},sv:function(){return{localeError:gs()}},ta:function(){return{localeError:fs()}},th:function(){return{localeError:vs()}},tr:function(){return{localeError:ys()}},ua:function(){return{localeError:_s()}},ur:function(){return{localeError:bs()}},vi:function(){return{localeError:ws()}},yo:function(){return{localeError:Is()}},zhCN:function(){return{localeError:ks()}},zhTW:function(){return{localeError:xs()}}},Symbol.toStringTag,{value:"Module"})),$s=Symbol("ZodOutput"),Es=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 Os(){return new Ts}const Ns=Os();function Cs(e,t){return new e({type:"string",...mn(t)})}function As(e,t){return new e({type:"string",coerce:!0,...mn(t)})}function Rs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...mn(t)})}function Us(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...mn(t)})}function Ps(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 Zs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...mn(t)})}function qs(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 Bs(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...mn(t)})}function Js(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...mn(t)})}function Hs(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 ia(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...mn(t)})}function oa(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 la(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...mn(t)})}function ua(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 ha(e,t){return new e({type:"boolean",coerce:!0,...mn(t)})}function ga(e,t){return new e({type:"bigint",...mn(t)})}function fa(e,t){return new e({type:"bigint",coerce:!0,...mn(t)})}function va(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...mn(t)})}function ya(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...mn(t)})}function _a(e,t){return new e({type:"symbol",...mn(t)})}function ba(e,t){return new e({type:"undefined",...mn(t)})}function wa(e,t){return new e({type:"null",...mn(t)})}function ka(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 Ea(e,t){return new e({type:"date",coerce:!0,...mn(t)})}function Ta(e,t){return new e({type:"nan",...mn(t)})}function Oa(e,t){return new Rr({check:"less_than",...mn(t),value:e,inclusive:!1})}function Na(e,t){return new Rr({check:"less_than",...mn(t),value:e,inclusive:!0})}function Ca(e,t){return new Ur({check:"greater_than",...mn(t),value:e,inclusive:!1})}function Aa(e,t){return new Ur({check:"greater_than",...mn(t),value:e,inclusive:!0})}function Ra(e){return Ca(0,e)}function Ua(e){return Oa(0,e)}function Pa(e){return Na(0,e)}function ja(e){return Aa(0,e)}function za(e,t){return new Pr({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 Za(e,t){return new Zr({check:"max_length",...mn(t),maximum:e})}function qa(e,t){return new qr({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 Br({check:"string_format",format:"regex",...mn(t),pattern:e})}function Ba(e){return new Jr({check:"string_format",format:"lowercase",...mn(e)})}function Ja(e){return new Hr({check:"string_format",format:"uppercase",...mn(e)})}function Ha(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 ei({check:"overwrite",tx:e})}function Qa(e){return Xa((t=>t.normalize(e)))}function el(){return Xa((e=>e.trim()))}function tl(){return Xa((e=>e.toLowerCase()))}function nl(){return Xa((e=>e.toUpperCase()))}function rl(e,t,n){return new e({type:"array",element:t,...mn(n)})}function il(e,t,n,r){const i=n instanceof ri;return new e({type:"tuple",items:t,rest:i?n:null,...mn(i?r:n)})}function ol(e,t){return new e({type:"file",...mn(t)})}function sl(e,t,n){const r=mn(n);r.abort??(r.abort=!0);return new e({type:"custom",check:"custom",fn:t,...r})}function al(e,t,n){return new e({type:"custom",check:"custom",fn:t,...mn(n)})}function ll(e){const t=ul((n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Nn(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(Nn(r))}},e(n.value,n))));return t}function ul(e,t){const n=new Cr({check:"custom",...mn(t)});return n._zod.check=e,n}function cl(e,t){const n=mn(t);let r=n.truthy??["true","1","yes","on","y","enabled"],i=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(r=r.map((e=>"string"==typeof e?e.toLowerCase():e)),i=i.map((e=>"string"==typeof e?e.toLowerCase():e)));const o=new Set(r),s=new Set(i),a=e.Pipe??So,l=e.Boolean??Pi,u=e.String??ii,c=new(e.Transform??mo)({type:"transform",transform:(e,t)=>{let r=e;return"sensitive"!==n.case&&(r=r.toLowerCase()),!!o.has(r)||!s.has(r)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:t.value,inst:c,continue:!1}),{})},error:n.error}),d=new a({type:"pipe",in:new u({type:"string",error:n.error}),out:c,error:n.error});return new a({type:"pipe",in:d,out:new l({type:"boolean",error:n.error}),error:n.error})}function dl(e,t,n,r={}){const i=mn(r),o={...mn(r),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...i};n instanceof RegExp&&(o.pattern=n);return new e(o)}class pl{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?Zn(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 i=e(...r);return this._def.output?Zn(this._def.output,i,void 0,{callee:t}):i};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 i=await e(...r);return this._def.output?Fn(this._def.output,i,void 0,{callee:t}):i};return t}input(...e){const t=this.constructor;return Array.isArray(e[0])?new t({type:"function",input:new no({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 ml(e){return new pl({type:"function",input:Array.isArray(null==e?void 0:e.input)?il(no,null==e?void 0:e.input):(null==e?void 0:e.input)??rl(Hi,xa(qi)),output:(null==e?void 0:e.output)??xa(qi)})}class hl{constructor(e){this.counter=0,this.metadataRegistry=(null==e?void 0:e.metadata)??Ns,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,i,o;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},l=this.seen.get(e);if(l){l.count++;return t.schemaPath.includes(e)&&(l.cycle=t.path),l.schema}const u={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,u);const c=null==(r=(n=e._zod).toJSONSchema)?void 0:r.call(n);if(c)u.schema=c;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},r=e._zod.parent;if(r)u.ref=r,this.process(r,n),this.seen.get(r).isParent=!0;else{const t=u.schema;switch(s.type){case"string":{const n=t;n.type="string";const{minimum:r,maximum:i,format:o,patterns:s,contentEncoding:l}=e._zod.bag;if("number"==typeof r&&(n.minLength=r),"number"==typeof i&&(n.maxLength=i),o&&(n.format=a[o]??o,""===n.format&&delete n.format),l&&(n.contentEncoding=l),s&&s.size>0){const e=[...s];1===e.length?n.pattern=e[0].source:e.length>1&&(u.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:i,format:o,multipleOf:s,exclusiveMaximum:a,exclusiveMinimum:l}=e._zod.bag;"string"==typeof o&&o.includes("int")?n.type="integer":n.type="number","number"==typeof l&&("draft-4"===this.target?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l),"number"==typeof r&&(n.minimum=r,"number"==typeof l&&"draft-4"!==this.target&&(l>=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 i&&(n.maximum=i,"number"==typeof a&&"draft-4"!==this.target&&(a<=i?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:i,maximum:o}=e._zod.bag;"number"==typeof i&&(r.minItems=i),"number"==typeof o&&(r.maxItems=o),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 o=new Set(Object.keys(r)),a=new Set([...o].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==(i=s.catchall)?void 0:i._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]}),i=this.process(s.right,{...n,path:[...n.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length,a=[...o(r)?r.allOf:[r],...o(i)?i.allOf:[i]];e.allOf=a;break}case"tuple":{const r=t;r.type="array";const i=s.items.map(((e,t)=>this.process(e,{...n,path:[...n.path,"prefixItems",t]})));if("draft-2020-12"===this.target?r.prefixItems=i:r.items=i,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:o,maximum:a}=e._zod.bag;"number"==typeof o&&(r.minItems=o),"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:i,maximum:o,mime:s}=e._zod.bag;void 0!==i&&(r.minLength=i),void 0!==o&&(r.maxLength=o),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),u.ref=s.innerType;break;case"success":t.type="boolean";break;case"default":this.process(s.innerType,n),u.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue));break;case"prefault":this.process(s.innerType,n),u.ref=s.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break;case"catch":{let e;this.process(s.innerType,n),u.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),u.ref=e;break}case"readonly":this.process(s.innerType,n),u.ref=s.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,n),u.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(u.schema,d),"input"===this.io&&fl(e)&&(delete u.schema.examples,delete u.schema.default),"input"===this.io&&u.schema._prefault&&((o=u.schema).default??(o.default=u.schema._prefault)),delete u.schema._prefault;return this.seen.get(e).schema}emit(e,t){var n,r,i,o,s,a;const l={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},u=this.seen.get(e);if(!u)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(l.external){const r=null==(t=l.external.registry.get(e[0]))?void 0:t.id,i=l.external.uri??(e=>e);if(r)return{ref:i(r)};const o=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=o,{defId:o,ref:`${i("__shared")}#/${n}/${o}`}}if(e[1]===u)return{ref:"#"};const r=`#/${n}/`,i=e[1].schema.id??"__schema"+this.counter++;return{defId:i,ref:r+i}},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 i=t.schema;for(const o in i)delete i[o];i.$ref=n};if("throw"===l.cycles)for(const f of this.seen.entries()){const e=f[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 f of this.seen.entries()){const t=f[1];if(e===f[0]){d(f);continue}if(l.external){const t=null==(r=l.external.registry.get(f[0]))?void 0:r.id;if(e!==f[0]&&t){d(f);continue}}(null==(i=this.metadataRegistry.get(f[0]))?void 0:i.id)?d(f):(t.cycle||t.count>1&&"ref"===l.reused)&&d(f)}const p=(e,t)=>{const n=this.seen.get(e),r=n.def??n.schema,i={...r};if(null===n.ref)return;const o=n.ref;if(n.ref=null,o){p(o,t);const e=this.seen.get(o).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target?(Object.assign(r,e),Object.assign(r,i)):(r.allOf=r.allOf??[],r.allOf.push(e))}n.isParent||this.override({zodSchema:e,jsonSchema:r,path:n.path??[]})};for(const f of[...this.seen.entries()].reverse())p(f[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==(o=l.external)?void 0:o.uri){const t=null==(s=l.external.registry.get(e))?void 0:s.id;if(!t)throw new Error("Schema is missing an `id` property");m.$id=l.external.uri(t)}Object.assign(m,u.def);const h=(null==(a=l.external)?void 0:a.defs)??{};for(const f of this.seen.entries()){const e=f[1];e.def&&e.defId&&(h[e.defId]=e.def)}l.external||Object.keys(h).length>0&&("draft-2020-12"===this.target?m.$defs=h:m.definitions=h);try{return JSON.parse(JSON.stringify(m))}catch(g){throw new Error("Error converting schema to JSON.")}}}function gl(e,t){if(e instanceof Ts){const n=new hl(t),r={};for(const t of e._idmap.entries()){const[e,r]=t;n.process(r)}const i={},o={registry:e,uri:null==t?void 0:t.uri,defs:r};for(const s of e._idmap.entries()){const[e,r]=s;i[e]=n.emit(r,{...t,external:o})}if(Object.keys(r).length>0){const e="draft-2020-12"===n.target?"$defs":"definitions";i.__shared={[e]:r}}return{schemas:i}}const n=new hl(t);return n.process(e),n.emit(e,t)}function fl(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 fl(r.element,n);case"object":for(const e in r.shape)if(fl(r.shape[e],n))return!0;return!1;case"union":for(const e of r.options)if(fl(e,n))return!0;return!1;case"intersection":return fl(r.left,n)||fl(r.right,n);case"tuple":for(const e of r.items)if(fl(e,n))return!0;return!(!r.rest||!fl(r.rest,n));case"record":case"map":return fl(r.keyType,n)||fl(r.valueType,n);case"set":return fl(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return fl(r.innerType,n);case"lazy":return fl(r.getter(),n);case"transform":return!0;case"pipe":return fl(r.in,n)||fl(r.out,n)}throw new Error(`Unknown schema type: ${r.type}`)}const vl=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),yl=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Zi,$ZodArray:Hi,$ZodAsyncError:Zt,$ZodBase64:$i,$ZodBase64URL:Ti,$ZodBigInt:ji,$ZodBigIntFormat:zi,$ZodBoolean:Pi,$ZodCIDRv4:xi,$ZodCIDRv6:Ii,$ZodCUID:pi,$ZodCUID2:mi,$ZodCatch:xo,$ZodCheck:Cr,$ZodCheckBigIntFormat:zr,$ZodCheckEndsWith:Gr,$ZodCheckGreaterThan:Ur,$ZodCheckIncludes:Vr,$ZodCheckLengthEquals:Fr,$ZodCheckLessThan:Rr,$ZodCheckLowerCase:Jr,$ZodCheckMaxLength:Zr,$ZodCheckMaxSize:Dr,$ZodCheckMimeType:Qr,$ZodCheckMinLength:qr,$ZodCheckMinSize:Mr,$ZodCheckMultipleOf:Pr,$ZodCheckNumberFormat:jr,$ZodCheckOverwrite:ei,$ZodCheckProperty:Xr,$ZodCheckRegex:Br,$ZodCheckSizeEquals:Lr,$ZodCheckStartsWith:Kr,$ZodCheckStringFormat:Wr,$ZodCheckUpperCase:Hr,$ZodCustom:Ao,$ZodCustomStringFormat:Ai,$ZodDate:Bi,$ZodDefault:vo,$ZodDiscriminatedUnion:Xi,$ZodE164:Oi,$ZodEmail:li,$ZodEmoji:ci,$ZodEnum:uo,$ZodError:Rn,$ZodFile:po,$ZodFunction:pl,$ZodGUID:si,$ZodIPv4:wi,$ZodIPv6:ki,$ZodISODate:yi,$ZodISODateTime:vi,$ZodISODuration:bi,$ZodISOTime:_i,$ZodIntersection:Qi,$ZodJWT:Ci,$ZodKSUID:fi,$ZodLazy:Co,$ZodLiteral:co,$ZodMap:oo,$ZodNaN:Io,$ZodNanoID:di,$ZodNever:Fi,$ZodNonOptional:bo,$ZodNull:Li,$ZodNullable:fo,$ZodNumber:Ri,$ZodNumberFormat:Ui,$ZodObject:Ki,$ZodOptional:go,$ZodPipe:So,$ZodPrefault:_o,$ZodPromise:No,$ZodReadonly:Eo,$ZodRealError:Un,$ZodRecord:io,$ZodRegistry:Ts,$ZodSet:ao,$ZodString:ii,$ZodStringFormat:oi,$ZodSuccess:ko,$ZodSymbol:Di,$ZodTemplateLiteral:Oo,$ZodTransform:mo,$ZodTuple:no,$ZodType:ri,$ZodULID:hi,$ZodURL:ui,$ZodUUID:ai,$ZodUndefined:Mi,$ZodUnion:Yi,$ZodUnknown:qi,$ZodVoid:Wi,$ZodXID:gi,$brand:Lt,$constructor:Mt,$input:Es,$output:$s,Doc:ti,JSONSchema:vl,JSONSchemaGenerator:hl,NEVER:Dt,TimePrecision:ta,_any:ka,_array:rl,_base64:Ys,_base64url:Xs,_bigint:ga,_boolean:ma,_catch:function(e,t,n){return new e({type:"catch",innerType:t,catchValue:"function"==typeof n?n:()=>n})},_check:ul,_cidrv4:Ks,_cidrv6:Gs,_coercedBigint:fa,_coercedBoolean:ha,_coercedDate:Ea,_coercedNumber:aa,_coercedString:As,_cuid:qs,_cuid2:Fs,_custom:sl,_date:$a,_default:function(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof n?n():ln(n)}})},_discriminatedUnion:function(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...mn(r)})},_e164:Qs,_email:Rs,_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:ol,_float32:ua,_float64:ca,_gt:Ca,_gte:Aa,_guid:Us,_includes:Ha,_int:la,_int32:da,_int64:va,_intersection:function(e,t,n){return new e({type:"intersection",left:t,right:n})},_ipv4:Hs,_ipv6:Vs,_isoDate:ra,_isoDateTime:na,_isoDuration:oa,_isoTime:ia,_jwt:ea,_ksuid:Js,_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:Oa,_lte:Na,_map:function(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...mn(r)})},_max:Na,_maxLength:Za,_maxSize:Da,_mime:Ya,_min:Aa,_minLength:qa,_minSize:Ma,_multipleOf:za,_nan:Ta,_nanoid:Zs,_nativeEnum:function(e,t,n){return new e({type:"enum",entries:t,...mn(n)})},_negative:Ua,_never:Ia,_nonnegative:ja,_nonoptional:function(e,t,n){return new e({type:"nonoptional",innerType:t,...mn(n)})},_nonpositive:Pa,_normalize:Qa,_null:wa,_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:qn,_pipe:function(e,t,n){return new e({type:"pipe",in:t,out:n})},_positive:Ra,_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:al,_regex:Wa,_safeParse:Wn,_safeParseAsync:Jn,_set:function(e,t,n){return new e({type:"set",valueType:t,...mn(n)})},_size:La,_startsWith:Va,_string:Cs,_stringFormat:dl,_stringbool:cl,_success:function(e,t){return new e({type:"success",innerType:t})},_superRefine:ll,_symbol:_a,_templateLiteral:function(e,t,n){return new e({type:"template_literal",parts:t,...mn(n)})},_toLowerCase:tl,_toUpperCase:nl,_transform:function(e,t){return new e({type:"transform",transform:t})},_trim:el,_tuple:il,_uint32:pa,_uint64:ya,_ulid:Ws,_undefined:ba,_union:function(e,t,n){return new e({type:"union",options:t,...mn(n)})},_unknown:xa,_uppercase:Ja,_url:Ms,_uuid:Ps,_uuidv4:js,_uuidv6:zs,_uuidv7:Ds,_void:Sa,_xid:Bs,clone:pn,config:Ft,flattenError:Pn,formatError:jn,function:ml,globalConfig:qt,globalRegistry:Ns,isValidBase64:Si,isValidBase64URL:Ei,isValidJWT:Ni,locales:Ss,parse:Zn,parseAsync:Fn,prettifyError:Mn,regexes:Nr,registry:Os,safeParse:Bn,safeParseAsync:Hn,toDotPath:Dn,toJSONSchema:gl,treeifyError:zn,util:Cn,version:ni},Symbol.toStringTag,{value:"Module"})),_l=Mt("ZodISODateTime",((e,t)=>{vi.init(e,t),Ml.init(e,t)}));function bl(e){return na(_l,e)}const wl=Mt("ZodISODate",((e,t)=>{yi.init(e,t),Ml.init(e,t)}));function kl(e){return ra(wl,e)}const xl=Mt("ZodISOTime",((e,t)=>{_i.init(e,t),Ml.init(e,t)}));function Il(e){return ia(xl,e)}const Sl=Mt("ZodISODuration",((e,t)=>{bi.init(e,t),Ml.init(e,t)}));function $l(e){return oa(Sl,e)}const El=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:wl,ZodISODateTime:_l,ZodISODuration:Sl,ZodISOTime:xl,date:kl,datetime:bl,duration:$l,time:Il},Symbol.toStringTag,{value:"Module"})),Tl=(e,t)=>{Rn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>jn(e,t)},flatten:{value:t=>Pn(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Jt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Jt,2)}},isEmpty:{get:()=>0===e.issues.length}})},Ol=Mt("ZodError",Tl),Nl=Mt("ZodError",Tl,{Parent:Error}),Cl=Ln(Nl),Al=qn(Nl),Rl=Wn(Nl),Ul=Jn(Nl),Pl=Mt("ZodType",((e,t)=>(ri.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)=>Cl(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Rl(e,t,n),e.parseAsync=async(t,n)=>Al(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ul(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(kc(t,n)),e.superRefine=t=>e.check(xc(t)),e.overwrite=t=>e.check(Xa(t)),e.optional=()=>Qu(e),e.nullable=()=>tc(e),e.nullish=()=>Qu(tc(e)),e.nonoptional=t=>ac(e,t),e.array=()=>Tu(e),e.or=t=>Uu([e,t]),e.and=t=>Du(e,t),e.transform=t=>mc(e,Yu(t)),e.default=t=>rc(e,t),e.prefault=t=>oc(e,t),e.catch=t=>cc(e,t),e.pipe=t=>mc(e,t),e.readonly=()=>gc(e),e.describe=t=>{const n=e.clone();return Ns.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){var t;return null==(t=Ns.get(e))?void 0:t.description},configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Ns.get(e);const n=e.clone();return Ns.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),jl=Mt("_ZodString",((e,t)=>{ii.init(e,t),Pl.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(Ha(...t)),e.startsWith=(...t)=>e.check(Va(...t)),e.endsWith=(...t)=>e.check(Ka(...t)),e.min=(...t)=>e.check(qa(...t)),e.max=(...t)=>e.check(Za(...t)),e.length=(...t)=>e.check(Fa(...t)),e.nonempty=(...t)=>e.check(qa(1,...t)),e.lowercase=t=>e.check(Ba(t)),e.uppercase=t=>e.check(Ja(t)),e.trim=()=>e.check(el()),e.normalize=(...t)=>e.check(Qa(...t)),e.toLowerCase=()=>e.check(tl()),e.toUpperCase=()=>e.check(nl())})),zl=Mt("ZodString",((e,t)=>{ii.init(e,t),jl.init(e,t),e.email=t=>e.check(Rs(Ll,t)),e.url=t=>e.check(Ms(Fl,t)),e.jwt=t=>e.check(ea(ou,t)),e.emoji=t=>e.check(Ls(Wl,t)),e.guid=t=>e.check(Us(Zl,t)),e.uuid=t=>e.check(Ps(ql,t)),e.uuidv4=t=>e.check(js(ql,t)),e.uuidv6=t=>e.check(zs(ql,t)),e.uuidv7=t=>e.check(Ds(ql,t)),e.nanoid=t=>e.check(Zs(Bl,t)),e.guid=t=>e.check(Us(Zl,t)),e.cuid=t=>e.check(qs(Jl,t)),e.cuid2=t=>e.check(Fs(Hl,t)),e.ulid=t=>e.check(Ws(Vl,t)),e.base64=t=>e.check(Ys(tu,t)),e.base64url=t=>e.check(Xs(ru,t)),e.xid=t=>e.check(Bs(Kl,t)),e.ksuid=t=>e.check(Js(Gl,t)),e.ipv4=t=>e.check(Hs(Yl,t)),e.ipv6=t=>e.check(Vs(Xl,t)),e.cidrv4=t=>e.check(Ks(Ql,t)),e.cidrv6=t=>e.check(Gs(eu,t)),e.e164=t=>e.check(Qs(iu,t)),e.datetime=t=>e.check(bl(t)),e.date=t=>e.check(kl(t)),e.time=t=>e.check(Il(t)),e.duration=t=>e.check($l(t))}));function Dl(e){return Cs(zl,e)}const Ml=Mt("ZodStringFormat",((e,t)=>{oi.init(e,t),jl.init(e,t)})),Ll=Mt("ZodEmail",((e,t)=>{li.init(e,t),Ml.init(e,t)}));const Zl=Mt("ZodGUID",((e,t)=>{si.init(e,t),Ml.init(e,t)}));const ql=Mt("ZodUUID",((e,t)=>{ai.init(e,t),Ml.init(e,t)}));const Fl=Mt("ZodURL",((e,t)=>{ui.init(e,t),Ml.init(e,t)}));const Wl=Mt("ZodEmoji",((e,t)=>{ci.init(e,t),Ml.init(e,t)}));const Bl=Mt("ZodNanoID",((e,t)=>{di.init(e,t),Ml.init(e,t)}));const Jl=Mt("ZodCUID",((e,t)=>{pi.init(e,t),Ml.init(e,t)}));const Hl=Mt("ZodCUID2",((e,t)=>{mi.init(e,t),Ml.init(e,t)}));const Vl=Mt("ZodULID",((e,t)=>{hi.init(e,t),Ml.init(e,t)}));const Kl=Mt("ZodXID",((e,t)=>{gi.init(e,t),Ml.init(e,t)}));const Gl=Mt("ZodKSUID",((e,t)=>{fi.init(e,t),Ml.init(e,t)}));const Yl=Mt("ZodIPv4",((e,t)=>{wi.init(e,t),Ml.init(e,t)}));const Xl=Mt("ZodIPv6",((e,t)=>{ki.init(e,t),Ml.init(e,t)}));const Ql=Mt("ZodCIDRv4",((e,t)=>{xi.init(e,t),Ml.init(e,t)}));const eu=Mt("ZodCIDRv6",((e,t)=>{Ii.init(e,t),Ml.init(e,t)}));const tu=Mt("ZodBase64",((e,t)=>{$i.init(e,t),Ml.init(e,t)}));function nu(e){return Ys(tu,e)}const ru=Mt("ZodBase64URL",((e,t)=>{Ti.init(e,t),Ml.init(e,t)}));const iu=Mt("ZodE164",((e,t)=>{Oi.init(e,t),Ml.init(e,t)}));const ou=Mt("ZodJWT",((e,t)=>{Ci.init(e,t),Ml.init(e,t)}));const su=Mt("ZodCustomStringFormat",((e,t)=>{Ai.init(e,t),Ml.init(e,t)}));const au=Mt("ZodNumber",((e,t)=>{Ri.init(e,t),Pl.init(e,t),e.gt=(t,n)=>e.check(Ca(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(Oa(t,n)),e.lte=(t,n)=>e.check(Na(t,n)),e.max=(t,n)=>e.check(Na(t,n)),e.int=t=>e.check(cu(t)),e.safe=t=>e.check(cu(t)),e.positive=t=>e.check(Ca(0,t)),e.nonnegative=t=>e.check(Aa(0,t)),e.negative=t=>e.check(Oa(0,t)),e.nonpositive=t=>e.check(Na(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 lu(e){return sa(au,e)}const uu=Mt("ZodNumberFormat",((e,t)=>{Ui.init(e,t),au.init(e,t)}));function cu(e){return la(uu,e)}const du=Mt("ZodBoolean",((e,t)=>{Pi.init(e,t),Pl.init(e,t)}));function pu(e){return ma(du,e)}const mu=Mt("ZodBigInt",((e,t)=>{ji.init(e,t),Pl.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(Ca(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(Oa(t,n)),e.lte=(t,n)=>e.check(Na(t,n)),e.max=(t,n)=>e.check(Na(t,n)),e.positive=t=>e.check(Ca(BigInt(0),t)),e.negative=t=>e.check(Oa(BigInt(0),t)),e.nonpositive=t=>e.check(Na(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 hu=Mt("ZodBigIntFormat",((e,t)=>{zi.init(e,t),mu.init(e,t)}));const gu=Mt("ZodSymbol",((e,t)=>{Di.init(e,t),Pl.init(e,t)}));const fu=Mt("ZodUndefined",((e,t)=>{Mi.init(e,t),Pl.init(e,t)}));const vu=Mt("ZodNull",((e,t)=>{Li.init(e,t),Pl.init(e,t)}));function yu(e){return wa(vu,e)}const _u=Mt("ZodAny",((e,t)=>{Zi.init(e,t),Pl.init(e,t)}));function bu(){return ka(_u)}const wu=Mt("ZodUnknown",((e,t)=>{qi.init(e,t),Pl.init(e,t)}));function ku(){return xa(wu)}const xu=Mt("ZodNever",((e,t)=>{Fi.init(e,t),Pl.init(e,t)}));function Iu(e){return Ia(xu,e)}const Su=Mt("ZodVoid",((e,t)=>{Wi.init(e,t),Pl.init(e,t)}));const $u=Mt("ZodDate",((e,t)=>{Bi.init(e,t),Pl.init(e,t),e.min=(t,n)=>e.check(Aa(t,n)),e.max=(t,n)=>e.check(Na(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 Eu=Mt("ZodArray",((e,t)=>{Hi.init(e,t),Pl.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(qa(t,n)),e.nonempty=t=>e.check(qa(1,t)),e.max=(t,n)=>e.check(Za(t,n)),e.length=(t,n)=>e.check(Fa(t,n)),e.unwrap=()=>e.element}));function Tu(e,t){return rl(Eu,e,t)}const Ou=Mt("ZodObject",((e,t)=>{Ki.init(e,t),Pl.init(e,t),Xt(e,"shape",(()=>t.shape)),e.keyof=()=>Ju(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ku()}),e.loose=()=>e.clone({...e._zod.def,catchall:ku()}),e.strict=()=>e.clone({...e._zod.def,catchall:Iu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>bn(e,t),e.merge=t=>wn(e,t),e.pick=t=>yn(e,t),e.omit=t=>_n(e,t),e.partial=(...t)=>kn(Xu,e,t[0]),e.required=(...t)=>xn(sc,e,t[0])}));function Nu(e,t){const n={type:"object",get shape(){return en(this,"shape",e?Qt(e):{}),this.shape},...mn(t)};return new Ou(n)}function Cu(e,t){return new Ou({type:"object",get shape(){return en(this,"shape",Qt(e)),this.shape},catchall:Iu(),...mn(t)})}function Au(e,t){return new Ou({type:"object",get shape(){return en(this,"shape",Qt(e)),this.shape},catchall:ku(),...mn(t)})}const Ru=Mt("ZodUnion",((e,t)=>{Yi.init(e,t),Pl.init(e,t),e.options=t.options}));function Uu(e,t){return new Ru({type:"union",options:e,...mn(t)})}const Pu=Mt("ZodDiscriminatedUnion",((e,t)=>{Ru.init(e,t),Xi.init(e,t)}));function ju(e,t,n){return new Pu({type:"union",options:t,discriminator:e,...mn(n)})}const zu=Mt("ZodIntersection",((e,t)=>{Qi.init(e,t),Pl.init(e,t)}));function Du(e,t){return new zu({type:"intersection",left:e,right:t})}const Mu=Mt("ZodTuple",((e,t)=>{no.init(e,t),Pl.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})}));function Lu(e,t,n){const r=t instanceof ri;return new Mu({type:"tuple",items:e,rest:r?t:null,...mn(r?n:t)})}const Zu=Mt("ZodRecord",((e,t)=>{io.init(e,t),Pl.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));function qu(e,t,n){return new Zu({type:"record",keyType:e,valueType:t,...mn(n)})}const Fu=Mt("ZodMap",((e,t)=>{oo.init(e,t),Pl.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));const Wu=Mt("ZodSet",((e,t)=>{ao.init(e,t),Pl.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 Bu=Mt("ZodEnum",((e,t)=>{uo.init(e,t),Pl.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 i={};for(const o of e){if(!n.has(o))throw new Error(`Key ${o} not found in enum`);i[o]=t.entries[o]}return new Bu({...t,checks:[],...mn(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new Bu({...t,checks:[],...mn(r),entries:i})}}));function Ju(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new Bu({type:"enum",entries:n,...mn(t)})}const Hu=Mt("ZodLiteral",((e,t)=>{co.init(e,t),Pl.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 Vu(e,t){return new Hu({type:"literal",values:Array.isArray(e)?e:[e],...mn(t)})}const Ku=Mt("ZodFile",((e,t)=>{po.init(e,t),Pl.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 Gu=Mt("ZodTransform",((e,t)=>{mo.init(e,t),Pl.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if("string"==typeof r)n.issues.push(Nn(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(Nn(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then((e=>(n.value=e,n))):(n.value=i,n)}}));function Yu(e){return new Gu({type:"transform",transform:e})}const Xu=Mt("ZodOptional",((e,t)=>{go.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function Qu(e){return new Xu({type:"optional",innerType:e})}const ec=Mt("ZodNullable",((e,t)=>{fo.init(e,t),Pl.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)=>{vo.init(e,t),Pl.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():ln(t)}})}const ic=Mt("ZodPrefault",((e,t)=>{_o.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function oc(e,t){return new ic({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():ln(t)}})}const sc=Mt("ZodNonOptional",((e,t)=>{bo.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ac(e,t){return new sc({type:"nonoptional",innerType:e,...mn(t)})}const lc=Mt("ZodSuccess",((e,t)=>{ko.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const uc=Mt("ZodCatch",((e,t)=>{xo.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));function cc(e,t){return new uc({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const dc=Mt("ZodNaN",((e,t)=>{Io.init(e,t),Pl.init(e,t)}));const pc=Mt("ZodPipe",((e,t)=>{So.init(e,t),Pl.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 hc=Mt("ZodReadonly",((e,t)=>{Eo.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function gc(e){return new hc({type:"readonly",innerType:e})}const fc=Mt("ZodTemplateLiteral",((e,t)=>{Oo.init(e,t),Pl.init(e,t)}));const vc=Mt("ZodLazy",((e,t)=>{Co.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.getter()}));function yc(e){return new vc({type:"lazy",getter:e})}const _c=Mt("ZodPromise",((e,t)=>{No.init(e,t),Pl.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const bc=Mt("ZodCustom",((e,t)=>{Ao.init(e,t),Pl.init(e,t)}));function wc(e,t){return sl(bc,e??(()=>!0),t)}function kc(e,t={}){return al(bc,e,t)}function xc(e){return ll(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(au,e)}Sc||(Sc={});const Ec=Object.freeze(Object.defineProperty({__proto__:null,bigint:function(e){return fa(mu,e)},boolean:function(e){return ha(du,e)},date:function(e){return Ea($u,e)},number:$c,string:function(e){return As(zl,e)}},Symbol.toStringTag,{value:"Module"}));Ft(Fo());const Tc=Object.freeze(Object.defineProperty({__proto__:null,$brand:Lt,$input:Es,$output:$s,NEVER:Dt,TimePrecision:ta,ZodAny:_u,ZodArray:Eu,ZodBase64:tu,ZodBase64URL:ru,ZodBigInt:mu,ZodBigIntFormat:hu,ZodBoolean:du,ZodCIDRv4:Ql,ZodCIDRv6:eu,ZodCUID:Jl,ZodCUID2:Hl,ZodCatch:uc,ZodCustom:bc,ZodCustomStringFormat:su,ZodDate:$u,ZodDefault:nc,ZodDiscriminatedUnion:Pu,ZodE164:iu,ZodEmail:Ll,ZodEmoji:Wl,ZodEnum:Bu,ZodError:Ol,ZodFile:Ku,get ZodFirstPartyTypeKind(){return Sc},ZodGUID:Zl,ZodIPv4:Yl,ZodIPv6:Xl,ZodISODate:wl,ZodISODateTime:_l,ZodISODuration:Sl,ZodISOTime:xl,ZodIntersection:zu,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:ou,ZodKSUID:Gl,ZodLazy:vc,ZodLiteral:Hu,ZodMap:Fu,ZodNaN:dc,ZodNanoID:Bl,ZodNever:xu,ZodNonOptional:sc,ZodNull:vu,ZodNullable:ec,ZodNumber:au,ZodNumberFormat:uu,ZodObject:Ou,ZodOptional:Xu,ZodPipe:pc,ZodPrefault:ic,ZodPromise:_c,ZodReadonly:hc,ZodRealError:Nl,ZodRecord:Zu,ZodSet:Wu,ZodString:zl,ZodStringFormat:Ml,ZodSuccess:lc,ZodSymbol:gu,ZodTemplateLiteral:fc,ZodTransform:Gu,ZodTuple:Mu,ZodType:Pl,ZodULID:Vl,ZodURL:Fl,ZodUUID:ql,ZodUndefined:fu,ZodUnion:Ru,ZodUnknown:wu,ZodVoid:Su,ZodXID:Kl,_ZodString:jl,_default:rc,any:bu,array:Tu,base64:nu,base64url:function(e){return Xs(ru,e)},bigint:function(e){return ga(mu,e)},boolean:pu,catch:cc,check:function(e){const t=new Cr({check:"custom"});return t._zod.check=e,t},cidrv4:function(e){return Ks(Ql,e)},cidrv6:function(e){return Gs(eu,e)},clone:pn,coerce:Ec,config:Ft,core:yl,cuid:function(e){return qs(Jl,e)},cuid2:function(e){return Fs(Hl,e)},custom:wc,date:function(e){return $a($u,e)},discriminatedUnion:ju,e164:function(e){return Qs(iu,e)},email:function(e){return Rs(Ll,e)},emoji:function(e){return Ls(Wl,e)},endsWith:Ka,enum:Ju,file:function(e){return ol(Ku,e)},flattenError:Pn,float32:function(e){return ua(uu,e)},float64:function(e){return ca(uu,e)},formatError:jn,function:ml,getErrorMap:function(){return Ft().customError},globalRegistry:Ns,gt:Ca,gte:Aa,guid:function(e){return Us(Zl,e)},hostname:function(e){return dl(su,"hostname",hr,e)},includes:Ha,instanceof:Ic,int:cu,int32:function(e){return da(uu,e)},int64:function(e){return va(hu,e)},intersection:Du,ipv4:function(e){return Hs(Yl,e)},ipv6:function(e){return Vs(Xl,e)},iso:El,json:function(e){const t=yc((()=>Uu([Dl(e),lu(),pu(),yu(),Tu(t),qu(Dl(),t)])));return t},jwt:function(e){return ea(ou,e)},keyof:function(e){const t=e._zod.def.shape;return Ju(Object.keys(t))},ksuid:function(e){return Js(Gl,e)},lazy:yc,length:Fa,literal:Vu,locales:Ss,looseObject:Au,lowercase:Ba,lt:Oa,lte:Na,map:function(e,t,n){return new Fu({type:"map",keyType:e,valueType:t,...mn(n)})},maxLength:Za,maxSize:Da,mime:Ya,minLength:qa,minSize:Ma,multipleOf:za,nan:function(e){return Ta(dc,e)},nanoid:function(e){return Zs(Bl,e)},nativeEnum:function(e,t){return new Bu({type:"enum",entries:e,...mn(t)})},negative:Ua,never:Iu,nonnegative:ja,nonoptional:ac,nonpositive:Pa,normalize:Qa,null:yu,nullable:tc,nullish:function(e){return Qu(tc(e))},number:lu,object:Nu,optional:Qu,overwrite:Xa,parse:Cl,parseAsync:Al,partialRecord:function(e,t,n){const r=pn(e);return r._zod.values=void 0,new Zu({type:"record",keyType:r,valueType:t,...mn(n)})},pipe:mc,positive:Ra,prefault:oc,preprocess:function(e,t){return mc(Yu(e),t)},prettifyError:Mn,promise:function(e){return new _c({type:"promise",innerType:e})},property:Ga,readonly:gc,record:qu,refine:kc,regex:Wa,regexes:Nr,registry:Os,safeParse:Rl,safeParseAsync:Ul,set:function(e,t){return new Wu({type:"set",valueType:e,...mn(t)})},setErrorMap:function(e){Ft({customError:e})},size:La,startsWith:Va,strictObject:Cu,string:Dl,stringFormat:function(e,t,n={}){return dl(su,e,t,n)},stringbool:(...e)=>cl({Pipe:pc,Boolean:du,String:zl,Transform:Gu},...e),success:function(e){return new lc({type:"success",innerType:e})},superRefine:xc,symbol:function(e){return _a(gu,e)},templateLiteral:function(e,t){return new fc({type:"template_literal",parts:e,...mn(t)})},toJSONSchema:gl,toLowerCase:tl,toUpperCase:nl,transform:Yu,treeifyError:zn,trim:el,tuple:Lu,uint32:function(e){return pa(uu,e)},uint64:function(e){return ya(hu,e)},ulid:function(e){return Ws(Vl,e)},undefined:function(e){return ba(fu,e)},union:Uu,unknown:ku,uppercase:Ja,url:function(e){return Ms(Fl,e)},uuid:function(e){return Ps(ql,e)},uuidv4:function(e){return js(ql,e)},uuidv6:function(e){return zs(ql,e)},uuidv7:function(e){return Ds(ql,e)},void:function(e){return Sa(Su,e)},xid:function(e){return Bs(Kl,e)}},Symbol.toStringTag,{value:"Module"})),Oc=Symbol("Let zodToJsonSchema decide on which parser to use"),Nc={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"},Cc=e=>{const t=(e=>"string"==typeof e?{...Nc,name:e}:{...Nc,...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 Rc(e,t,n,r,i){e[t]=n,Ac(e,t,r,i)}const Uc=(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 Pc(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Uc(t,e.currentPath):t.join("/")}}function jc(e,t){return ud(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":Rc(n,"minimum",r.value,r.message,t);break;case"max":Rc(n,"maximum",r.value,r.message,t)}return n};let Mc;const Lc=/^[cC][^\s-]{8,}$/,Zc=/^[0-9a-z]+$/,qc=/^[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),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])$/,Jc=/^(([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])$/,Hc=/^([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":Rc(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Rc(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,Zc,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":Rc(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Rc(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,Jc,r.message,t);break;case"emoji":td(n,Wc(),r.message,t);break;case"ulid":td(n,qc,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":ed(n,"binary",r.message,t);break;case"contentEncoding:base64":Rc(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":td(n,Hc,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 i;e.format||(null==(i=e.anyOf)?void 0:i.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}}})):Rc(e,"format",t,n,r)}function td(e,t,n,r){var i;e.pattern||(null==(i=e.allOf)?void 0:i.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}}})):Rc(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"),i=e.flags.includes("m"),o=e.flags.includes("s"),s=r?e.source.toLowerCase():e.source;let a="",l=!1,u=!1,c=!1;for(let d=0;d<s.length;d++)if(l)a+=s[d],l=!1;else{if(r)if(u){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(i){if("^"===s[d]){a+="(^|(?<=[\r\n]))";continue}if("$"===s[d]){a+="($|(?=[\r\n]))";continue}}o&&"."===s[d]?a+=u?`${s[d]}\r\n`:`[${s[d]}\r\n]`:(a+=s[d],"\\"===s[d]?l=!0:u&&"]"===s[d]?u=!1:u||"["!==s[d]||(u=!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,i,o,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]:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Pc(t)})),{}),additionalProperties:t.rejectedAdditionalProperties};const l={type:"object",additionalProperties:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return l;if((null==(r=e.keyType)?void 0:r._def.typeName)===Sc.ZodString&&(null==(i=e.keyType._def.checks)?void 0:i.length)){const{type:n,...r}=Yc(e.keyType._def,t);return{...l,propertyNames:r}}if((null==(o=e.keyType)?void 0:o._def.typeName)===Sc.ZodEnum)return{...l,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{...l,propertyNames:r}}return l}const id={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const od=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,n)=>ud(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:{}},i=[],o=e.shape();for(const a in o){let e=o[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 l=ud(e._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});void 0!==l&&(r.properties[a]=l,s||i.push(a))}i.length&&(r.required=i);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ud(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 ld=(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?Rc(n,"minimum",r.value,r.message,t):Rc(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Rc(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Rc(n,"maximum",r.value,r.message,t):Rc(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Rc(n,"maximum",r.value,r.message,t));break;case"multipleOf":Rc(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?Rc(n,"minimum",r.value,r.message,t):Rc(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Rc(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Rc(n,"maximum",r.value,r.message,t):Rc(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Rc(n,"maximum",r.value,r.message,t));break;case"multipleOf":Rc(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:Pc(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,i;const o={type:"array"};return(null==(n=e.type)?void 0:n._def)&&(null==(i=null==(r=e.type)?void 0:r._def)?void 0:i.typeName)!==Sc.ZodAny&&(o.items=ud(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Rc(o,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Rc(o,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Rc(o,"minItems",e.exactLength.value,e.exactLength.message,t),Rc(o,"maxItems",e.exactLength.value,e.exactLength.message,t)),o}(e,n);case Sc.ZodUnion:case Sc.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return od(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((e=>e._def.typeName in id&&(!e._def.checks||!e._def.checks.length)))){const e=n.reduce(((e,t)=>{const n=id[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 od(e,t)}(e,n);case Sc.ZodIntersection:return function(e,t){const n=[ud(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ud(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const i=[];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;i.push(t)}else i.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t})),i.length?{allOf:i,...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)=>ud(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:ud(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,n)=>ud(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:id[e.innerType._def.typeName],nullable:!0}:{type:[id[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=ud(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ud(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 ud(e.innerType._def,t);const r=ud(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Pc(t)},r]}:Pc(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:[ud(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Pc(t),ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Pc(t)],minItems:2,maxItems:2}}}(e,n);case Sc.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Rc(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Rc(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 ud(e.type._def,t)}(e,n);case Sc.ZodNaN:case Sc.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Pc({...e,currentPath:[...e.currentPath,"not"]})}}(n);case Sc.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ud(e.schema._def,t):Pc(t)}(e,n);case Sc.ZodAny:return Pc(n);case Sc.ZodUnknown:return function(e){return Pc(e)}(n);case Sc.ZodDefault:return function(e,t){return{...ud(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)=>ud(e.innerType._def,t))(e,n);case Sc.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ud(e.in._def,t);if("output"===t.pipeStrategy)return ud(e.out._def,t);const n=ud(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ud(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 ud(e,t,n=!1){var r;const i=t.seen.get(e);if(t.override){const o=null==(r=t.override)?void 0:r.call(t,e,t,i,n);if(o!==Oc)return o}if(i&&!n){const e=cd(i,t);if(void 0!==e)return e}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=ld(e,e.typeName,t),a="function"==typeof s?ud(s(),t):s;if(a&&dd(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return o.jsonSchema=a,n}return o.jsonSchema=a,a}const cd=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Uc(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`),Pc(t)):"seen"===t.$refStrategy?Pc(t):void 0}},dd=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function pd(...e){return e.reduce(((e,t)=>({...e,...null!=t?t:{}})),{})}function md(e){return Object.fromEntries([...e.headers])}var hd=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const i=()=>{const e=n.length,r=new Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join("")};if(null==e)return i;if(n.includes(r))throw new He({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},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 _d=/"__proto__"\s*:/,bd=/"constructor"\s*:/;function wd(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===_d.test(e)&&!1===bd.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 kd(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return wd(e)}finally{Error.stackTraceLimit=t}}var xd=Symbol.for("vercel.ai.validator");function Id(e){return function(e){return"object"==typeof e&&null!==e&&xd in e&&!0===e[xd]&&"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 Ot({value:e,cause:n.issues})}},{[xd]:!0,validate:n});var t,n}async function Sd({value:e,schema:t}){const n=await $d({value:e,schema:t});if(!n.success)throw Ot.wrap({value:e,cause:n.error});return n.value}async function $d({value:e,schema:t}){const n=Id(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:Ot.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Ot.wrap({value:e,cause:r}),rawValue:e}}}async function Ed({text:e,schema:t}){try{const n=kd(e);return null==t?{success:!0,value:n,rawValue:n}:await $d({value:n,schema:t})}catch(n){return{success:!1,error:lt.isInstance(n)?n:new lt({text:e,cause:n}),rawValue:void 0}}}function Td(e){try{return kd(e),!0}catch(t){return!1}}function Od({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 He({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Cd=()=>globalThis.fetch,Ad=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s})=>Rd({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s}),Rd=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:o,fetch:s=Cd()})=>{try{const u=await s(e,{method:"POST",headers:(a=t,Object.fromEntries(Object.entries(a).filter((([e,t])=>null!=t)))),body:n.content,signal:o}),c=md(u);if(!u.ok){let t;try{t=await i({response:u,url:e,requestBodyValues:n.values})}catch(l){if(fd(l)||je.isInstance(l))throw l;throw new je({message:"Failed to process error response",cause:l,statusCode:u.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(l){if(l instanceof Error&&(fd(l)||je.isInstance(l)))throw l;throw new je({message:"Failed to process successful response",cause:l,statusCode:u.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(l){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:l,url:e,requestBodyValues:n.values})}var a};function Ud({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:l,...u})=>({type:"provider-defined",id:e,name:t,args:u,inputSchema:n,outputSchema:i,execute:r,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:l})}function Pd({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:l,...u})=>({type:"provider-defined",id:e,name:t,args:u,inputSchema:n,outputSchema:r,execute:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:l})}async function jd(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var zd=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:o})=>{const s=await r.text(),a=md(r);if(""===s.trim())return{responseHeaders:a,value:new je({message:r.statusText,url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})};try{const l=await async function({text:e,schema:t}){try{const n=kd(e);return null==t?n:Sd({value:n,schema:t})}catch(n){if(lt.isInstance(n)||Ot.isInstance(n))throw n;throw new lt({text:e,cause:n})}}({text:s,schema:e});return{responseHeaders:a,value:new je({message:t(l),url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,data:l,isRetryable:null==n?void 0:n(r,l)})}}catch(l){return{responseHeaders:a,value:new je({message:r.statusText,url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})}}},Dd=e=>async({response:t})=>{const n=md(t);if(null==t.body)throw new Ze({});return{responseHeaders:n,value:Od({stream:t.body,schema:e})}},Md=e=>async({response:t,url:n,requestBodyValues:r})=>{const i=await t.text(),o=await Ed({text:i,schema:e}),s=md(t);if(!o.success)throw new je({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:s,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}};function Ld(e,t){const n=null!=void 0&&undefined;return Fd(((e,t)=>{const n=Cc(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,r])=>({...e,[t]:ud(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Pc(n)})),{}):void 0;const i="string"==typeof t?t:"title"===(null==t?void 0:t.nameStrategy)||null==t?void 0:t.name,o=ud(e._def,void 0===i?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Pc(n),s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(o.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===i?r?{...o,[n.definitionPath]:r}:o:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,i].join("/"),[n.definitionPath]:{...r,[i]:o}};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})(e,{$refStrategy:n?"root":"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}}})}function Zd(e,t){return function(e){return"_zod"in e}(e)?function(e){return Fd(gl(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Ul(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):Ld(e)}var qd=Symbol.for("vercel.ai.schema");function Fd(e,{validate:t}={}){return{[qd]:!0,_type:void 0,[xd]:!0,jsonSchema:e,validate:t}}function Wd(e){return null==e?Fd({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&qd in t&&!0===t[qd]&&"jsonSchema"in t&&"validate"in t?e:Zd(e);var t}var{btoa:Bd,atob:Jd}=globalThis;function Hd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Jd(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=Nu({error:Nu({message:Dl(),type:Dl().nullish(),param:bu().nullish(),code:Uu([Dl(),lu()]).nullish()})}),Yd=zd({errorSchema:Gd,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=Nu({logitBias:qu($c(),lu()).optional(),logprobs:Uu([pu(),lu()]).optional(),parallelToolCalls:pu().optional(),user:Dl().optional(),reasoningEffort:Ju(["minimal","low","medium","high"]).optional(),maxCompletionTokens:lu().optional(),store:pu().optional(),metadata:qu(Dl().max(64),Dl().max(512)).optional(),prediction:qu(Dl(),bu()).optional(),structuredOutputs:pu().optional(),serviceTier:Ju(["auto","flex","priority"]).optional(),strictJsonSchema:pu().optional(),textVerbosity:Ju(["low","medium","high"]).optional(),promptCacheKey:Dl().optional(),safetyIdentifier:Dl().optional()}),tp=Nu({key:Dl(),type:Ju(["eq","ne","gt","gte","lt","lte"]),value:Uu([Dl(),lu(),pu()])}),np=Nu({type:Ju(["and","or"]),filters:Tu(Uu([tp,yc((()=>np))]))}),rp=Uu([tp,np]),ip=Nu({vectorStoreIds:Tu(Dl()).optional(),maxNumResults:lu().optional(),ranking:Nu({ranker:Ju(["auto","default-2024-08-21"]).optional()}).optional(),filters:rp.optional()}),op=Ud({id:"openai.file_search",name:"file_search",inputSchema:Nu({query:Dl()})}),sp=Nu({searchContextSize:Ju(["low","medium","high"]).optional(),userLocation:Nu({type:Vu("approximate"),country:Dl().optional(),city:Dl().optional(),region:Dl().optional(),timezone:Dl().optional()}).optional()}),ap=Ud({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:Nu({})});var lp=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:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var m,h,g,f;const v=[],y=null!=(m=await Nd({provider:"openai",providerOptions:p,schema:ep}))?m:{},_=null==(h=y.structuredOutputs)||h;null!=i&&v.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==l?void 0:l.type)||null==l.schema||_||v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:w}=function({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:i,content:o}of e)switch(i){case"system":switch(t){case"system":n.push({role:"system",content:o});break;case"developer":n.push({role:"developer",content:o});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===o.length&&"text"===o[0].type){n.push({role:"user",content:o[0].text});break}n.push({role:"user",content:o.map(((e,t)=>{var n,r,i;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 Rt({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vd(e.data)}`}}}throw new Rt({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new Rt({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 Rt({functionality:`audio content parts with media type ${e.mediaType}`})}}}))});break;case"assistant":{let e="";const t=[];for(const n of o)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 o){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: ${i}`)}return{messages:n,warnings:r}}({prompt:e,systemMessageMode:mp(this.modelId)});v.push(...w);const k=null!=(g=y.strictJsonSchema)&&g,x={model:this.modelId,logit_bias:y.logitBias,logprobs:!0===y.logprobs||"number"==typeof y.logprobs||void 0,top_logprobs:"number"==typeof y.logprobs?y.logprobs:"boolean"==typeof y.logprobs&&y.logprobs?0:void 0,user:y.user,parallel_tool_calls:y.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,response_format:"json"===(null==l?void 0:l.type)?_&&null!=l.schema?{type:"json_schema",json_schema:{schema:l.schema,strict:k,name:null!=(f=l.name)?f:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,seed:u,verbosity:y.textVerbosity,max_completion_tokens:y.maxCompletionTokens,store:y.store,metadata:y.metadata,prediction:y.prediction,reasoning_effort:y.reasoningEffort,service_tier:y.serviceTier,prompt_cache_key:y.promptCacheKey,safety_identifier:y.safetyIdentifier,messages:b};var I;pp(this.modelId)?(null!=x.temperature&&(x.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,v.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=x.frequency_penalty&&(x.frequency_penalty=void 0,v.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=x.presence_penalty&&(x.presence_penalty=void 0,v.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=x.logit_bias&&(x.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=x.logprobs&&(x.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=x.top_logprobs&&(x.top_logprobs=void 0,v.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,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==y.serviceTier||((I=this.modelId).startsWith("o3")||I.startsWith("o4-mini")||I.startsWith("gpt-5")&&!I.startsWith("gpt-5-chat"))||(v.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"!==y.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)||(v.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:E}=function({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){const i=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:i};const o=[];for(const a of e)switch(a.type){case"function":o.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=ip.parse(a.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(a.args);o.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}default:i.push({type:"unsupported-tool",tool:a})}break;default:i.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:o,toolChoice:void 0,toolWarnings:i};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:i};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:i};default:throw new Rt({functionality:`tool choice type: ${s}`})}}({tools:c,toolChoice:d,structuredOutputs:_,strictJsonSchema:k});return{args:{...x,tools:S,tool_choice:$},warnings:[...v,...E]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p,m,h;const{args:g,warnings:f}=await this.getArgs(e),{responseHeaders:v,value:y,rawValue:_}=await Ad({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:g,failedResponseHandler:Yd,successfulResponseHandler:Md(cp),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=y.choices[0],w=[],k=b.message.content;null!=k&&k.length>0&&w.push({type:"text",text:k});for(const $ of null!=(t=b.message.tool_calls)?t:[])w.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:[])w.push({type:"source",sourceType:"url",id:gd(),url:$.url,title:$.title});const x=null==(i=y.usage)?void 0:i.completion_tokens_details,I=null==(o=y.usage)?void 0:o.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:w,finishReason:Qd(b.finish_reason),usage:{inputTokens:null!=(l=null==(a=y.usage)?void 0:a.prompt_tokens)?l:void 0,outputTokens:null!=(c=null==(u=y.usage)?void 0:u.completion_tokens)?c:void 0,totalTokens:null!=(p=null==(d=y.usage)?void 0:d.total_tokens)?p:void 0,reasoningTokens:null!=(m=null==x?void 0:x.reasoning_tokens)?m:void 0,cachedInputTokens:null!=(h=null==I?void 0:I.cached_tokens)?h:void 0},request:{body:g},response:{...Xd(y),headers:v,body:_},warnings:f,providerMetadata:S}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await Ad({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:r,failedResponseHandler:Yd,successfulResponseHandler:Dd(dp),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,c=!1;const d={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,p,m,h,g,f,v,y,_,b,w,k,x,I,S,$,E,T,O,N,C,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 R=t.value;if("error"in R)return a="error",void n.enqueue({type:"error",error:R.error});u&&(u=!1,n.enqueue({type:"response-metadata",...Xd(R)})),null!=R.usage&&(l.inputTokens=null!=(r=R.usage.prompt_tokens)?r:void 0,l.outputTokens=null!=(i=R.usage.completion_tokens)?i:void 0,l.totalTokens=null!=(o=R.usage.total_tokens)?o:void 0,l.reasoningTokens=null!=(m=null==(p=R.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?m:void 0,l.cachedInputTokens=null!=(g=null==(h=R.usage.prompt_tokens_details)?void 0:h.cached_tokens)?g:void 0,null!=(null==(f=R.usage.completion_tokens_details)?void 0:f.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(v=R.usage.completion_tokens_details)?void 0:v.accepted_prediction_tokens),null!=(null==(y=R.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(_=R.usage.completion_tokens_details)?void 0:_.rejected_prediction_tokens));const U=R.choices[0];if(null!=(null==U?void 0:U.finish_reason)&&(a=Qd(U.finish_reason)),null!=(null==(b=null==U?void 0:U.logprobs)?void 0:b.content)&&(d.openai.logprobs=U.logprobs.content),null==(null==U?void 0:U.delta))return;const P=U.delta;if(null!=P.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:P.content})),null!=P.tool_calls)for(const e of P.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==(w=e.function)?void 0:w.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!=(k=e.function.arguments)?k:""},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!=(T=null==(E=e.function)?void 0:E.arguments)?T:""),n.enqueue({type:"tool-input-delta",id:r.id,delta:null!=(O=e.function.arguments)?O:""}),null!=(null==(N=r.function)?void 0:N.name)&&null!=(null==(C=r.function)?void 0:C.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!=P.annotations)for(const e of P.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:l,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:i}}}},up=Nu({prompt_tokens:lu().nullish(),completion_tokens:lu().nullish(),total_tokens:lu().nullish(),prompt_tokens_details:Nu({cached_tokens:lu().nullish()}).nullish(),completion_tokens_details:Nu({reasoning_tokens:lu().nullish(),accepted_prediction_tokens:lu().nullish(),rejected_prediction_tokens:lu().nullish()}).nullish()}).nullish(),cp=Nu({id:Dl().nullish(),created:lu().nullish(),model:Dl().nullish(),choices:Tu(Nu({message:Nu({role:Vu("assistant").nullish(),content:Dl().nullish(),tool_calls:Tu(Nu({id:Dl().nullish(),type:Vu("function"),function:Nu({name:Dl(),arguments:Dl()})})).nullish(),annotations:Tu(Nu({type:Vu("url_citation"),start_index:lu(),end_index:lu(),url:Dl(),title:Dl()})).nullish()}),index:lu(),logprobs:Nu({content:Tu(Nu({token:Dl(),logprob:lu(),top_logprobs:Tu(Nu({token:Dl(),logprob:lu()}))})).nullish()}).nullish(),finish_reason:Dl().nullish()})),usage:up}),dp=Uu([Nu({id:Dl().nullish(),created:lu().nullish(),model:Dl().nullish(),choices:Tu(Nu({delta:Nu({role:Ju(["assistant"]).nullish(),content:Dl().nullish(),tool_calls:Tu(Nu({index:lu(),id:Dl().nullish(),type:Vu("function").nullish(),function:Nu({name:Dl().nullish(),arguments:Dl().nullish()})})).nullish(),annotations:Tu(Nu({type:Vu("url_citation"),start_index:lu(),end_index:lu(),url:Dl(),title:Dl()})).nullish()}).nullish(),logprobs:Nu({content:Tu(Nu({token:Dl(),logprob:lu(),top_logprobs:Tu(Nu({token:Dl(),logprob:lu()}))})).nullish()}).nullish(),finish_reason:Dl().nullish(),index:lu()})),usage:up}),Gd]);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=hp[e])?void 0:t.systemMessageMode)?n:"developer":"system"}var hp={"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 gp({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 fp(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 vp=Nu({echo:pu().optional(),logitBias:qu(Dl(),lu()).optional(),suffix:Dl().optional(),user:Dl().optional(),logprobs:Uu([pu(),lu()]).optional()}),yp=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:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,tools:u,toolChoice:c,seed:d,providerOptions:p}){const m=[],h={...await Nd({provider:"openai",providerOptions:p,schema:vp}),...await Nd({provider:this.providerOptionsName,providerOptions:p,schema:vp})};null!=i&&m.push({type:"unsupported-setting",setting:"topK"}),(null==u?void 0:u.length)&&m.push({type:"unsupported-setting",setting:"tools"}),null!=c&&m.push({type:"unsupported-setting",setting:"toolChoice"}),null!=l&&"text"!==l.type&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:g,stopSequences:f}=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:i,content:o}of e)switch(i){case"system":throw new Xe({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":r+=`${t}:\n${o.map((e=>{if("text"===e.type)return e.text})).filter(Boolean).join("")}\n\n`;break;case"assistant":r+=`${n}:\n${o.map((e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new Rt({functionality:"tool-call messages"})}})).join("")}\n\n`;break;case"tool":throw new Rt({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${i}`)}return r+=`${n}:\n`,{prompt:r,stopSequences:[`\n${t}:`]}}({prompt:e}),v=[...null!=f?f:[],...null!=a?a:[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:!0===(null==h?void 0:h.logprobs)?0:!1===(null==h?void 0:h.logprobs)||null==h?void 0:h.logprobs,suffix:h.suffix,user:h.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,seed:d,prompt:g,stop:v.length>0?v:void 0},warnings:m}}async doGenerate(e){var t,n,r;const{args:i,warnings:o}=await this.getArgs(e),{responseHeaders:s,value:a,rawValue:l}=await Ad({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:i,failedResponseHandler:Yd,successfulResponseHandler:Md(bp),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=a.choices[0],c={openai:{}};return null!=u.logprobs&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.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:fp(u.finish_reason),request:{body:i},response:{...gp(a),headers:s,body:l},providerMetadata:c,warnings:o}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await Ad({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:r,failedResponseHandler:Yd,successfulResponseHandler:Dd(wp),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:o.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});u&&(u=!1,n.enqueue({type:"response-metadata",...gp(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(l.inputTokens=r.usage.prompt_tokens,l.outputTokens=r.usage.completion_tokens,l.totalTokens=r.usage.total_tokens);const i=r.choices[0];null!=(null==i?void 0:i.finish_reason)&&(s=fp(i.finish_reason)),null!=(null==i?void 0:i.logprobs)&&(a.openai.logprobs=i.logprobs),null!=(null==i?void 0:i.text)&&i.text.length>0&&n.enqueue({type:"text-delta",id:"0",delta:i.text})},flush(e){u||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:l})}})),request:{body:r},response:{headers:i}}}},_p=Nu({prompt_tokens:lu(),completion_tokens:lu(),total_tokens:lu()}),bp=Nu({id:Dl().nullish(),created:lu().nullish(),model:Dl().nullish(),choices:Tu(Nu({text:Dl(),finish_reason:Dl(),logprobs:Nu({tokens:Tu(Dl()),token_logprobs:Tu(lu()),top_logprobs:Tu(qu(Dl(),lu())).nullish()}).nullish()})),usage:_p.nullish()}),wp=Uu([Nu({id:Dl().nullish(),created:lu().nullish(),model:Dl().nullish(),choices:Tu(Nu({text:Dl(),finish_reason:Dl().nullish(),index:lu(),logprobs:Nu({tokens:Tu(Dl()),token_logprobs:Tu(lu()),top_logprobs:Tu(qu(Dl(),lu())).nullish()}).nullish()})),usage:_p.nullish()}),Gd]),kp=Nu({dimensions:lu().optional(),user:Dl().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 i;if(e.length>this.maxEmbeddingsPerCall)throw new xt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=null!=(i=await Nd({provider:"openai",providerOptions:r,schema:kp}))?i:{},{responseHeaders:s,value:a,rawValue:l}=await Ad({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:pd(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:Yd,successfulResponseHandler:Md(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:l}}}},Ip=Nu({data:Tu(Nu({embedding:Tu(lu())})),usage:Nu({prompt_tokens:lu()}).nullish()}),Sp={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},$p=new Set(["gpt-image-1"]),Ep=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:i,providerOptions:o,headers:s,abortSignal:a}){var l,u,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!=i&&p.push({type:"unsupported-setting",setting:"seed"});const m=null!=(c=null==(u=null==(l=this.config._internal)?void 0:l.currentDate)?void 0:u.call(l))?c:new Date,{value:h,responseHeaders:g}=await Ad({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:pd(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...null!=(d=o.openai)?d:{},...$p.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Yd,successfulResponseHandler:Md(Tp),abortSignal:a,fetch:this.config.fetch});return{images:h.data.map((e=>e.b64_json)),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:g},providerMetadata:{openai:{images:h.data.map((e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null))}}}}},Tp=Nu({data:Tu(Nu({b64_json:Dl(),revised_prompt:Dl().optional()}))}),Op=Nu({container:Uu([Dl(),Nu({fileIds:Tu(Dl()).optional()})]).optional()}),Np={codeInterpreter:Ud({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:Nu({})}),fileSearch:op,webSearchPreview:ap};function Cp(e,t){return!!t&&t.some((t=>e.startsWith(t)))}var Ap=Nu({itemId:Dl().nullish(),reasoningEncryptedContent:Dl().nullish()});function Rp({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 Up=Tu(Nu({token:Dl(),logprob:lu(),top_logprobs:Tu(Nu({token:Dl(),logprob:lu()}))})),Pp=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({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:o,frequencyPenalty:s,seed:a,prompt:l,providerOptions:u,tools:c,toolChoice:d,responseFormat:p}){var m,h;const g=[],f=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!=i&&g.push({type:"unsupported-setting",setting:"topK"}),null!=a&&g.push({type:"unsupported-setting",setting:"seed"}),null!=o&&g.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=s&&g.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=n&&g.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:v,warnings:y}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,i,o,s,a,l;const u=[],c=[];for(const{role:d,content:p}of e)switch(d){case"system":switch(t){case"system":u.push({role:"system",content:p});break;case"developer":u.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":u.push({role:"user",content:p.map(((e,t)=>{var r,i,o;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&&Cp(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Vd(e.data)}`},detail:null==(i=null==(r=e.providerOptions)?void 0:r.openai)?void 0:i.imageDetail}}if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new Rt({functionality:"PDF file parts with URLs"});return{type:"input_file",..."string"==typeof e.data&&Cp(e.data,n)?{file_id:e.data}:{filename:null!=(o=e.filename)?o:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vd(e.data)}`}}}throw new Rt({functionality:`file part media type ${e.mediaType}`})}}))});break;case"assistant":{const e={};for(const t of p)switch(t.type){case"text":u.push({role:"assistant",content:[{type:"output_text",text:t.text}],id:null!=(o=null==(i=null==(r=t.providerOptions)?void 0:r.openai)?void 0:i.itemId)?o:void 0});break;case"tool-call":if(t.providerExecuted)break;u.push({type:"function_call",call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:null!=(l=null==(a=null==(s=t.providerOptions)?void 0:s.openai)?void 0:a.itemId)?l: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 i=e[r],o=[];t.text.length>0?o.push({type:"summary_text",text:t.text}):void 0!==i&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),void 0===i?(e[r]={type:"reasoning",id:r,encrypted_content:null==n?void 0:n.reasoningEncryptedContent,summary:o},u.push(e[r])):i.summary.push(...o)}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)}u.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${d}`)}return{messages:u,warnings:c}}({prompt:l,systemMessageMode:f.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);const _=await Nd({provider:"openai",providerOptions:u,schema:qp}),b=null!=(m=null==_?void 0:_.strictJsonSchema)&&m,w="number"==typeof(null==_?void 0:_.logprobs)?null==_?void 0:_.logprobs:!0===(null==_?void 0:_.logprobs)?20:void 0,k=w?Array.isArray(null==_?void 0:_.include)?[...null==_?void 0:_.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:null==_?void 0:_.include,x={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...("json"===(null==p?void 0:p.type)||(null==_?void 0:_.textVerbosity))&&{text:{..."json"===(null==p?void 0:p.type)&&{format:null!=p.schema?{type:"json_schema",strict:b,name:null!=(h=p.name)?h:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(null==_?void 0:_.textVerbosity)&&{verbosity:_.textVerbosity}}},metadata:null==_?void 0:_.metadata,parallel_tool_calls:null==_?void 0:_.parallelToolCalls,previous_response_id:null==_?void 0:_.previousResponseId,store:null==_?void 0:_.store,user:null==_?void 0:_.user,instructions:null==_?void 0:_.instructions,service_tier:null==_?void 0:_.serviceTier,include:k,prompt_cache_key:null==_?void 0:_.promptCacheKey,safety_identifier:null==_?void 0:_.safetyIdentifier,top_logprobs:w,...f.isReasoningModel&&(null!=(null==_?void 0:_.reasoningEffort)||null!=(null==_?void 0:_.reasoningSummary))&&{reasoning:{...null!=(null==_?void 0:_.reasoningEffort)&&{effort:_.reasoningEffort},...null!=(null==_?void 0:_.reasoningSummary)&&{summary:_.reasoningSummary}}},...f.requiredAutoTruncation&&{truncation:"auto"}};f.isReasoningModel?(null!=x.temperature&&(x.temperature=void 0,g.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,g.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==_?void 0:_.reasoningEffort)&&g.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==_?void 0:_.reasoningSummary)&&g.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==_?void 0:_.serviceTier)||f.supportsFlexProcessing||(g.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==_?void 0:_.serviceTier)||f.supportsPriorityProcessing||(g.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 i=[];for(const s of e)switch(s.type){case"function":i.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=ip.parse(s.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(s.args);i.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=Op.parse(s.args);i.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:i,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:i,toolChoice:o,toolWarnings:r};case"tool":return{tools:i,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 Rt({functionality:`tool choice type: ${o}`})}}({tools:c,toolChoice:d,strictJsonSchema:b});return{args:{...x,tools:I,tool_choice:S},warnings:[...g,...$]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p,m,h,g,f,v;const{args:y,warnings:_}=await this.getArgs(e),b=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:w,value:k,rawValue:x}=await Ad({url:b,headers:pd(this.config.headers(),e.headers),body:y,failedResponseHandler:Yd,successfulResponseHandler:Md(Nu({id:Dl(),created_at:lu(),error:Nu({code:Dl(),message:Dl()}).nullish(),model:Dl(),output:Tu(ju("type",[Nu({type:Vu("message"),role:Vu("assistant"),id:Dl(),content:Tu(Nu({type:Vu("output_text"),text:Dl(),logprobs:Up.nullish(),annotations:Tu(ju("type",[Nu({type:Vu("url_citation"),start_index:lu(),end_index:lu(),url:Dl(),title:Dl()}),Nu({type:Vu("file_citation"),start_index:lu(),end_index:lu(),file_id:Dl(),quote:Dl()})]))}))}),Nu({type:Vu("function_call"),call_id:Dl(),name:Dl(),arguments:Dl(),id:Dl()}),Nu({type:Vu("web_search_call"),id:Dl(),status:Dl().optional(),action:Nu({type:Vu("search"),query:Dl().optional()}).nullish()}),Nu({type:Vu("computer_call"),id:Dl(),status:Dl().optional()}),Nu({type:Vu("file_search_call"),id:Dl(),status:Dl().optional(),queries:Tu(Dl()).nullish(),results:Tu(Nu({attributes:Nu({file_id:Dl(),filename:Dl(),score:lu(),text:Dl()})})).nullish()}),Nu({type:Vu("reasoning"),id:Dl(),encrypted_content:Dl().nullish(),summary:Tu(Nu({type:Vu("summary_text"),text:Dl()}))})])),incomplete_details:Nu({reason:Dl()}).nullable(),usage:jp})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(k.error)throw new je({message:k.error.message,url:b,requestBodyValues:y,statusCode:400,responseHeaders:w,responseBody:x,isRetryable:!1});const I=[],S=[];for(const E of k.output)switch(E.type){case"reasoning":0===E.summary.length&&E.summary.push({type:"summary_text",text:""});for(const e of E.summary)I.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:E.id,reasoningEncryptedContent:null!=(t=E.encrypted_content)?t:null}}});break;case"message":for(const t of E.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&S.push(t.logprobs),I.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:E.id}}});for(const e of t.annotations)"url_citation"===e.type?I.push({type:"source",sourceType:"url",id:null!=(s=null==(o=(i=this.config).generateId)?void 0:o.call(i))?s:gd(),url:e.url,title:e.title}):"file_citation"===e.type&&I.push({type:"source",sourceType:"document",id:null!=(u=null==(l=(a=this.config).generateId)?void 0:l.call(a))?u:gd(),mediaType:"text/plain",title:e.quote,filename:e.file_id})}break;case"function_call":I.push({type:"tool-call",toolCallId:E.call_id,toolName:E.name,input:E.arguments,providerMetadata:{openai:{itemId:E.id}}});break;case"web_search_call":I.push({type:"tool-call",toolCallId:E.id,toolName:"web_search_preview",input:null!=(d=null==(c=E.action)?void 0:c.query)?d:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:E.id,toolName:"web_search_preview",result:{status:E.status||"completed",...(null==(p=E.action)?void 0:p.query)&&{query:E.action.query}},providerExecuted:!0});break;case"computer_call":I.push({type:"tool-call",toolCallId:E.id,toolName:"computer_use",input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:E.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:E.status||"completed"},providerExecuted:!0});break;case"file_search_call":I.push({type:"tool-call",toolCallId:E.id,toolName:"file_search",input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:E.id,toolName:"file_search",result:{type:"file_search_tool_result",status:E.status||"completed",...E.queries&&{queries:E.queries},...E.results&&{results:E.results}},providerExecuted:!0})}const $={openai:{responseId:k.id}};return S.length>0&&($.openai.logprobs=S),{content:I,finishReason:Rp({finishReason:null==(m=k.incomplete_details)?void 0:m.reason,hasToolCalls:I.some((e=>"tool-call"===e.type))}),usage:{inputTokens:k.usage.input_tokens,outputTokens:k.usage.output_tokens,totalTokens:k.usage.input_tokens+k.usage.output_tokens,reasoningTokens:null!=(g=null==(h=k.usage.output_tokens_details)?void 0:h.reasoning_tokens)?g:void 0,cachedInputTokens:null!=(v=null==(f=k.usage.input_tokens_details)?void 0:f.cached_tokens)?v:void 0},request:{body:y},response:{id:k.id,timestamp:new Date(1e3*k.created_at),modelId:k.model,headers:w,body:x},providerMetadata:$,warnings:_}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i}=await Ad({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Yd,successfulResponseHandler:Dd(Mp),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this;let s="unknown";const a={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=null;const c={};let d=!1;const p={};return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,m,h,g,f,v,y,_,b,w,k,x,I,S,$,E,T,O;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const N=t.value;if(Zp(N))"function_call"===N.item.type?(c[N.output_index]={toolName:N.item.name,toolCallId:N.item.call_id},n.enqueue({type:"tool-input-start",id:N.item.call_id,toolName:N.item.name})):"web_search_call"===N.item.type?(c[N.output_index]={toolName:"web_search_preview",toolCallId:N.item.id},n.enqueue({type:"tool-input-start",id:N.item.id,toolName:"web_search_preview"})):"computer_call"===N.item.type?(c[N.output_index]={toolName:"computer_use",toolCallId:N.item.id},n.enqueue({type:"tool-input-start",id:N.item.id,toolName:"computer_use"})):"file_search_call"===N.item.type?(c[N.output_index]={toolName:"file_search",toolCallId:N.item.id},n.enqueue({type:"tool-input-start",id:N.item.id,toolName:"file_search"})):"message"===N.item.type?n.enqueue({type:"text-start",id:N.item.id,providerMetadata:{openai:{itemId:N.item.id}}}):function(e){return Zp(e)&&"reasoning"===e.item.type}(N)&&(p[N.item.id]={encryptedContent:N.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${N.item.id}:0`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:null!=(r=N.item.encrypted_content)?r:null}}}));else if(Lp(N)){if("function_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.call_id}),n.enqueue({type:"tool-call",toolCallId:N.item.call_id,toolName:N.item.name,input:N.item.arguments,providerMetadata:{openai:{itemId:N.item.id}}});else if("web_search_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.id}),n.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"web_search_preview",input:null!=(m=null==(i=N.item.action)?void 0:i.query)?m:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:N.item.status||"completed",...(null==(h=N.item.action)?void 0:h.query)&&{query:N.item.action.query}},providerExecuted:!0});else if("computer_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.id}),n.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:N.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.id}),n.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"file_search",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:N.item.status||"completed",...N.item.queries&&{queries:N.item.queries},...N.item.results&&{results:N.item.results}},providerExecuted:!0});else if("message"===N.item.type)n.enqueue({type:"text-end",id:N.item.id});else if(function(e){return Lp(e)&&"reasoning"===e.item.type}(N)){const e=p[N.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${N.item.id}:${t}`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:null!=(g=N.item.encrypted_content)?g:null}}});delete p[N.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(N)){const e=c[N.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:N.delta})}else!function(e){return"response.created"===e.type}(N)?!function(e){return"response.output_text.delta"===e.type}(N)?!function(e){return"response.reasoning_summary_part.added"===e.type}(N)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(N)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(N)?!function(e){return"response.output_text.annotation.added"===e.type}(N)?function(e){return"error"===e.type}(N)&&n.enqueue({type:"error",error:N}):"url_citation"===N.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=($=null==(S=(I=o.config).generateId)?void 0:S.call(I))?$:gd(),url:N.annotation.url,title:N.annotation.title}):"file_citation"===N.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=(O=null==(T=(E=o.config).generateId)?void 0:T.call(E))?O:gd(),mediaType:"text/plain",title:N.annotation.quote,filename:N.annotation.file_id}):(s=Rp({finishReason:null==(_=N.response.incomplete_details)?void 0:_.reason,hasToolCalls:d}),a.inputTokens=N.response.usage.input_tokens,a.outputTokens=N.response.usage.output_tokens,a.totalTokens=N.response.usage.input_tokens+N.response.usage.output_tokens,a.reasoningTokens=null!=(w=null==(b=N.response.usage.output_tokens_details)?void 0:b.reasoning_tokens)?w:void 0,a.cachedInputTokens=null!=(x=null==(k=N.response.usage.input_tokens_details)?void 0:k.cached_tokens)?x:void 0):n.enqueue({type:"reasoning-delta",id:`${N.item_id}:${N.summary_index}`,delta:N.delta,providerMetadata:{openai:{itemId:N.item_id}}}):N.summary_index>0&&(null==(f=p[N.item_id])||f.summaryParts.push(N.summary_index),n.enqueue({type:"reasoning-start",id:`${N.item_id}:${N.summary_index}`,providerMetadata:{openai:{itemId:N.item_id,reasoningEncryptedContent:null!=(y=null==(v=p[N.item_id])?void 0:v.encryptedContent)?y:null}}})):(n.enqueue({type:"text-delta",id:N.item_id,delta:N.delta}),N.logprobs&&l.push(N.logprobs)):(u=N.response.id,n.enqueue({type:"response-metadata",id:N.response.id,timestamp:new Date(1e3*N.response.created_at),modelId:N.response.model}))},flush(e){const t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),e.enqueue({type:"finish",finishReason:s,usage:a,providerMetadata:t})}})),request:{body:t},response:{headers:r}}}},jp=Nu({input_tokens:lu(),input_tokens_details:Nu({cached_tokens:lu().nullish()}).nullish(),output_tokens:lu(),output_tokens_details:Nu({reasoning_tokens:lu().nullish()}).nullish()}),zp=Nu({type:Vu("response.output_text.delta"),item_id:Dl(),delta:Dl(),logprobs:Up.nullish()}),Dp=Nu({type:Vu("error"),code:Dl(),message:Dl(),param:Dl().nullish(),sequence_number:lu()}),Mp=Uu([zp,Nu({type:Ju(["response.completed","response.incomplete"]),response:Nu({incomplete_details:Nu({reason:Dl()}).nullish(),usage:jp})}),Nu({type:Vu("response.created"),response:Nu({id:Dl(),created_at:lu(),model:Dl()})}),Nu({type:Vu("response.output_item.added"),output_index:lu(),item:ju("type",[Nu({type:Vu("message"),id:Dl()}),Nu({type:Vu("reasoning"),id:Dl(),encrypted_content:Dl().nullish()}),Nu({type:Vu("function_call"),id:Dl(),call_id:Dl(),name:Dl(),arguments:Dl()}),Nu({type:Vu("web_search_call"),id:Dl(),status:Dl(),action:Nu({type:Vu("search"),query:Dl().optional()}).nullish()}),Nu({type:Vu("computer_call"),id:Dl(),status:Dl()}),Nu({type:Vu("file_search_call"),id:Dl(),status:Dl(),queries:Tu(Dl()).nullish(),results:Tu(Nu({attributes:Nu({file_id:Dl(),filename:Dl(),score:lu(),text:Dl()})})).optional()})])}),Nu({type:Vu("response.output_item.done"),output_index:lu(),item:ju("type",[Nu({type:Vu("message"),id:Dl()}),Nu({type:Vu("reasoning"),id:Dl(),encrypted_content:Dl().nullish()}),Nu({type:Vu("function_call"),id:Dl(),call_id:Dl(),name:Dl(),arguments:Dl(),status:Vu("completed")}),Nu({type:Vu("web_search_call"),id:Dl(),status:Vu("completed"),action:Nu({type:Vu("search"),query:Dl().optional()}).nullish()}),Nu({type:Vu("computer_call"),id:Dl(),status:Vu("completed")}),Nu({type:Vu("file_search_call"),id:Dl(),status:Vu("completed"),queries:Tu(Dl()).nullish(),results:Tu(Nu({attributes:Nu({file_id:Dl(),filename:Dl(),score:lu(),text:Dl()})})).nullish()})])}),Nu({type:Vu("response.function_call_arguments.delta"),item_id:Dl(),output_index:lu(),delta:Dl()}),Nu({type:Vu("response.output_text.annotation.added"),annotation:ju("type",[Nu({type:Vu("url_citation"),url:Dl(),title:Dl()}),Nu({type:Vu("file_citation"),file_id:Dl(),quote:Dl()})])}),Nu({type:Vu("response.reasoning_summary_part.added"),item_id:Dl(),summary_index:lu()}),Nu({type:Vu("response.reasoning_summary_text.delta"),item_id:Dl(),summary_index:lu(),delta:Dl()}),Dp,Nu({type:Dl()}).loose()]);function Lp(e){return"response.output_item.done"===e.type}function Zp(e){return"response.output_item.added"===e.type}var qp=Nu({metadata:bu().nullish(),parallelToolCalls:pu().nullish(),previousResponseId:Dl().nullish(),store:pu().nullish(),user:Dl().nullish(),reasoningEffort:Dl().nullish(),strictJsonSchema:pu().nullish(),instructions:Dl().nullish(),reasoningSummary:Dl().nullish(),serviceTier:Ju(["auto","flex","priority"]).nullish(),include:Tu(Ju(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:Ju(["low","medium","high"]).nullish(),promptCacheKey:Dl().nullish(),safetyIdentifier:Dl().nullish(),logprobs:Uu([pu(),lu().min(1).max(20)]).optional()}),Fp=Nu({instructions:Dl().nullish(),speed:lu().min(.25).max(4).default(1).nullish()}),Wp=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:i,language:o,providerOptions:s}){const a=[],l=await Nd({provider:"openai",providerOptions:s,schema:Fp}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:i};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const e={};for(const t in e){const n=e[t];void 0!==n&&(u[t]=n)}}return o&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:u,warnings:a}}async doGenerate(e){var t,n,r;const i=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{requestBody:o,warnings:s}=await this.getArgs(e),{value:a,responseHeaders:l,rawValue:u}=await Ad({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:o,failedResponseHandler:Yd,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=md(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(i){throw new je({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:s,request:{body:JSON.stringify(o)},response:{timestamp:i,modelId:this.modelId,headers:l,body:u}}}},Bp=Nu({include:Tu(Dl()).optional(),language:Dl().optional(),prompt:Dl().optional(),temperature:lu().min(0).max(1).default(0).optional(),timestampGranularities:Tu(Ju(["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"},Hp=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}),i=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Hd(e)]);if(i.append("model",this.modelId),i.append("file",new File([o],"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&&i.append(t,String(n))}return{formData:i,warnings:[]}}async doGenerate(e){var t,n,r,i,o,s,a,l;const u=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:h}=await(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s})=>Rd({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s}))({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),formData:c,failedResponseHandler:Yd,successfulResponseHandler:Md(Vp),abortSignal:e.abortSignal,fetch:this.config.fetch}),g=null!=p.language&&p.language in Jp?Jp[p.language]:void 0;return{text:p.text,segments:null!=(a=null!=(s=null==(i=p.segments)?void 0:i.map((e=>({text:e.text,startSecond:e.start,endSecond:e.end}))))?s:null==(o=p.words)?void 0:o.map((e=>({text:e.word,startSecond:e.start,endSecond:e.end}))))?a:[],language:g,durationInSeconds:null!=(l=p.duration)?l:void 0,warnings:d,response:{timestamp:u,modelId:this.modelId,headers:m,body:h}}}},Vp=Nu({text:Dl(),language:Dl().nullish(),duration:lu().nullish(),words:Tu(Nu({word:Dl(),start:lu(),end:lu()})).nullish(),segments:Tu(Nu({id:lu(),seek:lu(),start:lu(),end:lu(),text:Dl(),tokens:Tu(lu()),temperature:lu(),avg_logprob:lu(),compression_ratio:lu(),no_speech_prob:lu()})).nullish()});function Kp(e={}){var t,n;const r=null!=(t=Kd(e.baseURL))?t:"https://api.openai.com/v1",i=null!=(n=e.name)?n:"openai",o=()=>({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:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),a=t=>new Ep(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),l=t=>new Hp(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),u=t=>new Wp(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:o,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 Pp(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(e){return c(e)};return p.languageModel=c,p.chat=t=>new lp(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.completion=t=>new yp(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.responses=d,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=a,p.imageModel=a,p.transcription=l,p.transcriptionModel=l,p.speech=u,p.speechModel=u,p.tools=Np,p}var Gp=Kp(),Yp=zd({errorSchema:Nu({type:Vu("error"),error:Nu({type:Dl(),message:Dl()})}),errorToMessage:e=>e.error.message}),Xp=Nu({citations:Nu({enabled:pu()}).optional(),title:Dl().optional(),context:Dl().optional()}),Qp=Nu({sendReasoning:pu().optional(),thinking:Nu({type:Uu([Vu("enabled"),Vu("disabled")]),budgetTokens:lu().optional()}).optional(),disableParallelToolUse:pu().optional()});function em(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 tm=Nu({maxUses:lu().optional(),allowedDomains:Tu(Dl()).optional(),blockedDomains:Tu(Dl()).optional(),userLocation:Nu({type:Vu("approximate"),city:Dl().optional(),region:Dl().optional(),country:Dl().optional(),timezone:Dl().optional()}).optional()}),nm=Tu(Nu({url:Dl(),title:Dl(),pageAge:Dl().nullable(),encryptedContent:Dl(),type:Dl()})),rm=Pd({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Nu({query:Dl()}),outputSchema:nm});function im(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var om=Nu({type:Vu("code_execution_result"),stdout:Dl(),stderr:Dl(),return_code:lu()}),sm=Pd({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Nu({code:Dl()}),outputSchema:om});function am(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 Rt({functionality:"URL-based text documents are not supported for citations"});throw new Rt({functionality:"unsupported data type for text documents: "+typeof e})}async function lm({prompt:e,sendReasoning:t,warnings:n}){var r,i,o,s,a;const l=new Set,u=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:Xp});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:Xp});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let h=0;h<u.length;h++){const e=u[h],g=h===u.length-1,f=e.type;switch(f){case"system":if(null!=c)throw new Rt({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:em(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],u=e===a.length-1,c=null!=(r=em(s.providerOptions))?r:u?em(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){l.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!=(i=n.title)?i:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}else{if("text/plain"!==s.mediaType)throw new Rt({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:am(s.data)},title:null!=(o=n.title)?o: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],i=e===a.length-1,o=null!=(s=em(r.providerOptions))?s:i?em(n.providerOptions):void 0,l=r.output;let u;switch(l.type){case"content":u=l.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 Rt({functionality:`media type: ${e.mediaType}`})}}));break;case"text":case"error-text":u=l.value;break;default:u=JSON.stringify(l.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:u,is_error:"error-text"===l.type||"error-json"===l.type||void 0,cache_control:o})}break;default:throw new Error(`Unsupported role: ${e}`)}}d.push({role:"user",content:t});break}case"assistant":{const r=[];for(let i=0;i<e.messages.length;i++){const o=e.messages[i],s=i===e.messages.length-1,{content:l}=o;for(let e=0;e<l.length;e++){const i=l[e],u=e===l.length-1,c=null!=(a=em(i.providerOptions))?a:u?em(o.providerOptions):void 0;switch(i.type){case"text":r.push({type:"text",text:g&&s&&u?i.text.trim():i.text,cache_control:c});break;case"reasoning":if(t){const e=await Nd({provider:"anthropic",providerOptions:i.providerOptions,schema:fm});null!=e?null!=e.signature?r.push({type:"thinking",thinking:i.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(i.providerExecuted){if("web_search"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"web_search",input:i.input,cache_control:c});break}if("code_execution"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"code_execution",input:i.input,cache_control:c});break}n.push({type:"other",message:`provider executed tool call for tool ${i.toolName} is not supported`});break}r.push({type:"tool_use",id:i.toolCallId,name:i.toolName,input:i.input,cache_control:c});break;case"tool-result":if("web_search"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=nm.parse(e.value);r.push({type:"web_search_tool_result",tool_use_id:i.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"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=om.parse(e.value);r.push({type:"code_execution_tool_result",tool_use_id:i.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 ${i.toolName} is not supported`})}}}d.push({role:"assistant",content:r});break}default:throw new Error(`content type: ${f}`)}}return{prompt:{system:c,messages:d},betas:l}}function um({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 cm={webSearchResult:Nu({type:Vu("web_search_result_location"),cited_text:Dl(),url:Dl(),title:Dl(),encrypted_index:Dl()}),pageLocation:Nu({type:Vu("page_location"),cited_text:Dl(),document_index:lu(),document_title:Dl().nullable(),start_page_number:lu(),end_page_number:lu()}),charLocation:Nu({type:Vu("char_location"),cited_text:Dl(),document_index:lu(),document_title:Dl().nullable(),start_char_index:lu(),end_char_index:lu()})},dm=ju("type",[cm.webSearchResult,cm.pageLocation,cm.charLocation]);function pm(e,t,n,r){if("page_location"===e.type||"char_location"===e.type){const i=function(e,t,n){var r;const i=t[e.document_index];if(!i)return null;const o="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:i.mediaType,title:null!=(r=e.document_title)?r:i.title,filename:i.filename,providerMetadata:{anthropic:o}}}(e,t,n);i&&r(i)}}ju("type",[cm.pageLocation,cm.charLocation]);var mm=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:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var m,h,g;const f=[];null!=o&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=s&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=u&&f.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==l?void 0:l.type)&&(null==l.schema?f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):null!=c&&f.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const v="json"===(null==l?void 0:l.type)&&null!=l.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:l.schema}:void 0,y=await Nd({provider:"anthropic",providerOptions:p,schema:Qp}),{prompt:_,betas:b}=await lm({prompt:e,sendReasoning:null==(m=null==y?void 0:y.sendReasoning)||m,warnings:f}),w="enabled"===(null==(h=null==y?void 0:y.thinking)?void 0:h.type),k=null==(g=null==y?void 0:y.thinking)?void 0:g.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:a,...w&&{thinking:{type:"enabled",budget_tokens:k}},system:_.system,messages:_.messages};if(w){if(null==k)throw new Rt({functionality:"thinking requires a budget"});null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=i&&(x.top_k=void 0,f.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),null!=r&&(x.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),x.max_tokens=t+k}const{tools:I,toolChoice:S,toolWarnings:$,betas:E}=function({tools:e,toolChoice:t,disableParallelToolUse:n}){e=(null==e?void 0:e.length)?e:void 0;const r=[],i=new Set;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};const o=[];for(const a of e)if(im(a))o.push(a);else switch(a.type){case"function":const e=em(a.providerOptions);o.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":i.add("computer-use-2025-01-24"),o.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":i.add("computer-use-2024-10-22"),o.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":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":i.add("computer-use-2024-10-22"),o.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":i.add("computer-use-2025-01-24"),o.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":i.add("computer-use-2024-10-22"),o.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{const e=tm.parse(a.args);o.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":i.add("code-execution-2025-05-22"),o.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:o,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};const s=t.type;switch(s){case"auto":return{tools:o,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"required":return{tools:o,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case"tool":return{tools:o,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new Rt({functionality:`tool choice type: ${s}`})}}(null!=v?{tools:[v],toolChoice:{type:"tool",toolName:v.name},disableParallelToolUse:null==y?void 0:y.disableParallelToolUse}:{tools:null!=c?c:[],toolChoice:d,disableParallelToolUse:null==y?void 0:y.disableParallelToolUse});return{args:{...x,tools:I,tool_choice:S},warnings:[...f,...$],betas:new Set([...b,...E]),usesJsonResponseTool:null!=v}}async getHeaders({betas:e,headers:t}){return pd(await jd(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,i=null==r?void 0:r.citations;return null!=(n=null==i?void 0:i.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,i,o;const{args:s,warnings:a,betas:l,usesJsonResponseTool:u}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:m}=await Ad({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:l,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Yp,successfulResponseHandler:Md(hm),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=[];for(const g of p.content)switch(g.type){case"text":if(!u&&(h.push({type:"text",text:g.text}),g.citations))for(const e of g.citations)pm(e,c,this.generateId,(e=>h.push(e)));break;case"thinking":h.push({type:"reasoning",text:g.thinking,providerMetadata:{anthropic:{signature:g.signature}}});break;case"redacted_thinking":h.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:g.data}}});break;case"tool_use":h.push(u?{type:"text",text:JSON.stringify(g.input)}:{type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input)});break;case"server_tool_use":"web_search"!==g.name&&"code_execution"!==g.name||h.push({type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input),providerExecuted:!0});break;case"web_search_tool_result":if(Array.isArray(g.content)){h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",result:g.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 g.content)h.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 h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0});break;case"code_execution_tool_result":"code_execution_result"===g.content.type?h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",result:{type:g.content.type,stdout:g.content.stdout,stderr:g.content.stderr,return_code:g.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===g.content.type&&h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0})}return{content:h,finishReason:um({finishReason:p.stop_reason,isJsonResponseFromTool:u}),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!=(i=p.model)?i:void 0,headers:d,body:m},warnings:a,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:null!=(o=p.usage.cache_creation_input_tokens)?o:null}}}}async doStream(e){const{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...t,stream:!0},{responseHeaders:a,value:l}=await Ad({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Yp,successfulResponseHandler:Dd(gm),abortSignal:e.abortSignal,fetch:this.config.fetch});let u="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,m;const h=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,l,g,f,v;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const y=t.value;switch(y.type){case"ping":return;case"content_block_start":{const e=y.content_block.type;switch(m=e,e){case"text":return d[y.index]={type:"text"},void n.enqueue({type:"text-start",id:String(y.index)});case"thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index)});case"redacted_thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index),providerMetadata:{anthropic:{redactedData:y.content_block.data}}});case"tool_use":return d[y.index]=i?{type:"text"}:{type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:""},void n.enqueue(i?{type:"text-start",id:String(y.index)}:{type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name});case"server_tool_use":return void("web_search"!==y.content_block.name&&"code_execution"!==y.content_block.name||(d[y.index]={type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:"",providerExecuted:!0},n.enqueue({type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name,providerExecuted:!0})));case"web_search_tool_result":{const e=y.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:h(),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=y.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[y.index]){const e=d[y.index];switch(e.type){case"text":n.enqueue({type:"text-end",id:String(y.index)});break;case"reasoning":n.enqueue({type:"reasoning-end",id:String(y.index)});break;case"tool-call":i||(n.enqueue({type:"tool-input-end",id:e.toolCallId}),n.enqueue(e))}delete d[y.index]}return void(m=void 0);case"content_block_delta":{const e=y.delta.type;switch(e){case"text_delta":if(i)return;return void n.enqueue({type:"text-delta",id:String(y.index),delta:y.delta.text});case"thinking_delta":return void n.enqueue({type:"reasoning-delta",id:String(y.index),delta:y.delta.thinking});case"signature_delta":return void("thinking"===m&&n.enqueue({type:"reasoning-delta",id:String(y.index),delta:"",providerMetadata:{anthropic:{signature:y.delta.signature}}}));case"input_json_delta":{const e=d[y.index],t=y.delta.partial_json;if(i){if("text"!==(null==e?void 0:e.type))return;n.enqueue({type:"text-delta",id:String(y.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 pm(y.delta.citation,o,h,(e=>n.enqueue(e)));default:throw new Error(`Unsupported delta type: ${e}`)}}case"message_start":return c.inputTokens=y.message.usage.input_tokens,c.cachedInputTokens=null!=(s=y.message.usage.cache_read_input_tokens)?s:void 0,p={anthropic:{usage:y.message.usage,cacheCreationInputTokens:null!=(a=y.message.usage.cache_creation_input_tokens)?a:null}},void n.enqueue({type:"response-metadata",id:null!=(l=y.message.id)?l:void 0,modelId:null!=(g=y.message.model)?g:void 0});case"message_delta":return c.outputTokens=y.usage.output_tokens,c.totalTokens=(null!=(f=c.inputTokens)?f:0)+(null!=(v=y.usage.output_tokens)?v:0),void(u=um({finishReason:y.delta.stop_reason,isJsonResponseFromTool:i}));case"message_stop":return void n.enqueue({type:"finish",finishReason:u,usage:c,providerMetadata:p});case"error":return void n.enqueue({type:"error",error:y.error});default:throw new Error(`Unsupported chunk type: ${y}`)}}})),request:{body:s},response:{headers:a}}}},hm=Nu({type:Vu("message"),id:Dl().nullish(),model:Dl().nullish(),content:Tu(ju("type",[Nu({type:Vu("text"),text:Dl(),citations:Tu(dm).optional()}),Nu({type:Vu("thinking"),thinking:Dl(),signature:Dl()}),Nu({type:Vu("redacted_thinking"),data:Dl()}),Nu({type:Vu("tool_use"),id:Dl(),name:Dl(),input:ku()}),Nu({type:Vu("server_tool_use"),id:Dl(),name:Dl(),input:qu(Dl(),ku()).nullish()}),Nu({type:Vu("web_search_tool_result"),tool_use_id:Dl(),content:Uu([Tu(Nu({type:Vu("web_search_result"),url:Dl(),title:Dl(),encrypted_content:Dl(),page_age:Dl().nullish()})),Nu({type:Vu("web_search_tool_result_error"),error_code:Dl()})])}),Nu({type:Vu("code_execution_tool_result"),tool_use_id:Dl(),content:Uu([Nu({type:Vu("code_execution_result"),stdout:Dl(),stderr:Dl(),return_code:lu()}),Nu({type:Vu("code_execution_tool_result_error"),error_code:Dl()})])})])),stop_reason:Dl().nullish(),usage:Au({input_tokens:lu(),output_tokens:lu(),cache_creation_input_tokens:lu().nullish(),cache_read_input_tokens:lu().nullish()})}),gm=ju("type",[Nu({type:Vu("message_start"),message:Nu({id:Dl().nullish(),model:Dl().nullish(),usage:Au({input_tokens:lu(),output_tokens:lu(),cache_creation_input_tokens:lu().nullish(),cache_read_input_tokens:lu().nullish()})})}),Nu({type:Vu("content_block_start"),index:lu(),content_block:ju("type",[Nu({type:Vu("text"),text:Dl()}),Nu({type:Vu("thinking"),thinking:Dl()}),Nu({type:Vu("tool_use"),id:Dl(),name:Dl()}),Nu({type:Vu("redacted_thinking"),data:Dl()}),Nu({type:Vu("server_tool_use"),id:Dl(),name:Dl(),input:qu(Dl(),ku()).nullish()}),Nu({type:Vu("web_search_tool_result"),tool_use_id:Dl(),content:Uu([Tu(Nu({type:Vu("web_search_result"),url:Dl(),title:Dl(),encrypted_content:Dl(),page_age:Dl().nullish()})),Nu({type:Vu("web_search_tool_result_error"),error_code:Dl()})])}),Nu({type:Vu("code_execution_tool_result"),tool_use_id:Dl(),content:Uu([Nu({type:Vu("code_execution_result"),stdout:Dl(),stderr:Dl(),return_code:lu()}),Nu({type:Vu("code_execution_tool_result_error"),error_code:Dl()})])})])}),Nu({type:Vu("content_block_delta"),index:lu(),delta:ju("type",[Nu({type:Vu("input_json_delta"),partial_json:Dl()}),Nu({type:Vu("text_delta"),text:Dl()}),Nu({type:Vu("thinking_delta"),thinking:Dl()}),Nu({type:Vu("signature_delta"),signature:Dl()}),Nu({type:Vu("citations_delta"),citation:dm})])}),Nu({type:Vu("content_block_stop"),index:lu()}),Nu({type:Vu("error"),error:Nu({type:Dl(),message:Dl()})}),Nu({type:Vu("message_delta"),delta:Nu({stop_reason:Dl().nullish()}),usage:Nu({output_tokens:lu()})}),Nu({type:Vu("message_stop")}),Nu({type:Vu("ping")})]),fm=Nu({signature:Dl().optional(),redactedData:Dl().optional()}),vm=Ud({id:"anthropic.bash_20241022",name:"bash",inputSchema:Tc.object({command:Tc.string(),restart:Tc.boolean().optional()})}),ym=Ud({id:"anthropic.bash_20250124",name:"bash",inputSchema:Tc.object({command:Tc.string(),restart:Tc.boolean().optional()})}),_m=Ud({id:"anthropic.computer_20241022",name:"computer",inputSchema:Nu({action:Ju(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:Tu(lu().int()).optional(),text:Dl().optional()})}),bm=Ud({id:"anthropic.computer_20250124",name:"computer",inputSchema:Nu({action:Ju(["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:Lu([lu().int(),lu().int()]).optional(),duration:lu().optional(),scroll_amount:lu().optional(),scroll_direction:Ju(["up","down","left","right"]).optional(),start_coordinate:Lu([lu().int(),lu().int()]).optional(),text:Dl().optional()})}),wm={bash_20241022:vm,bash_20250124:ym,textEditor_20241022:Ud({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Nu({command:Ju(["view","create","str_replace","insert","undo_edit"]),path:Dl(),file_text:Dl().optional(),insert_line:lu().int().optional(),new_str:Dl().optional(),old_str:Dl().optional(),view_range:Tu(lu().int()).optional()})}),textEditor_20250124:Ud({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:Nu({command:Ju(["view","create","str_replace","insert","undo_edit"]),path:Dl(),file_text:Dl().optional(),insert_line:lu().int().optional(),new_str:Dl().optional(),old_str:Dl().optional(),view_range:Tu(lu().int()).optional()})}),textEditor_20250429:Ud({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Nu({command:Ju(["view","create","str_replace","insert"]),path:Dl(),file_text:Dl().optional(),insert_line:lu().int().optional(),new_str:Dl().optional(),old_str:Dl().optional(),view_range:Tu(lu().int()).optional()})}),computer_20241022:_m,computer_20250124:bm,webSearch_20250305:(e={})=>rm(e),codeExecution_20250522:(e={})=>sm(e)};function km(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}),i=t=>{var i;return new mm(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(i=e.generateId)?i:gd,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},o=function(e){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(e)};return o.languageModel=i,o.chat=i,o.messages=i,o.textEmbeddingModel=e=>{throw new yt({modelId:e,modelType:"textEmbeddingModel"})},o.imageModel=e=>{throw new yt({modelId:e,modelType:"imageModel"})},o.tools=wm,o}var xm=km(),Im=zd({errorSchema:Nu({error:Nu({code:lu().nullable(),message:Dl(),status:Dl()})}),errorToMessage:e=>e.error.message}),Sm=Nu({outputDimensionality:lu().optional(),taskType:Ju(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),$m=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 i=await Nd({provider:"google",providerOptions:r,schema:Sm});if(e.length>this.maxEmbeddingsPerCall)throw new xt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=pd(await jd(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType},failedResponseHandler:Im,successfulResponseHandler:Md(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:l}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:e}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType})))},failedResponseHandler:Im,successfulResponseHandler:Md(Em),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map((e=>e.values)),usage:void 0,response:{headers:s,body:l}}}},Em=Nu({embeddings:Tu(Nu({values:Tu(lu())}))}),Tm=Nu({embedding:Nu({values:Tu(lu())})});function Om(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:i,items:o,allOf:s,anyOf:a,oneOf:l,format:u,const:c,minLength:d,enum:p}=e,m={};if(n&&(m.description=n),r&&(m.required=r),u&&(m.format=u),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!=i&&(m.properties=Object.entries(i).reduce(((e,[t,n])=>(e[t]=Om(n),e)),{})),o&&(m.items=Array.isArray(o)?o.map(Om):Om(o)),s&&(m.allOf=s.map(Om)),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=Om(e[0]);"object"==typeof t&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(Om),m.nullable=!0}else m.anyOf=a.map(Om);return l&&(m.oneOf=l.map(Om)),void 0!==d&&(m.minLength=d),m}function Nm(e){return e.includes("/")?e:`models/${e}`}var Cm=Nu({responseModalities:Tu(Ju(["TEXT","IMAGE"])).optional(),thinkingConfig:Nu({thinkingBudget:lu().optional(),includeThoughts:pu().optional()}).optional(),cachedContent:Dl().optional(),structuredOutputs:pu().optional(),safetySettings:Tu(Nu({category:Ju(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Ju(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Ju(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:pu().optional(),labels:qu(Dl(),Dl()).optional()});function Am({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 Rm=Nu({web:Nu({uri:Dl(),title:Dl()}).nullish(),retrievedContext:Nu({uri:Dl(),title:Dl()}).nullish()}),Um=Nu({webSearchQueries:Tu(Dl()).nullish(),retrievalQueries:Tu(Dl()).nullish(),searchEntryPoint:Nu({renderedContent:Dl()}).nullish(),groundingChunks:Tu(Rm).nullish(),groundingSupports:Tu(Nu({segment:Nu({startIndex:lu().nullish(),endIndex:lu().nullish(),text:Dl().nullish()}),segment_text:Dl().nullish(),groundingChunkIndices:Tu(lu()).nullish(),supportChunkIndices:Tu(lu()).nullish(),confidenceScores:Tu(lu()).nullish(),confidenceScore:Tu(lu()).nullish()})).nullish(),retrievalMetadata:Uu([Nu({webDynamicRetrievalScore:lu()}),Nu({})]).nullish()}),Pm=Ud({id:"google.google_search",name:"google_search",inputSchema:Nu({mode:Ju(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:lu().default(1)})}),jm=Nu({retrievedUrl:Dl(),urlRetrievalStatus:Dl()}),zm=Nu({urlMetadata:Tu(jm)}),Dm=Ud({id:"google.url_context",name:"url_context",inputSchema:Nu({})}),Mm=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:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var m,h;const g=[],f=await Nd({provider:"google",providerOptions:p,schema:Cm});!0!==(null==(m=null==f?void 0:f.thinkingConfig)?void 0:m.includeThoughts)||this.config.provider.startsWith("google.vertex.")||g.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 v=this.modelId.toLowerCase().startsWith("gemma-"),{contents:y,systemInstruction:_}=function(e,t){var n;const r=[],i=[];let o=!0;const s=null!=(n=null==t?void 0:t.isGemmaModel)&&n;for(const{role:a,content:l}of e)switch(a){case"system":if(!o)throw new Rt({functionality:"system messages are only supported at the beginning of the conversation"});r.push({text:l});break;case"user":{o=!1;const e=[];for(const t of l)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}}i.push({role:"user",parts:e});break}case"assistant":o=!1,i.push({role:"model",parts:l.map((e=>{var t,n,r,i,o,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==(i=null==(r=e.providerOptions)?void 0:r.google)?void 0:i.thoughtSignature};case"file":if("image/png"!==e.mediaType)throw new Rt({functionality:"Only PNG images are supported in assistant messages"});if(e.data instanceof URL)throw new Rt({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==(o=e.providerOptions)?void 0:o.google)?void 0:s.thoughtSignature}}})).filter((e=>void 0!==e))});break;case"tool":o=!1,i.push({role:"user",parts:l.map((e=>({functionResponse:{name:e.toolName,response:{name:e.toolName,content:e.output.value}}})))})}if(s&&r.length>0&&i.length>0&&"user"===i[0].role){const e=r.map((e=>e.text)).join("\n\n");i[0].parts.unshift({text:e+"\n\n"})}return{systemInstruction:r.length>0&&!s?{parts:r}:void 0,contents:i}}(e,{isGemmaModel:v}),{tools:b,toolConfig:w,toolWarnings:k}=function({tools:e,toolChoice:t,modelId:n}){var r;e=(null==e?void 0:e.length)?e:void 0;const i=[],o=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:i};const a=e.some((e=>"function"===e.type)),l=e.some((e=>"provider-defined"===e.type));if(a&&l&&i.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."}),l){const t={};return e.filter((e=>"provider-defined"===e.type)).forEach((e=>{switch(e.id){case"google.google_search":o?t.googleSearch={}:t.googleSearchRetrieval=s?{dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:{};break;case"google.url_context":o?t.urlContext={}:i.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":o?t.codeExecution={}:i.push({type:"unsupported-tool",tool:e,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:i.push({type:"unsupported-tool",tool:e})}})),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}const u=[];for(const d of e)"function"===d.type?u.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:Om(d.inputSchema)}):i.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:u},toolConfig:void 0,toolWarnings:i};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:i};case"none":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:i};case"required":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:i};case"tool":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:throw new Rt({functionality:`tool choice type: ${c}`})}}({tools:c,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:o,presencePenalty:s,stopSequences:a,seed:u,responseMimeType:"json"===(null==l?void 0:l.type)?"application/json":void 0,responseSchema:"json"!==(null==l?void 0:l.type)||null==l.schema||null!=(h=null==f?void 0:f.structuredOutputs)&&!h?void 0:Om(l.schema),...(null==f?void 0:f.audioTimestamp)&&{audioTimestamp:f.audioTimestamp},responseModalities:null==f?void 0:f.responseModalities,thinkingConfig:null==f?void 0:f.thinkingConfig},contents:y,systemInstruction:v?void 0:_,safetySettings:null==f?void 0:f.safetySettings,tools:b,toolConfig:w,cachedContent:null==f?void 0:f.cachedContent,labels:null==f?void 0:f.labels},warnings:[...g,...k]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p;const{args:m,warnings:h}=await this.getArgs(e),g=JSON.stringify(m),f=pd(await jd(this.config.headers),e.headers),{responseHeaders:v,value:y,rawValue:_}=await Ad({url:`${this.config.baseURL}/${Nm(this.modelId)}:generateContent`,headers:f,body:m,failedResponseHandler:Im,successfulResponseHandler:Md(Wm),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=y.candidates[0],w=[],k=null!=(n=null==(t=b.content)?void 0:t.parts)?n:[],x=y.usageMetadata;let I;for(const $ of k)if("executableCode"in $&&(null==(r=$.executableCode)?void 0:r.code)){const e=this.config.generateId();I=e,w.push({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify($.executableCode),providerExecuted:!0})}else"codeExecutionResult"in $&&$.codeExecutionResult?(w.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?w.push({type:!0===$.thought?"reasoning":"text",text:$.text,providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"functionCall"in $?w.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 $&&w.push({type:"file",data:$.inlineData.data,mediaType:$.inlineData.mimeType});const S=null!=(i=Lm({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))?i:[];for(const $ of S)w.push($);return{content:w,finishReason:Am({finishReason:b.finishReason,hasToolCalls:w.some((e=>"tool-call"===e.type))}),usage:{inputTokens:null!=(o=null==x?void 0:x.promptTokenCount)?o: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!=(l=null==x?void 0:x.thoughtsTokenCount)?l:void 0,cachedInputTokens:null!=(u=null==x?void 0:x.cachedContentTokenCount)?u:void 0},warnings:h,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:g},response:{headers:v,body:_}}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=pd(await jd(this.config.headers),e.headers),{responseHeaders:o,value:s}=await Ad({url:`${this.config.baseURL}/${Nm(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:Im,successfulResponseHandler:Dd(Bm),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u;const c=this.config.generateId;let d=!1,p=null,m=null,h=0;const g=new Set;let f;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,s,v,y,_,b,w,k,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&&(l.inputTokens=null!=(r=S.promptTokenCount)?r:void 0,l.outputTokens=null!=(i=S.candidatesTokenCount)?i:void 0,l.totalTokens=null!=(o=S.totalTokenCount)?o:void 0,l.reasoningTokens=null!=(s=S.thoughtsTokenCount)?s:void 0,l.cachedInputTokens=null!=(v=S.cachedContentTokenCount)?v:void 0);const $=null==(y=I.candidates)?void 0:y[0];if(null==$)return;const E=$.content,T=Lm({groundingMetadata:$.groundingMetadata,generateId:c});if(null!=T)for(const e of T)"url"!==e.sourceType||g.has(e.url)||(g.add(e.url),n.enqueue(e));if(null!=E){const e=null!=(_=E.parts)?_:[];for(const i of e)if("executableCode"in i&&(null==(b=i.executableCode)?void 0:b.code)){const e=c();f=e,n.enqueue({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(i.executableCode),providerExecuted:!0}),d=!0}else if("codeExecutionResult"in i&&i.codeExecutionResult){const e=f;e&&(n.enqueue({type:"tool-result",toolCallId:e,toolName:"code_execution",result:{outcome:i.codeExecutionResult.outcome,output:i.codeExecutionResult.output},providerExecuted:!0}),f=void 0)}else"text"in i&&null!=i.text&&i.text.length>0&&(!0===i.thought?(null!==p&&(n.enqueue({type:"text-end",id:p}),p=null),null===m&&(m=String(h++),n.enqueue({type:"reasoning-start",id:m,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"reasoning-delta",id:m,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})):(null!==m&&(n.enqueue({type:"reasoning-end",id:m}),m=null),null===p&&(p=String(h++),n.enqueue({type:"text-start",id:p,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"text-delta",id:p,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})));const t=function(e){return null==e?void 0:e.filter((e=>"inlineData"in e))}(E.parts);if(null!=t)for(const i of t)n.enqueue({type:"file",mediaType:i.inlineData.mimeType,data:i.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:E.parts,generateId:c});if(null!=r)for(const i of r)n.enqueue({type:"tool-input-start",id:i.toolCallId,toolName:i.toolName,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-delta",id:i.toolCallId,delta:i.args,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-end",id:i.toolCallId,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.args,providerMetadata:i.providerMetadata}),d=!0}null!=$.finishReason&&(a=Am({finishReason:$.finishReason,hasToolCalls:d}),u={google:{groundingMetadata:null!=(w=$.groundingMetadata)?w:null,urlContextMetadata:null!=(k=$.urlContextMetadata)?k:null,safetyRatings:null!=(x=$.safetyRatings)?x:null}},null!=S&&(u.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:l,providerMetadata:u})}})),response:{headers:o},request:{body:r}}}};function Lm({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=Nu({parts:Tu(Uu([Nu({functionCall:Nu({name:Dl(),args:ku()}),thoughtSignature:Dl().nullish()}),Nu({inlineData:Nu({mimeType:Dl(),data:Dl()})}),Nu({executableCode:Nu({language:Dl(),code:Dl()}).nullish(),codeExecutionResult:Nu({outcome:Dl(),output:Dl()}).nullish(),text:Dl().nullish(),thought:pu().nullish(),thoughtSignature:Dl().nullish()})])).nullish()}),qm=Nu({category:Dl().nullish(),probability:Dl().nullish(),probabilityScore:lu().nullish(),severity:Dl().nullish(),severityScore:lu().nullish(),blocked:pu().nullish()}),Fm=Nu({cachedContentTokenCount:lu().nullish(),thoughtsTokenCount:lu().nullish(),promptTokenCount:lu().nullish(),candidatesTokenCount:lu().nullish(),totalTokenCount:lu().nullish()}),Wm=Nu({candidates:Tu(Nu({content:Zm.nullish().or(Nu({}).strict()),finishReason:Dl().nullish(),safetyRatings:Tu(qm).nullish(),groundingMetadata:Um.nullish(),urlContextMetadata:zm.nullish()})),usageMetadata:Fm.nullish()}),Bm=Nu({candidates:Tu(Nu({content:Zm.nullish(),finishReason:Dl().nullish(),safetyRatings:Tu(qm).nullish(),groundingMetadata:Um.nullish(),urlContextMetadata:zm.nullish()})).nullish(),usageMetadata:Fm.nullish()}),Jm={googleSearch:Pm,urlContext:Dm,codeExecution:Pd({id:"google.code_execution",name:"code_execution",inputSchema:Nu({language:Dl().describe("The programming language of the code."),code:Dl().describe("The code to be executed.")}),outputSchema:Nu({outcome:Dl().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:Dl().describe("The output from the code execution.")})})},Hm=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:i,n:o=1,size:s="1024x1024",aspectRatio:a="1:1",seed:l,providerOptions:u,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!=l&&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:u,schema:Km}),h=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,g={sampleCount:o};null!=a&&(g.aspectRatio=a),m&&Object.assign(g,m);const f={instances:[{prompt:i}],parameters:g},{responseHeaders:v,value:y}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:pd(await jd(this.config.headers),c),body:f,failedResponseHandler:Im,successfulResponseHandler:Md(Vm),abortSignal:d,fetch:this.config.fetch});return{images:y.predictions.map((e=>e.bytesBase64Encoded)),warnings:null!=p?p:[],providerMetadata:{google:{images:y.predictions.map((e=>({})))}},response:{timestamp:h,modelId:this.modelId,headers:v}}}},Vm=Nu({predictions:Tu(Nu({bytesBase64Encoded:Dl()})).default([])}),Km=Nu({personGeneration:Ju(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Ju(["1:1","3:4","4:3","9:16","16:9"]).nullish()});function Gm(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}),i=t=>{var i;return new Mm(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(i=e.generateId)?i: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})},o=t=>new $m(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,i={})=>new Hm(t,i,{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 i(e)};return a.languageModel=i,a.chat=i,a.generativeAI=i,a.embedding=o,a.textEmbedding=o,a.textEmbeddingModel=o,a.image=s,a.imageModel=s,a.tools=Jm,a}var Ym=Gm(),Xm=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},Qm=class{constructor(e){o(this,"getTokenFn"),o(this,"refreshTokenFn"),o(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)}},eh={baseUrl:"undefined"!=typeof process&&(null==(r=process.env)?void 0:r.ECHO_BASE_URL)||"https://echo.merit.systems"};var th="https://echo.router.merit.systems",nh=class{constructor(e,t){o(this,"isRefreshing",!1),o(this,"refreshPromise",null),this.baseUrl=e,this.tokenProvider=t}async request(e,t={}){var n;const r=await this.tokenProvider.getAccessToken(),i=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...r&&{Authorization:`Bearer ${r}`}}});if(401===i.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 i}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"})}},rh=class extends Error{constructor(e,t,n){super(t),o(this,"code"),o(this,"statusCode"),o(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 ih(e,t,n){if("TypeError"===e.name)return new rh("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]),i=r[2];return new rh(`HTTP_${e}`,`${i}${t?` while ${t}`:""}`,n?{statusCode:e,endpoint:n}:{statusCode:e})}return new rh("UNKNOWN_ERROR",`${e.message}${t?` while ${t}`:""}`,n?{endpoint:n}:void 0)}var oh=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 ih(r,t,n);throw new rh("UNKNOWN_ERROR","Unknown error occurred",n?{endpoint:n}:void 0)}}},sh=class extends oh{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}`}},ah=class extends oh{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")}},lh=class extends oh{constructor(e){super(e)}async getSupportedModels(){return this.handleRequest((()=>this.http.get("/api/v1/supported-models")),"fetching supported models","/api/v1/supported-models")}async listSupportedModels(){try{return(await this.getSupportedModels()).models}catch(e){throw e}}async getSupportedModelsByProvider(){try{return(await this.getSupportedModels()).models_by_provider}catch(e){throw e}}},uh=class extends oh{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(i){throw i}}},ch=class extends oh{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")}},dh=class{constructor(e){var t;if(o(this,"http"),o(this,"config"),o(this,"tokenProvider"),o(this,"balance"),o(this,"payments"),o(this,"apps"),o(this,"users"),o(this,"models"),this.config=(t=e,{...eh,...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 Xm(e)}this.http=new nh(this.config.baseUrl,this.tokenProvider),this.balance=new ah(this.http),this.payments=new uh(this.http),this.apps=new sh(this.http,this.config.baseUrl),this.users=new ch(this.http),this.models=new lh(this.http)}};function ph({appId:e,baseRouterUrl:t=th},n){const r=async()=>{const r=await n(e);return Kp({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),responses:async e=>(await r()).responses(e),completion:async e=>(await r()).completion(e),embedding:async e=>(await r()).embedding(e),textEmbedding:async e=>(await r()).textEmbedding(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),image:async e=>(await r()).image(e),imageModel:async e=>(await r()).imageModel(e),transcription:async e=>(await r()).transcription(e),speech:async e=>(await r()).speech(e),tools:Gp.tools})}function mh({appId:e,baseRouterUrl:t=th},n){const r=async()=>{const r=await n(e);return km({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),messages:async e=>(await r()).messages(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),imageModel:async e=>(await r()).imageModel(e),tools:xm.tools})}function hh({appId:e,baseRouterUrl:t=th},n){const r=async()=>{const r=await n(e);return Gm({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),image:async(e,t)=>(await r()).image(e,t),imageModel:async e=>(await r()).imageModel(e),textEmbedding:async e=>(await r()).textEmbedding(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),generativeAI:async e=>(await r()).generativeAI(e),embedding:async e=>(await r()).embedding(e),tools:Ym.tools})}function gh({apiUrl:e}){var t,r;const i=Ee(),[o,s]=n.useState(null);return n.useEffect((()=>{if(!i.user)return void s(null);const t=new Qm({getTokenFn:()=>{var e;return Promise.resolve((null==(e=i.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{await i.signinSilent()},onRefreshErrorFn:e=>{console.error("Token refresh failed:",e),i.signoutSilent()}}),n=new dh({baseUrl:e,tokenProvider:t});return s(n),()=>{s(null)}}),[e,i.user,null==(r=null==(t=i.user)?void 0:t.profile)?void 0:r.sub,i.signinSilent,i.signoutSilent]),o}const fh=n.createContext(null),vh=n.createContext(null);function yh({config:e,children:r}){var i,o,s;const a=Ee(),l=a.user,u=l?function(e){return{id:e.profile.sub||"",email:e.profile.email||"",name:e.profile.name||e.profile.preferred_username||"",picture:e.profile.picture||""}}(l):null,c=e.apiUrl||"https://echo.merit.systems",d=(null==(i=a.user)?void 0:i.access_token)||null,p=gh({apiUrl:c}),{balance:m,freeTierBalance:h,refreshBalance:g,error:f,isLoading:v}=function(e,t){const[r,i]=n.useState(null),[o,s]=n.useState(null),[a,l]=n.useState(null),[u,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)]);i(n),s(r),l(null)}catch(n){const e=ih(n instanceof Error?n:new Error(String(n)),"refreshing balance");throw l(e.message),e}finally{c(!1)}}),[e,t]);return n.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(i(null),s(null),l(null))}),[e,t,d]),{balance:r,freeTierBalance:o,error:a,isLoading:u,refreshBalance:d}}(p,e.appId),{createPaymentLink:y,error:_,isLoading:b}=function(e){const[t,r]=n.useState(null),[i,o]=n.useState(!1);return{createPaymentLink:n.useCallback((async(t,n,i)=>{if(!e)throw new Error("Not authenticated");o(!0);try{const o=await e.payments.createPaymentLink({amount:t,description:n||"Echo Credits",successUrl:i||window.location.origin});return r(null),o.paymentLink.url}catch(s){const e=ih(s instanceof Error?s:new Error(String(s)),"creating payment link");throw r(e.message),e}finally{o(!1)}}),[e]),error:t,isLoading:i}}(p),w=n.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),k=n.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(o=a.user)?void 0:o.access_token]),x=(null==(s=a.error)?void 0:s.message)||f||_||null,I=a.isLoading&&!a.isAuthenticated,S=a.isLoading&&a.isAuthenticated,$=I||v||b,E=n.useMemo((()=>({user:u||null,rawUser:l,balance:m,freeTierBalance:h,isAuthenticated:a.isAuthenticated,isLoading:$,error:x,token:d,echoClient:p,signIn:a.signinRedirect,signOut:w,refreshBalance:g,createPaymentLink:y,getToken:k,clearAuth:w,config:e})),[u,l,m,h,a.isAuthenticated,$,x,d,p,a.signinRedirect,w,g,y,k,e]),T=n.useMemo((()=>({isRefreshing:S})),[S]);return t.jsx(fh.Provider,{value:E,children:t.jsx(vh.Provider,{value:T,children:r})})}function _h(){const e=n.useContext(fh);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:bh,setPrototypeOf:wh,isFrozen:kh,getPrototypeOf:xh,getOwnPropertyDescriptor:Ih}=Object;let{freeze:Sh,seal:$h,create:Eh}=Object,{apply:Th,construct:Oh}="undefined"!=typeof Reflect&&Reflect;Sh||(Sh=function(e){return e}),$h||($h=function(e){return e}),Th||(Th=function(e,t,n){return e.apply(t,n)}),Oh||(Oh=function(e,t){return new e(...t)});const Nh=Bh(Array.prototype.forEach),Ch=Bh(Array.prototype.lastIndexOf),Ah=Bh(Array.prototype.pop),Rh=Bh(Array.prototype.push),Uh=Bh(Array.prototype.splice),Ph=Bh(String.prototype.toLowerCase),jh=Bh(String.prototype.toString),zh=Bh(String.prototype.match),Dh=Bh(String.prototype.replace),Mh=Bh(String.prototype.indexOf),Lh=Bh(String.prototype.trim),Zh=Bh(Object.prototype.hasOwnProperty),qh=Bh(RegExp.prototype.test),Fh=(Wh=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Oh(Wh,t)});var Wh;function Bh(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return Th(e,t,r)}}function Jh(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Ph;wh&&wh(e,null);let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(kh(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Hh(e){for(let t=0;t<e.length;t++){Zh(e,t)||(e[t]=null)}return e}function Vh(e){const t=Eh(null);for(const[n,r]of bh(e)){Zh(e,n)&&(Array.isArray(r)?t[n]=Hh(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=Vh(r):t[n]=r)}return t}function Kh(e,t){for(;null!==e;){const n=Ih(e,t);if(n){if(n.get)return Bh(n.get);if("function"==typeof n.value)return Bh(n.value)}e=xh(e)}return function(){return null}}const Gh=Sh(["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"]),Yh=Sh(["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"]),Xh=Sh(["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"]),Qh=Sh(["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"]),eg=Sh(["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"]),tg=Sh(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ng=Sh(["#text"]),rg=Sh(["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"]),ig=Sh(["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"]),og=Sh(["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"]),sg=Sh(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ag=$h(/\{\{[\w\W]*|[\w\W]*\}\}/gm),lg=$h(/<%[\w\W]*|[\w\W]*%>/gm),ug=$h(/\$\{[\w\W]*/gm),cg=$h(/^data-[\-\w.\u00B7-\uFFFF]+$/),dg=$h(/^aria-[\-\w]+$/),pg=$h(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),mg=$h(/^(?:\w+script|data):/i),hg=$h(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),gg=$h(/^html$/i),fg=$h(/^[a-z][.\w]*(-[.\w]+)+$/i);var vg=Object.freeze({__proto__:null,ARIA_ATTR:dg,ATTR_WHITESPACE:hg,CUSTOM_ELEMENT:fg,DATA_ATTR:cg,DOCTYPE_NAME:gg,ERB_EXPR:lg,IS_ALLOWED_URI:pg,IS_SCRIPT_OR_DATA:mg,MUSTACHE_EXPR:ag,TMPLIT_EXPR:ug});const yg=1,_g=3,bg=7,wg=8,kg=9;var xg=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!==kg||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const i=r,o=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:l,Element:u,NodeFilter:c,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:h}=t,g=u.prototype,f=Kh(g,"cloneNode"),v=Kh(g,"remove"),y=Kh(g,"nextSibling"),_=Kh(g,"childNodes"),b=Kh(g,"parentNode");if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let w,k="";const{implementation:x,createNodeIterator:I,createDocumentFragment:S,getElementsByTagName:$}=r,{importNode:E}=i;let T={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof bh&&"function"==typeof b&&x&&void 0!==x.createHTMLDocument;const{MUSTACHE_EXPR:O,ERB_EXPR:N,TMPLIT_EXPR:C,DATA_ATTR:A,ARIA_ATTR:R,IS_SCRIPT_OR_DATA:U,ATTR_WHITESPACE:P,CUSTOM_ELEMENT:j}=vg;let{IS_ALLOWED_URI:z}=vg,D=null;const M=Jh({},[...Gh,...Yh,...Xh,...eg,...ng]);let L=null;const Z=Jh({},[...rg,...ig,...og,...sg]);let q=Object.seal(Eh(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,B=!0,J=!0,H=!1,V=!0,K=!1,G=!0,Y=!1,X=!1,Q=!1,ee=!1,te=!1,ne=!1,re=!0,ie=!1,oe=!0,se=!1,ae={},le=null;const ue=Jh({},["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=Jh({},["audio","video","img","source","image","track"]);let pe=null;const me=Jh({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),he="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",fe="http://www.w3.org/1999/xhtml";let ve=fe,ye=!1,_e=null;const be=Jh({},[he,ge,fe],jh);let we=Jh({},["mi","mo","mn","ms","mtext"]),ke=Jh({},["annotation-xml"]);const xe=Jh({},["title","style","font","a","script"]);let Ie=null;const Se=["application/xhtml+xml","text/html"];let $e=null,Ee=null;const Te=r.createElement("form"),Oe=function(e){return e instanceof RegExp||e instanceof Function},Ne=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Ee||Ee!==e){if(e&&"object"==typeof e||(e={}),e=Vh(e),Ie=-1===Se.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,$e="application/xhtml+xml"===Ie?jh:Ph,D=Zh(e,"ALLOWED_TAGS")?Jh({},e.ALLOWED_TAGS,$e):M,L=Zh(e,"ALLOWED_ATTR")?Jh({},e.ALLOWED_ATTR,$e):Z,_e=Zh(e,"ALLOWED_NAMESPACES")?Jh({},e.ALLOWED_NAMESPACES,jh):be,pe=Zh(e,"ADD_URI_SAFE_ATTR")?Jh(Vh(me),e.ADD_URI_SAFE_ATTR,$e):me,ce=Zh(e,"ADD_DATA_URI_TAGS")?Jh(Vh(de),e.ADD_DATA_URI_TAGS,$e):de,le=Zh(e,"FORBID_CONTENTS")?Jh({},e.FORBID_CONTENTS,$e):ue,F=Zh(e,"FORBID_TAGS")?Jh({},e.FORBID_TAGS,$e):Vh({}),W=Zh(e,"FORBID_ATTR")?Jh({},e.FORBID_ATTR,$e):Vh({}),ae=!!Zh(e,"USE_PROFILES")&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,J=!1!==e.ALLOW_DATA_ATTR,H=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,ie=e.SANITIZE_NAMED_PROPS||!1,oe=!1!==e.KEEP_CONTENT,se=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||pg,ve=e.NAMESPACE||fe,we=e.MATHML_TEXT_INTEGRATION_POINTS||we,ke=e.HTML_INTEGRATION_POINTS||ke,q=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Oe(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(q.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Oe(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(q.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(q.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),K&&(J=!1),te&&(ee=!0),ae&&(D=Jh({},ng),L=[],!0===ae.html&&(Jh(D,Gh),Jh(L,rg)),!0===ae.svg&&(Jh(D,Yh),Jh(L,ig),Jh(L,sg)),!0===ae.svgFilters&&(Jh(D,Xh),Jh(L,ig),Jh(L,sg)),!0===ae.mathMl&&(Jh(D,eg),Jh(L,og),Jh(L,sg))),e.ADD_TAGS&&(D===M&&(D=Vh(D)),Jh(D,e.ADD_TAGS,$e)),e.ADD_ATTR&&(L===Z&&(L=Vh(L)),Jh(L,e.ADD_ATTR,$e)),e.ADD_URI_SAFE_ATTR&&Jh(pe,e.ADD_URI_SAFE_ATTR,$e),e.FORBID_CONTENTS&&(le===ue&&(le=Vh(le)),Jh(le,e.FORBID_CONTENTS,$e)),oe&&(D["#text"]=!0),Y&&Jh(D,["html","head","body"]),D.table&&(Jh(D,["tbody"]),delete F.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Fh('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Fh('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');w=e.TRUSTED_TYPES_POLICY,k=w.createHTML("")}else void 0===w&&(w=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 i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(o){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o)),null!==w&&"string"==typeof k&&(k=w.createHTML(""));Sh&&Sh(e),Ee=e}},Ce=Jh({},[...Yh,...Xh,...Qh]),Ae=Jh({},[...eg,...tg]),Re=function(e){Rh(n.removed,{element:e});try{b(e).removeChild(e)}catch(t){v(e)}},Ue=function(e,t){try{Rh(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){Rh(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Re(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},Pe=function(e){let t=null,n=null;if(Q)e="<remove></remove>"+e;else{const t=zh(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Ie&&ve===fe&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const i=w?w.createHTML(e):e;if(ve===fe)try{t=(new m).parseFromString(i,Ie)}catch(s){}if(!t||!t.documentElement){t=x.createDocument(ve,"template",null);try{t.documentElement.innerHTML=ye?k:i}catch(s){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),ve===fe?$.call(t,Y?"html":"body")[0]:Y?t.documentElement:o},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 l&&e instanceof l};function Me(e,t,r){Nh(e,(e=>{e.call(n,t,r,Ee)}))}const Le=function(e){let t=null;if(Me(T.beforeSanitizeElements,e,null),ze(e))return Re(e),!0;const r=$e(e.nodeName);if(Me(T.uponSanitizeElement,e,{tagName:r,allowedTags:D}),G&&e.hasChildNodes()&&!De(e.firstElementChild)&&qh(/<[/\w!]/g,e.innerHTML)&&qh(/<[/\w!]/g,e.textContent))return Re(e),!0;if(e.nodeType===bg)return Re(e),!0;if(G&&e.nodeType===wg&&qh(/<[/\w]/g,e.data))return Re(e),!0;if(!D[r]||F[r]){if(!F[r]&&qe(r)){if(q.tagNameCheck instanceof RegExp&&qh(q.tagNameCheck,r))return!1;if(q.tagNameCheck instanceof Function&&q.tagNameCheck(r))return!1}if(oe&&!le[r]){const t=b(e)||e.parentNode,n=_(e)||e.childNodes;if(n&&t){for(let r=n.length-1;r>=0;--r){const i=f(n[r],!0);i.__removalCount=(e.__removalCount||0)+1,t.insertBefore(i,y(e))}}}return Re(e),!0}return e instanceof u&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:ve,tagName:"template"});const n=Ph(e.tagName),r=Ph(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===fe?"svg"===n:t.namespaceURI===he?"svg"===n&&("annotation-xml"===r||we[r]):Boolean(Ce[n]):e.namespaceURI===he?t.namespaceURI===fe?"math"===n:t.namespaceURI===ge?"math"===n&&ke[r]:Boolean(Ae[n]):e.namespaceURI===fe?!(t.namespaceURI===ge&&!ke[r])&&!(t.namespaceURI===he&&!we[r])&&!Ae[n]&&(xe[n]||!Ce[n]):!("application/xhtml+xml"!==Ie||!_e[e.namespaceURI]))}(e)?(Re(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!qh(/<\/no(script|embed|frames)/i,e.innerHTML)?(K&&e.nodeType===_g&&(t=e.textContent,Nh([O,N,C],(e=>{t=Dh(t,e," ")})),e.textContent!==t&&(Rh(n.removed,{element:e.cloneNode()}),e.textContent=t)),Me(T.afterSanitizeElements,e,null),!1):(Re(e),!0)},Ze=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in r||n in Te))return!1;if(J&&!W[t]&&qh(A,t));else if(B&&qh(R,t));else if(!L[t]||W[t]){if(!(qe(e)&&(q.tagNameCheck instanceof RegExp&&qh(q.tagNameCheck,e)||q.tagNameCheck instanceof Function&&q.tagNameCheck(e))&&(q.attributeNameCheck instanceof RegExp&&qh(q.attributeNameCheck,t)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(t))||"is"===t&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&qh(q.tagNameCheck,n)||q.tagNameCheck instanceof Function&&q.tagNameCheck(n))))return!1}else if(pe[t]);else if(qh(z,Dh(n,P,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Mh(n,"data:")||!ce[e]){if(H&&!qh(U,Dh(n,P,"")));else if(n)return!1}else;return!0},qe=function(e){return"annotation-xml"!==e&&zh(e,j)},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 i=t.length;for(;i--;){const s=t[i],{name:a,namespaceURI:l,value:u}=s,c=$e(a),d=u;let p="value"===a?d:Lh(d);if(r.attrName=c,r.attrValue=p,r.keepAttr=!0,r.forceKeepAttr=void 0,Me(T.uponSanitizeAttribute,e,r),p=r.attrValue,!ie||"id"!==c&&"name"!==c||(Ue(a,e),p="user-content-"+p),G&&qh(/((--!?|])>)|<\/(style|title)/i,p)){Ue(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Ue(a,e);continue}if(!V&&qh(/\/>/i,p)){Ue(a,e);continue}K&&Nh([O,N,C],(e=>{p=Dh(p,e," ")}));const m=$e(e.nodeName);if(Ze(m,c,p)){if(w&&"object"==typeof h&&"function"==typeof h.getAttributeType)if(l);else switch(h.getAttributeType(m,c)){case"TrustedHTML":p=w.createHTML(p);break;case"TrustedScriptURL":p=w.createScriptURL(p)}if(p!==d)try{l?e.setAttributeNS(l,a,p):e.setAttribute(a,p),ze(e)?Re(e):Ah(n.removed)}catch(o){Ue(a,e)}}else Ue(a,e)}Me(T.afterSanitizeAttributes,e,null)},We=function e(t){let n=null;const r=je(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,o=null,a=null,u=null;if(ye=!e,ye&&(e="\x3c!--\x3e"),"string"!=typeof e&&!De(e)){if("function"!=typeof e.toString)throw Fh("toString is not a function");if("string"!=typeof(e=e.toString()))throw Fh("dirty is not a string, aborting")}if(!n.isSupported)return e;if(X||Ne(t),n.removed=[],"string"==typeof e&&(se=!1),se){if(e.nodeName){const t=$e(e.nodeName);if(!D[t]||F[t])throw Fh("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof l)r=Pe("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),o.nodeType===yg&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o);else{if(!ee&&!K&&!Y&&-1===e.indexOf("<"))return w&&ne?w.createHTML(e):e;if(r=Pe(e),!r)return ee?null:ne?k:""}r&&Q&&Re(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(u=S.call(r.ownerDocument);r.firstChild;)u.appendChild(r.firstChild);else u=r;return(L.shadowroot||L.shadowrootmode)&&(u=E.call(i,u,!0)),u}let d=Y?r.outerHTML:r.innerHTML;return Y&&D["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&qh(gg,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),K&&Nh([O,N,C],(e=>{d=Dh(d,e," ")})),w&&ne?w.createHTML(d):d},n.setConfig=function(){Ne(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),X=!0},n.clearConfig=function(){Ee=null,X=!1},n.isValidAttribute=function(e,t,n){Ee||Ne({});const r=$e(e),i=$e(t);return Ze(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Rh(T[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=Ch(T[e],t);return-1===n?void 0:Uh(T[e],n,1)[0]}return Ah(T[e])},n.removeHooks=function(e){T[e]=[]},n.removeAllHooks=function(){T={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Ig=(()=>{if("undefined"!=typeof window)return xg;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return xg(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Sg(e){if(!e)return"";const t=String(e);try{let e=Ig.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 $g(e,t={}){const{onComplete:n,onCancel:r,onError:i}=t,o=function(e){if(!e)return"";const t=Sg(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==i||i(e),e}try{const e=window.open(o,"echo-payment","width=600,height=700,scrollbars=yes,resizable=yes");if(e&&!e.closed)return new Promise((t=>{const i=()=>{try{if(e.closed)return null==n||n(),void t();setTimeout(i,1e3)}catch{null==n||n(),t()}};i(),setTimeout((()=>{e.close(),null==r||r(),t()}),6e5)}));return confirm("Payment will open in a new tab. Click OK to continue, or Cancel to abort.")?(sessionStorage.setItem("echo_payment_flow","true"),window.location.href=o,new Promise((e=>{const t=()=>{"completed"===sessionStorage.getItem("echo_payment_flow")&&(sessionStorage.removeItem("echo_payment_flow"),null==n||n(),window.removeEventListener("focus",t),e())};window.addEventListener("focus",t),setTimeout((()=>{window.removeEventListener("focus",t),sessionStorage.removeItem("echo_payment_flow"),null==r||r(),e()}),18e5)}))):(null==r||r(),Promise.resolve())}catch(s){const e=s instanceof Error?s:new Error("Payment flow failed");throw null==i||i(e),e}}const Eg=({className:e="",width:n=16,height:r=16,variant:i="light"})=>{const o="dark"===i?"#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: ${o};\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)"})]})]})};const Tg=({onAddCredits:e,onCancel:r,isProcessing:i})=>{const[o,s]=n.useState(""),a=n.useRef(null);n.useEffect((()=>{a.current&&a.current.focus()}),[]);const l=""!==o&&Number(o)>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:o,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(o);t>0&&e(t)},disabled:i||!l,style:{padding:"8px 16px",backgroundColor:i||!l?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:i||!l?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!i&&l&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!i&&l&&(e.currentTarget.style.backgroundColor="#dc2626")},children:i?"Processing...":"Add Credits"})]})]})};const Og=n.createContext(null);var Ng,Cg=Object.defineProperty,Ag="AI_NoObjectGeneratedError",Rg=`vercel.ai.error.${Ag}`,Ug=Symbol.for(Rg),Pg=class extends Ae{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:i,finishReason:o}){super({name:Ag,message:e,cause:t}),this[Ng]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=o}static isInstance(e){return Ae.hasMarker(e,Rg)}};Ng=Ug;var jg=Uu([Dl(),Ic(Uint8Array),Ic(ArrayBuffer),wc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),zg=yc((()=>Uu([yu(),Dl(),lu(),pu(),qu(Dl(),zg),Tu(zg)]))),Dg=qu(Dl(),qu(Dl(),zg)),Mg=Nu({type:Vu("text"),text:Dl(),providerOptions:Dg.optional()}),Lg=Nu({type:Vu("image"),image:Uu([jg,Ic(URL)]),mediaType:Dl().optional(),providerOptions:Dg.optional()}),Zg=Nu({type:Vu("file"),data:Uu([jg,Ic(URL)]),filename:Dl().optional(),mediaType:Dl(),providerOptions:Dg.optional()}),qg=Nu({type:Vu("reasoning"),text:Dl(),providerOptions:Dg.optional()}),Fg=Nu({type:Vu("tool-call"),toolCallId:Dl(),toolName:Dl(),input:ku(),providerOptions:Dg.optional(),providerExecuted:pu().optional()}),Wg=ju("type",[Nu({type:Vu("text"),value:Dl()}),Nu({type:Vu("json"),value:zg}),Nu({type:Vu("error-text"),value:Dl()}),Nu({type:Vu("error-json"),value:zg}),Nu({type:Vu("content"),value:Tu(Uu([Nu({type:Vu("text"),text:Dl()}),Nu({type:Vu("media"),data:Dl(),mediaType:Dl()})]))})]),Bg=Nu({type:Vu("tool-result"),toolCallId:Dl(),toolName:Dl(),output:Wg,providerOptions:Dg.optional()}),Jg=Nu({role:Vu("system"),content:Dl(),providerOptions:Dg.optional()}),Hg=Nu({role:Vu("user"),content:Uu([Dl(),Tu(Uu([Mg,Lg,Zg]))]),providerOptions:Dg.optional()}),Vg=Nu({role:Vu("assistant"),content:Uu([Dl(),Tu(Uu([Mg,Zg,qg,Fg,Bg]))]),providerOptions:Dg.optional()});Uu([Jg,Hg,Vg,Nu({role:Vu("tool"),content:Tu(Bg),providerOptions:Dg.optional()})]),hd({prefix:"aitxt",size:24}),TransformStream;var Kg=Uu([Cu({type:Vu("text-start"),id:Dl(),providerMetadata:Dg.optional()}),Cu({type:Vu("text-delta"),id:Dl(),delta:Dl(),providerMetadata:Dg.optional()}),Cu({type:Vu("text-end"),id:Dl(),providerMetadata:Dg.optional()}),Cu({type:Vu("error"),errorText:Dl()}),Cu({type:Vu("tool-input-start"),toolCallId:Dl(),toolName:Dl(),providerExecuted:pu().optional(),dynamic:pu().optional()}),Cu({type:Vu("tool-input-delta"),toolCallId:Dl(),inputTextDelta:Dl()}),Cu({type:Vu("tool-input-available"),toolCallId:Dl(),toolName:Dl(),input:ku(),providerExecuted:pu().optional(),providerMetadata:Dg.optional(),dynamic:pu().optional()}),Cu({type:Vu("tool-input-error"),toolCallId:Dl(),toolName:Dl(),input:ku(),providerExecuted:pu().optional(),providerMetadata:Dg.optional(),dynamic:pu().optional(),errorText:Dl()}),Cu({type:Vu("tool-output-available"),toolCallId:Dl(),output:ku(),providerExecuted:pu().optional(),dynamic:pu().optional(),preliminary:pu().optional()}),Cu({type:Vu("tool-output-error"),toolCallId:Dl(),errorText:Dl(),providerExecuted:pu().optional(),dynamic:pu().optional()}),Cu({type:Vu("reasoning"),text:Dl(),providerMetadata:Dg.optional()}),Cu({type:Vu("reasoning-start"),id:Dl(),providerMetadata:Dg.optional()}),Cu({type:Vu("reasoning-delta"),id:Dl(),delta:Dl(),providerMetadata:Dg.optional()}),Cu({type:Vu("reasoning-end"),id:Dl(),providerMetadata:Dg.optional()}),Cu({type:Vu("reasoning-part-finish")}),Cu({type:Vu("source-url"),sourceId:Dl(),url:Dl(),title:Dl().optional(),providerMetadata:Dg.optional()}),Cu({type:Vu("source-document"),sourceId:Dl(),mediaType:Dl(),title:Dl(),filename:Dl().optional(),providerMetadata:Dg.optional()}),Cu({type:Vu("file"),url:Dl(),mediaType:Dl(),providerMetadata:Dg.optional()}),Cu({type:Dl().startsWith("data-"),id:Dl().optional(),data:ku(),transient:pu().optional()}),Cu({type:Vu("start-step")}),Cu({type:Vu("finish-step")}),Cu({type:Vu("start"),messageId:Dl().optional(),messageMetadata:ku().optional()}),Cu({type:Vu("finish"),messageMetadata:ku().optional()}),Cu({type:Vu("abort")}),Cu({type:Vu("message-metadata"),messageMetadata:ku()})]);function Gg(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 i=t[r];if(void 0===i)continue;const o=r in e?e[r]:void 0,s=!(null===i||"object"!=typeof i||Array.isArray(i)||i instanceof Date||i instanceof RegExp),a=!(null==o||"object"!=typeof o||Array.isArray(o)||o instanceof Date||o instanceof RegExp);n[r]=s&&a?Gg(o,i):i}return n}function Yg(e){const t=["ROOT"];let n=-1,r=null;function i(e,i,o){switch(e){case'"':n=i,t.pop(),t.push(o),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=i,r=i,t.pop(),t.push(o),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(o),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=i,t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"{":n=i,t.pop(),t.push(o),t.push("INSIDE_OBJECT_START");break;case"[":n=i,t.pop(),t.push(o),t.push("INSIDE_ARRAY_START")}}function o(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 l=0;l<e.length;l++){const a=e[l];switch(t[t.length-1]){case"ROOT":i(a,l,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=l,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":i(a,l,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(a,l);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=l;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=l}break;case"INSIDE_ARRAY_START":if("]"===a)n=l,t.pop();else n=l,i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=l,t.pop();break;default:n=l}break;case"INSIDE_ARRAY_AFTER_COMMA":i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=l;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=l;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l);break;default:t.pop()}break;case"INSIDE_LITERAL":{const i=e.substring(r,l+1);"false".startsWith(i)||"true".startsWith(i)||"null".startsWith(i)?n=l:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(a,l):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l));break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--){switch(t[l]){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 Xg(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:Yg(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Qg(e){return e.type.startsWith("tool-")}function ef(e){return e.type.split("-").slice(1).join("-")}function tf({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 nf({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:o,onData:s}){return e.pipeThrough(new TransformStream({async transform(e,a){await r((async({state:r,write:l})=>{var u,c,d,p;function m(e){const t=r.message.parts.filter(Qg).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){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 g(e){var t;const n=r.message.parts.find((t=>Qg(t)&&t.toolCallId===e.toolCallId)),i=e,o=n;null!=n?(n.state=e.state,o.input=i.input,o.output=i.output,o.errorText=i.errorText,o.rawInput=i.rawInput,o.preliminary=i.preliminary,o.providerExecuted=null!=(t=i.providerExecuted)?t:n.providerExecuted,null!=i.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=i.providerMetadata)):r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...null!=i.providerMetadata?{callProviderMetadata:i.providerMetadata}:{}})}function f(e){var t;const n=r.message.parts.find((t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId)),i=e,o=n;null!=n?(n.state=e.state,o.toolName=e.toolName,o.input=i.input,o.output=i.output,o.errorText=i.errorText,o.rawInput=null!=(t=i.rawInput)?t:o.rawInput,o.preliminary=i.preliminary,null!=i.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=i.providerMetadata)):r.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,...null!=i.providerMetadata?{callProviderMetadata:i.providerMetadata}:{}})}async function v(e){if(null!=e){const n=null!=r.message.metadata?Gg(r.message.metadata,e):e;null!=t&&await Sd({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),l();break}case"text-delta":{const t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(u=e.providerMetadata)?u:t.providerMetadata,l();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],l();break}case"reasoning-start":{const t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),l();break}case"reasoning-delta":{const t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,l();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],l();break}case"file":r.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url}),l();break;case"source-url":r.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),l();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}),l();break;case"tool-input-start":{const t=r.message.parts.filter(Qg);r.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic},e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0}):g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted}),l();break}case"tool-input-delta":{const t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;const{value:n}=await Xg(t.text);t.dynamic?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}):g({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}),l();break}case"tool-input-available":e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerMetadata:e.providerMetadata}):g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),l(),o&&!e.providerExecuted&&await o({toolCall:e});break;case"tool-input-error":e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerMetadata:e.providerMetadata}):g({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),l();break;case"tool-output-available":if(e.dynamic){const t=h(e.toolCallId);f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary})}else{const t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:ef(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}l();break;case"tool-output-error":if(e.dynamic){const t=h(e.toolCallId);f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText})}else{const t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:ef(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText})}l();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 v(e.messageMetadata),null==e.messageId&&null==e.messageMetadata||l();break;case"finish":case"message-metadata":await v(e.messageMetadata),null!=e.messageMetadata&&l();break;case"error":null==i||i(new Error(e.errorText));break;default:if(function(e){return e.type.startsWith("data-")}(e)){null!=(null==n?void 0:n[e.type])&&await Sd({value:e.data,schema:n[e.type]});const t=e;if(t.transient){null==s||s(t);break}const i=null!=t.id?r.message.parts.find((e=>t.type===e.type&&t.id===e.id)):void 0;null!=i?i.data=t.data:r.message.parts.push(t),null==s||s(t),l()}}a.enqueue(e)}))}}))}hd({prefix:"aitxt",size:24}),hd({prefix:"aiobj",size:24});var rf=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()}))}};hd({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)Cg(e,n,{get:t[n],enumerable:!0})})({},{object:()=>sf,text:()=>of});var of=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),sf=({schema:e})=>{const t=Wd(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await Xg(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 Pg({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const i=await $d({value:r.value,schema:t});if(!i.success)throw new Pg({message:"No object generated: response did not match schema.",cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}}},af=Au({name:Dl(),version:Dl()}),lf=Au({_meta:Qu(Nu({}).loose())}),uf=lf,cf=Nu({method:Dl(),params:Qu(lf)}),df=Au({experimental:Qu(Nu({}).loose()),logging:Qu(Nu({}).loose()),prompts:Qu(Au({listChanged:Qu(pu())})),resources:Qu(Au({subscribe:Qu(pu()),listChanged:Qu(pu())})),tools:Qu(Au({listChanged:Qu(pu())}))});uf.extend({protocolVersion:Dl(),capabilities:df,serverInfo:af,instructions:Qu(Dl())});var pf=uf.extend({nextCursor:Qu(Dl())}),mf=Nu({name:Dl(),description:Qu(Dl()),inputSchema:Nu({type:Vu("object"),properties:Qu(Nu({}).loose())}).loose()}).loose();pf.extend({tools:Tu(mf)});var hf=Nu({type:Vu("text"),text:Dl()}).loose(),gf=Nu({type:Vu("image"),data:nu(),mimeType:Dl()}).loose(),ff=Nu({uri:Dl(),mimeType:Qu(Dl())}).loose(),vf=ff.extend({text:Dl()}),yf=ff.extend({blob:nu()}),_f=Nu({type:Vu("resource"),resource:Uu([vf,yf])}).loose();uf.extend({content:Tu(Uu([hf,gf,_f])),isError:pu().default(!1).optional()}).or(uf.extend({toolResult:ku()}));var bf="2.0",wf=Nu({jsonrpc:Vu(bf),id:Uu([Dl(),lu().int()])}).merge(cf).strict(),kf=Nu({jsonrpc:Vu(bf),id:Uu([Dl(),lu().int()]),result:uf}).strict(),xf=Nu({jsonrpc:Vu(bf),id:Uu([Dl(),lu().int()]),error:Nu({code:lu().int(),message:Dl(),data:Qu(ku())})}).strict();Uu([wf,Nu({jsonrpc:Vu(bf)}).merge(Nu({method:Dl(),params:Qu(lf)})).strict(),kf,xf]);var If,Sf,$f=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:s}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:e,...t}){var n,r,i,o,s;const a=await jd(this.body),l=await jd(this.headers),u=await jd(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:{...l,...t.headers},credentials:u,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:{...l,...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},h=null!=(i=null==c?void 0:c.credentials)?i:u,g=null!=(o=this.fetch)?o:globalThis.fetch,f=await g(d,{method:"POST",headers:{"Content-Type":"application/json",...p},body:JSON.stringify(m),credentials:h,signal:e});if(!f.ok)throw new Error(null!=(s=await f.text())?s:"Failed to fetch the chat response.");if(!f.body)throw new Error("The response body is empty.");return this.processResponseStream(f.body)}async reconnectToStream(e){var t,n,r,i,o;const s=await jd(this.body),a=await jd(this.headers),l=await jd(this.credentials),u=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:l,requestMetadata:e.metadata})),c=null!=(n=null==u?void 0:u.api)?n:`${this.api}/${e.chatId}/stream`,d=void 0!==(null==u?void 0:u.headers)?u.headers:{...a,...e.headers},p=null!=(r=null==u?void 0:u.credentials)?r:l,m=null!=(i=this.fetch)?i:globalThis.fetch,h=await m(c,{method:"GET",headers:d,credentials:p});if(204===h.status)return null;if(!h.ok)throw new Error(null!=(o=await h.text())?o:"Failed to fetch the chat response.");if(!h.body)throw new Error("The response body is empty.");return this.processResponseStream(h.body)}},Ef=class extends $f{constructor(e={}){super(e)}processResponseStream(e){return Od({stream:e,schema:Kg}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Tf=class{constructor({generateId:e=gd,id:t=e(),transport:n=new Ef,messageMetadataSchema:r,dataPartSchemas:i,state:o,onError:s,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new rf,this.sendMessage=async(e,t)=>{var n,r,i,o;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!=(i=s.id)?i:this.generateId(),role:null!=(o=s.role)?o:"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 i=this.state.messages,o=i[i.length-1];this.state.replaceMessage(i.length-1,{...o,parts:o.parts.map((e=>Qg(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=>Qg(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=i,this.state=o,this.onError=s,this.onToolCall=a,this.onFinish=l,this.onData=u,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:i}){var o,s,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;try{const s={state:tf({lastMessage:this.state.snapshot(l),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:i});const u=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:nf({stream:a,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:u,onError:e=>{throw e}}),onError:e=>{throw e}}),null==(o=this.onFinish)||o.call(this,{message:s.state.message}),this.setStatus({status:"ready"})}catch(u){if("AbortError"===u.name)return this.setStatus({status:"ready"}),null;this.onError&&u instanceof Error&&this.onError(u),this.setStatus({status:"error",error:u})}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})}},Of=Nu({type:Vu("text"),text:Dl(),state:Ju(["streaming","done"]).optional(),providerMetadata:Dg.optional()}),Nf=Nu({type:Vu("reasoning"),text:Dl(),state:Ju(["streaming","done"]).optional(),providerMetadata:Dg.optional()}),Cf=Nu({type:Vu("source-url"),sourceId:Dl(),url:Dl(),title:Dl().optional(),providerMetadata:Dg.optional()}),Af=Nu({type:Vu("source-document"),sourceId:Dl(),mediaType:Dl(),title:Dl(),filename:Dl().optional(),providerMetadata:Dg.optional()}),Rf=Nu({type:Vu("file"),mediaType:Dl(),filename:Dl().optional(),url:Dl(),providerMetadata:Dg.optional()}),Uf=Nu({type:Vu("step-start")}),Pf=Nu({type:Dl().startsWith("data-"),id:Dl().optional(),data:ku()}),jf=[Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("input-streaming"),input:ku().optional(),output:Iu().optional(),errorText:Iu().optional()}),Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("input-available"),input:ku(),output:Iu().optional(),errorText:Iu().optional(),callProviderMetadata:Dg.optional()}),Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("output-available"),input:ku(),output:ku(),errorText:Iu().optional(),callProviderMetadata:Dg.optional(),preliminary:pu().optional()}),Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("output-error"),input:ku(),output:Iu().optional(),errorText:Dl(),callProviderMetadata:Dg.optional()})],zf=[Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("input-streaming"),input:ku().optional(),output:Iu().optional(),errorText:Iu().optional()}),Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("input-available"),input:ku(),output:Iu().optional(),errorText:Iu().optional(),callProviderMetadata:Dg.optional()}),Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("output-available"),input:ku(),output:ku(),errorText:Iu().optional(),callProviderMetadata:Dg.optional(),preliminary:pu().optional()}),Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("output-error"),input:ku(),output:Iu().optional(),errorText:Dl(),callProviderMetadata:Dg.optional()})];function Df(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Mf(){if(Sf)return If;return Sf=1,If=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(...i){clearTimeout(n);const o=Date.now(),s=t-(o-r);s<=0?(r=o,e.apply(this,i)):n=setTimeout((()=>{r=Date.now(),e.apply(this,i)}),s)}}}Nu({id:Dl(),role:Ju(["system","user","assistant"]),metadata:ku().optional(),parts:Tu(Uu([Of,Nf,Cf,Af,Rf,Uf,Pf,...jf,...zf]))});const Lf=Df(Mf());var Zf,qf,Ff,Wf,Bf,Jf,Hf,Vf,Kf,Gf=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Yf=(e,t,n)=>(Gf(e,t,"read from private field"),n?n.call(e):t.get(e)),Xf=(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)},Qf=(e,t,n,r)=>(Gf(e,t,"write to private field"),t.set(e,n),n);var ev,tv=class{constructor(e=[]){Xf(this,Zf,void 0),Xf(this,qf,"ready"),Xf(this,Ff,void 0),Xf(this,Wf,new Set),Xf(this,Bf,new Set),Xf(this,Jf,new Set),this.pushMessage=e=>{Qf(this,Zf,Yf(this,Zf).concat(e)),Yf(this,Hf).call(this)},this.popMessage=()=>{Qf(this,Zf,Yf(this,Zf).slice(0,-1)),Yf(this,Hf).call(this)},this.replaceMessage=(e,t)=>{Qf(this,Zf,[...Yf(this,Zf).slice(0,e),this.snapshot(t),...Yf(this,Zf).slice(e+1)]),Yf(this,Hf).call(this)},this.snapshot=e=>structuredClone(e),this["~registerMessagesCallback"]=(e,t)=>{const n=t?(r=e,null!=(i=t)?Lf(r,i):r):e;var r,i;return Yf(this,Wf).add(n),()=>{Yf(this,Wf).delete(n)}},this["~registerStatusCallback"]=e=>(Yf(this,Bf).add(e),()=>{Yf(this,Bf).delete(e)}),this["~registerErrorCallback"]=e=>(Yf(this,Jf).add(e),()=>{Yf(this,Jf).delete(e)}),Xf(this,Hf,(()=>{Yf(this,Wf).forEach((e=>e()))})),Xf(this,Vf,(()=>{Yf(this,Bf).forEach((e=>e()))})),Xf(this,Kf,(()=>{Yf(this,Jf).forEach((e=>e()))})),Qf(this,Zf,e)}get status(){return Yf(this,qf)}set status(e){Qf(this,qf,e),Yf(this,Vf).call(this)}get error(){return Yf(this,Ff)}set error(e){Qf(this,Ff,e),Yf(this,Kf).call(this)}get messages(){return Yf(this,Zf)}set messages(e){Qf(this,Zf,[...e]),Yf(this,Hf).call(this)}};Zf=new WeakMap,qf=new WeakMap,Ff=new WeakMap,Wf=new WeakMap,Bf=new WeakMap,Jf=new WeakMap,Hf=new WeakMap,Vf=new WeakMap,Kf=new WeakMap;var nv=class extends Tf{constructor({messages:e,...t}){const n=new tv(e);super({...t,state:n}),Xf(this,ev,void 0),this["~registerMessagesCallback"]=(e,t)=>Yf(this,ev)["~registerMessagesCallback"](e,t),this["~registerStatusCallback"]=e=>Yf(this,ev)["~registerStatusCallback"](e),this["~registerErrorCallback"]=e=>Yf(this,ev)["~registerErrorCallback"](e),Qf(this,ev,n)}};ev=new WeakMap;var rv,iv=Object.defineProperty,ov="AI_NoObjectGeneratedError",sv=`vercel.ai.error.${ov}`,av=Symbol.for(sv),lv=class extends Ae{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:i,finishReason:o}){super({name:ov,message:e,cause:t}),this[rv]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=o}static isInstance(e){return Ae.hasMarker(e,sv)}};rv=av;var uv,cv="AI_MessageConversionError",dv=`vercel.ai.error.${cv}`,pv=Symbol.for(dv),mv=class extends Ae{constructor({originalMessage:e,message:t}){super({name:cv,message:t}),this[uv]=!0,this.originalMessage=e}static isInstance(e){return Ae.hasMarker(e,dv)}};uv=pv;var hv=Uu([Dl(),Ic(Uint8Array),Ic(ArrayBuffer),wc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),gv=yc((()=>Uu([yu(),Dl(),lu(),pu(),qu(Dl(),gv),Tu(gv)]))),fv=qu(Dl(),qu(Dl(),gv)),vv=Nu({type:Vu("text"),text:Dl(),providerOptions:fv.optional()}),yv=Nu({type:Vu("image"),image:Uu([hv,Ic(URL)]),mediaType:Dl().optional(),providerOptions:fv.optional()}),_v=Nu({type:Vu("file"),data:Uu([hv,Ic(URL)]),filename:Dl().optional(),mediaType:Dl(),providerOptions:fv.optional()}),bv=Nu({type:Vu("reasoning"),text:Dl(),providerOptions:fv.optional()}),wv=Nu({type:Vu("tool-call"),toolCallId:Dl(),toolName:Dl(),input:ku(),providerOptions:fv.optional(),providerExecuted:pu().optional()}),kv=ju("type",[Nu({type:Vu("text"),value:Dl()}),Nu({type:Vu("json"),value:gv}),Nu({type:Vu("error-text"),value:Dl()}),Nu({type:Vu("error-json"),value:gv}),Nu({type:Vu("content"),value:Tu(Uu([Nu({type:Vu("text"),text:Dl()}),Nu({type:Vu("media"),data:Dl(),mediaType:Dl()})]))})]),xv=Nu({type:Vu("tool-result"),toolCallId:Dl(),toolName:Dl(),output:kv,providerOptions:fv.optional()}),Iv=Nu({role:Vu("system"),content:Dl(),providerOptions:fv.optional()}),Sv=Nu({role:Vu("user"),content:Uu([Dl(),Tu(Uu([vv,yv,_v]))]),providerOptions:fv.optional()}),$v=Nu({role:Vu("assistant"),content:Uu([Dl(),Tu(Uu([vv,_v,bv,wv,xv]))]),providerOptions:fv.optional()});function Ev({output:e,tool:t,errorMode:n}){return"text"===n?{type:"error-text",value:qe(e)}:"json"===n?{type:"error-json",value:Tv(e)}:(null==t?void 0:t.toModelOutput)?t.toModelOutput(e):"string"==typeof e?{type:"text",value:e}:{type:"json",value:Tv(e)}}function Tv(e){return void 0===e?null:e}function Ov(e){const t=["ROOT"];let n=-1,r=null;function i(e,i,o){switch(e){case'"':n=i,t.pop(),t.push(o),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=i,r=i,t.pop(),t.push(o),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(o),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=i,t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"{":n=i,t.pop(),t.push(o),t.push("INSIDE_OBJECT_START");break;case"[":n=i,t.pop(),t.push(o),t.push("INSIDE_ARRAY_START")}}function o(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 l=0;l<e.length;l++){const a=e[l];switch(t[t.length-1]){case"ROOT":i(a,l,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=l,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":i(a,l,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(a,l);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=l;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=l}break;case"INSIDE_ARRAY_START":if("]"===a)n=l,t.pop();else n=l,i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=l,t.pop();break;default:n=l}break;case"INSIDE_ARRAY_AFTER_COMMA":i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=l;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=l;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l);break;default:t.pop()}break;case"INSIDE_LITERAL":{const i=e.substring(r,l+1);"false".startsWith(i)||"true".startsWith(i)||"null".startsWith(i)?n=l:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(a,l):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l));break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--){switch(t[l]){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 Cv(e){return e.type.split("-").slice(1).join("-")}Uu([Iv,Sv,$v,Nu({role:Vu("tool"),content:Tu(xv),providerOptions:fv.optional()})]),hd({prefix:"aitxt",size:24}),TransformStream,Uu([Cu({type:Vu("text-start"),id:Dl(),providerMetadata:fv.optional()}),Cu({type:Vu("text-delta"),id:Dl(),delta:Dl(),providerMetadata:fv.optional()}),Cu({type:Vu("text-end"),id:Dl(),providerMetadata:fv.optional()}),Cu({type:Vu("error"),errorText:Dl()}),Cu({type:Vu("tool-input-start"),toolCallId:Dl(),toolName:Dl(),providerExecuted:pu().optional(),dynamic:pu().optional()}),Cu({type:Vu("tool-input-delta"),toolCallId:Dl(),inputTextDelta:Dl()}),Cu({type:Vu("tool-input-available"),toolCallId:Dl(),toolName:Dl(),input:ku(),providerExecuted:pu().optional(),providerMetadata:fv.optional(),dynamic:pu().optional()}),Cu({type:Vu("tool-input-error"),toolCallId:Dl(),toolName:Dl(),input:ku(),providerExecuted:pu().optional(),providerMetadata:fv.optional(),dynamic:pu().optional(),errorText:Dl()}),Cu({type:Vu("tool-output-available"),toolCallId:Dl(),output:ku(),providerExecuted:pu().optional(),dynamic:pu().optional(),preliminary:pu().optional()}),Cu({type:Vu("tool-output-error"),toolCallId:Dl(),errorText:Dl(),providerExecuted:pu().optional(),dynamic:pu().optional()}),Cu({type:Vu("reasoning"),text:Dl(),providerMetadata:fv.optional()}),Cu({type:Vu("reasoning-start"),id:Dl(),providerMetadata:fv.optional()}),Cu({type:Vu("reasoning-delta"),id:Dl(),delta:Dl(),providerMetadata:fv.optional()}),Cu({type:Vu("reasoning-end"),id:Dl(),providerMetadata:fv.optional()}),Cu({type:Vu("reasoning-part-finish")}),Cu({type:Vu("source-url"),sourceId:Dl(),url:Dl(),title:Dl().optional(),providerMetadata:fv.optional()}),Cu({type:Vu("source-document"),sourceId:Dl(),mediaType:Dl(),title:Dl(),filename:Dl().optional(),providerMetadata:fv.optional()}),Cu({type:Vu("file"),url:Dl(),mediaType:Dl(),providerMetadata:fv.optional()}),Cu({type:Dl().startsWith("data-"),id:Dl().optional(),data:ku(),transient:pu().optional()}),Cu({type:Vu("start-step")}),Cu({type:Vu("finish-step")}),Cu({type:Vu("start"),messageId:Dl().optional(),messageMetadata:ku().optional()}),Cu({type:Vu("finish"),messageMetadata:ku().optional()}),Cu({type:Vu("abort")}),Cu({type:Vu("message-metadata"),messageMetadata:ku()})]),hd({prefix:"aitxt",size:24}),hd({prefix:"aiobj",size:24}),hd({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)iv(e,n,{get:t[n],enumerable:!0})})({},{object:()=>Rv,text:()=>Av});var Av=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),Rv=({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:Ov(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 lv({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const i=await $d({value:r.value,schema:t});if(!i.success)throw new lv({message:"No object generated: response did not match schema.",cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}}},Uv=Au({name:Dl(),version:Dl()}),Pv=Au({_meta:Qu(Nu({}).loose())}),jv=Pv,zv=Nu({method:Dl(),params:Qu(Pv)}),Dv=Au({experimental:Qu(Nu({}).loose()),logging:Qu(Nu({}).loose()),prompts:Qu(Au({listChanged:Qu(pu())})),resources:Qu(Au({subscribe:Qu(pu()),listChanged:Qu(pu())})),tools:Qu(Au({listChanged:Qu(pu())}))});jv.extend({protocolVersion:Dl(),capabilities:Dv,serverInfo:Uv,instructions:Qu(Dl())});var Mv=jv.extend({nextCursor:Qu(Dl())}),Lv=Nu({name:Dl(),description:Qu(Dl()),inputSchema:Nu({type:Vu("object"),properties:Qu(Nu({}).loose())}).loose()}).loose();Mv.extend({tools:Tu(Lv)});var Zv=Nu({type:Vu("text"),text:Dl()}).loose(),qv=Nu({type:Vu("image"),data:nu(),mimeType:Dl()}).loose(),Fv=Nu({uri:Dl(),mimeType:Qu(Dl())}).loose(),Wv=Fv.extend({text:Dl()}),Bv=Fv.extend({blob:nu()}),Jv=Nu({type:Vu("resource"),resource:Uu([Wv,Bv])}).loose();jv.extend({content:Tu(Uu([Zv,qv,Jv])),isError:pu().default(!1).optional()}).or(jv.extend({toolResult:ku()}));var Hv="2.0",Vv=Nu({jsonrpc:Vu(Hv),id:Uu([Dl(),lu().int()])}).merge(zv).strict(),Kv=Nu({jsonrpc:Vu(Hv),id:Uu([Dl(),lu().int()]),result:jv}).strict(),Gv=Nu({jsonrpc:Vu(Hv),id:Uu([Dl(),lu().int()]),error:Nu({code:lu().int(),message:Dl(),data:Qu(ku())})}).strict();Uu([Vv,Nu({jsonrpc:Vu(Hv)}).merge(Nu({method:Dl(),params:Qu(Pv)})).strict(),Kv,Gv]);var Yv=Nu({type:Vu("text"),text:Dl(),state:Ju(["streaming","done"]).optional(),providerMetadata:fv.optional()}),Xv=Nu({type:Vu("reasoning"),text:Dl(),state:Ju(["streaming","done"]).optional(),providerMetadata:fv.optional()}),Qv=Nu({type:Vu("source-url"),sourceId:Dl(),url:Dl(),title:Dl().optional(),providerMetadata:fv.optional()}),ey=Nu({type:Vu("source-document"),sourceId:Dl(),mediaType:Dl(),title:Dl(),filename:Dl().optional(),providerMetadata:fv.optional()}),ty=Nu({type:Vu("file"),mediaType:Dl(),filename:Dl().optional(),url:Dl(),providerMetadata:fv.optional()}),ny=Nu({type:Vu("step-start")}),ry=Nu({type:Dl().startsWith("data-"),id:Dl().optional(),data:ku()}),iy=[Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("input-streaming"),input:ku().optional(),output:Iu().optional(),errorText:Iu().optional()}),Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("input-available"),input:ku(),output:Iu().optional(),errorText:Iu().optional(),callProviderMetadata:fv.optional()}),Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("output-available"),input:ku(),output:ku(),errorText:Iu().optional(),callProviderMetadata:fv.optional(),preliminary:pu().optional()}),Nu({type:Vu("dynamic-tool"),toolName:Dl(),toolCallId:Dl(),state:Vu("output-error"),input:ku(),output:Iu().optional(),errorText:Dl(),callProviderMetadata:fv.optional()})],oy=[Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("input-streaming"),input:ku().optional(),output:Iu().optional(),errorText:Iu().optional()}),Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("input-available"),input:ku(),output:Iu().optional(),errorText:Iu().optional(),callProviderMetadata:fv.optional()}),Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("output-available"),input:ku(),output:ku(),errorText:Iu().optional(),callProviderMetadata:fv.optional(),preliminary:pu().optional()}),Nu({type:Dl().startsWith("tool-"),toolCallId:Dl(),state:Vu("output-error"),input:ku(),output:Iu().optional(),errorText:Dl(),callProviderMetadata:fv.optional()})];function sy(){const e=function(){const e=n.useContext(Og);if(!e)throw new Error("useChat must be used within an EchoChatProvider");return e}();return{async sendMessages(t){const{messages:n,abortSignal:r,...i}=t,o=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,o;if(0===i.length)return;const s=[];for(const n of i)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 mv({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 i=Cv(n);if("input-streaming"===n.state)throw new mv({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:i,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:i,output:Ev({output:"output-error"===n.state?n.errorText:n.output,tool:null==(o=null==t?void 0:t.tools)?void 0:o[i],errorMode:"output-error"===n.state?"json":"none"})})}}n.push({role:"assistant",content:s});const a=i.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:Cv(e);return{type:"tool-result",toolCallId:e.toolCallId,toolName:r,output:Ev({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 mv({originalMessage:r,message:`Unsupported tool part state: ${e.state}`})}}))}),i=[]},i=[];for(const t of r.parts)"text"===t.type||"reasoning"===t.type||"file"===t.type||"dynamic-tool"===t.type||Nv(t)?i.push(t):"step-start"===t.type&&e();e();break}break;default:{const e=r.role;throw new mv({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:o,abortSignal:r,...i})},reconnectToStream:async()=>null}}Nu({id:Dl(),role:Ju(["system","user","assistant"]),metadata:ku().optional(),parts:Tu(Uu([Yv,Xv,Qv,ey,ty,ny,ry,...iy,...oy]))}),e.EchoChatProvider=function({chatFn:e,children:n}){return t.jsx(Og.Provider,{value:e,children:n})},e.EchoProvider=function({config:e,children:r}){const[i,o]=n.useState(!1);if(n.useEffect((()=>{o(!0)}),[]),!i)return null;const s=e.apiUrl||"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,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 C({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(yh,{config:e,children:r})})},e.EchoSignIn=function({onSuccess:e,onError:r,className:i="",children:o}){const{signIn:s,isLoading:a,user:l,error:u}=_h(),[c,d]=n.useState(!1);n.useEffect((()=>{l&&e&&e(l)}),[l,e]),n.useEffect((()=>{u&&r&&r(new Error(u))}),[u,r]);const p=async()=>{try{await s()}catch(e){r&&r(e instanceof Error?e:new Error("Sign in failed"))}};return l?t.jsx("div",{className:`echo-signin-success ${i}`,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(Eg,{width:16,height:16,variant:"light"}),t.jsxs("span",{children:["Signed in as ",Sg((null==l?void 0:l.name)||(null==l?void 0:l.email))]})]})}):t.jsx("div",{className:`echo-signin ${i}`,children:o?t.jsx("div",{onClick:p,style:{cursor:"pointer"},children:o}):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(Eg,{width:16,height:16,variant:"light"}),t.jsx("span",{children:a?"Signing in...":"Sign in"})]})})},e.EchoTokenPurchase=function({onPurchaseComplete:e,onError:r,className:i="",children:o}){const{createPaymentLink:s,user:a,balance:l,freeTierBalance:u,refreshBalance:c}=_h(),[d,p]=n.useState(!1),[m,h]=n.useState(null),[g,f]=n.useState(!1),[v,y]=n.useState(!1),_=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),b=()=>{var e,t;return(((null==(e=null==u?void 0:u.userSpendInfo)?void 0:e.amountLeft)||0)<0?0:(null==(t=null==u?void 0:u.userSpendInfo)?void 0:t.amountLeft)||0)+((null==l?void 0:l.balance)||0)},w=async t=>{if(!a){const e=new Error("Please sign in to purchase tokens");return h(e.message),void(r&&r(e))}try{p(!0),h(null);const n=await s(t);await $g(n,{onComplete:async()=>{try{await c(),f(!1),y(!1),e&&l&&e(l)}catch(t){const e=t instanceof Error?t:new Error("Failed to refresh balance");h(e.message),r&&r(e)}finally{p(!1)}},onCancel:()=>{p(!1)},onError:e=>{h(e.message),r&&r(e),p(!1)}})}catch(n){const e=n instanceof Error?n:new Error("Failed to create payment link");h(e.message),r&&r(e),p(!1)}},k=()=>{f(!1),y(!1),h(null)};if(!a)return t.jsx("div",{className:`echo-token-purchase ${i}`,children:t.jsx("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px"},children:"Please sign in to purchase tokens"})});const x=()=>{const[e,r]=n.useState(!1);return t.jsxs("button",{onClick:()=>f(!0),className:`echo-token-purchase-compact ${i}`,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:[t.jsx(Eg,{width:16,height:16,variant:"light"}),t.jsx("span",{children:_(b())}),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"})]})]})},I=()=>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&&k()},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.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:_(b())}),t.jsxs("div",{style:{marginBottom:"8px"},children:[u&&b()>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:[_(u.userSpendInfo.amountLeft<0?0:u.userSpendInfo.amountLeft)," ","Free Tier",u.userSpendInfo&&u.userSpendInfo.spendLimit&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",_(u.userSpendInfo.amountSpent>u.userSpendInfo.spendLimit?u.userSpendInfo.spendLimit:u.userSpendInfo.amountSpent)," ","of"," ",_(u.userSpendInfo.spendLimit)," ","spent)"]})]})]}),u.userSpendInfo&&u.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,u.userSpendInfo.amountLeft)/(u.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:[_(l.balance)," Paid Credits",l.totalSpent&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",_(l.totalSpent)," /"," ",_(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"}),v?t.jsx(Tg,{onAddCredits:w,onCancel:()=>y(!1),isProcessing:d}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsx("button",{onClick:()=>w(10),disabled:d,style:{width:"100%",padding:"12px 16px",backgroundColor:d?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:d?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{d||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{d||(e.currentTarget.style.backgroundColor="#dc2626")},children:d?"Processing...":"Add $10 Credits"}),t.jsx("button",{onClick:()=>y(!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"})]})]}),m&&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:m}),t.jsx("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"flex-end",borderTop:"1px solid #f3f4f6"},children:t.jsx("button",{onClick:k,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:[o?t.jsx("div",{onClick:()=>f(!0),style:{cursor:"pointer"},children:o}):t.jsx(x,{}),g&&t.jsx(I,{})]})},e.Logo=Eg,e.useChat=function(){return function({experimental_throttle:e,resume:t=!1,...r}={}){const i=n.useRef("chat"in r?r.chat:new nv(r));("chat"in r&&r.chat!==i.current||"id"in r&&i.current.id!==r.id)&&(i.current="chat"in r?r.chat:new nv(r));const o="id"in r?r.id:null,s=n.useCallback((t=>i.current["~registerMessagesCallback"](t,e)),[e,o]),a=n.useSyncExternalStore(s,(()=>i.current.messages),(()=>i.current.messages)),l=n.useSyncExternalStore(i.current["~registerStatusCallback"],(()=>i.current.status),(()=>i.current.status)),u=n.useSyncExternalStore(i.current["~registerErrorCallback"],(()=>i.current.error),(()=>i.current.error)),c=n.useCallback((e=>{"function"==typeof e&&(e=e(i.current.messages)),i.current.messages=e}),[i]);return n.useEffect((()=>{t&&i.current.resumeStream()}),[t,i]),{id:i.current.id,messages:a,setMessages:c,sendMessage:i.current.sendMessage,regenerate:i.current.regenerate,clearError:i.current.clearError,stop:i.current.stop,error:u,resumeStream:i.current.resumeStream,status:l,addToolResult:i.current.addToolResult}}({transport:sy()})},e.useEcho=_h,e.useEchoClient=gh,e.useEchoModelProviders=()=>{const{token:e,config:t}=_h();return n.useMemo((()=>{const n={appId:t.appId,baseRouterUrl:t.baseRouterUrl},r=async()=>e;return{openai:ph(n,r),anthropic:mh(n,r),google:hh(n,r)}}),[e,t.appId,t.baseRouterUrl])},e.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:r=!0}=e,{token:i,user:o}=_h(),[s,a]=n.useState(void 0),[l,u]=n.useState(null),[c,d]=n.useState(!1),p=n.useRef(null);return n.useEffect((()=>{if(p.current&&p.current.abort(),!r||!i)return a(void 0),u(null),void d(!1);return(async()=>{const e=new AbortController;p.current=e,d(!0),u(null);try{if(e.signal.aborted)return;const{default:n}=await import("openai");if(e.signal.aborted)return;const r=new n({apiKey:i,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")?u("OpenAI package not found. Please install it with: pnpm add openai"):u(`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()}}),[i,o,t,r]),{openai:s,isReady:void 0!==s&&!c,error:l,isLoading:c}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
|
|
4
3
|
//# sourceMappingURL=echo-react-sdk.umd.js.map
|