@opentiny/next-sdk 0.1.14 → 0.1.15-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/agent/AgentModelProvider.ts +546 -22
  2. package/agent/type.ts +12 -6
  3. package/agent/utils/generateReActPrompt.ts +55 -0
  4. package/agent/utils/parseReActAction.ts +34 -0
  5. package/dist/McpSdk.d.ts +14 -0
  6. package/dist/WebAgent.d.ts +5 -0
  7. package/dist/WebMcp.d.ts +20 -0
  8. package/dist/WebMcpClient.d.ts +389 -1152
  9. package/dist/WebMcpServer.d.ts +79 -78
  10. package/dist/Zod.d.ts +1 -0
  11. package/dist/agent/AgentModelProvider.d.ts +40 -4
  12. package/dist/agent/type.d.ts +13 -3
  13. package/dist/agent/utils/generateReActPrompt.d.ts +9 -0
  14. package/dist/agent/utils/getAISDKTools.d.ts +1 -0
  15. package/dist/agent/utils/parseReActAction.d.ts +14 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.es.dev.js +36353 -34348
  18. package/dist/index.es.js +28821 -25466
  19. package/dist/index.js +3880 -25
  20. package/dist/index.umd.dev.js +34230 -32225
  21. package/dist/index.umd.js +220 -128
  22. package/dist/mcpsdk@1.24.3.dev.js +22539 -0
  23. package/dist/mcpsdk@1.24.3.es.dev.js +22537 -0
  24. package/dist/mcpsdk@1.24.3.es.js +16781 -0
  25. package/dist/mcpsdk@1.24.3.js +43 -0
  26. package/dist/remoter/createRemoter.d.ts +9 -0
  27. package/dist/remoter/tooltips.d.ts +36 -0
  28. package/dist/script/utils.d.ts +1 -0
  29. package/dist/transport/ExtensionClientTransport.d.ts +3 -2
  30. package/dist/transport/ExtensionContentServerTransport.d.ts +3 -2
  31. package/dist/transport/ExtensionPageServerTransport.d.ts +4 -4
  32. package/dist/vite-build-tsc.d.ts +2 -0
  33. package/dist/vite.config.d.ts +2 -0
  34. package/dist/vite.config.mcpSdk.d.ts +2 -0
  35. package/dist/vite.config.webAgent.d.ts +2 -0
  36. package/dist/vite.config.webMcp.d.ts +2 -0
  37. package/dist/vite.config.webMcpFull.d.ts +2 -0
  38. package/dist/vite.config.zod.d.ts +2 -0
  39. package/dist/webagent.dev.js +24569 -20836
  40. package/dist/webagent.es.dev.js +23907 -20174
  41. package/dist/webagent.es.js +25326 -20723
  42. package/dist/webagent.js +209 -110
  43. package/dist/webmcp-full.dev.js +21225 -20021
  44. package/dist/webmcp-full.es.dev.js +21223 -20019
  45. package/dist/webmcp-full.es.js +16710 -14437
  46. package/dist/webmcp-full.js +42 -15
  47. package/dist/webmcp.dev.js +14 -22
  48. package/dist/webmcp.es.dev.js +12 -20
  49. package/dist/webmcp.es.js +172 -179
  50. package/dist/webmcp.js +1 -1
  51. package/dist/zod@3.25.76.dev.js +30 -32
  52. package/dist/zod@3.25.76.es.dev.js +28 -30
  53. package/dist/zod@3.25.76.es.js +143 -145
  54. package/dist/zod@3.25.76.js +1 -1
  55. package/package.json +11 -9
  56. package/remoter/createRemoter.ts +126 -71
  57. package/remoter/tooltips.ts +260 -0
  58. package/transport/ExtensionPageServerTransport.ts +2 -4
  59. package/tsconfig.json +5 -3
  60. package/vite-build-tsc.ts +60 -0
  61. package/vite-env.d.ts +5 -0
  62. package/dist/WebMcpClient.js +0 -363
  63. package/dist/WebMcpServer.js +0 -283
  64. package/dist/agent/AgentModelProvider.js +0 -293
  65. package/dist/agent/type.js +0 -1
  66. package/dist/agent/utils/getAISDKTools.js +0 -36
  67. package/dist/mcpsdk@1.17.0.dev.js +0 -21391
  68. package/dist/mcpsdk@1.17.0.es.dev.js +0 -21389
  69. package/dist/mcpsdk@1.17.0.es.js +0 -14505
  70. package/dist/mcpsdk@1.17.0.js +0 -16
  71. package/dist/remoter/QrCode.js +0 -55
  72. package/dist/remoter/createRemoter.js +0 -743
  73. package/dist/transport/ExtensionClientTransport.js +0 -81
  74. package/dist/transport/ExtensionContentServerTransport.js +0 -128
  75. package/dist/transport/ExtensionPageServerTransport.js +0 -118
  76. package/dist/transport/messages.js +0 -51
  77. package/dist/utils/uuid.js +0 -10
package/dist/webagent.js CHANGED
@@ -1,126 +1,200 @@
1
- (function(gr,gn){typeof exports=="object"&&typeof module<"u"?gn(exports):typeof define=="function"&&define.amd?define(["exports"],gn):(gr=typeof globalThis<"u"?globalThis:gr||self,gn(gr.WebAgent={}))})(this,function(gr){"use strict";var gn="vercel.ai.error",Km=Symbol.for(gn),Yl,Qm=class Jm extends Error{constructor({name:e,message:r,cause:a}){super(r),this[Yl]=!0,this.name=e,this.cause=a}static isInstance(e){return Jm.hasMarker(e,gn)}static hasMarker(e,r){const a=Symbol.for(r);return e!=null&&typeof e=="object"&&a in e&&typeof e[a]=="boolean"&&e[a]===!0}};Yl=Km;var he=Qm,Xl="AI_APICallError",eu=`vercel.ai.error.${Xl}`,Ym=Symbol.for(eu),tu,Ue=class extends he{constructor({message:t,url:e,requestBodyValues:r,statusCode:a,responseHeaders:n,responseBody:s,cause:o,isRetryable:i=a!=null&&(a===408||a===409||a===429||a>=500),data:l}){super({name:Xl,message:t,cause:o}),this[tu]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=n,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(t){return he.hasMarker(t,eu)}};tu=Ym;var ru="AI_EmptyResponseBodyError",nu=`vercel.ai.error.${ru}`,Xm=Symbol.for(nu),au,su=class extends he{constructor({message:t="Empty response body"}={}){super({name:ru,message:t}),this[au]=!0}static isInstance(t){return he.hasMarker(t,nu)}};au=Xm;function yn(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var ou="AI_InvalidArgumentError",iu=`vercel.ai.error.${ou}`,ev=Symbol.for(iu),lu,vo=class extends he{constructor({message:e,cause:r,argument:a}){super({name:ou,message:e,cause:r}),this[lu]=!0,this.argument=a}static isInstance(e){return he.hasMarker(e,iu)}};lu=ev;var uu="AI_InvalidPromptError",cu=`vercel.ai.error.${uu}`,tv=Symbol.for(cu),du,Br=class extends he{constructor({prompt:t,message:e,cause:r}){super({name:uu,message:`Invalid prompt: ${e}`,cause:r}),this[du]=!0,this.prompt=t}static isInstance(t){return he.hasMarker(t,cu)}};du=tv;var pu="AI_InvalidResponseDataError",hu=`vercel.ai.error.${pu}`,rv=Symbol.for(hu),fu,Zn=class extends he{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:pu,message:e}),this[fu]=!0,this.data=t}static isInstance(t){return he.hasMarker(t,hu)}};fu=rv;var mu="AI_JSONParseError",vu=`vercel.ai.error.${mu}`,nv=Symbol.for(vu),gu,Tr=class extends he{constructor({text:t,cause:e}){super({name:mu,message:`JSON parsing failed: Text: ${t}.
2
- Error message: ${yn(e)}`,cause:e}),this[gu]=!0,this.text=t}static isInstance(t){return he.hasMarker(t,vu)}};gu=nv;var yu="AI_LoadAPIKeyError",_u=`vercel.ai.error.${yu}`,av=Symbol.for(_u),wu,La=class extends he{constructor({message:t}){super({name:yu,message:t}),this[wu]=!0}static isInstance(t){return he.hasMarker(t,_u)}};wu=av;var bu="AI_NoSuchModelError",xu=`vercel.ai.error.${bu}`,sv=Symbol.for(xu),Eu,go=class extends he{constructor({errorName:t=bu,modelId:e,modelType:r,message:a=`No such ${r}: ${e}`}){super({name:t,message:a}),this[Eu]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return he.hasMarker(t,xu)}};Eu=sv;var Su="AI_TooManyEmbeddingValuesForCallError",Iu=`vercel.ai.error.${Su}`,ov=Symbol.for(Iu),Tu,iv=class extends he{constructor(t){super({name:Su,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Tu]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return he.hasMarker(t,Iu)}};Tu=ov;var ku="AI_TypeValidationError",Pu=`vercel.ai.error.${ku}`,lv=Symbol.for(Pu),Cu,uv=class Ql extends he{constructor({value:e,cause:r}){super({name:ku,message:`Type validation failed: Value: ${JSON.stringify(e)}.
3
- Error message: ${yn(r)}`,cause:r}),this[Cu]=!0,this.value=e}static isInstance(e){return he.hasMarker(e,Pu)}static wrap({value:e,cause:r}){return Ql.isInstance(r)&&r.value===e?r:new Ql({value:e,cause:r})}};Cu=lv;var er=uv,Ru="AI_UnsupportedFunctionalityError",Ou=`vercel.ai.error.${Ru}`,cv=Symbol.for(Ou),$u,Nt=class extends he{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:Ru,message:e}),this[$u]=!0,this.functionality=t}static isInstance(t){return he.hasMarker(t,Ou)}};$u=cv;let Au=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function yo(t){}function dv(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=yo,onError:r=yo,onRetry:a=yo,onComment:n}=t;let s="",o=!0,i,l="",u="";function d(f){const m=o?f.replace(/^\xEF\xBB\xBF/,""):f,[v,w]=pv(`${s}${m}`);for(const y of v)h(y);s=w,o=!1}function h(f){if(f===""){c();return}if(f.startsWith(":")){n&&n(f.slice(f.startsWith(": ")?2:1));return}const m=f.indexOf(":");if(m!==-1){const v=f.slice(0,m),w=f[m+1]===" "?2:1,y=f.slice(m+w);g(v,y,f);return}g(f,"",f)}function g(f,m,v){switch(f){case"event":u=m;break;case"data":l=`${l}${m}
4
- `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?a(parseInt(m,10)):r(new Au(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:v}));break;default:r(new Au(`Unknown field "${f.length>20?`${f.slice(0,20)}…`:f}"`,{type:"unknown-field",field:f,value:m,line:v}));break}}function c(){l.length>0&&e({id:i,event:u||void 0,data:l.endsWith(`
5
- `)?l.slice(0,-1):l}),i=void 0,l="",u=""}function p(f={}){s&&f.consume&&h(s),o=!0,i=void 0,l="",u="",s=""}return{feed:d,reset:p}}function pv(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
6
- `,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?n===t.length-1?o=-1:o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
7
- `&&a++}}return[e,r]}let hv=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=dv({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}};function j(t,e,r){function a(i,l){var u;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(u=i._zod).traits??(u.traits=new Set),i._zod.traits.add(t),e(i,l);for(const d in o.prototype)d in i||Object.defineProperty(i,d,{value:o.prototype[d].bind(i)});i._zod.constr=o,i._zod.def=l}const n=(r==null?void 0:r.Parent)??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function o(i){var l;const u=r!=null&&r.Parent?new s:this;a(u,i),(l=u._zod).deferred??(l.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(o,"init",{value:a}),Object.defineProperty(o,Symbol.hasInstance,{value:i=>{var l,u;return r!=null&&r.Parent&&i instanceof r.Parent?!0:(u=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:u.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class Vn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Nu={};function kr(t){return Nu}function Mu(t){const e=Object.values(t).filter(a=>typeof a=="number");return Object.entries(t).filter(([a,n])=>e.indexOf(+a)===-1).map(([a,n])=>n)}function fv(t,e){return typeof e=="bigint"?e.toString():e}function _o(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function wo(t){return t==null}function bo(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function mv(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}function De(t,e,r){Object.defineProperty(t,e,{get(){{const a=r();return t[e]=a,a}},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function za(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Bn(t){return JSON.stringify(t)}const Du=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ua(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const vv=_o(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Fa(t){if(Ua(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Ua(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const gv=new Set(["string","number","symbol"]);function Hn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hr(t,e,r){const a=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(a._zod.parent=t),a}function X(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function yv(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const _v={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]};function wv(t,e){const r={},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=a.shape[n])}return Hr(t,{...t._zod.def,shape:r,checks:[]})}function bv(t,e){const r={...t._zod.def.shape},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return Hr(t,{...t._zod.def,shape:r,checks:[]})}function xv(t,e){if(!Fa(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const a={...t._zod.def.shape,...e};return za(this,"shape",a),a},checks:[]};return Hr(t,r)}function Ev(t,e){return Hr(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return za(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Sv(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=t?new t({type:"optional",innerType:a[s]}):a[s])}else for(const s in a)n[s]=t?new t({type:"optional",innerType:a[s]}):a[s];return Hr(e,{...e._zod.def,shape:n,checks:[]})}function Iv(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=new t({type:"nonoptional",innerType:a[s]}))}else for(const s in a)n[s]=new t({type:"nonoptional",innerType:a[s]});return Hr(e,{...e._zod.def,shape:n,checks:[]})}function Jn(t,e=0){var r;for(let a=e;a<t.issues.length;a++)if(((r=t.issues[a])==null?void 0:r.continue)!==!0)return!0;return!1}function Jr(t,e){return e.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(t),r})}function qa(t){return typeof t=="string"?t:t==null?void 0:t.message}function Pr(t,e,r){var n,s,o,i,l,u;const a={...t,path:t.path??[]};if(!t.message){const d=qa((o=(s=(n=t.inst)==null?void 0:n._zod.def)==null?void 0:s.error)==null?void 0:o.call(s,t))??qa((i=e==null?void 0:e.error)==null?void 0:i.call(e,t))??qa((l=r.customError)==null?void 0:l.call(r,t))??qa((u=r.localeError)==null?void 0:u.call(r,t))??"Invalid input";a.message=d}return delete a.inst,delete a.continue,e!=null&&e.reportInput||delete a.input,a}function xo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Wn(...t){const[e,r,a]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:a}:{...e}}const ju=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,fv,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Lu=j("$ZodError",ju),zu=j("$ZodError",ju,{Parent:Error});function Tv(t,e=r=>r.message){const r={},a=[];for(const n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:r}}function kv(t,e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>n({issues:i}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return n(t),a}const Pv=t=>(e,r,a,n)=>{const s=a?Object.assign(a,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Vn;if(o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Pr(l,s,kr())));throw Du(i,n==null?void 0:n.callee),i}return o.value},Cv=t=>async(e,r,a,n)=>{const s=a?Object.assign(a,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Pr(l,s,kr())));throw Du(i,n==null?void 0:n.callee),i}return o.value},Uu=t=>(e,r,a)=>{const n=a?{...a,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new Vn;return s.issues.length?{success:!1,error:new(t??Lu)(s.issues.map(o=>Pr(o,n,kr())))}:{success:!0,data:s.value}},Rv=Uu(zu),Fu=t=>async(e,r,a)=>{const n=a?Object.assign(a,{async:!0}):{async:!0};let s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>Pr(o,n,kr())))}:{success:!0,data:s.value}},Ov=Fu(zu),$v=/^[cC][^\s-]{8,}$/,Av=/^[0-9a-z]+$/,Nv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Mv=/^[0-9a-vA-V]{20}$/,Dv=/^[A-Za-z0-9]{27}$/,jv=/^[a-zA-Z0-9_-]{21}$/,Lv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,zv=/^([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})$/,qu=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Uv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Fv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function qv(){return new RegExp(Fv,"u")}const Zv=/^(?:(?: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])$/,Vv=/^(([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})$/,Bv=/^((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])$/,Hv=/^(([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])$/,Jv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zu=/^[A-Za-z0-9_-]*$/,Wv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Gv=/^\+(?:[0-9]){6,14}[0-9]$/,Vu="(?:(?:\\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])))",Kv=new RegExp(`^${Vu}$`);function Bu(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Qv(t){return new RegExp(`^${Bu(t)}$`)}function Yv(t){const e=Bu({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const a=`${e}(?:${r.join("|")})`;return new RegExp(`^${Vu}T(?:${a})$`)}const Xv=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},eg=/^\d+$/,tg=/^-?\d+(?:\.\d+)?/i,rg=/true|false/i,ng=/null/i,ag=/^[^A-Z]*$/,sg=/^[^a-z]*$/,Et=j("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Hu={number:"number",bigint:"bigint",object:"date"},Ju=j("$ZodCheckLessThan",(t,e)=>{Et.init(t,e);const r=Hu[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value<=e.value:a.value<e.value)||a.issues.push({origin:r,code:"too_big",maximum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Wu=j("$ZodCheckGreaterThan",(t,e)=>{Et.init(t,e);const r=Hu[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value>=e.value:a.value>e.value)||a.issues.push({origin:r,code:"too_small",minimum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),og=j("$ZodCheckMultipleOf",(t,e)=>{Et.init(t,e),t._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):mv(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),ig=j("$ZodCheckNumberFormat",(t,e)=>{var o;Et.init(t,e),e.format=e.format||"float64";const r=(o=e.format)==null?void 0:o.includes("int"),a=r?"int":"number",[n,s]=_v[e.format];t._zod.onattach.push(i=>{const l=i._zod.bag;l.format=e.format,l.minimum=n,l.maximum=s,r&&(l.pattern=eg)}),t._zod.check=i=>{const l=i.value;if(r){if(!Number.isInteger(l)){i.issues.push({expected:a,format:e.format,code:"invalid_type",input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort});return}}l<n&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:t})}}),lg=j("$ZodCheckMaxLength",(t,e)=>{var r;Et.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!wo(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(a._zod.bag.maximum=e.maximum)}),t._zod.check=a=>{const n=a.value;if(n.length<=e.maximum)return;const o=xo(n);a.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),ug=j("$ZodCheckMinLength",(t,e)=>{var r;Et.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!wo(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(a._zod.bag.minimum=e.minimum)}),t._zod.check=a=>{const n=a.value;if(n.length>=e.minimum)return;const o=xo(n);a.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),cg=j("$ZodCheckLengthEquals",(t,e)=>{var r;Et.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!wo(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=a=>{const n=a.value,s=n.length;if(s===e.length)return;const o=xo(n),i=s>e.length;a.issues.push({origin:o,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!e.abort})}}),Za=j("$ZodCheckStringFormat",(t,e)=>{var r,a;Et.init(t,e),t._zod.onattach.push(n=>{const s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(a=t._zod).check??(a.check=()=>{})}),dg=j("$ZodCheckRegex",(t,e)=>{Za.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),pg=j("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ag),Za.init(t,e)}),hg=j("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sg),Za.init(t,e)}),fg=j("$ZodCheckIncludes",(t,e)=>{Et.init(t,e);const r=Hn(e.includes),a=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=a,t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),mg=j("$ZodCheckStartsWith",(t,e)=>{Et.init(t,e);const r=new RegExp(`^${Hn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.startsWith(e.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:a.value,inst:t,continue:!e.abort})}}),vg=j("$ZodCheckEndsWith",(t,e)=>{Et.init(t,e);const r=new RegExp(`.*${Hn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.endsWith(e.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:a.value,inst:t,continue:!e.abort})}}),gg=j("$ZodCheckOverwrite",(t,e)=>{Et.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class yg{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const a=e.split(`
8
- `).filter(o=>o),n=Math.min(...a.map(o=>o.length-o.trimStart().length)),s=a.map(o=>o.slice(n)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,r=this==null?void 0:this.args,n=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...r,n.join(`
9
- `))}}const _g={major:4,minor:0,patch:0},Fe=j("$ZodType",(t,e)=>{var n;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=_g;const a=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&a.unshift(t);for(const s of a)for(const o of s._zod.onattach)o(t);if(a.length===0)(r=t._zod).deferred??(r.deferred=[]),(n=t._zod.deferred)==null||n.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,i,l)=>{let u=Jn(o),d;for(const h of i){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(u)continue;const g=o.issues.length,c=h._zod.check(o);if(c instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Vn;if(d||c instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await c,o.issues.length!==g&&(u||(u=Jn(o,g)))});else{if(o.issues.length===g)continue;u||(u=Jn(o,g))}}return d?d.then(()=>o):o};t._zod.run=(o,i)=>{const l=t._zod.parse(o,i);if(l instanceof Promise){if(i.async===!1)throw new Vn;return l.then(u=>s(u,a,i))}return s(l,a,i)}}t["~standard"]={validate:s=>{var o;try{const i=Rv(t,s);return i.success?{value:i.data}:{issues:(o=i.error)==null?void 0:o.issues}}catch{return Ov(t,s).then(l=>{var u;return l.success?{value:l.data}:{issues:(u=l.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}}),Eo=j("$ZodString",(t,e)=>{var r;Fe.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??Xv(t._zod.bag),t._zod.parse=(a,n)=>{if(e.coerce)try{a.value=String(a.value)}catch{}return typeof a.value=="string"||a.issues.push({expected:"string",code:"invalid_type",input:a.value,inst:t}),a}}),Je=j("$ZodStringFormat",(t,e)=>{Za.init(t,e),Eo.init(t,e)}),wg=j("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=zv),Je.init(t,e)}),bg=j("$ZodUUID",(t,e)=>{if(e.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(a===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=qu(a))}else e.pattern??(e.pattern=qu());Je.init(t,e)}),xg=j("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Uv),Je.init(t,e)}),Eg=j("$ZodURL",(t,e)=>{Je.init(t,e),t._zod.check=r=>{try{const a=r.value,n=new URL(a),s=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Wv.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!a.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Sg=j("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=qv()),Je.init(t,e)}),Ig=j("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=jv),Je.init(t,e)}),Tg=j("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=$v),Je.init(t,e)}),kg=j("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Av),Je.init(t,e)}),Pg=j("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Nv),Je.init(t,e)}),Cg=j("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Mv),Je.init(t,e)}),Rg=j("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Dv),Je.init(t,e)}),Og=j("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Yv(e)),Je.init(t,e)}),$g=j("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Kv),Je.init(t,e)}),Ag=j("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Qv(e)),Je.init(t,e)}),Ng=j("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Lv),Je.init(t,e)}),Mg=j("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Zv),Je.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv4"})}),Dg=j("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Vv),Je.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),jg=j("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Bv),Je.init(t,e)}),Lg=j("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Hv),Je.init(t,e),t._zod.check=r=>{const[a,n]=r.value.split("/");try{if(!n)throw new Error;const s=Number(n);if(`${s}`!==n)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Gu(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const zg=j("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Jv),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Gu(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Ug(t){if(!Zu.test(t))return!1;const e=t.replace(/[-_]/g,a=>a==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gu(r)}const Fg=j("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Zu),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Ug(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),qg=j("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Gv),Je.init(t,e)});function Zg(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[a]=r;if(!a)return!1;const n=JSON.parse(atob(a));return!("typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}const Vg=j("$ZodJWT",(t,e)=>{Je.init(t,e),t._zod.check=r=>{Zg(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ku=j("$ZodNumber",(t,e)=>{Fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??tg,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),Bg=j("$ZodNumber",(t,e)=>{ig.init(t,e),Ku.init(t,e)}),Hg=j("$ZodBoolean",(t,e)=>{Fe.init(t,e),t._zod.pattern=rg,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=!!r.value}catch{}const n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),Jg=j("$ZodNull",(t,e)=>{Fe.init(t,e),t._zod.pattern=ng,t._zod.values=new Set([null]),t._zod.parse=(r,a)=>{const n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),Wg=j("$ZodAny",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),Gg=j("$ZodUnknown",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),Kg=j("$ZodNever",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Qu(t,e,r){t.issues.length&&e.issues.push(...Jr(r,t.issues)),e.value[r]=t.value}const Qg=j("$ZodArray",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const s=[];for(let o=0;o<n.length;o++){const i=n[o],l=e.element._zod.run({value:i,issues:[]},a);l instanceof Promise?s.push(l.then(u=>Qu(u,r,o))):Qu(l,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Va(t,e,r){t.issues.length&&e.issues.push(...Jr(r,t.issues)),e.value[r]=t.value}function Yu(t,e,r,a){t.issues.length?a[r]===void 0?r in a?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Jr(r,t.issues)):t.value===void 0?r in a&&(e.value[r]=void 0):e.value[r]=t.value}const Yg=j("$ZodObject",(t,e)=>{Fe.init(t,e);const r=_o(()=>{const h=Object.keys(e.shape);for(const c of h)if(!(e.shape[c]instanceof Fe))throw new Error(`Invalid element at key "${c}": expected a Zod schema`);const g=yv(e.shape);return{shape:e.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(g)}});De(t._zod,"propValues",()=>{const h=e.shape,g={};for(const c in h){const p=h[c]._zod;if(p.values){g[c]??(g[c]=new Set);for(const f of p.values)g[c].add(f)}}return g});const a=h=>{const g=new yg(["shape","payload","ctx"]),c=r.value,p=w=>{const y=Bn(w);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};g.write("const input = payload.value;");const f=Object.create(null);let m=0;for(const w of c.keys)f[w]=`key_${m++}`;g.write("const newResult = {}");for(const w of c.keys)if(c.optionalKeys.has(w)){const y=f[w];g.write(`const ${y} = ${p(w)};`);const _=Bn(w);g.write(`
10
- if (${y}.issues.length) {
11
- if (input[${_}] === undefined) {
12
- if (${_} in input) {
13
- newResult[${_}] = undefined;
1
+ (function(Jt,Zr){typeof exports=="object"&&typeof module<"u"?Zr(exports):typeof define=="function"&&define.amd?define(["exports"],Zr):(Jt=typeof globalThis<"u"?globalThis:Jt||self,Zr(Jt.WebAgent={}))})(this,(function(Jt){"use strict";var Zr="vercel.ai.error",x2=Symbol.for(Zr),ac,R2=class $2 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[ac]=!0,this.name=t,this.cause=n}static isInstance(t){return $2.hasMarker(t,Zr)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};ac=x2;var ue=R2,ic="AI_APICallError",lc=`vercel.ai.error.${ic}`,P2=Symbol.for(lc),cc,Pe=class extends ue{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:ic,message:e,cause:a}),this[cc]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return ue.hasMarker(e,lc)}};cc=P2;var uc="AI_EmptyResponseBodyError",dc=`vercel.ai.error.${uc}`,O2=Symbol.for(dc),pc,fc=class extends ue{constructor({message:e="Empty response body"}={}){super({name:uc,message:e}),this[pc]=!0}static isInstance(e){return ue.hasMarker(e,dc)}};pc=O2;function Fr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var hc="AI_InvalidArgumentError",mc=`vercel.ai.error.${hc}`,M2=Symbol.for(mc),gc,io=class extends ue{constructor({message:t,cause:r,argument:n}){super({name:hc,message:t,cause:r}),this[gc]=!0,this.argument=n}static isInstance(t){return ue.hasMarker(t,mc)}};gc=M2;var vc="AI_InvalidPromptError",_c=`vercel.ai.error.${vc}`,N2=Symbol.for(_c),yc,br=class extends ue{constructor({prompt:e,message:t,cause:r}){super({name:vc,message:`Invalid prompt: ${t}`,cause:r}),this[yc]=!0,this.prompt=e}static isInstance(e){return ue.hasMarker(e,_c)}};yc=N2;var wc="AI_InvalidResponseDataError",bc=`vercel.ai.error.${wc}`,A2=Symbol.for(bc),kc,_n=class extends ue{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:wc,message:t}),this[kc]=!0,this.data=e}static isInstance(e){return ue.hasMarker(e,bc)}};kc=A2;var Sc="AI_JSONParseError",Cc=`vercel.ai.error.${Sc}`,q2=Symbol.for(Cc),Tc,sr=class extends ue{constructor({text:e,cause:t}){super({name:Sc,message:`JSON parsing failed: Text: ${e}.
2
+ Error message: ${Fr(t)}`,cause:t}),this[Tc]=!0,this.text=e}static isInstance(e){return ue.hasMarker(e,Cc)}};Tc=q2;var $c="AI_LoadAPIKeyError",Ec=`vercel.ai.error.${$c}`,L2=Symbol.for(Ec),Ic,ar=class extends ue{constructor({message:e}){super({name:$c,message:e}),this[Ic]=!0}static isInstance(e){return ue.hasMarker(e,Ec)}};Ic=L2;var xc="AI_NoSuchModelError",Rc=`vercel.ai.error.${xc}`,j2=Symbol.for(Rc),Pc,Oc=class extends ue{constructor({errorName:e=xc,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Pc]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return ue.hasMarker(e,Rc)}};Pc=j2;var Mc="AI_TooManyEmbeddingValuesForCallError",Nc=`vercel.ai.error.${Mc}`,U2=Symbol.for(Nc),Ac,z2=class extends ue{constructor(e){super({name:Mc,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[Ac]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ue.hasMarker(e,Nc)}};Ac=U2;var qc="AI_TypeValidationError",Lc=`vercel.ai.error.${qc}`,D2=Symbol.for(Lc),jc,Z2=class sc extends ue{constructor({value:t,cause:r}){super({name:qc,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
+ Error message: ${Fr(r)}`,cause:r}),this[jc]=!0,this.value=t}static isInstance(t){return ue.hasMarker(t,Lc)}static wrap({value:t,cause:r}){return sc.isInstance(r)&&r.value===t?r:new sc({value:t,cause:r})}};jc=D2;var At=Z2,Uc="AI_UnsupportedFunctionalityError",zc=`vercel.ai.error.${Uc}`,F2=Symbol.for(zc),Dc,Ct=class extends ue{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Uc,message:t}),this[Dc]=!0,this.functionality=e}static isInstance(e){return ue.hasMarker(e,zc)}};Dc=F2;class Zc extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function ca(e){}function Fc(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ca,onError:r=ca,onRetry:n=ca,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(w){const m=a?w.replace(/^\xEF\xBB\xBF/,""):w,[y,_]=V2(`${s}${m}`);for(const f of y)g(f);s=_,a=!1}function g(w){if(w===""){d();return}if(w.startsWith(":")){o&&o(w.slice(w.startsWith(": ")?2:1));return}const m=w.indexOf(":");if(m!==-1){const y=w.slice(0,m),_=w[m+1]===" "?2:1,f=w.slice(m+_);h(y,f,w);return}h(w,"",w)}function h(w,m,y){switch(w){case"event":c=m;break;case"data":l=`${l}${m}
4
+ `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):r(new Zc(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:y}));break;default:r(new Zc(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:m,line:y}));break}}function d(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
5
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function p(w={}){s&&w.consume&&g(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:p}}function V2(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
6
+ `,n);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){r=e.slice(n);break}else{const i=e.slice(n,a);t.push(i),n=a+1,e[n-1]==="\r"&&e[n]===`
7
+ `&&n++}}return[t,r]}class Vr extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=Fc({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}const Vc=Object.freeze({status:"aborted"});function J(e,t,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const c=r?.Parent?new s:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class yn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Hc={};function ir(e){return Hc}function Bc(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function H2(e,t){return typeof t=="bigint"?t.toString():t}function ua(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function da(e){return e==null}function pa(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function B2(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function Te(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function lo(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function wn(e){return JSON.stringify(e)}const Jc=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const J2=ua(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function uo(e){if(co(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(co(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const G2=new Set(["string","number","symbol"]);function bn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kr(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function re(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function W2(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const K2={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]};function Y2(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return kr(e,{...e._zod.def,shape:r,checks:[]})}function Q2(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return kr(e,{...e._zod.def,shape:r,checks:[]})}function X2(e,t){if(!uo(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return lo(this,"shape",n),n},checks:[]};return kr(e,r)}function eg(e,t){return kr(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return lo(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function tg(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(const s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return kr(t,{...t._zod.def,shape:o,checks:[]})}function rg(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return kr(t,{...t._zod.def,shape:o,checks:[]})}function kn(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Sr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function po(e){return typeof e=="string"?e:e?.message}function lr(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=po(e.inst?._zod.def?.error?.(e))??po(t?.error?.(e))??po(r.customError?.(e))??po(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function fa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Sn(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Gc=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,H2,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Wc=J("$ZodError",Gc),Kc=J("$ZodError",Gc,{Parent:Error});function ng(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function og(e,t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),n}const sg=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new yn;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>lr(l,s,ir())));throw Jc(i,o?.callee),i}return a.value},ag=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>lr(l,s,ir())));throw Jc(i,o?.callee),i}return a.value},Yc=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new yn;return s.issues.length?{success:!1,error:new(e??Wc)(s.issues.map(a=>lr(a,o,ir())))}:{success:!0,data:s.value}},Qc=Yc(Kc),Xc=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>lr(a,o,ir())))}:{success:!0,data:s.value}},ig=Xc(Kc),lg=/^[cC][^\s-]{8,}$/,cg=/^[0-9a-z]+$/,ug=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,dg=/^[0-9a-vA-V]{20}$/,pg=/^[A-Za-z0-9]{27}$/,fg=/^[a-zA-Z0-9_-]{21}$/,hg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,mg=/^([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})$/,eu=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)$/,gg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _g(){return new RegExp(vg,"u")}const yg=/^(?:(?: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])$/,wg=/^(([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})$/,bg=/^((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])$/,kg=/^(([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])$/,Sg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,tu=/^[A-Za-z0-9_-]*$/,Cg=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Tg=/^\+(?:[0-9]){6,14}[0-9]$/,ru="(?:(?:\\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])))",$g=new RegExp(`^${ru}$`);function nu(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Eg(e){return new RegExp(`^${nu(e)}$`)}function Ig(e){const t=nu({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${ru}T(?:${n})$`)}const xg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Rg=/^\d+$/,Pg=/^-?\d+(?:\.\d+)?/i,Og=/true|false/i,Mg=/null/i,Ng=/^[^A-Z]*$/,Ag=/^[^a-z]*$/,it=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ou={number:"number",bigint:"bigint",object:"date"},su=J("$ZodCheckLessThan",(e,t)=>{it.init(e,t);const r=ou[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),au=J("$ZodCheckGreaterThan",(e,t)=>{it.init(e,t);const r=ou[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),qg=J("$ZodCheckMultipleOf",(e,t)=>{it.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):B2(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Lg=J("$ZodCheckNumberFormat",(e,t)=>{it.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=K2[t.format];e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,i.minimum=o,i.maximum=s,r&&(i.pattern=Rg)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}i<o&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),jg=J("$ZodCheckMaxLength",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!da(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const a=fa(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ug=J("$ZodCheckMinLength",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!da(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const a=fa(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),zg=J("$ZodCheckLengthEquals",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!da(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const a=fa(o),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),fo=J("$ZodCheckStringFormat",(e,t)=>{var r,n;it.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Dg=J("$ZodCheckRegex",(e,t)=>{fo.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Zg=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ng),fo.init(e,t)}),Fg=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ag),fo.init(e,t)}),Vg=J("$ZodCheckIncludes",(e,t)=>{it.init(e,t);const r=bn(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Hg=J("$ZodCheckStartsWith",(e,t)=>{it.init(e,t);const r=new RegExp(`^${bn(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),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})}}),Bg=J("$ZodCheckEndsWith",(e,t)=>{it.init(e,t);const r=new RegExp(`.*${bn(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),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})}}),Jg=J("$ZodCheckOverwrite",(e,t)=>{it.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Gg{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
8
+ `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
9
+ `))}}const Wg={major:4,minor:0,patch:0},Oe=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Wg;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,i)=>{let l=kn(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const g=s.issues.length,h=u._zod.check(s);if(h instanceof Promise&&i?.async===!1)throw new yn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==g&&(l||(l=kn(s,g)))});else{if(s.issues.length===g)continue;l||(l=kn(s,g))}}return c?c.then(()=>s):s};e._zod.run=(s,a)=>{const i=e._zod.parse(s,a);if(i instanceof Promise){if(a.async===!1)throw new yn;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=Qc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ig(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),ha=J("$ZodString",(e,t)=>{Oe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??xg(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Le=J("$ZodStringFormat",(e,t)=>{fo.init(e,t),ha.init(e,t)}),Kg=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=mg),Le.init(e,t)}),Yg=J("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=eu(n))}else t.pattern??(t.pattern=eu());Le.init(e,t)}),Qg=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=gg),Le.init(e,t)}),Xg=J("$ZodURL",(e,t)=>{Le.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Cg.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),e1=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=_g()),Le.init(e,t)}),t1=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=fg),Le.init(e,t)}),r1=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=lg),Le.init(e,t)}),n1=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cg),Le.init(e,t)}),o1=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ug),Le.init(e,t)}),s1=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=dg),Le.init(e,t)}),a1=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=pg),Le.init(e,t)}),i1=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Ig(t)),Le.init(e,t)}),l1=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=$g),Le.init(e,t)}),c1=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Eg(t)),Le.init(e,t)}),u1=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=hg),Le.init(e,t)}),d1=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=yg),Le.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),p1=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=wg),Le.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),f1=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=bg),Le.init(e,t)}),h1=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=kg),Le.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function iu(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const m1=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Sg),Le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{iu(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function g1(e){if(!tu.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return iu(r)}const v1=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=tu),Le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{g1(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),_1=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Tg),Le.init(e,t)});function y1(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const w1=J("$ZodJWT",(e,t)=>{Le.init(e,t),e._zod.check=r=>{y1(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),lu=J("$ZodNumber",(e,t)=>{Oe.init(e,t),e._zod.pattern=e._zod.bag.pattern??Pg,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),b1=J("$ZodNumber",(e,t)=>{Lg.init(e,t),lu.init(e,t)}),k1=J("$ZodBoolean",(e,t)=>{Oe.init(e,t),e._zod.pattern=Og,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),S1=J("$ZodNull",(e,t)=>{Oe.init(e,t),e._zod.pattern=Mg,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),C1=J("$ZodAny",(e,t)=>{Oe.init(e,t),e._zod.parse=r=>r}),T1=J("$ZodUnknown",(e,t)=>{Oe.init(e,t),e._zod.parse=r=>r}),$1=J("$ZodNever",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function cu(e,t,r){e.issues.length&&t.issues.push(...Sr(r,e.issues)),t.value[r]=e.value}const E1=J("$ZodArray",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const i=o[a],l=t.element._zod.run({value:i,issues:[]},n);l instanceof Promise?s.push(l.then(c=>cu(c,r,a))):cu(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function ho(e,t,r){e.issues.length&&t.issues.push(...Sr(r,e.issues)),t.value[r]=e.value}function uu(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Sr(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const I1=J("$ZodObject",(e,t)=>{Oe.init(e,t);const r=ua(()=>{const g=Object.keys(t.shape);for(const d of g)if(!(t.shape[d]instanceof Oe))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const h=W2(t.shape);return{shape:t.shape,keys:g,keySet:new Set(g),numKeys:g.length,optionalKeys:new Set(h)}});Te(e._zod,"propValues",()=>{const g=t.shape,h={};for(const d in g){const p=g[d]._zod;if(p.values){h[d]??(h[d]=new Set);for(const w of p.values)h[d].add(w)}}return h});const n=g=>{const h=new Gg(["shape","payload","ctx"]),d=r.value,p=_=>{const f=wn(_);return`shape[${f}]._zod.run({ value: input[${f}], issues: [] }, ctx)`};h.write("const input = payload.value;");const w=Object.create(null);let m=0;for(const _ of d.keys)w[_]=`key_${m++}`;h.write("const newResult = {}");for(const _ of d.keys)if(d.optionalKeys.has(_)){const f=w[_];h.write(`const ${f} = ${p(_)};`);const b=wn(_);h.write(`
10
+ if (${f}.issues.length) {
11
+ if (input[${b}] === undefined) {
12
+ if (${b} in input) {
13
+ newResult[${b}] = undefined;
14
14
  }
15
15
  } else {
16
16
  payload.issues = payload.issues.concat(
17
- ${y}.issues.map((iss) => ({
17
+ ${f}.issues.map((iss) => ({
18
18
  ...iss,
19
- path: iss.path ? [${_}, ...iss.path] : [${_}],
19
+ path: iss.path ? [${b}, ...iss.path] : [${b}],
20
20
  }))
21
21
  );
22
22
  }
23
- } else if (${y}.value === undefined) {
24
- if (${_} in input) newResult[${_}] = undefined;
23
+ } else if (${f}.value === undefined) {
24
+ if (${b} in input) newResult[${b}] = undefined;
25
25
  } else {
26
- newResult[${_}] = ${y}.value;
26
+ newResult[${b}] = ${f}.value;
27
27
  }
28
- `)}else{const y=f[w];g.write(`const ${y} = ${p(w)};`),g.write(`
29
- if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
28
+ `)}else{const f=w[_];h.write(`const ${f} = ${p(_)};`),h.write(`
29
+ if (${f}.issues.length) payload.issues = payload.issues.concat(${f}.issues.map(iss => ({
30
30
  ...iss,
31
- path: iss.path ? [${Bn(w)}, ...iss.path] : [${Bn(w)}]
32
- })));`),g.write(`newResult[${Bn(w)}] = ${y}.value`)}g.write("payload.value = newResult;"),g.write("return payload;");const v=g.compile();return(w,y)=>v(h,w,y)};let n;const s=Ua,o=!Nu.jitless,l=o&&vv.value,u=e.catchall;let d;t._zod.parse=(h,g)=>{d??(d=r.value);const c=h.value;if(!s(c))return h.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),h;const p=[];if(o&&l&&(g==null?void 0:g.async)===!1&&g.jitless!==!0)n||(n=a(e.shape)),h=n(h,g);else{h.value={};const y=d.shape;for(const _ of d.keys){const E=y[_],I=E._zod.run({value:c[_],issues:[]},g),S=E._zod.optin==="optional"&&E._zod.optout==="optional";I instanceof Promise?p.push(I.then(R=>S?Yu(R,h,_,c):Va(R,h,_))):S?Yu(I,h,_,c):Va(I,h,_)}}if(!u)return p.length?Promise.all(p).then(()=>h):h;const f=[],m=d.keySet,v=u._zod,w=v.def.type;for(const y of Object.keys(c)){if(m.has(y))continue;if(w==="never"){f.push(y);continue}const _=v.run({value:c[y],issues:[]},g);_ instanceof Promise?p.push(_.then(E=>Va(E,h,y))):Va(_,h,y)}return f.length&&h.issues.push({code:"unrecognized_keys",keys:f,input:c,inst:t}),p.length?Promise.all(p).then(()=>h):h}});function Xu(t,e,r,a){for(const n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>Pr(s,a,kr())))}),e}const ec=j("$ZodUnion",(t,e)=>{Fe.init(t,e),De(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),De(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),De(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),De(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>bo(a.source)).join("|")})$`)}}),t._zod.parse=(r,a)=>{let n=!1;const s=[];for(const o of e.options){const i=o._zod.run({value:r.value,issues:[]},a);if(i instanceof Promise)s.push(i),n=!0;else{if(i.issues.length===0)return i;s.push(i)}}return n?Promise.all(s).then(o=>Xu(o,r,t,a)):Xu(s,r,t,a)}}),Xg=j("$ZodDiscriminatedUnion",(t,e)=>{ec.init(t,e);const r=t._zod.parse;De(t._zod,"propValues",()=>{const n={};for(const s of e.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const[i,l]of Object.entries(o)){n[i]||(n[i]=new Set);for(const u of l)n[i].add(u)}}return n});const a=_o(()=>{const n=e.options,s=new Map;for(const o of n){const i=o._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});t._zod.parse=(n,s)=>{const o=n.value;if(!Ua(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;const i=a.value.get(o==null?void 0:o[e.discriminator]);return i?i._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),n)}}),ey=j("$ZodIntersection",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value,s=e.left._zod.run({value:n,issues:[]},a),o=e.right._zod.run({value:n,issues:[]},a);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,u])=>tc(r,l,u)):tc(r,s,o)}});function So(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Fa(t)&&Fa(e)){const r=Object.keys(e),a=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(const s of a){const o=So(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};n[s]=o.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let a=0;a<t.length;a++){const n=t[a],s=e[a],o=So(n,s);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function tc(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Jn(t))return t;const a=So(e.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}const ty=j("$ZodRecord",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Fa(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;const s=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;r.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const u=e.valueType._zod.run({value:n[l],issues:[]},a);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Jr(l,d.issues)),r.value[l]=d.value})):(u.issues.length&&r.issues.push(...Jr(l,u.issues)),r.value[l]=u.value)}let i;for(const l in n)o.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:i})}else{r.value={};for(const o of Reflect.ownKeys(n)){if(o==="__proto__")continue;const i=e.keyType._zod.run({value:o,issues:[]},a);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(u=>Pr(u,a,kr())),input:o,path:[o],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:n[o],issues:[]},a);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...Jr(o,u.issues)),r.value[i.value]=u.value})):(l.issues.length&&r.issues.push(...Jr(o,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),ry=j("$ZodEnum",(t,e)=>{Fe.init(t,e);const r=Mu(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(a=>gv.has(typeof a)).map(a=>typeof a=="string"?Hn(a):a.toString()).join("|")})$`),t._zod.parse=(a,n)=>{const s=a.value;return t._zod.values.has(s)||a.issues.push({code:"invalid_value",values:r,input:s,inst:t}),a}}),ny=j("$ZodLiteral",(t,e)=>{Fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Hn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,a)=>{const n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}}),ay=j("$ZodTransform",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=e.transform(r.value,r);if(a.async)return(n instanceof Promise?n:Promise.resolve(n)).then(o=>(r.value=o,r));if(n instanceof Promise)throw new Vn;return r.value=n,r}}),sy=j("$ZodOptional",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",De(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),De(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${bo(r.source)})?$`):void 0}),t._zod.parse=(r,a)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,a):r.value===void 0?r:e.innerType._zod.run(r,a)}),oy=j("$ZodNullable",(t,e)=>{Fe.init(t,e),De(t._zod,"optin",()=>e.innerType._zod.optin),De(t._zod,"optout",()=>e.innerType._zod.optout),De(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${bo(r.source)}|null)$`):void 0}),De(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,a)=>r.value===null?r:e.innerType._zod.run(r,a)}),iy=j("$ZodDefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",De(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>rc(s,e)):rc(n,e)}});function rc(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const ly=j("$ZodPrefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",De(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,a))}),uy=j("$ZodNonOptional",(t,e)=>{Fe.init(t,e),De(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(a=>a!==void 0)):void 0}),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>nc(s,t)):nc(n,t)}});function nc(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const cy=j("$ZodCatch",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",De(t._zod,"optout",()=>e.innerType._zod.optout),De(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Pr(o,a,kr()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Pr(s,a,kr()))},input:r.value}),r.issues=[]),r)}}),dy=j("$ZodPipe",(t,e)=>{Fe.init(t,e),De(t._zod,"values",()=>e.in._zod.values),De(t._zod,"optin",()=>e.in._zod.optin),De(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,a)=>{const n=e.in._zod.run(r,a);return n instanceof Promise?n.then(s=>ac(s,e,a)):ac(n,e,a)}});function ac(t,e,r){return Jn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const py=j("$ZodReadonly",(t,e)=>{Fe.init(t,e),De(t._zod,"propValues",()=>e.innerType._zod.propValues),De(t._zod,"values",()=>e.innerType._zod.values),De(t._zod,"optin",()=>e.innerType._zod.optin),De(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(sc):sc(n)}});function sc(t){return t.value=Object.freeze(t.value),t}const hy=j("$ZodLazy",(t,e)=>{Fe.init(t,e),De(t._zod,"innerType",()=>e.getter()),De(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),De(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),De(t._zod,"optin",()=>t._zod.innerType._zod.optin),De(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,a)=>t._zod.innerType._zod.run(r,a)}),fy=j("$ZodCustom",(t,e)=>{Et.init(t,e),Fe.init(t,e),t._zod.parse=(r,a)=>r,t._zod.check=r=>{const a=r.value,n=e.fn(a);if(n instanceof Promise)return n.then(s=>oc(s,r,a,t));oc(n,r,a,t)}});function oc(t,e,r,a){if(!t){const n={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(n.params=a._zod.def.params),e.issues.push(Wn(n))}}class ic{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const a=r[0];if(this._map.set(e,a),a&&typeof a=="object"&&"id"in a){if(this._idmap.has(a.id))throw new Error(`ID ${a.id} already exists in the registry`);this._idmap.set(a.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const a={...this.get(r)??{}};return delete a.id,{...a,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function my(){return new ic}const Gn=my();function vy(t,e){return new t({type:"string",...X(e)})}function gy(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function lc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function yy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function _y(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function wy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function by(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function xy(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function Ey(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function Sy(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function Iy(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function Ty(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function ky(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function Py(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function Cy(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function Ry(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function Oy(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function $y(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function Ay(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function uc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function Ny(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function My(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function Dy(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function jy(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function Ly(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function zy(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function Uy(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function Fy(t,e){return new t({type:"number",checks:[],...X(e)})}function qy(t,e){return new t({type:"number",coerce:!0,checks:[],...X(e)})}function Zy(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function Vy(t,e){return new t({type:"boolean",...X(e)})}function By(t,e){return new t({type:"null",...X(e)})}function Hy(t){return new t({type:"any"})}function Jy(t){return new t({type:"unknown"})}function Wy(t,e){return new t({type:"never",...X(e)})}function cc(t,e){return new Ju({check:"less_than",...X(e),value:t,inclusive:!1})}function Io(t,e){return new Ju({check:"less_than",...X(e),value:t,inclusive:!0})}function dc(t,e){return new Wu({check:"greater_than",...X(e),value:t,inclusive:!1})}function To(t,e){return new Wu({check:"greater_than",...X(e),value:t,inclusive:!0})}function pc(t,e){return new og({check:"multiple_of",...X(e),value:t})}function hc(t,e){return new lg({check:"max_length",...X(e),maximum:t})}function Ba(t,e){return new ug({check:"min_length",...X(e),minimum:t})}function fc(t,e){return new cg({check:"length_equals",...X(e),length:t})}function Gy(t,e){return new dg({check:"string_format",format:"regex",...X(e),pattern:t})}function Ky(t){return new pg({check:"string_format",format:"lowercase",...X(t)})}function Qy(t){return new hg({check:"string_format",format:"uppercase",...X(t)})}function Yy(t,e){return new fg({check:"string_format",format:"includes",...X(e),includes:t})}function Xy(t,e){return new mg({check:"string_format",format:"starts_with",...X(e),prefix:t})}function e_(t,e){return new vg({check:"string_format",format:"ends_with",...X(e),suffix:t})}function Kn(t){return new gg({check:"overwrite",tx:t})}function t_(t){return Kn(e=>e.normalize(t))}function r_(){return Kn(t=>t.trim())}function n_(){return Kn(t=>t.toLowerCase())}function a_(){return Kn(t=>t.toUpperCase())}function s_(t,e,r){return new t({type:"array",element:e,...X(r)})}function o_(t,e,r){const a=X(r);return a.abort??(a.abort=!0),new t({type:"custom",check:"custom",fn:e,...a})}function i_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}class mc{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??Gn,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var h,g,c;var a;const n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=(g=(h=e._zod).toJSONSchema)==null?void 0:g.call(h);if(l)i.schema=l;else{const p={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)i.ref=f,this.process(f,p),this.seen.get(f).isParent=!0;else{const m=i.schema;switch(n.type){case"string":{const v=m;v.type="string";const{minimum:w,maximum:y,format:_,patterns:E,contentEncoding:I}=e._zod.bag;if(typeof w=="number"&&(v.minLength=w),typeof y=="number"&&(v.maxLength=y),_&&(v.format=s[_]??_,v.format===""&&delete v.format),I&&(v.contentEncoding=I),E&&E.size>0){const S=[...E];S.length===1?v.pattern=S[0].source:S.length>1&&(i.schema.allOf=[...S.map(R=>({...this.target==="draft-7"?{type:"string"}:{},pattern:R.source}))])}break}case"number":{const v=m,{minimum:w,maximum:y,format:_,multipleOf:E,exclusiveMaximum:I,exclusiveMinimum:S}=e._zod.bag;typeof _=="string"&&_.includes("int")?v.type="integer":v.type="number",typeof S=="number"&&(v.exclusiveMinimum=S),typeof w=="number"&&(v.minimum=w,typeof S=="number"&&(S>=w?delete v.minimum:delete v.exclusiveMinimum)),typeof I=="number"&&(v.exclusiveMaximum=I),typeof y=="number"&&(v.maximum=y,typeof I=="number"&&(I<=y?delete v.maximum:delete v.exclusiveMaximum)),typeof E=="number"&&(v.multipleOf=E);break}case"boolean":{const v=m;v.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const v=m,{minimum:w,maximum:y}=e._zod.bag;typeof w=="number"&&(v.minItems=w),typeof y=="number"&&(v.maxItems=y),v.type="array",v.items=this.process(n.element,{...p,path:[...p.path,"items"]});break}case"object":{const v=m;v.type="object",v.properties={};const w=n.shape;for(const E in w)v.properties[E]=this.process(w[E],{...p,path:[...p.path,"properties",E]});const y=new Set(Object.keys(w)),_=new Set([...y].filter(E=>{const I=n.shape[E]._zod;return this.io==="input"?I.optin===void 0:I.optout===void 0}));_.size>0&&(v.required=Array.from(_)),((c=n.catchall)==null?void 0:c._zod.def.type)==="never"?v.additionalProperties=!1:n.catchall?n.catchall&&(v.additionalProperties=this.process(n.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(v.additionalProperties=!1);break}case"union":{const v=m;v.anyOf=n.options.map((w,y)=>this.process(w,{...p,path:[...p.path,"anyOf",y]}));break}case"intersection":{const v=m,w=this.process(n.left,{...p,path:[...p.path,"allOf",0]}),y=this.process(n.right,{...p,path:[...p.path,"allOf",1]}),_=I=>"allOf"in I&&Object.keys(I).length===1,E=[..._(w)?w.allOf:[w],..._(y)?y.allOf:[y]];v.allOf=E;break}case"tuple":{const v=m;v.type="array";const w=n.items.map((E,I)=>this.process(E,{...p,path:[...p.path,"prefixItems",I]}));if(this.target==="draft-2020-12"?v.prefixItems=w:v.items=w,n.rest){const E=this.process(n.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?v.items=E:v.additionalItems=E}n.rest&&(v.items=this.process(n.rest,{...p,path:[...p.path,"items"]}));const{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(v.minItems=y),typeof _=="number"&&(v.maxItems=_);break}case"record":{const v=m;v.type="object",v.propertyNames=this.process(n.keyType,{...p,path:[...p.path,"propertyNames"]}),v.additionalProperties=this.process(n.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const v=m,w=Mu(n.entries);w.every(y=>typeof y=="number")&&(v.type="number"),w.every(y=>typeof y=="string")&&(v.type="string"),v.enum=w;break}case"literal":{const v=m,w=[];for(const y of n.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(y))}else w.push(y);if(w.length!==0)if(w.length===1){const y=w[0];v.type=y===null?"null":typeof y,v.const=y}else w.every(y=>typeof y=="number")&&(v.type="number"),w.every(y=>typeof y=="string")&&(v.type="string"),w.every(y=>typeof y=="boolean")&&(v.type="string"),w.every(y=>y===null)&&(v.type="null"),v.enum=w;break}case"file":{const v=m,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:_,mime:E}=e._zod.bag;y!==void 0&&(w.minLength=y),_!==void 0&&(w.maxLength=_),E?E.length===1?(w.contentMediaType=E[0],Object.assign(v,w)):v.anyOf=E.map(I=>({...w,contentMediaType:I})):Object.assign(v,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const v=this.process(n.innerType,p);m.anyOf=[v,{type:"null"}];break}case"nonoptional":{this.process(n.innerType,p),i.ref=n.innerType;break}case"success":{const v=m;v.type="boolean";break}case"default":{this.process(n.innerType,p),i.ref=n.innerType,m.default=JSON.parse(JSON.stringify(n.defaultValue));break}case"prefault":{this.process(n.innerType,p),i.ref=n.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break}case"catch":{this.process(n.innerType,p),i.ref=n.innerType;let v;try{v=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=v;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const v=m,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");v.type="string",v.pattern=w.source;break}case"pipe":{const v=this.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;this.process(v,p),i.ref=v;break}case"readonly":{this.process(n.innerType,p),i.ref=n.innerType,m.readOnly=!0;break}case"promise":{this.process(n.innerType,p),i.ref=n.innerType;break}case"optional":{this.process(n.innerType,p),i.ref=n.innerType;break}case"lazy":{const v=e._zod.innerType;this.process(v,p),i.ref=v;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(i.schema,u),this.io==="input"&&it(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){var d,h,g,c,p,f;const a={cycles:(r==null?void 0:r.cycles)??"ref",reused:(r==null?void 0:r.reused)??"inline",external:(r==null?void 0:r.external)??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=m=>{var E;const v=this.target==="draft-2020-12"?"$defs":"definitions";if(a.external){const I=(E=a.external.registry.get(m[0]))==null?void 0:E.id,S=a.external.uri??($=>$);if(I)return{ref:S(I)};const R=m[1].defId??m[1].schema.id??`schema${this.counter++}`;return m[1].defId=R,{defId:R,ref:`${S("__shared")}#/${v}/${R}`}}if(m[1]===n)return{ref:"#"};const y=`#/${v}/`,_=m[1].schema.id??`__schema${this.counter++}`;return{defId:_,ref:y+_}},o=m=>{if(m[1].schema.$ref)return;const v=m[1],{ref:w,defId:y}=s(m);v.def={...v.schema},y&&(v.defId=y);const _=v.schema;for(const E in _)delete _[E];_.$ref=w};if(a.cycles==="throw")for(const m of this.seen.entries()){const v=m[1];if(v.cycle)throw new Error(`Cycle detected: #/${(d=v.cycle)==null?void 0:d.join("/")}/<root>
31
+ path: iss.path ? [${wn(_)}, ...iss.path] : [${wn(_)}]
32
+ })));`),h.write(`newResult[${wn(_)}] = ${f}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const y=h.compile();return(_,f)=>y(g,_,f)};let o;const s=co,a=!Hc.jitless,l=a&&J2.value,c=t.catchall;let u;e._zod.parse=(g,h)=>{u??(u=r.value);const d=g.value;if(!s(d))return g.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),g;const p=[];if(a&&l&&h?.async===!1&&h.jitless!==!0)o||(o=n(t.shape)),g=o(g,h);else{g.value={};const f=u.shape;for(const b of u.keys){const k=f[b],S=k._zod.run({value:d[b],issues:[]},h),C=k._zod.optin==="optional"&&k._zod.optout==="optional";S instanceof Promise?p.push(S.then(I=>C?uu(I,g,b,d):ho(I,g,b))):C?uu(S,g,b,d):ho(S,g,b)}}if(!c)return p.length?Promise.all(p).then(()=>g):g;const w=[],m=u.keySet,y=c._zod,_=y.def.type;for(const f of Object.keys(d)){if(m.has(f))continue;if(_==="never"){w.push(f);continue}const b=y.run({value:d[f],issues:[]},h);b instanceof Promise?p.push(b.then(k=>ho(k,g,f))):ho(b,g,f)}return w.length&&g.issues.push({code:"unrecognized_keys",keys:w,input:d,inst:e}),p.length?Promise.all(p).then(()=>g):g}});function du(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>lr(s,n,ir())))}),t}const pu=J("$ZodUnion",(e,t)=>{Oe.init(e,t),Te(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Te(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>pa(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>du(a,r,e,n)):du(s,r,e,n)}}),x1=J("$ZodDiscriminatedUnion",(e,t)=>{pu.init(e,t);const r=e._zod.parse;Te(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const c of l)o[i].add(c)}}return o});const n=ua(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!co(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=n.value.get(a?.[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),R1=J("$ZodIntersection",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>fu(r,l,c)):fu(r,s,a)}});function ma(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(uo(e)&&uo(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(const s of n){const a=ma(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const o=e[n],s=t[n],a=ma(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function fu(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),kn(e))return e;const n=ma(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const P1=J("$ZodRecord",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!uo(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Sr(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Sr(l,c.issues)),r.value[l]=c.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>lr(c,n,ir())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...Sr(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Sr(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),O1=J("$ZodEnum",(e,t)=>{Oe.init(e,t);const r=Bc(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>G2.has(typeof n)).map(n=>typeof n=="string"?bn(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),M1=J("$ZodLiteral",(e,t)=>{Oe.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?bn(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),N1=J("$ZodTransform",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new yn;return r.value=o,r}}),A1=J("$ZodOptional",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Te(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Te(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pa(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),q1=J("$ZodNullable",(e,t)=>{Oe.init(e,t),Te(e._zod,"optin",()=>t.innerType._zod.optin),Te(e._zod,"optout",()=>t.innerType._zod.optout),Te(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pa(r.source)}|null)$`):void 0}),Te(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),L1=J("$ZodDefault",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Te(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>hu(s,t)):hu(o,t)}});function hu(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const j1=J("$ZodPrefault",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Te(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),U1=J("$ZodNonOptional",(e,t)=>{Oe.init(e,t),Te(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>mu(s,e)):mu(o,e)}});function mu(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const z1=J("$ZodCatch",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Te(e._zod,"optout",()=>t.innerType._zod.optout),Te(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(a=>lr(a,n,ir()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>lr(s,n,ir()))},input:r.value}),r.issues=[]),r)}}),D1=J("$ZodPipe",(e,t)=>{Oe.init(e,t),Te(e._zod,"values",()=>t.in._zod.values),Te(e._zod,"optin",()=>t.in._zod.optin),Te(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>gu(s,t,n)):gu(o,t,n)}});function gu(e,t,r){return kn(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Z1=J("$ZodReadonly",(e,t)=>{Oe.init(e,t),Te(e._zod,"propValues",()=>t.innerType._zod.propValues),Te(e._zod,"values",()=>t.innerType._zod.values),Te(e._zod,"optin",()=>t.innerType._zod.optin),Te(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(vu):vu(o)}});function vu(e){return e.value=Object.freeze(e.value),e}const F1=J("$ZodLazy",(e,t)=>{Oe.init(e,t),Te(e._zod,"innerType",()=>t.getter()),Te(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Te(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Te(e._zod,"optin",()=>e._zod.innerType._zod.optin),Te(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),V1=J("$ZodCustom",(e,t)=>{it.init(e,t),Oe.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>_u(s,r,n,e));_u(o,r,n,e)}});function _u(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Sn(o))}}class yu{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"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,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function H1(){return new yu}const Cn=H1();function B1(e,t){return new e({type:"string",...re(t)})}function J1(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...re(t)})}function wu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...re(t)})}function G1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...re(t)})}function W1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(t)})}function K1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(t)})}function Y1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(t)})}function bu(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function Q1(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...re(t)})}function X1(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(t)})}function ev(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...re(t)})}function tv(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(t)})}function rv(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...re(t)})}function nv(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...re(t)})}function ov(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(t)})}function sv(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(t)})}function av(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(t)})}function iv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(t)})}function lv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(t)})}function ku(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...re(t)})}function cv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...re(t)})}function uv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...re(t)})}function dv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...re(t)})}function pv(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(t)})}function fv(e,t){return new e({type:"string",format:"date",check:"string_format",...re(t)})}function hv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...re(t)})}function mv(e,t){return new e({type:"string",format:"duration",check:"string_format",...re(t)})}function gv(e,t){return new e({type:"number",checks:[],...re(t)})}function vv(e,t){return new e({type:"number",coerce:!0,checks:[],...re(t)})}function _v(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function yv(e,t){return new e({type:"boolean",...re(t)})}function wv(e,t){return new e({type:"null",...re(t)})}function bv(e){return new e({type:"any"})}function kv(e){return new e({type:"unknown"})}function Sv(e,t){return new e({type:"never",...re(t)})}function Su(e,t){return new su({check:"less_than",...re(t),value:e,inclusive:!1})}function ga(e,t){return new su({check:"less_than",...re(t),value:e,inclusive:!0})}function Cu(e,t){return new au({check:"greater_than",...re(t),value:e,inclusive:!1})}function va(e,t){return new au({check:"greater_than",...re(t),value:e,inclusive:!0})}function Tu(e,t){return new qg({check:"multiple_of",...re(t),value:e})}function $u(e,t){return new jg({check:"max_length",...re(t),maximum:e})}function mo(e,t){return new Ug({check:"min_length",...re(t),minimum:e})}function Eu(e,t){return new zg({check:"length_equals",...re(t),length:e})}function Cv(e,t){return new Dg({check:"string_format",format:"regex",...re(t),pattern:e})}function Tv(e){return new Zg({check:"string_format",format:"lowercase",...re(e)})}function $v(e){return new Fg({check:"string_format",format:"uppercase",...re(e)})}function Ev(e,t){return new Vg({check:"string_format",format:"includes",...re(t),includes:e})}function Iv(e,t){return new Hg({check:"string_format",format:"starts_with",...re(t),prefix:e})}function xv(e,t){return new Bg({check:"string_format",format:"ends_with",...re(t),suffix:e})}function Tn(e){return new Jg({check:"overwrite",tx:e})}function Rv(e){return Tn(t=>t.normalize(e))}function Pv(){return Tn(e=>e.trim())}function Ov(){return Tn(e=>e.toLowerCase())}function Mv(){return Tn(e=>e.toUpperCase())}function Nv(e,t,r){return new e({type:"array",element:t,...re(r)})}function Av(e,t,r){const n=re(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function qv(e,t,r){return new e({type:"custom",check:"custom",fn:t,...re(r)})}class Iu{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Cn,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const g={...r,schemaPath:[...r.schemaPath,t],path:r.path},h=t._zod.parent;if(h)i.ref=h,this.process(h,g),this.seen.get(h).isParent=!0;else{const d=i.schema;switch(o.type){case"string":{const p=d;p.type="string";const{minimum:w,maximum:m,format:y,patterns:_,contentEncoding:f}=t._zod.bag;if(typeof w=="number"&&(p.minLength=w),typeof m=="number"&&(p.maxLength=m),y&&(p.format=s[y]??y,p.format===""&&delete p.format),f&&(p.contentEncoding=f),_&&_.size>0){const b=[..._];b.length===1?p.pattern=b[0].source:b.length>1&&(i.schema.allOf=[...b.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const p=d,{minimum:w,maximum:m,format:y,multipleOf:_,exclusiveMaximum:f,exclusiveMinimum:b}=t._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof w=="number"&&(p.minimum=w,typeof b=="number"&&(b>=w?delete p.minimum:delete p.exclusiveMinimum)),typeof f=="number"&&(p.exclusiveMaximum=f),typeof m=="number"&&(p.maximum=m,typeof f=="number"&&(f<=m?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{const p=d;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=d,{minimum:w,maximum:m}=t._zod.bag;typeof w=="number"&&(p.minItems=w),typeof m=="number"&&(p.maxItems=m),p.type="array",p.items=this.process(o.element,{...g,path:[...g.path,"items"]});break}case"object":{const p=d;p.type="object",p.properties={};const w=o.shape;for(const _ in w)p.properties[_]=this.process(w[_],{...g,path:[...g.path,"properties",_]});const m=new Set(Object.keys(w)),y=new Set([...m].filter(_=>{const f=o.shape[_]._zod;return this.io==="input"?f.optin===void 0:f.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...g,path:[...g.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=d;p.anyOf=o.options.map((w,m)=>this.process(w,{...g,path:[...g.path,"anyOf",m]}));break}case"intersection":{const p=d,w=this.process(o.left,{...g,path:[...g.path,"allOf",0]}),m=this.process(o.right,{...g,path:[...g.path,"allOf",1]}),y=f=>"allOf"in f&&Object.keys(f).length===1,_=[...y(w)?w.allOf:[w],...y(m)?m.allOf:[m]];p.allOf=_;break}case"tuple":{const p=d;p.type="array";const w=o.items.map((_,f)=>this.process(_,{...g,path:[...g.path,"prefixItems",f]}));if(this.target==="draft-2020-12"?p.prefixItems=w:p.items=w,o.rest){const _=this.process(o.rest,{...g,path:[...g.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}o.rest&&(p.items=this.process(o.rest,{...g,path:[...g.path,"items"]}));const{minimum:m,maximum:y}=t._zod.bag;typeof m=="number"&&(p.minItems=m),typeof y=="number"&&(p.maxItems=y);break}case"record":{const p=d;p.type="object",p.propertyNames=this.process(o.keyType,{...g,path:[...g.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...g,path:[...g.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=d,w=Bc(o.entries);w.every(m=>typeof m=="number")&&(p.type="number"),w.every(m=>typeof m=="string")&&(p.type="string"),p.enum=w;break}case"literal":{const p=d,w=[];for(const m of o.values)if(m===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof m=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(m))}else w.push(m);if(w.length!==0)if(w.length===1){const m=w[0];p.type=m===null?"null":typeof m,p.const=m}else w.every(m=>typeof m=="number")&&(p.type="number"),w.every(m=>typeof m=="string")&&(p.type="string"),w.every(m=>typeof m=="boolean")&&(p.type="string"),w.every(m=>m===null)&&(p.type="null"),p.enum=w;break}case"file":{const p=d,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:m,maximum:y,mime:_}=t._zod.bag;m!==void 0&&(w.minLength=m),y!==void 0&&(w.maxLength=y),_?_.length===1?(w.contentMediaType=_[0],Object.assign(p,w)):p.anyOf=_.map(f=>({...w,contentMediaType:f})):Object.assign(p,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(o.innerType,g);d.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,g),i.ref=o.innerType;break}case"success":{const p=d;p.type="boolean";break}case"default":{this.process(o.innerType,g),i.ref=o.innerType,d.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,g),i.ref=o.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,g),i.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=d,w=t._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=w.source;break}case"pipe":{const p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,g),i.ref=p;break}case"readonly":{this.process(o.innerType,g),i.ref=o.innerType,d.readOnly=!0;break}case"promise":{this.process(o.innerType,g),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,g),i.ref=o.innerType;break}case"lazy":{const p=t._zod.innerType;this.process(p,g),i.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&De(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const g=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const w=n.external.registry.get(u[0])?.id,m=n.external.uri??(_=>_);if(w)return{ref:m(w)};const y=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=y,{defId:y,ref:`${m("__shared")}#/${g}/${y}`}}if(u[1]===o)return{ref:"#"};const d=`#/${g}/`,p=u[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:d+p}},a=u=>{if(u[1].schema.$ref)return;const g=u[1],{ref:h,defId:d}=s(u);g.def={...g.schema},d&&(g.defId=d);const p=g.schema;for(const w in p)delete p[w];p.$ref=h};if(n.cycles==="throw")for(const u of this.seen.entries()){const g=u[1];if(g.cycle)throw new Error(`Cycle detected: #/${g.cycle?.join("/")}/<root>
33
33
 
34
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const m of this.seen.entries()){const v=m[1];if(e===m[0]){o(m);continue}if(a.external){const y=(h=a.external.registry.get(m[0]))==null?void 0:h.id;if(e!==m[0]&&y){o(m);continue}}if((g=this.metadataRegistry.get(m[0]))==null?void 0:g.id){o(m);continue}if(v.cycle){o(m);continue}if(v.count>1&&a.reused==="ref"){o(m);continue}}const i=(m,v)=>{const w=this.seen.get(m),y=w.def??w.schema,_={...y};if(w.ref===null)return;const E=w.ref;if(w.ref=null,E){i(E,v);const I=this.seen.get(E).schema;I.$ref&&v.target==="draft-7"?(y.allOf=y.allOf??[],y.allOf.push(I)):(Object.assign(y,I),Object.assign(y,_))}w.isParent||this.override({zodSchema:m,jsonSchema:y,path:w.path??[]})};for(const m of[...this.seen.entries()].reverse())i(m[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(c=a.external)!=null&&c.uri){const m=(p=a.external.registry.get(e))==null?void 0:p.id;if(!m)throw new Error("Schema is missing an `id` property");l.$id=a.external.uri(m)}Object.assign(l,n.def);const u=((f=a.external)==null?void 0:f.defs)??{};for(const m of this.seen.entries()){const v=m[1];v.def&&v.defId&&(u[v.defId]=v.def)}a.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?l.$defs=u:l.definitions=u);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function l_(t,e){if(t instanceof ic){const a=new mc(e),n={};for(const i of t._idmap.entries()){const[l,u]=i;a.process(u)}const s={},o={registry:t,uri:e==null?void 0:e.uri,defs:n};for(const i of t._idmap.entries()){const[l,u]=i;s[l]=a.emit(u,{...e,external:o})}if(Object.keys(n).length>0){const i=a.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:n}}return{schemas:s}}const r=new mc(e);return r.process(t),r.emit(t,e)}function it(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return it(n.element,r);case"object":{for(const s in n.shape)if(it(n.shape[s],r))return!0;return!1}case"union":{for(const s of n.options)if(it(s,r))return!0;return!1}case"intersection":return it(n.left,r)||it(n.right,r);case"tuple":{for(const s of n.items)if(it(s,r))return!0;return!!(n.rest&&it(n.rest,r))}case"record":return it(n.keyType,r)||it(n.valueType,r);case"map":return it(n.keyType,r)||it(n.valueType,r);case"set":return it(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return it(n.innerType,r);case"lazy":return it(n.getter(),r);case"default":return it(n.innerType,r);case"prefault":return it(n.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return it(n.in,r)||it(n.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${n.type}`)}const u_=j("ZodISODateTime",(t,e)=>{Og.init(t,e),Ye.init(t,e)});function c_(t){return jy(u_,t)}const d_=j("ZodISODate",(t,e)=>{$g.init(t,e),Ye.init(t,e)});function p_(t){return Ly(d_,t)}const h_=j("ZodISOTime",(t,e)=>{Ag.init(t,e),Ye.init(t,e)});function f_(t){return zy(h_,t)}const m_=j("ZodISODuration",(t,e)=>{Ng.init(t,e),Ye.init(t,e)});function v_(t){return Uy(m_,t)}const Ha=j("ZodError",(t,e)=>{Lu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>kv(t,r)},flatten:{value:r=>Tv(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),g_=Pv(Ha),y_=Cv(Ha),__=Uu(Ha),vc=Fu(Ha),Ve=j("ZodType",(t,e)=>(Fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(r,a)=>Hr(t,r,a),t.brand=()=>t,t.register=(r,a)=>(r.add(t,a),t),t.parse=(r,a)=>g_(t,r,a,{callee:t.parse}),t.safeParse=(r,a)=>__(t,r,a),t.parseAsync=async(r,a)=>y_(t,r,a,{callee:t.parseAsync}),t.safeParseAsync=async(r,a)=>vc(t,r,a),t.spa=t.safeParseAsync,t.refine=(r,a)=>t.check(h0(r,a)),t.superRefine=r=>t.check(f0(r)),t.overwrite=r=>t.check(Kn(r)),t.optional=()=>at(t),t.nullable=()=>Ic(t),t.nullish=()=>at(Ic(t)),t.nonoptional=r=>a0(t,r),t.array=()=>Y(t),t.or=r=>Ae([t,r]),t.and=r=>W_(t,r),t.transform=r=>kc(t,Y_(r)),t.default=r=>t0(t,r),t.prefault=r=>n0(t,r),t.catch=r=>o0(t,r),t.pipe=r=>kc(t,r),t.readonly=()=>u0(t),t.describe=r=>{const a=t.clone();return Gn.add(a,{description:r}),a},Object.defineProperty(t,"description",{get(){var r;return(r=Gn.get(t))==null?void 0:r.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Gn.get(t);const a=t.clone();return Gn.add(a,r[0]),a},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),gc=j("_ZodString",(t,e)=>{Eo.init(t,e),Ve.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...a)=>t.check(Gy(...a)),t.includes=(...a)=>t.check(Yy(...a)),t.startsWith=(...a)=>t.check(Xy(...a)),t.endsWith=(...a)=>t.check(e_(...a)),t.min=(...a)=>t.check(Ba(...a)),t.max=(...a)=>t.check(hc(...a)),t.length=(...a)=>t.check(fc(...a)),t.nonempty=(...a)=>t.check(Ba(1,...a)),t.lowercase=a=>t.check(Ky(a)),t.uppercase=a=>t.check(Qy(a)),t.trim=()=>t.check(r_()),t.normalize=(...a)=>t.check(t_(...a)),t.toLowerCase=()=>t.check(n_()),t.toUpperCase=()=>t.check(a_())}),w_=j("ZodString",(t,e)=>{Eo.init(t,e),gc.init(t,e),t.email=r=>t.check(gy(b_,r)),t.url=r=>t.check(xy(x_,r)),t.jwt=r=>t.check(Dy(D_,r)),t.emoji=r=>t.check(Ey(E_,r)),t.guid=r=>t.check(lc(yc,r)),t.uuid=r=>t.check(yy(Ja,r)),t.uuidv4=r=>t.check(_y(Ja,r)),t.uuidv6=r=>t.check(wy(Ja,r)),t.uuidv7=r=>t.check(by(Ja,r)),t.nanoid=r=>t.check(Sy(S_,r)),t.guid=r=>t.check(lc(yc,r)),t.cuid=r=>t.check(Iy(I_,r)),t.cuid2=r=>t.check(Ty(T_,r)),t.ulid=r=>t.check(ky(k_,r)),t.base64=r=>t.check(uc(_c,r)),t.base64url=r=>t.check(Ny(N_,r)),t.xid=r=>t.check(Py(P_,r)),t.ksuid=r=>t.check(Cy(C_,r)),t.ipv4=r=>t.check(Ry(R_,r)),t.ipv6=r=>t.check(Oy(O_,r)),t.cidrv4=r=>t.check($y($_,r)),t.cidrv6=r=>t.check(Ay(A_,r)),t.e164=r=>t.check(My(M_,r)),t.datetime=r=>t.check(c_(r)),t.date=r=>t.check(p_(r)),t.time=r=>t.check(f_(r)),t.duration=r=>t.check(v_(r))});function x(t){return vy(w_,t)}const Ye=j("ZodStringFormat",(t,e)=>{Je.init(t,e),gc.init(t,e)}),b_=j("ZodEmail",(t,e)=>{xg.init(t,e),Ye.init(t,e)}),yc=j("ZodGUID",(t,e)=>{wg.init(t,e),Ye.init(t,e)}),Ja=j("ZodUUID",(t,e)=>{bg.init(t,e),Ye.init(t,e)}),x_=j("ZodURL",(t,e)=>{Eg.init(t,e),Ye.init(t,e)}),E_=j("ZodEmoji",(t,e)=>{Sg.init(t,e),Ye.init(t,e)}),S_=j("ZodNanoID",(t,e)=>{Ig.init(t,e),Ye.init(t,e)}),I_=j("ZodCUID",(t,e)=>{Tg.init(t,e),Ye.init(t,e)}),T_=j("ZodCUID2",(t,e)=>{kg.init(t,e),Ye.init(t,e)}),k_=j("ZodULID",(t,e)=>{Pg.init(t,e),Ye.init(t,e)}),P_=j("ZodXID",(t,e)=>{Cg.init(t,e),Ye.init(t,e)}),C_=j("ZodKSUID",(t,e)=>{Rg.init(t,e),Ye.init(t,e)}),R_=j("ZodIPv4",(t,e)=>{Mg.init(t,e),Ye.init(t,e)}),O_=j("ZodIPv6",(t,e)=>{Dg.init(t,e),Ye.init(t,e)}),$_=j("ZodCIDRv4",(t,e)=>{jg.init(t,e),Ye.init(t,e)}),A_=j("ZodCIDRv6",(t,e)=>{Lg.init(t,e),Ye.init(t,e)}),_c=j("ZodBase64",(t,e)=>{zg.init(t,e),Ye.init(t,e)});function wc(t){return uc(_c,t)}const N_=j("ZodBase64URL",(t,e)=>{Fg.init(t,e),Ye.init(t,e)}),M_=j("ZodE164",(t,e)=>{qg.init(t,e),Ye.init(t,e)}),D_=j("ZodJWT",(t,e)=>{Vg.init(t,e),Ye.init(t,e)}),ko=j("ZodNumber",(t,e)=>{Ku.init(t,e),Ve.init(t,e),t.gt=(a,n)=>t.check(dc(a,n)),t.gte=(a,n)=>t.check(To(a,n)),t.min=(a,n)=>t.check(To(a,n)),t.lt=(a,n)=>t.check(cc(a,n)),t.lte=(a,n)=>t.check(Io(a,n)),t.max=(a,n)=>t.check(Io(a,n)),t.int=a=>t.check(bc(a)),t.safe=a=>t.check(bc(a)),t.positive=a=>t.check(dc(0,a)),t.nonnegative=a=>t.check(To(0,a)),t.negative=a=>t.check(cc(0,a)),t.nonpositive=a=>t.check(Io(0,a)),t.multipleOf=(a,n)=>t.check(pc(a,n)),t.step=(a,n)=>t.check(pc(a,n)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function U(t){return Fy(ko,t)}const j_=j("ZodNumberFormat",(t,e)=>{Bg.init(t,e),ko.init(t,e)});function bc(t){return Zy(j_,t)}const L_=j("ZodBoolean",(t,e)=>{Hg.init(t,e),Ve.init(t,e)});function nt(t){return Vy(L_,t)}const z_=j("ZodNull",(t,e)=>{Jg.init(t,e),Ve.init(t,e)});function U_(t){return By(z_,t)}const F_=j("ZodAny",(t,e)=>{Wg.init(t,e),Ve.init(t,e)});function Mt(){return Hy(F_)}const q_=j("ZodUnknown",(t,e)=>{Gg.init(t,e),Ve.init(t,e)});function Cr(){return Jy(q_)}const Z_=j("ZodNever",(t,e)=>{Kg.init(t,e),Ve.init(t,e)});function V_(t){return Wy(Z_,t)}const B_=j("ZodArray",(t,e)=>{Qg.init(t,e),Ve.init(t,e),t.element=e.element,t.min=(r,a)=>t.check(Ba(r,a)),t.nonempty=r=>t.check(Ba(1,r)),t.max=(r,a)=>t.check(hc(r,a)),t.length=(r,a)=>t.check(fc(r,a)),t.unwrap=()=>t.element});function Y(t,e){return s_(B_,t,e)}const xc=j("ZodObject",(t,e)=>{Yg.init(t,e),Ve.init(t,e),De(t,"shape",()=>e.shape),t.keyof=()=>vt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Cr()}),t.loose=()=>t.clone({...t._zod.def,catchall:Cr()}),t.strict=()=>t.clone({...t._zod.def,catchall:V_()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>xv(t,r),t.merge=r=>Ev(t,r),t.pick=r=>wv(t,r),t.omit=r=>bv(t,r),t.partial=(...r)=>Sv(Sc,t,r[0]),t.required=(...r)=>Iv(Tc,t,r[0])});function P(t,e){const r={type:"object",get shape(){return za(this,"shape",{...t}),this.shape},...X(e)};return new xc(r)}function _n(t,e){return new xc({type:"object",get shape(){return za(this,"shape",{...t}),this.shape},catchall:Cr(),...X(e)})}const Ec=j("ZodUnion",(t,e)=>{ec.init(t,e),Ve.init(t,e),t.options=e.options});function Ae(t,e){return new Ec({type:"union",options:t,...X(e)})}const H_=j("ZodDiscriminatedUnion",(t,e)=>{Ec.init(t,e),Xg.init(t,e)});function wn(t,e,r){return new H_({type:"union",options:e,discriminator:t,...X(r)})}const J_=j("ZodIntersection",(t,e)=>{ey.init(t,e),Ve.init(t,e)});function W_(t,e){return new J_({type:"intersection",left:t,right:e})}const G_=j("ZodRecord",(t,e)=>{ty.init(t,e),Ve.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function St(t,e,r){return new G_({type:"record",keyType:t,valueType:e,...X(r)})}const Po=j("ZodEnum",(t,e)=>{ry.init(t,e),Ve.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(a,n)=>{const s={};for(const o of a)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Po({...e,checks:[],...X(n),entries:s})},t.exclude=(a,n)=>{const s={...e.entries};for(const o of a)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Po({...e,checks:[],...X(n),entries:s})}});function vt(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(a=>[a,a])):t;return new Po({type:"enum",entries:r,...X(e)})}const K_=j("ZodLiteral",(t,e)=>{ny.init(t,e),Ve.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function H(t,e){return new K_({type:"literal",values:Array.isArray(t)?t:[t],...X(e)})}const Q_=j("ZodTransform",(t,e)=>{ay.init(t,e),Ve.init(t,e),t._zod.parse=(r,a)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Wn(s,r.value,e));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(Wn(o))}};const n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function Y_(t){return new Q_({type:"transform",transform:t})}const Sc=j("ZodOptional",(t,e)=>{sy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function at(t){return new Sc({type:"optional",innerType:t})}const X_=j("ZodNullable",(t,e)=>{oy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ic(t){return new X_({type:"nullable",innerType:t})}const e0=j("ZodDefault",(t,e)=>{iy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function t0(t,e){return new e0({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const r0=j("ZodPrefault",(t,e)=>{ly.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function n0(t,e){return new r0({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Tc=j("ZodNonOptional",(t,e)=>{uy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function a0(t,e){return new Tc({type:"nonoptional",innerType:t,...X(e)})}const s0=j("ZodCatch",(t,e)=>{cy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function o0(t,e){return new s0({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const i0=j("ZodPipe",(t,e)=>{dy.init(t,e),Ve.init(t,e),t.in=e.in,t.out=e.out});function kc(t,e){return new i0({type:"pipe",in:t,out:e})}const l0=j("ZodReadonly",(t,e)=>{py.init(t,e),Ve.init(t,e)});function u0(t){return new l0({type:"readonly",innerType:t})}const c0=j("ZodLazy",(t,e)=>{hy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.getter()});function Pc(t){return new c0({type:"lazy",getter:t})}const Co=j("ZodCustom",(t,e)=>{fy.init(t,e),Ve.init(t,e)});function d0(t){const e=new Et({check:"custom"});return e._zod.check=t,e}function p0(t,e){return o_(Co,t??(()=>!0),e)}function h0(t,e={}){return i_(Co,t,e)}function f0(t){const e=d0(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(Wn(a,r.value,e._zod.def));else{const n=a;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(Wn(n))}},t(r.value,r)));return e}function Wa(t,e={error:`Input not instance of ${t.name}`}){const r=new Co({type:"custom",check:"custom",fn:a=>a instanceof t,abort:!0,...X(e)});return r._zod.bag.Class=t,r}function m0(t){return qy(ko,t)}var $e;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{const s={};for(const o of n)s[o]=o;return s},t.getValidEnumValues=n=>{const s=t.objectKeys(n).filter(i=>typeof n[n[i]]!="number"),o={};for(const i of s)o[i]=n[i];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(s){return n[s]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const s=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&s.push(o);return s},t.find=(n,s)=>{for(const o of n)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,s=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=a,t.jsonStringifyReplacer=(n,s)=>typeof s=="bigint"?s.toString():s})($e||($e={}));var Cc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Cc||(Cc={}));const Q=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rr=t=>{switch(typeof t){case"undefined":return Q.undefined;case"string":return Q.string;case"number":return Number.isNaN(t)?Q.nan:Q.number;case"boolean":return Q.boolean;case"function":return Q.function;case"bigint":return Q.bigint;case"symbol":return Q.symbol;case"object":return Array.isArray(t)?Q.array:t===null?Q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Q.promise:typeof Map<"u"&&t instanceof Map?Q.map:typeof Set<"u"&&t instanceof Set?Q.set:typeof Date<"u"&&t instanceof Date?Q.date:Q.object;default:return Q.unknown}},Z=$e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class yr extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return n(this),a}static assert(e){if(!(e instanceof yr))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},a=[];for(const n of this.issues)if(n.path.length>0){const s=n.path[0];r[s]=r[s]||[],r[s].push(e(n))}else a.push(e(n));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}}yr.create=t=>new yr(t);const Ro=(t,e)=>{let r;switch(t.code){case Z.invalid_type:t.received===Q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,$e.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:r=`Unrecognized key(s) in object: ${$e.joinValues(t.keys,", ")}`;break;case Z.invalid_union:r="Invalid input";break;case Z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${$e.joinValues(t.options)}`;break;case Z.invalid_enum_value:r=`Invalid enum value. Expected ${$e.joinValues(t.options)}, received '${t.received}'`;break;case Z.invalid_arguments:r="Invalid function arguments";break;case Z.invalid_return_type:r="Invalid function return type";break;case Z.invalid_date:r="Invalid date";break;case Z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:$e.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Z.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Z.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Z.custom:r="Invalid input";break;case Z.invalid_intersection_types:r="Intersection results could not be merged";break;case Z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Z.not_finite:r="Number must be finite";break;default:r=e.defaultError,$e.assertNever(t)}return{message:r}};let v0=Ro;function g0(){return v0}const y0=t=>{const{data:e,path:r,errorMaps:a,issueData:n}=t,s=[...r,...n.path||[]],o={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let i="";const l=a.filter(u=>!!u).slice().reverse();for(const u of l)i=u(o,{data:e,defaultError:i}).message;return{...n,path:s,message:i}};function G(t,e){const r=g0(),a=y0({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ro?void 0:Ro].filter(n=>!!n)});t.common.issues.push(a)}class yt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const a=[];for(const n of r){if(n.status==="aborted")return ce;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){const a=[];for(const n of r){const s=await n.key,o=await n.value;a.push({key:s,value:o})}return yt.mergeObjectSync(e,a)}static mergeObjectSync(e,r){const a={};for(const n of r){const{key:s,value:o}=n;if(s.status==="aborted"||o.status==="aborted")return ce;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[s.value]=o.value)}return{status:e.value,value:a}}}const ce=Object.freeze({status:"aborted"}),Qn=t=>({status:"dirty",value:t}),Dt=t=>({status:"valid",value:t}),Rc=t=>t.status==="aborted",Oc=t=>t.status==="dirty",bn=t=>t.status==="valid",Ga=t=>typeof Promise<"u"&&t instanceof Promise;var te;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(te||(te={}));class tr{constructor(e,r,a,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $c=(t,e)=>{if(bn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new yr(t.common.issues);return this._error=r,this._error}}};function ge(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:n}}class Te{get description(){return this._def.description}_getType(e){return Rr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new yt,ctx:{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Ga(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){const a={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},n=this._parseSync({data:e,path:a.path,parent:a});return $c(a,n)}"~validate"(e){var a,n;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:r});return bn(s)?{value:s.value}:{issues:r.common.issues}}catch(s){(n=(a=s==null?void 0:s.message)==null?void 0:a.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>bn(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){const a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){const a={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},n=this._parse({data:e,path:a.path,parent:a}),s=await(Ga(n)?n:Promise.resolve(n));return $c(a,s)}refine(e,r){const a=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,s)=>{const o=e(n),i=()=>s.addIssue({code:Z.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof r=="function"?r(a,n):r),!1))}_refinement(e){return new Kr({schema:this,typeName:V.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return br.create(this,this._def)}nullable(){return Qr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return rr.create(this)}promise(){return ts.create(this,this._def)}or(e){return Qa.create([this,e],this._def)}and(e){return Ya.create(this,e,this._def)}transform(e){return new Kr({...ge(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new rs({...ge(this._def),innerType:this,defaultValue:r,typeName:V.ZodDefault})}brand(){return new Uc({typeName:V.ZodBranded,type:this,...ge(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ns({...ge(this._def),innerType:this,catchValue:r,typeName:V.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Fo.create(this,e)}readonly(){return as.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const _0=/^c[^\s-]{8,}$/i,w0=/^[0-9a-z]+$/,b0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,x0=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,E0=/^[a-z0-9_-]{21}$/i,S0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,I0=/^[-+]?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)?)??$/,T0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,k0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Oo;const P0=/^(?:(?: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])$/,C0=/^(?:(?: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])$/,R0=/^(([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]))$/,O0=/^(([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])$/,$0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,A0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ac="((\\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])))",N0=new RegExp(`^${Ac}$`);function Nc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function M0(t){return new RegExp(`^${Nc(t)}$`)}function D0(t){let e=`${Ac}T${Nc(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function j0(t,e){return!!((e==="v4"||!e)&&P0.test(t)||(e==="v6"||!e)&&R0.test(t))}function L0(t,e){if(!S0.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function z0(t,e){return!!((e==="v4"||!e)&&C0.test(t)||(e==="v6"||!e)&&O0.test(t))}class _r extends Te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Q.string){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_type,expected:Q.string,received:s.parsedType}),ce}const a=new yt;let n;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){const o=e.data.length>s.value,i=e.data.length<s.value;(o||i)&&(n=this._getOrReturnCtx(e,n),o?G(n,{code:Z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&G(n,{code:Z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")T0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"email",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")Oo||(Oo=new RegExp(k0,"u")),Oo.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"emoji",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")x0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"uuid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")E0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"nanoid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")_0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"cuid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")w0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"cuid2",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")b0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"ulid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),G(n,{validation:"url",code:Z.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"regex",code:Z.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?D0(s).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?N0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?M0(s).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?I0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"duration",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?j0(e.data,s.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"ip",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?L0(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"jwt",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?z0(e.data,s.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"cidr",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?$0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"base64",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?A0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"base64url",code:Z.invalid_string,message:s.message}),a.dirty()):$e.assertNever(s);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(n=>e.test(n),{validation:r,code:Z.invalid_string,...te.errToObj(a)})}_addCheck(e){return new _r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...te.errToObj(e)})}url(e){return this._addCheck({kind:"url",...te.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...te.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...te.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...te.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...te.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...te.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...te.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...te.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...te.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...te.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...te.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...te.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...te.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...te.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...te.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...te.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...te.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...te.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...te.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...te.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...te.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...te.errToObj(r)})}nonempty(e){return this.min(1,te.errToObj(e))}trim(){return new _r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}_r.create=t=>new _r({checks:[],typeName:V.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...ge(t)});function U0(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}class xn extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Q.number){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_type,expected:Q.number,received:s.parsedType}),ce}let a;const n=new yt;for(const s of this._def.checks)s.kind==="int"?$e.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:Z.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="multipleOf"?U0(e.data,s.value)!==0&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:Z.not_finite,message:s.message}),n.dirty()):$e.assertNever(s);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,te.toString(r))}gt(e,r){return this.setLimit("min",e,!1,te.toString(r))}lte(e,r){return this.setLimit("max",e,!0,te.toString(r))}lt(e,r){return this.setLimit("max",e,!1,te.toString(r))}setLimit(e,r,a,n){return new xn({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:te.toString(n)}]})}_addCheck(e){return new xn({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:te.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:te.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:te.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:te.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:te.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:te.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:te.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:te.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:te.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&$e.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}}xn.create=t=>new xn({checks:[],typeName:V.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class Yn extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Q.bigint)return this._getInvalidInput(e);let a;const n=new yt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):$e.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return G(r,{code:Z.invalid_type,expected:Q.bigint,received:r.parsedType}),ce}gte(e,r){return this.setLimit("min",e,!0,te.toString(r))}gt(e,r){return this.setLimit("min",e,!1,te.toString(r))}lte(e,r){return this.setLimit("max",e,!0,te.toString(r))}lt(e,r){return this.setLimit("max",e,!1,te.toString(r))}setLimit(e,r,a,n){return new Yn({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:te.toString(n)}]})}_addCheck(e){return new Yn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:te.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:te.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:te.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:te.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:te.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Yn.create=t=>new Yn({checks:[],typeName:V.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...ge(t)});class $o extends Te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Q.boolean){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.boolean,received:a.parsedType}),ce}return Dt(e.data)}}$o.create=t=>new $o({typeName:V.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class Ka extends Te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Q.date){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_type,expected:Q.date,received:s.parsedType}),ce}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_date}),ce}const a=new yt;let n;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):$e.assertNever(s);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ka({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:te.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:te.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Ka.create=t=>new Ka({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:V.ZodDate,...ge(t)});class Mc extends Te{_parse(e){if(this._getType(e)!==Q.symbol){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.symbol,received:a.parsedType}),ce}return Dt(e.data)}}Mc.create=t=>new Mc({typeName:V.ZodSymbol,...ge(t)});class Ao extends Te{_parse(e){if(this._getType(e)!==Q.undefined){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.undefined,received:a.parsedType}),ce}return Dt(e.data)}}Ao.create=t=>new Ao({typeName:V.ZodUndefined,...ge(t)});class No extends Te{_parse(e){if(this._getType(e)!==Q.null){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.null,received:a.parsedType}),ce}return Dt(e.data)}}No.create=t=>new No({typeName:V.ZodNull,...ge(t)});class Mo extends Te{constructor(){super(...arguments),this._any=!0}_parse(e){return Dt(e.data)}}Mo.create=t=>new Mo({typeName:V.ZodAny,...ge(t)});class Do extends Te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Dt(e.data)}}Do.create=t=>new Do({typeName:V.ZodUnknown,...ge(t)});class Or extends Te{_parse(e){const r=this._getOrReturnCtx(e);return G(r,{code:Z.invalid_type,expected:Q.never,received:r.parsedType}),ce}}Or.create=t=>new Or({typeName:V.ZodNever,...ge(t)});class Dc extends Te{_parse(e){if(this._getType(e)!==Q.undefined){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.void,received:a.parsedType}),ce}return Dt(e.data)}}Dc.create=t=>new Dc({typeName:V.ZodVoid,...ge(t)});class rr extends Te{_parse(e){const{ctx:r,status:a}=this._processInputParams(e),n=this._def;if(r.parsedType!==Q.array)return G(r,{code:Z.invalid_type,expected:Q.array,received:r.parsedType}),ce;if(n.exactLength!==null){const o=r.data.length>n.exactLength.value,i=r.data.length<n.exactLength.value;(o||i)&&(G(r,{code:o?Z.too_big:Z.too_small,minimum:i?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(G(r,{code:Z.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(G(r,{code:Z.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>n.type._parseAsync(new tr(r,o,r.path,i)))).then(o=>yt.mergeArray(a,o));const s=[...r.data].map((o,i)=>n.type._parseSync(new tr(r,o,r.path,i)));return yt.mergeArray(a,s)}get element(){return this._def.type}min(e,r){return new rr({...this._def,minLength:{value:e,message:te.toString(r)}})}max(e,r){return new rr({...this._def,maxLength:{value:e,message:te.toString(r)}})}length(e,r){return new rr({...this._def,exactLength:{value:e,message:te.toString(r)}})}nonempty(e){return this.min(1,e)}}rr.create=(t,e)=>new rr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...ge(e)});function En(t){if(t instanceof st){const e={};for(const r in t.shape){const a=t.shape[r];e[r]=br.create(En(a))}return new st({...t._def,shape:()=>e})}else return t instanceof rr?new rr({...t._def,type:En(t.element)}):t instanceof br?br.create(En(t.unwrap())):t instanceof Qr?Qr.create(En(t.unwrap())):t instanceof Wr?Wr.create(t.items.map(e=>En(e))):t}class st extends Te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=$e.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Q.object){const u=this._getOrReturnCtx(e);return G(u,{code:Z.invalid_type,expected:Q.object,received:u.parsedType}),ce}const{status:a,ctx:n}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof Or&&this._def.unknownKeys==="strip"))for(const u in n.data)o.includes(u)||i.push(u);const l=[];for(const u of o){const d=s[u],h=n.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new tr(n,h,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof Or){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of i)l.push({key:{status:"valid",value:d},value:{status:"valid",value:n.data[d]}});else if(u==="strict")i.length>0&&(G(n,{code:Z.unrecognized_keys,keys:i}),a.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of i){const h=n.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new tr(n,h,n.path,d)),alwaysSet:d in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const h=await d.key,g=await d.value;u.push({key:h,value:g,alwaysSet:d.alwaysSet})}return u}).then(u=>yt.mergeObjectSync(a,u)):yt.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return te.errToObj,new st({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{var s,o;const n=((o=(s=this._def).errorMap)==null?void 0:o.call(s,r,a).message)??a.defaultError;return r.code==="unrecognized_keys"?{message:te.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new st({...this._def,unknownKeys:"strip"})}passthrough(){return new st({...this._def,unknownKeys:"passthrough"})}extend(e){return new st({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new st({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:V.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new st({...this._def,catchall:e})}pick(e){const r={};for(const a of $e.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new st({...this._def,shape:()=>r})}omit(e){const r={};for(const a of $e.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new st({...this._def,shape:()=>r})}deepPartial(){return En(this)}partial(e){const r={};for(const a of $e.objectKeys(this.shape)){const n=this.shape[a];e&&!e[a]?r[a]=n:r[a]=n.optional()}return new st({...this._def,shape:()=>r})}required(e){const r={};for(const a of $e.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof br;)s=s._def.innerType;r[a]=s}return new st({...this._def,shape:()=>r})}keyof(){return Lc($e.objectKeys(this.shape))}}st.create=(t,e)=>new st({shape:()=>t,unknownKeys:"strip",catchall:Or.create(),typeName:V.ZodObject,...ge(e)}),st.strictCreate=(t,e)=>new st({shape:()=>t,unknownKeys:"strict",catchall:Or.create(),typeName:V.ZodObject,...ge(e)}),st.lazycreate=(t,e)=>new st({shape:t,unknownKeys:"strip",catchall:Or.create(),typeName:V.ZodObject,...ge(e)});class Qa extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),a=this._def.options;function n(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const o=s.map(i=>new yr(i.ctx.common.issues));return G(r,{code:Z.invalid_union,unionErrors:o}),ce}if(r.common.async)return Promise.all(a.map(async s=>{const o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let s;const o=[];for(const l of a){const u={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=o.map(l=>new yr(l));return G(r,{code:Z.invalid_union,unionErrors:i}),ce}}get options(){return this._def.options}}Qa.create=(t,e)=>new Qa({options:t,typeName:V.ZodUnion,...ge(e)});const wr=t=>t instanceof zo?wr(t.schema):t instanceof Kr?wr(t.innerType()):t instanceof es?[t.value]:t instanceof Gr?t.options:t instanceof Uo?$e.objectValues(t.enum):t instanceof rs?wr(t._def.innerType):t instanceof Ao?[void 0]:t instanceof No?[null]:t instanceof br?[void 0,...wr(t.unwrap())]:t instanceof Qr?[null,...wr(t.unwrap())]:t instanceof Uc||t instanceof as?wr(t.unwrap()):t instanceof ns?wr(t._def.innerType):[];class jo extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==Q.object)return G(r,{code:Z.invalid_type,expected:Q.object,received:r.parsedType}),ce;const a=this.discriminator,n=r.data[a],s=this.optionsMap.get(n);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(G(r,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),ce)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){const n=new Map;for(const s of r){const o=wr(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of o){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new jo({typeName:V.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...ge(a)})}}function Lo(t,e){const r=Rr(t),a=Rr(e);if(t===e)return{valid:!0,data:t};if(r===Q.object&&a===Q.object){const n=$e.objectKeys(e),s=$e.objectKeys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(const i of s){const l=Lo(t[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(r===Q.array&&a===Q.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let s=0;s<t.length;s++){const o=t[s],i=e[s],l=Lo(o,i);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return r===Q.date&&a===Q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Ya extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=(s,o)=>{if(Rc(s)||Rc(o))return ce;const i=Lo(s.value,o.value);return i.valid?((Oc(s)||Oc(o))&&r.dirty(),{status:r.value,value:i.data}):(G(a,{code:Z.invalid_intersection_types}),ce)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,o])=>n(s,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}Ya.create=(t,e,r)=>new Ya({left:t,right:e,typeName:V.ZodIntersection,...ge(r)});class Wr extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.array)return G(a,{code:Z.invalid_type,expected:Q.array,received:a.parsedType}),ce;if(a.data.length<this._def.items.length)return G(a,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ce;!this._def.rest&&a.data.length>this._def.items.length&&(G(a,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...a.data].map((o,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new tr(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(s).then(o=>yt.mergeArray(r,o)):yt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new Wr({...this._def,rest:e})}}Wr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Wr({items:t,typeName:V.ZodTuple,rest:null,...ge(e)})};class Xa extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.object)return G(a,{code:Z.invalid_type,expected:Q.object,received:a.parsedType}),ce;const n=[],s=this._def.keyType,o=this._def.valueType;for(const i in a.data)n.push({key:s._parse(new tr(a,i,a.path,i)),value:o._parse(new tr(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?yt.mergeObjectAsync(r,n):yt.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof Te?new Xa({keyType:e,valueType:r,typeName:V.ZodRecord,...ge(a)}):new Xa({keyType:_r.create(),valueType:e,typeName:V.ZodRecord,...ge(r)})}}class jc extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.map)return G(a,{code:Z.invalid_type,expected:Q.map,received:a.parsedType}),ce;const n=this._def.keyType,s=this._def.valueType,o=[...a.data.entries()].map(([i,l],u)=>({key:n._parse(new tr(a,i,a.path,[u,"key"])),value:s._parse(new tr(a,l,a.path,[u,"value"]))}));if(a.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of o){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return ce;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of o){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return ce;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}}}}jc.create=(t,e,r)=>new jc({valueType:e,keyType:t,typeName:V.ZodMap,...ge(r)});class Xn extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.set)return G(a,{code:Z.invalid_type,expected:Q.set,received:a.parsedType}),ce;const n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(G(a,{code:Z.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(G(a,{code:Z.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());const s=this._def.valueType;function o(l){const u=new Set;for(const d of l){if(d.status==="aborted")return ce;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const i=[...a.data.values()].map((l,u)=>s._parse(new tr(a,l,a.path,u)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new Xn({...this._def,minSize:{value:e,message:te.toString(r)}})}max(e,r){return new Xn({...this._def,maxSize:{value:e,message:te.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Xn.create=(t,e)=>new Xn({valueType:t,minSize:null,maxSize:null,typeName:V.ZodSet,...ge(e)});class zo extends Te{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}zo.create=(t,e)=>new zo({getter:t,typeName:V.ZodLazy,...ge(e)});class es extends Te{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return G(r,{received:r.data,code:Z.invalid_literal,expected:this._def.value}),ce}return{status:"valid",value:e.data}}get value(){return this._def.value}}es.create=(t,e)=>new es({value:t,typeName:V.ZodLiteral,...ge(e)});function Lc(t,e){return new Gr({values:t,typeName:V.ZodEnum,...ge(e)})}class Gr extends Te{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),a=this._def.values;return G(r,{expected:$e.joinValues(a),received:r.parsedType,code:Z.invalid_type}),ce}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),a=this._def.values;return G(r,{received:r.data,code:Z.invalid_enum_value,options:a}),ce}return Dt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Gr.create(e,{...this._def,...r})}exclude(e,r=this._def){return Gr.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}}Gr.create=Lc;class Uo extends Te{_parse(e){const r=$e.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==Q.string&&a.parsedType!==Q.number){const n=$e.objectValues(r);return G(a,{expected:$e.joinValues(n),received:a.parsedType,code:Z.invalid_type}),ce}if(this._cache||(this._cache=new Set($e.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=$e.objectValues(r);return G(a,{received:a.data,code:Z.invalid_enum_value,options:n}),ce}return Dt(e.data)}get enum(){return this._def.values}}Uo.create=(t,e)=>new Uo({values:t,typeName:V.ZodNativeEnum,...ge(e)});class ts extends Te{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==Q.promise&&r.common.async===!1)return G(r,{code:Z.invalid_type,expected:Q.promise,received:r.parsedType}),ce;const a=r.parsedType===Q.promise?r.data:Promise.resolve(r.data);return Dt(a.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ts.create=(t,e)=>new ts({type:t,typeName:V.ZodPromise,...ge(e)});class Kr extends Te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:o=>{G(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){const o=n.transform(a.data,s);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.value==="aborted")return ce;const l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?ce:l.status==="dirty"||r.value==="dirty"?Qn(l.value):l});{if(r.value==="aborted")return ce;const i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?ce:i.status==="dirty"||r.value==="dirty"?Qn(i.value):i}}if(n.type==="refinement"){const o=i=>{const l=n.refinement(i,s);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){const i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?ce:(i.status==="dirty"&&r.dirty(),o(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?ce:(i.status==="dirty"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(n.type==="transform")if(a.common.async===!1){const o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!bn(o))return ce;const i=n.transform(o.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>bn(o)?Promise.resolve(n.transform(o.value,s)).then(i=>({status:r.value,value:i})):ce);$e.assertNever(n)}}Kr.create=(t,e,r)=>new Kr({schema:t,typeName:V.ZodEffects,effect:e,...ge(r)}),Kr.createWithPreprocess=(t,e,r)=>new Kr({schema:e,effect:{type:"preprocess",transform:t},typeName:V.ZodEffects,...ge(r)});class br extends Te{_parse(e){return this._getType(e)===Q.undefined?Dt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}br.create=(t,e)=>new br({innerType:t,typeName:V.ZodOptional,...ge(e)});class Qr extends Te{_parse(e){return this._getType(e)===Q.null?Dt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Qr.create=(t,e)=>new Qr({innerType:t,typeName:V.ZodNullable,...ge(e)});class rs extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);let a=r.data;return r.parsedType===Q.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}rs.create=(t,e)=>new rs({innerType:t,typeName:V.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ge(e)});class ns extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return Ga(n)?n.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new yr(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new yr(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}ns.create=(t,e)=>new ns({innerType:t,typeName:V.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ge(e)});class zc extends Te{_parse(e){if(this._getType(e)!==Q.nan){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.nan,received:a.parsedType}),ce}return{status:"valid",value:e.data}}}zc.create=t=>new zc({typeName:V.ZodNaN,...ge(t)});class Uc extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}class Fo extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?ce:s.status==="dirty"?(r.dirty(),Qn(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{const n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?ce:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,r){return new Fo({in:e,out:r,typeName:V.ZodPipeline})}}class as extends Te{_parse(e){const r=this._def.innerType._parse(e),a=n=>(bn(n)&&(n.value=Object.freeze(n.value)),n);return Ga(r)?r.then(n=>a(n)):a(r)}unwrap(){return this._def.innerType}}as.create=(t,e)=>new as({innerType:t,typeName:V.ZodReadonly,...ge(e)});var V;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(V||(V={}));const O=_r.create,dt=xn.create,lt=$o.create,F0=Mo.create,ea=Do.create;Or.create;const ee=rr.create,W=st.create,_t=Qa.create,q0=jo.create;Ya.create,Wr.create;const ta=Xa.create,me=es.create,xr=Gr.create;ts.create;const q=br.create;Qr.create;function qo(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function Z0(t,e){if(t==null)return Promise.resolve();const r=e==null?void 0:e.abortSignal;return new Promise((a,n)=>{if(r!=null&&r.aborted){n(Fc());return}const s=setTimeout(()=>{o(),a()},t),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",i)},i=()=>{o(),n(Fc())};r==null||r.addEventListener("abort",i)})}function Fc(){return new DOMException("Delay was aborted","AbortError")}function ra(t){return Object.fromEntries([...t.headers])}var na=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new vo({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},V0=na();function Zo(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function Yr(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var B0=["fetch failed","failed to fetch"];function qc({error:t,url:e,requestBodyValues:r}){if(Yr(t))return t;if(t instanceof TypeError&&B0.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Ue({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function Vo(t=globalThis){var e,r,a;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(a=(r=t.process)==null?void 0:r.versions)!=null&&a.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function H0(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function aa(t,...e){const r=H0(t??{}),a=new Headers(r),n=a.get("user-agent")||"";return a.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(a)}var Zc="3.0.12",J0=()=>globalThis.fetch,Vc=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:a,abortSignal:n,fetch:s=J0()})=>{try{const o=await s(t,{method:"GET",headers:aa(e,`ai-sdk/provider-utils/${Zc}`,Vo()),signal:n}),i=ra(o);if(!o.ok){let l;try{l=await a({response:o,url:t,requestBodyValues:{}})}catch(u){throw Yr(u)||Ue.isInstance(u)?u:new Ue({message:"Failed to process error response",cause:u,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:o,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Yr(l)||Ue.isInstance(l))?l:new Ue({message:"Failed to process successful response",cause:l,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(o){throw qc({error:o,url:t,requestBodyValues:{}})}};function W0({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([a,n])=>{const s=a.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:n}:{mediaTypePrefix:s.replace(/\*/,""),regexes:n}}).filter(({mediaTypePrefix:a})=>t.startsWith(a)).flatMap(({regexes:a})=>a).some(a=>a.test(e))}function ss({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var G0=/"__proto__"\s*:/,K0=/"constructor"\s*:/;function Q0(t){const e=JSON.parse(t);return e===null||typeof e!="object"||G0.test(t)===!1&&K0.test(t)===!1?e:Y0(e)}function Y0(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function Bc(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return Q0(t)}finally{Error.stackTraceLimit=e}}var os=Symbol.for("vercel.ai.validator");function X0(t){return{[os]:!0,validate:t}}function ew(t){return typeof t=="object"&&t!==null&&os in t&&t[os]===!0&&"validate"in t}function Sn(t){let e;return()=>(e==null&&(e=t()),e)}function tw(t){return ew(t)?t:typeof t=="function"?t():rw(t)}function rw(t){return X0(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new er({value:e,cause:r.issues})}})}async function Bo({value:t,schema:e}){const r=await $r({value:t,schema:e});if(!r.success)throw er.wrap({value:t,cause:r.error});return r.value}async function $r({value:t,schema:e}){const r=tw(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:er.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:er.wrap({value:t,cause:a}),rawValue:t}}}async function nw({text:t,schema:e}){try{const r=Bc(t);return e==null?r:Bo({value:r,schema:e})}catch(r){throw Tr.isInstance(r)||er.isInstance(r)?r:new Tr({text:t,cause:r})}}async function Xr({text:t,schema:e}){try{const r=Bc(t);return e==null?{success:!0,value:r,rawValue:r}:await $r({value:r,schema:e})}catch(r){return{success:!1,error:Tr.isInstance(r)?r:new Tr({text:t,cause:r}),rawValue:void 0}}}function aw({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new hv).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await Xr({text:r,schema:e}))}}))}var sw=()=>globalThis.fetch,Ho=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>ow({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),ow=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=sw()})=>{try{const i=await o(t,{method:"POST",headers:aa(e,`ai-sdk/provider-utils/${Zc}`,Vo()),body:r.content,signal:s}),l=ra(i);if(!i.ok){let u;try{u=await n({response:i,url:t,requestBodyValues:r.values})}catch(d){throw Yr(d)||Ue.isInstance(d)?d:new Ue({message:"Failed to process error response",cause:d,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw u.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(u){throw u instanceof Error&&(Yr(u)||Ue.isInstance(u))?u:new Ue({message:"Failed to process successful response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw qc({error:i,url:t,requestBodyValues:r.values})}};function iw(t){return{...t,type:"dynamic"}}async function Ar(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var sa=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=ra(a);if(o.trim()==="")return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await nw({text:o,schema:t});return{responseHeaders:i,value:new Ue({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},lw=t=>async({response:e})=>{const r=ra(e);if(e.body==null)throw new su({});return{responseHeaders:r,value:aw({stream:e.body,schema:t})}},is=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await Xr({text:n,schema:t}),o=ra(e);if(!s.success)throw new Ue({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},uw=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},cw=Symbol("Let zodToJsonSchema decide on which parser to use"),Hc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},dw=t=>typeof t=="string"?{...Hc,name:t}:{...Hc,...t};function Pt(){return{}}function pw(t,e){var r,a,n;const s={type:"array"};return(r=t.type)!=null&&r._def&&((n=(a=t.type)==null?void 0:a._def)==null?void 0:n.typeName)!==V.ZodAny&&(s.items=je(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(s.minItems=t.minLength.value),t.maxLength&&(s.maxItems=t.maxLength.value),t.exactLength&&(s.minItems=t.exactLength.value,s.maxItems=t.exactLength.value),s}function hw(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function fw(){return{type:"boolean"}}function Jc(t,e){return je(t.type._def,e)}var mw=(t,e)=>je(t.innerType._def,e);function Wc(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>Wc(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return vw(t)}}var vw=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function gw(t,e){return{...je(t.innerType._def,e),default:t.defaultValue()}}function yw(t,e){return e.effectStrategy==="input"?je(t.schema._def,e):Pt()}function _w(t){return{type:"string",enum:Array.from(t.values)}}var ww=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function bw(t,e){const r=[je(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),je(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=[];return r.forEach(n=>{if(ww(n))a.push(...n.allOf);else{let s=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:o,...i}=n;s=i}a.push(s)}}),a.length?{allOf:a}:void 0}function xw(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Jo=void 0,Jt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Jo===void 0&&(Jo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Jo),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Gc(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"email":switch(e.emailStrategy){case"format:email":Wt(r,"email",a.message,e);break;case"format:idn-email":Wt(r,"idn-email",a.message,e);break;case"pattern:zod":wt(r,Jt.email,a.message,e);break}break;case"url":Wt(r,"uri",a.message,e);break;case"uuid":Wt(r,"uuid",a.message,e);break;case"regex":wt(r,a.regex,a.message,e);break;case"cuid":wt(r,Jt.cuid,a.message,e);break;case"cuid2":wt(r,Jt.cuid2,a.message,e);break;case"startsWith":wt(r,RegExp(`^${Wo(a.value,e)}`),a.message,e);break;case"endsWith":wt(r,RegExp(`${Wo(a.value,e)}$`),a.message,e);break;case"datetime":Wt(r,"date-time",a.message,e);break;case"date":Wt(r,"date",a.message,e);break;case"time":Wt(r,"time",a.message,e);break;case"duration":Wt(r,"duration",a.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"includes":{wt(r,RegExp(Wo(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&Wt(r,"ipv4",a.message,e),a.version!=="v4"&&Wt(r,"ipv6",a.message,e);break}case"base64url":wt(r,Jt.base64url,a.message,e);break;case"jwt":wt(r,Jt.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&wt(r,Jt.ipv4Cidr,a.message,e),a.version!=="v4"&&wt(r,Jt.ipv6Cidr,a.message,e);break}case"emoji":wt(r,Jt.emoji(),a.message,e);break;case"ulid":{wt(r,Jt.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Wt(r,"binary",a.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{wt(r,Jt.base64,a.message,e);break}}break}case"nanoid":wt(r,Jt.nanoid,a.message,e)}return r}function Wo(t,e){return e.patternStrategy==="escape"?Sw(t):t}var Ew=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Sw(t){let e="";for(let r=0;r<t.length;r++)Ew.has(t[r])||(e+="\\"),e+=t[r];return e}function Wt(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function wt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Kc(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Kc(e,a)}function Kc(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let s="",o=!1,i=!1,l=!1;for(let u=0;u<n.length;u++){if(o){s+=n[u],o=!1;continue}if(a.i){if(i){if(n[u].match(/[a-z]/)){l?(s+=n[u],s+=`${n[u-2]}-${n[u]}`.toUpperCase(),l=!1):n[u+1]==="-"&&((r=n[u+2])!=null&&r.match(/[a-z]/))?(s+=n[u],l=!0):s+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){s+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(a.m){if(n[u]==="^"){s+=`(^|(?<=[\r
35
- ]))`;continue}else if(n[u]==="$"){s+=`($|(?=[\r
36
- ]))`;continue}}if(a.s&&n[u]==="."){s+=i?`${n[u]}\r
37
- `:`[${n[u]}\r
38
- ]`;continue}s+=n[u],n[u]==="\\"?o=!0:i&&n[u]==="]"?i=!1:!i&&n[u]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Qc(t,e){var r,a,n,s,o,i;const l={type:"object",additionalProperties:(r=je(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodString&&((n=t.keyType._def.checks)!=null&&n.length)){const{type:u,...d}=Gc(t.keyType._def,e);return{...l,propertyNames:d}}else{if(((s=t.keyType)==null?void 0:s._def.typeName)===V.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:u,...d}=Jc(t.keyType._def,e);return{...l,propertyNames:d}}}return l}function Iw(t,e){if(e.mapStrategy==="record")return Qc(t,e);const r=je(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Pt(),a=je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Pt();return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function Tw(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function kw(){return{not:Pt()}}function Pw(){return{type:"null"}}var Go={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Cw(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in Go&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=Go[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return Rw(t,e)}var Rw=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>je(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function Ow(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Go[t.innerType._def.typeName],"null"]};const r=je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function $w(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function Aw(t,e){const r={type:"object",properties:{}},a=[],n=t.shape();for(const o in n){let i=n[o];if(i===void 0||i._def===void 0)continue;const l=Mw(i),u=je(i._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||a.push(o))}a.length&&(r.required=a);const s=Nw(t,e);return s!==void 0&&(r.additionalProperties=s),r}function Nw(t,e){if(t.catchall._def.typeName!=="ZodNever")return je(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mw(t){try{return t.isOptional()}catch{return!0}}var Dw=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return je(t.innerType._def,e);const a=je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return a?{anyOf:[{not:Pt()},a]}:Pt()},jw=(t,e)=>{if(e.pipeStrategy==="input")return je(t.in._def,e);if(e.pipeStrategy==="output")return je(t.out._def,e);const r=je(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=je(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function Lw(t,e){return je(t.type._def,e)}function zw(t,e){const a={type:"array",uniqueItems:!0,items:je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(a.minItems=t.minSize.value),t.maxSize&&(a.maxItems=t.maxSize.value),a}function Uw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:je(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function Fw(){return{not:Pt()}}function qw(){return Pt()}var Zw=(t,e)=>je(t.innerType._def,e),Vw=(t,e,r)=>{switch(e){case V.ZodString:return Gc(t,r);case V.ZodNumber:return $w(t);case V.ZodObject:return Aw(t,r);case V.ZodBigInt:return hw(t);case V.ZodBoolean:return fw();case V.ZodDate:return Wc(t,r);case V.ZodUndefined:return Fw();case V.ZodNull:return Pw();case V.ZodArray:return pw(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return Cw(t,r);case V.ZodIntersection:return bw(t,r);case V.ZodTuple:return Uw(t,r);case V.ZodRecord:return Qc(t,r);case V.ZodLiteral:return xw(t);case V.ZodEnum:return _w(t);case V.ZodNativeEnum:return Tw(t);case V.ZodNullable:return Ow(t,r);case V.ZodOptional:return Dw(t,r);case V.ZodMap:return Iw(t,r);case V.ZodSet:return zw(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return Lw(t,r);case V.ZodNaN:case V.ZodNever:return kw();case V.ZodEffects:return yw(t,r);case V.ZodAny:return Pt();case V.ZodUnknown:return qw();case V.ZodDefault:return gw(t,r);case V.ZodBranded:return Jc(t,r);case V.ZodReadonly:return Zw(t,r);case V.ZodCatch:return mw(t,r);case V.ZodPipeline:return jw(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function je(t,e,r=!1){var a;const n=e.seen.get(t);if(e.override){const l=(a=e.override)==null?void 0:a.call(e,t,e,n,r);if(l!==cw)return l}if(n&&!r){const l=Bw(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=Vw(t,t.typeName,e),i=typeof o=="function"?je(o(),e):o;if(i&&Hw(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var Bw=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:uw(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Pt()):e.$refStrategy==="seen"?Pt():void 0}},Hw=(t,e,r)=>(t.description&&(r.description=t.description),r),Jw=t=>{const e=dw(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}},Ww=(t,e)=>{var r;const a=Jw(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[d,h])=>{var g;return{...u,[d]:(g=je(h._def,{...a,currentPath:[...a.basePath,a.definitionPath,d]},!0))!=null?g:Pt()}},{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,o=(r=je(t._def,s===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1))!=null?r:Pt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);const l=s===void 0?n?{...o,[a.definitionPath]:n}:o:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...n,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Gw=Ww;function Kw(t,e){var r;const a=(r=void 0)!=null?r:!1;return ls(()=>Gw(t,{$refStrategy:a?"root":"none"}),{validate:async n=>{const s=await t.safeParseAsync(n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Qw(t,e){var r;const a=(r=void 0)!=null?r:!1;return ls(()=>l_(t,{target:"draft-7",io:"output",reused:a?"ref":"inline"}),{validate:async n=>{const s=await vc(t,n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Yw(t){return"_zod"in t}function en(t,e){return Yw(t)?Qw(t):Kw(t)}var Ko=Symbol.for("vercel.ai.schema");function ls(t,{validate:e}={}){return{[Ko]:!0,_type:void 0,[os]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function Xw(t){return typeof t=="object"&&t!==null&&Ko in t&&t[Ko]===!0&&"jsonSchema"in t&&"validate"in t}function us(t){return t==null?ls({properties:{},additionalProperties:!1}):Xw(t)?t:typeof t=="function"?t():en(t)}var{btoa:eb,atob:tb}=globalThis;function Qo(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=tb(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function Yo(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return eb(e)}function rb(t){return t==null?void 0:t.replace(/\/$/,"")}function nb(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*Yc({execute:t,input:e,options:r}){const a=t(e,r);if(nb(a)){let n;for await(const s of a)n=s,yield{type:"preliminary",output:s};yield{type:"final",output:n}}else yield{type:"final",output:await a}}var ab=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sb(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Xo=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,ib=Object.getOwnPropertyNames,lb=Object.prototype.hasOwnProperty,ub=(t,e)=>{for(var r in e)Xo(t,r,{get:e[r],enumerable:!0})},cb=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ib(e))!lb.call(t,n)&&n!==r&&Xo(t,n,{get:()=>e[n],enumerable:!(a=ob(e,n))||a.enumerable});return t},db=t=>cb(Xo({},"__esModule",{value:!0}),t),Xc={};ub(Xc,{SYMBOL_FOR_REQ_CONTEXT:()=>ed,getContext:()=>hb});var pb=db(Xc);const ed=Symbol.for("@vercel/request-context");function hb(){var e,r;return((r=(e=globalThis[ed])==null?void 0:e.get)==null?void 0:r.call(e))??{}}var ei=Object.defineProperty,fb=Object.getOwnPropertyDescriptor,mb=Object.getOwnPropertyNames,vb=Object.prototype.hasOwnProperty,gb=(t,e)=>{for(var r in e)ei(t,r,{get:e[r],enumerable:!0})},yb=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of mb(e))!vb.call(t,n)&&n!==r&&ei(t,n,{get:()=>e[n],enumerable:!(a=fb(e,n))||a.enumerable});return t},_b=t=>yb(ei({},"__esModule",{value:!0}),t),td={};gb(td,{getContext:()=>wb.getContext,getVercelOidcToken:()=>bb,getVercelOidcTokenSync:()=>xb});var rd=_b(td),wb=pb;async function bb(){return""}function xb(){return""}var Eb="vercel.ai.gateway.error",ti=Symbol.for(Eb),nd,ad,Ct=class Wm extends(ad=Error,nd=ti,ad){constructor({message:e,statusCode:r=500,cause:a}){super(e),this[nd]=!0,this.statusCode=r,this.cause=a}static isInstance(e){return Wm.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&ti in e&&e[ti]===!0}},sd="GatewayAuthenticationError",Sb=`vercel.ai.gateway.error.${sd}`,od=Symbol.for(Sb),id,ld,ri=class Gm extends(ld=Ct,id=od,ld){constructor({message:e="Authentication failed",statusCode:r=401,cause:a}={}){super({message:e,statusCode:r,cause:a}),this[id]=!0,this.name=sd,this.type="authentication_error"}static isInstance(e){return Ct.hasMarker(e)&&od in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:a="Authentication failed",statusCode:n=401,cause:s}){let o;return e?o=`AI Gateway authentication failed: Invalid API key.
34
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const g=u[1];if(t===u[0]){a(u);continue}if(n.external){const d=n.external.registry.get(u[0])?.id;if(t!==u[0]&&d){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(g.cycle){a(u);continue}if(g.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,g)=>{const h=this.seen.get(u),d=h.def??h.schema,p={...d};if(h.ref===null)return;const w=h.ref;if(h.ref=null,w){i(w,g);const m=this.seen.get(w).schema;m.$ref&&g.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(m)):(Object.assign(d,m),Object.assign(d,p))}h.isParent||this.override({zodSchema:u,jsonSchema:d,path:h.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const g=u[1];g.def&&g.defId&&(c[g.defId]=g.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function xu(e,t){if(e instanceof yu){const n=new Iu(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;n.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;s[l]=n.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const r=new Iu(t);return r.process(e),r.emit(e,t)}function De(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return De(o.element,r);case"object":{for(const s in o.shape)if(De(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(De(s,r))return!0;return!1}case"intersection":return De(o.left,r)||De(o.right,r);case"tuple":{for(const s of o.items)if(De(s,r))return!0;return!!(o.rest&&De(o.rest,r))}case"record":return De(o.keyType,r)||De(o.valueType,r);case"map":return De(o.keyType,r)||De(o.valueType,r);case"set":return De(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return De(o.innerType,r);case"lazy":return De(o.getter(),r);case"default":return De(o.innerType,r);case"prefault":return De(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return De(o.in,r)||De(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const Lv=J("ZodISODateTime",(e,t)=>{i1.init(e,t),Ue.init(e,t)});function Ru(e){return pv(Lv,e)}const jv=J("ZodISODate",(e,t)=>{l1.init(e,t),Ue.init(e,t)});function Uv(e){return fv(jv,e)}const zv=J("ZodISOTime",(e,t)=>{c1.init(e,t),Ue.init(e,t)});function Dv(e){return hv(zv,e)}const Zv=J("ZodISODuration",(e,t)=>{u1.init(e,t),Ue.init(e,t)});function Fv(e){return mv(Zv,e)}const go=J("ZodError",(e,t)=>{Wc.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>og(e,r)},flatten:{value:r=>ng(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Vv=sg(go),Hv=ag(go),Bv=Yc(go),_a=Xc(go),Ae=J("ZodType",(e,t)=>(Oe.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>kr(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Vv(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Bv(e,r,n),e.parseAsync=async(r,n)=>Hv(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>_a(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(q_(r,n)),e.superRefine=r=>e.check(L_(r)),e.overwrite=r=>e.check(Tn(r)),e.optional=()=>K(e),e.nullable=()=>Du(e),e.nullish=()=>K(Du(e)),e.nonoptional=r=>I_(e,r),e.array=()=>A(e),e.or=r=>ne([e,r]),e.and=r=>ba(e,r),e.transform=r=>Sa(e,Uu(r)),e.default=r=>T_(e,r),e.prefault=r=>E_(e,r),e.catch=r=>R_(e,r),e.pipe=r=>Sa(e,r),e.readonly=()=>M_(e),e.describe=r=>{const n=e.clone();return Cn.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Cn.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Cn.get(e);const n=e.clone();return Cn.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Pu=J("_ZodString",(e,t)=>{ha.init(e,t),Ae.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Cv(...n)),e.includes=(...n)=>e.check(Ev(...n)),e.startsWith=(...n)=>e.check(Iv(...n)),e.endsWith=(...n)=>e.check(xv(...n)),e.min=(...n)=>e.check(mo(...n)),e.max=(...n)=>e.check($u(...n)),e.length=(...n)=>e.check(Eu(...n)),e.nonempty=(...n)=>e.check(mo(1,...n)),e.lowercase=n=>e.check(Tv(n)),e.uppercase=n=>e.check($v(n)),e.trim=()=>e.check(Pv()),e.normalize=(...n)=>e.check(Rv(...n)),e.toLowerCase=()=>e.check(Ov()),e.toUpperCase=()=>e.check(Mv())}),Jv=J("ZodString",(e,t)=>{ha.init(e,t),Pu.init(e,t),e.email=r=>e.check(J1(Gv,r)),e.url=r=>e.check(bu(Mu,r)),e.jwt=r=>e.check(dv(c_,r)),e.emoji=r=>e.check(Q1(Kv,r)),e.guid=r=>e.check(wu(Ou,r)),e.uuid=r=>e.check(G1(vo,r)),e.uuidv4=r=>e.check(W1(vo,r)),e.uuidv6=r=>e.check(K1(vo,r)),e.uuidv7=r=>e.check(Y1(vo,r)),e.nanoid=r=>e.check(X1(Yv,r)),e.guid=r=>e.check(wu(Ou,r)),e.cuid=r=>e.check(ev(Qv,r)),e.cuid2=r=>e.check(tv(Xv,r)),e.ulid=r=>e.check(rv(e_,r)),e.base64=r=>e.check(ku(Nu,r)),e.base64url=r=>e.check(cv(i_,r)),e.xid=r=>e.check(nv(t_,r)),e.ksuid=r=>e.check(ov(r_,r)),e.ipv4=r=>e.check(sv(n_,r)),e.ipv6=r=>e.check(av(o_,r)),e.cidrv4=r=>e.check(iv(s_,r)),e.cidrv6=r=>e.check(lv(a_,r)),e.e164=r=>e.check(uv(l_,r)),e.datetime=r=>e.check(Ru(r)),e.date=r=>e.check(Uv(r)),e.time=r=>e.check(Dv(r)),e.duration=r=>e.check(Fv(r))});function v(e){return B1(Jv,e)}const Ue=J("ZodStringFormat",(e,t)=>{Le.init(e,t),Pu.init(e,t)}),Gv=J("ZodEmail",(e,t)=>{Qg.init(e,t),Ue.init(e,t)}),Ou=J("ZodGUID",(e,t)=>{Kg.init(e,t),Ue.init(e,t)}),vo=J("ZodUUID",(e,t)=>{Yg.init(e,t),Ue.init(e,t)}),Mu=J("ZodURL",(e,t)=>{Xg.init(e,t),Ue.init(e,t)});function Wv(e){return bu(Mu,e)}const Kv=J("ZodEmoji",(e,t)=>{e1.init(e,t),Ue.init(e,t)}),Yv=J("ZodNanoID",(e,t)=>{t1.init(e,t),Ue.init(e,t)}),Qv=J("ZodCUID",(e,t)=>{r1.init(e,t),Ue.init(e,t)}),Xv=J("ZodCUID2",(e,t)=>{n1.init(e,t),Ue.init(e,t)}),e_=J("ZodULID",(e,t)=>{o1.init(e,t),Ue.init(e,t)}),t_=J("ZodXID",(e,t)=>{s1.init(e,t),Ue.init(e,t)}),r_=J("ZodKSUID",(e,t)=>{a1.init(e,t),Ue.init(e,t)}),n_=J("ZodIPv4",(e,t)=>{d1.init(e,t),Ue.init(e,t)}),o_=J("ZodIPv6",(e,t)=>{p1.init(e,t),Ue.init(e,t)}),s_=J("ZodCIDRv4",(e,t)=>{f1.init(e,t),Ue.init(e,t)}),a_=J("ZodCIDRv6",(e,t)=>{h1.init(e,t),Ue.init(e,t)}),Nu=J("ZodBase64",(e,t)=>{m1.init(e,t),Ue.init(e,t)});function Au(e){return ku(Nu,e)}const i_=J("ZodBase64URL",(e,t)=>{v1.init(e,t),Ue.init(e,t)}),l_=J("ZodE164",(e,t)=>{_1.init(e,t),Ue.init(e,t)}),c_=J("ZodJWT",(e,t)=>{w1.init(e,t),Ue.init(e,t)}),ya=J("ZodNumber",(e,t)=>{lu.init(e,t),Ae.init(e,t),e.gt=(n,o)=>e.check(Cu(n,o)),e.gte=(n,o)=>e.check(va(n,o)),e.min=(n,o)=>e.check(va(n,o)),e.lt=(n,o)=>e.check(Su(n,o)),e.lte=(n,o)=>e.check(ga(n,o)),e.max=(n,o)=>e.check(ga(n,o)),e.int=n=>e.check(qu(n)),e.safe=n=>e.check(qu(n)),e.positive=n=>e.check(Cu(0,n)),e.nonnegative=n=>e.check(va(0,n)),e.negative=n=>e.check(Su(0,n)),e.nonpositive=n=>e.check(ga(0,n)),e.multipleOf=(n,o)=>e.check(Tu(n,o)),e.step=(n,o)=>e.check(Tu(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function q(e){return gv(ya,e)}const u_=J("ZodNumberFormat",(e,t)=>{b1.init(e,t),ya.init(e,t)});function qu(e){return _v(u_,e)}const d_=J("ZodBoolean",(e,t)=>{k1.init(e,t),Ae.init(e,t)});function ce(e){return yv(d_,e)}const p_=J("ZodNull",(e,t)=>{S1.init(e,t),Ae.init(e,t)});function wa(e){return wv(p_,e)}const f_=J("ZodAny",(e,t)=>{C1.init(e,t),Ae.init(e,t)});function et(){return bv(f_)}const h_=J("ZodUnknown",(e,t)=>{T1.init(e,t),Ae.init(e,t)});function $e(){return kv(h_)}const m_=J("ZodNever",(e,t)=>{$1.init(e,t),Ae.init(e,t)});function g_(e){return Sv(m_,e)}const v_=J("ZodArray",(e,t)=>{E1.init(e,t),Ae.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(mo(r,n)),e.nonempty=r=>e.check(mo(1,r)),e.max=(r,n)=>e.check($u(r,n)),e.length=(r,n)=>e.check(Eu(r,n)),e.unwrap=()=>e.element});function A(e,t){return Nv(v_,e,t)}const Lu=J("ZodObject",(e,t)=>{I1.init(e,t),Ae.init(e,t),Te(e,"shape",()=>t.shape),e.keyof=()=>_e(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:$e()}),e.loose=()=>e.clone({...e._zod.def,catchall:$e()}),e.strict=()=>e.clone({...e._zod.def,catchall:g_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>X2(e,r),e.merge=r=>eg(e,r),e.pick=r=>Y2(e,r),e.omit=r=>Q2(e,r),e.partial=(...r)=>tg(zu,e,r[0]),e.required=(...r)=>rg(Zu,e,r[0])});function T(e,t){const r={type:"object",get shape(){return lo(this,"shape",{...e}),this.shape},...re(t)};return new Lu(r)}function ze(e,t){return new Lu({type:"object",get shape(){return lo(this,"shape",{...e}),this.shape},catchall:$e(),...re(t)})}const ju=J("ZodUnion",(e,t)=>{pu.init(e,t),Ae.init(e,t),e.options=t.options});function ne(e,t){return new ju({type:"union",options:e,...re(t)})}const __=J("ZodDiscriminatedUnion",(e,t)=>{ju.init(e,t),x1.init(e,t)});function Ze(e,t,r){return new __({type:"union",options:t,discriminator:e,...re(r)})}const y_=J("ZodIntersection",(e,t)=>{R1.init(e,t),Ae.init(e,t)});function ba(e,t){return new y_({type:"intersection",left:e,right:t})}const w_=J("ZodRecord",(e,t)=>{P1.init(e,t),Ae.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ve(e,t,r){return new w_({type:"record",keyType:e,valueType:t,...re(r)})}const ka=J("ZodEnum",(e,t)=>{O1.init(e,t),Ae.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const a of n)if(r.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new ka({...t,checks:[],...re(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new ka({...t,checks:[],...re(o),entries:s})}});function _e(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ka({type:"enum",entries:r,...re(t)})}const b_=J("ZodLiteral",(e,t)=>{M1.init(e,t),Ae.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 L(e,t){return new b_({type:"literal",values:Array.isArray(e)?e:[e],...re(t)})}const k_=J("ZodTransform",(e,t)=>{N1.init(e,t),Ae.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Sn(s,r.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(Sn(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Uu(e){return new k_({type:"transform",transform:e})}const zu=J("ZodOptional",(e,t)=>{A1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K(e){return new zu({type:"optional",innerType:e})}const S_=J("ZodNullable",(e,t)=>{q1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Du(e){return new S_({type:"nullable",innerType:e})}const C_=J("ZodDefault",(e,t)=>{L1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function T_(e,t){return new C_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const $_=J("ZodPrefault",(e,t)=>{j1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function E_(e,t){return new $_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Zu=J("ZodNonOptional",(e,t)=>{U1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function I_(e,t){return new Zu({type:"nonoptional",innerType:e,...re(t)})}const x_=J("ZodCatch",(e,t)=>{z1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function R_(e,t){return new x_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const P_=J("ZodPipe",(e,t)=>{D1.init(e,t),Ae.init(e,t),e.in=t.in,e.out=t.out});function Sa(e,t){return new P_({type:"pipe",in:e,out:t})}const O_=J("ZodReadonly",(e,t)=>{Z1.init(e,t),Ae.init(e,t)});function M_(e){return new O_({type:"readonly",innerType:e})}const N_=J("ZodLazy",(e,t)=>{F1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Fu(e){return new N_({type:"lazy",getter:e})}const Ca=J("ZodCustom",(e,t)=>{V1.init(e,t),Ae.init(e,t)});function A_(e){const t=new it({check:"custom"});return t._zod.check=e,t}function Vu(e,t){return Av(Ca,e??(()=>!0),t)}function q_(e,t={}){return qv(Ca,e,t)}function L_(e){const t=A_(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Sn(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Sn(o))}},e(r.value,r)));return t}function _o(e,t={error:`Input not instance of ${e.name}`}){const r=new Ca({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...re(t)});return r._zod.bag.Class=e,r}function Hu(e,t){return Sa(Uu(e),t)}const Bu={custom:"custom"};function Ju(e){return vv(ya,e)}var Q;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Q||(Q={}));function Hr(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}async function j_(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(Gu());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(Gu())};r?.addEventListener("abort",i)})}function Gu(){return new DOMException("Delay was aborted","AbortError")}var yo=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function $n(e){return Object.fromEntries([...e.headers])}var En=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new io({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},In=En();function Ta(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Cr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var U_=["fetch failed","failed to fetch"];function Wu({error:e,url:t,requestBodyValues:r}){if(Cr(e))return e;if(e instanceof TypeError&&U_.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Pe({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function xn(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function z_(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function cr(e,...t){const r=new Headers(z_(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var Ku="3.0.18",D_=()=>globalThis.fetch,Yu=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=D_()})=>{try{const a=await s(e,{method:"GET",headers:cr(t,`ai-sdk/provider-utils/${Ku}`,xn()),signal:o}),i=$n(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw Cr(c)||Pe.isInstance(c)?c:new Pe({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Cr(l)||Pe.isInstance(l))?l:new Pe({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw Wu({error:a,url:e,requestBodyValues:{}})}};function Z_({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function F_({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ar({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ar({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ar({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ar({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function wo({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var V_=/"__proto__"\s*:/,H_=/"constructor"\s*:/;function Qu(e){const t=JSON.parse(e);return t===null||typeof t!="object"||V_.test(e)===!1&&H_.test(e)===!1?t:B_(t)}function B_(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){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 o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function $a(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Qu(e)}try{return Qu(e)}finally{Error.stackTraceLimit=t}}var bo=Symbol.for("vercel.ai.validator");function J_(e){return{[bo]:!0,validate:e}}function G_(e){return typeof e=="object"&&e!==null&&bo in e&&e[bo]===!0&&"validate"in e}function Br(e){let t;return()=>(t==null&&(t=e()),t)}function W_(e){return G_(e)?e:typeof e=="function"?e():K_(e)}function K_(e){return J_(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new At({value:t,cause:r.issues})}})}async function Ea({value:e,schema:t}){const r=await Tt({value:e,schema:t});if(!r.success)throw At.wrap({value:e,cause:r.error});return r.value}async function Tt({value:e,schema:t}){const r=W_(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:At.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:At.wrap({value:e,cause:n}),rawValue:e}}}async function Y_({text:e,schema:t}){try{const r=$a(e);return t==null?r:Ea({value:r,schema:t})}catch(r){throw sr.isInstance(r)||At.isInstance(r)?r:new sr({text:e,cause:r})}}async function Tr({text:e,schema:t}){try{const r=$a(e);return t==null?{success:!0,value:r,rawValue:r}:await Tt({value:r,schema:t})}catch(r){return{success:!1,error:sr.isInstance(r)?r:new sr({text:e,cause:r}),rawValue:void 0}}}function Xu(e){try{return $a(e),!0}catch{return!1}}function Q_({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Tr({text:r,schema:t}))}}))}async function ed({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Tt({value:t[e],schema:r});if(!n.success)throw new io({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var X_=()=>globalThis.fetch,Jr=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>ey({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),ey=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=X_()})=>{try{const i=await a(e,{method:"POST",headers:cr(t,`ai-sdk/provider-utils/${Ku}`,xn()),body:r.content,signal:s}),l=$n(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Cr(u)||Pe.isInstance(u)?u:new Pe({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Cr(c)||Pe.isInstance(c))?c:new Pe({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw Wu({error:i,url:e,requestBodyValues:r.values})}};function vC(e){return e}function td(e){return{...e,type:"dynamic"}}async function qt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var $r=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=$n(n);if(a.trim()==="")return{responseHeaders:i,value:new Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await Y_({text:a,schema:e});return{responseHeaders:i,value:new Pe({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},rd=e=>async({response:t})=>{const r=$n(t);if(t.body==null)throw new fc({});return{responseHeaders:r,value:Q_({stream:t.body,schema:e})}},Gr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Tr({text:o,schema:e}),a=$n(t);if(!s.success)throw new Pe({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},ty=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},ry=Symbol("Let zodToJsonSchema decide on which parser to use"),nd={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ny=e=>typeof e=="string"?{...nd,name:e}:{...nd,...e};function ht(){return{}}function oy(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==Q.ZodAny&&(s.items=Ee(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function sy(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function ay(){return{type:"boolean"}}function od(e,t){return Ee(e.type._def,t)}var iy=(e,t)=>Ee(e.innerType._def,t);function sd(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>sd(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ly(e)}}var ly=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function cy(e,t){return{...Ee(e.innerType._def,t),default:e.defaultValue()}}function uy(e,t){return t.effectStrategy==="input"?Ee(e.schema._def,t):ht()}function dy(e){return{type:"string",enum:Array.from(e.values)}}var py=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function fy(e,t){const r=[Ee(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ee(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(py(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}n.push(s)}}),n.length?{allOf:n}:void 0}function hy(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Ia=void 0,$t={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ia===void 0&&(Ia=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ia),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ad(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Et(r,"email",n.message,t);break;case"format:idn-email":Et(r,"idn-email",n.message,t);break;case"pattern:zod":tt(r,$t.email,n.message,t);break}break;case"url":Et(r,"uri",n.message,t);break;case"uuid":Et(r,"uuid",n.message,t);break;case"regex":tt(r,n.regex,n.message,t);break;case"cuid":tt(r,$t.cuid,n.message,t);break;case"cuid2":tt(r,$t.cuid2,n.message,t);break;case"startsWith":tt(r,RegExp(`^${xa(n.value,t)}`),n.message,t);break;case"endsWith":tt(r,RegExp(`${xa(n.value,t)}$`),n.message,t);break;case"datetime":Et(r,"date-time",n.message,t);break;case"date":Et(r,"date",n.message,t);break;case"time":Et(r,"time",n.message,t);break;case"duration":Et(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{tt(r,RegExp(xa(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Et(r,"ipv4",n.message,t),n.version!=="v4"&&Et(r,"ipv6",n.message,t);break}case"base64url":tt(r,$t.base64url,n.message,t);break;case"jwt":tt(r,$t.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&tt(r,$t.ipv4Cidr,n.message,t),n.version!=="v4"&&tt(r,$t.ipv6Cidr,n.message,t);break}case"emoji":tt(r,$t.emoji(),n.message,t);break;case"ulid":{tt(r,$t.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Et(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{tt(r,$t.base64,n.message,t);break}}break}case"nanoid":tt(r,$t.nanoid,n.message,t)}return r}function xa(e,t){return t.patternStrategy==="escape"?gy(e):e}var my=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function gy(e){let t="";for(let r=0;r<e.length;r++)my.has(e[r])||(t+="\\"),t+=e[r];return t}function Et(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function tt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:id(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=id(t,n)}function id(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
35
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
36
+ ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
37
+ `:`[${o[c]}\r
38
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}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 s}function ld(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Q.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=ad(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Q.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=od(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function vy(e,t){if(t.mapStrategy==="record")return ld(e,t);const r=Ee(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ht(),n=Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ht();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function _y(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function yy(){return{not:ht()}}function wy(){return{type:"null"}}var Ra={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function by(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ra&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Ra[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return ky(e,t)}var ky=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ee(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Sy(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ra[e.innerType._def.typeName],"null"]};const r=Ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Cy(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function Ty(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=Ey(i),c=Ee(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=$y(e,t);return s!==void 0&&(r.additionalProperties=s),r}function $y(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ee(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Ey(e){try{return e.isOptional()}catch{return!0}}var Iy=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ee(e.innerType._def,t);const n=Ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ht()},n]}:ht()},xy=(e,t)=>{if(t.pipeStrategy==="input")return Ee(e.in._def,t);if(t.pipeStrategy==="output")return Ee(e.out._def,t);const r=Ee(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ee(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Ry(e,t){return Ee(e.type._def,t)}function Py(e,t){const n={type:"array",uniqueItems:!0,items:Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function Oy(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ee(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ee(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ee(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function My(){return{not:ht()}}function Ny(){return ht()}var Ay=(e,t)=>Ee(e.innerType._def,t),qy=(e,t,r)=>{switch(t){case Q.ZodString:return ad(e,r);case Q.ZodNumber:return Cy(e);case Q.ZodObject:return Ty(e,r);case Q.ZodBigInt:return sy(e);case Q.ZodBoolean:return ay();case Q.ZodDate:return sd(e,r);case Q.ZodUndefined:return My();case Q.ZodNull:return wy();case Q.ZodArray:return oy(e,r);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return by(e,r);case Q.ZodIntersection:return fy(e,r);case Q.ZodTuple:return Oy(e,r);case Q.ZodRecord:return ld(e,r);case Q.ZodLiteral:return hy(e);case Q.ZodEnum:return dy(e);case Q.ZodNativeEnum:return _y(e);case Q.ZodNullable:return Sy(e,r);case Q.ZodOptional:return Iy(e,r);case Q.ZodMap:return vy(e,r);case Q.ZodSet:return Py(e,r);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return Ry(e,r);case Q.ZodNaN:case Q.ZodNever:return yy();case Q.ZodEffects:return uy(e,r);case Q.ZodAny:return ht();case Q.ZodUnknown:return Ny();case Q.ZodDefault:return cy(e,r);case Q.ZodBranded:return od(e,r);case Q.ZodReadonly:return Ay(e,r);case Q.ZodCatch:return iy(e,r);case Q.ZodPipeline:return xy(e,r);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(n=>{})()}};function Ee(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==ry)return l}if(o&&!r){const l=Ly(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=qy(e,e.typeName,t),i=typeof a=="function"?Ee(a(),t):a;if(i&&jy(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var Ly=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ty(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ht()):t.$refStrategy==="seen"?ht():void 0}},jy=(e,t,r)=>(e.description&&(r.description=e.description),r),Uy=e=>{const t=ny(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},zy=(e,t)=>{var r;const n=Uy(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,g])=>{var h;return{...c,[u]:(h=Ee(g._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:ht()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Ee(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:ht(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Dy=zy;function Zy(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rn(()=>Dy(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Fy(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rn(()=>xu(e,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async o=>{const s=await _a(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Vy(e){return"_zod"in e}function Er(e,t){return Vy(e)?Fy(e):Zy(e)}var Pa=Symbol.for("vercel.ai.schema");function Rn(e,{validate:t}={}){return{[Pa]:!0,_type:void 0,[bo]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Hy(e){return typeof e=="object"&&e!==null&&Pa in e&&e[Pa]===!0&&"jsonSchema"in e&&"validate"in e}function ko(e){return e==null?Rn({properties:{},additionalProperties:!1}):Hy(e)?e:typeof e=="function"?e():Er(e)}var{btoa:By,atob:Jy}=globalThis;function Oa(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=Jy(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function So(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return By(t)}function Gy(e){return e instanceof Uint8Array?So(e):e}function cd(e){return e?.replace(/\/$/,"")}function Wy(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*ud({execute:e,input:t,options:r}){const n=e(t,r);if(Wy(n)){let o;for await(const s of n)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await n}}function dd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ma,pd;function Ky(){if(pd)return Ma;pd=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,g)=>{for(var h in g)e(u,h,{get:g[h],enumerable:!0})},s=(u,g,h,d)=>{if(g&&typeof g=="object"||typeof g=="function")for(let p of r(g))!n.call(u,p)&&p!==h&&e(u,p,{get:()=>g[p],enumerable:!(d=t(g,p))||d.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Ma=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Ma}var Na,fd;function Yy(){if(fd)return Na;fd=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(g,h)=>{for(var d in h)e(g,d,{get:h[d],enumerable:!0})},s=(g,h,d,p)=>{if(h&&typeof h=="object"||typeof h=="function")for(let w of r(h))!n.call(g,w)&&w!==d&&e(g,w,{get:()=>h[w],enumerable:!(p=t(h,w))||p.enumerable});return g},a=g=>s(e({},"__esModule",{value:!0}),g),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Na=a(i);var l=Ky();async function c(){return""}function u(){return""}return Na}var hd=Yy(),Qy="vercel.ai.gateway.error",Aa=Symbol.for(Qy),md,gd,mt=class E2 extends(gd=Error,md=Aa,gd){constructor({message:t,statusCode:r=500,cause:n}){super(t),this[md]=!0,this.statusCode=r,this.cause=n}static isInstance(t){return E2.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Aa in t&&t[Aa]===!0}},vd="GatewayAuthenticationError",Xy=`vercel.ai.gateway.error.${vd}`,_d=Symbol.for(Xy),yd,wd,qa=class I2 extends(wd=mt,yd=_d,wd){constructor({message:t="Authentication failed",statusCode:r=401,cause:n}={}){super({message:t,statusCode:r,cause:n}),this[yd]=!0,this.name=vd,this.type="authentication_error"}static isInstance(t){return mt.hasMarker(t)&&_d in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
39
39
 
40
40
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
41
41
 
42
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?o=`AI Gateway authentication failed: Invalid OIDC token.
42
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?a=`AI Gateway authentication failed: Invalid OIDC token.
43
43
 
44
44
  Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
45
45
 
46
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:o=`AI Gateway authentication failed: No authentication provided.
46
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
47
47
 
48
48
  Option 1 - API key:
49
49
  Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
50
50
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
51
51
 
52
52
  Option 2 - OIDC token:
53
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Gm({message:o,statusCode:n,cause:s})}},ud="GatewayInvalidRequestError",Ib=`vercel.ai.gateway.error.${ud}`,cd=Symbol.for(Ib),dd,pd,Tb=class extends(pd=Ct,dd=cd,pd){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[dd]=!0,this.name=ud,this.type="invalid_request_error"}static isInstance(t){return Ct.hasMarker(t)&&cd in t}},hd="GatewayRateLimitError",kb=`vercel.ai.gateway.error.${hd}`,fd=Symbol.for(kb),md,vd,Pb=class extends(vd=Ct,md=fd,vd){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[md]=!0,this.name=hd,this.type="rate_limit_exceeded"}static isInstance(t){return Ct.hasMarker(t)&&fd in t}},gd="GatewayModelNotFoundError",Cb=`vercel.ai.gateway.error.${gd}`,yd=Symbol.for(Cb),Rb=Sn(()=>en(P({modelId:x()}))),_d,wd,bd=class extends(wd=Ct,_d=yd,wd){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:a}={}){super({message:t,statusCode:e,cause:a}),this[_d]=!0,this.name=gd,this.type="model_not_found",this.modelId=r}static isInstance(t){return Ct.hasMarker(t)&&yd in t}},xd="GatewayInternalServerError",Ob=`vercel.ai.gateway.error.${xd}`,Ed=Symbol.for(Ob),Sd,Id,Td=class extends(Id=Ct,Sd=Ed,Id){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Sd]=!0,this.name=xd,this.type="internal_server_error"}static isInstance(t){return Ct.hasMarker(t)&&Ed in t}},kd="GatewayResponseError",$b=`vercel.ai.gateway.error.${kd}`,Pd=Symbol.for($b),Cd,Rd,Ab=class extends(Rd=Ct,Cd=Pd,Rd){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:a,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[Cd]=!0,this.name=kd,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return Ct.hasMarker(t)&&Pd in t}};async function Od({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:a,authMethod:n}){const s=await $r({value:t,schema:Nb});if(!s.success)return new Ab({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:s.error,cause:a});const o=s.value,i=o.error.type,l=o.error.message;switch(i){case"authentication_error":return ri.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:e,cause:a});case"invalid_request_error":return new Tb({message:l,statusCode:e,cause:a});case"rate_limit_exceeded":return new Pb({message:l,statusCode:e,cause:a});case"model_not_found":{const u=await $r({value:o.error.param,schema:Rb});return new bd({message:l,statusCode:e,modelId:u.success?u.value.modelId:void 0,cause:a})}case"internal_server_error":return new Td({message:l,statusCode:e,cause:a});default:return new Td({message:l,statusCode:e,cause:a})}}var Nb=Sn(()=>en(P({error:P({message:x(),type:x().nullish(),param:Cr().nullish(),code:Ae([x(),U()]).nullish()})})));function tn(t,e){var r;return Ct.isInstance(t)?t:Ue.isInstance(t)?Od({response:Mb(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):Od({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function Mb(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var $d="ai-gateway-auth-method";async function oa(t){const e=await $r({value:t[$d],schema:Db});return e.success?e.value:void 0}var Db=Sn(()=>en(Ae([H("api-key"),H("oidc")]))),Ad=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Vc({url:`${this.config.baseURL}/config`,headers:await Ar(this.config.headers()),successfulResponseHandler:is(jb),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await tn(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await Vc({url:`${t.origin}/v1/credits`,headers:await Ar(this.config.headers()),successfulResponseHandler:is(Lb),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await tn(t)}}},jb=Sn(()=>en(P({models:Y(P({id:x(),name:x(),description:x().nullish(),pricing:P({input:x(),output:x(),input_cache_read:x().nullish(),input_cache_write:x().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:a})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:P({specificationVersion:H("v2"),provider:x(),modelId:x()}),modelType:vt(["language","embedding","image"]).nullish()}))}))),Lb=Sn(()=>en(P({balance:x(),total_used:x()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),zb=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await Ar(this.config.headers());try{const{responseHeaders:s,value:o,rawValue:i}=await Ho({url:this.getUrl(),headers:qo(n,t.headers,this.getModelConfigHeaders(this.modelId,!1),await Ar(this.config.o11yHeaders)),body:e,successfulResponseHandler:is(Mt()),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:l=>l}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...o,request:{body:e},response:{headers:s,body:i},warnings:r}}catch(s){throw await tn(s,await oa(n))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await Ar(this.config.headers());try{const{value:s,responseHeaders:o}=await Ho({url:this.getUrl(),headers:qo(n,t.headers,this.getModelConfigHeaders(this.modelId,!0),await Ar(this.config.o11yHeaders)),body:e,successfulResponseHandler:lw(Mt()),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:i=>i}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const u=i.value;if(u.type==="raw"&&!t.includeRawChunks)return;u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp=="string"&&(u.timestamp=new Date(u.timestamp)),l.enqueue(u)}else l.error(i.error)}})),request:{body:e},response:{headers:o}}}catch(s){throw await tn(s,await oa(n))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const a=r;if(a.data instanceof Uint8Array){const n=Uint8Array.from(a.data),s=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${s}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},Ub=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;const s=await Ar(this.config.headers());try{const{responseHeaders:o,value:i,rawValue:l}=await Ho({url:this.getUrl(),headers:qo(s,e??{},this.getModelConfigHeaders(),await Ar(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...a?{providerOptions:a}:{}},successfulResponseHandler:is(Fb),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:u=>u}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(n=i.usage)!=null?n:void 0,providerMetadata:i.providerMetadata,response:{headers:o,body:l}}}catch(o){throw await tn(o,await oa(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Fb=Sn(()=>en(P({embeddings:Y(Y(U())),usage:P({tokens:U()}).nullish(),providerMetadata:St(x(),St(x(),Cr())).optional()})));async function qb(){var t;return(t=rd.getContext().headers)==null?void 0:t["x-vercel-id"]}var Zb="2.0.0",Vb="0.0.1";function Bb(t={}){var e,r;let a=null,n=null;const s=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let o=0;const i=(r=rb(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const p=await Jb(t);if(p)return aa({Authorization:`Bearer ${p.token}`,"ai-gateway-protocol-version":Vb,[$d]:p.authMethod,...t.headers},`ai-sdk/gateway/${Zb}`);throw ri.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const p=ss({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),f=ss({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=ss({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const v=await qb();return{...p&&{"ai-o11y-deployment-id":p},...f&&{"ai-o11y-environment":f},...m&&{"ai-o11y-region":m},...v&&{"ai-o11y-request-id":v}}}},d=p=>new zb(p,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:u()}),h=async()=>{var p,f,m;const v=(m=(f=(p=t._internal)==null?void 0:p.currentDate)==null?void 0:f.call(p).getTime())!=null?m:Date.now();return(!a||v-o>s)&&(o=v,a=new Ad({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(w=>(n=w,w)).catch(async w=>{throw await tn(w,await oa(await l()))})),n?Promise.resolve(n):a},g=async()=>new Ad({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async p=>{throw await tn(p,await oa(await l()))}),c=function(p){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(p)};return c.getAvailableModels=h,c.getCredits=g,c.imageModel=p=>{throw new go({modelId:p,modelType:"imageModel"})},c.languageModel=d,c.textEmbeddingModel=p=>new Ub(p,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:u()}),c}var Hb=Bb();async function Jb(t){const e=ss({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await rd.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var Wb=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},rn="1.9.0",Nd=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Gb(t){var e=new Set([t]),r=new Set,a=t.match(Nd);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return function(l){return l===t};function s(i){return r.add(i),!1}function o(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var u=l.match(Nd);if(!u)return s(l);var d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return d.prerelease!=null||n.major!==d.major?s(l):n.major===0?n.minor===d.minor&&n.patch<=d.patch?o(l):s(l):n.minor<=d.minor?o(l):s(l)}}var Kb=Gb(rn),Qb=rn.split(".")[0],ia=Symbol.for("opentelemetry.js.api."+Qb),la=Wb;function ua(t,e,r,a){var n;a===void 0&&(a=!1);var s=la[ia]=(n=la[ia])!==null&&n!==void 0?n:{version:rn};if(!a&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(s.version!==rn){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+rn);return r.error(o.stack||o.message),!1}return s[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+rn+"."),!0}function nn(t){var e,r,a=(e=la[ia])===null||e===void 0?void 0:e.version;if(!(!a||!Kb(a)))return(r=la[ia])===null||r===void 0?void 0:r[t]}function ca(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+rn+".");var r=la[ia];r&&delete r[t]}var Yb=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},Xb=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},e1=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("verbose",this._namespace,e)},t}();function da(t,e,r){var a=nn("diag");if(a)return r.unshift(e),a[t].apply(a,Xb([],Yb(r),!1))}var Rt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Rt||(Rt={}));function t1(t,e){t<Rt.NONE?t=Rt.NONE:t>Rt.ALL&&(t=Rt.ALL),e=e||{};function r(a,n){var s=e[a];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:r("error",Rt.ERROR),warn:r("warn",Rt.WARN),info:r("info",Rt.INFO),debug:r("debug",Rt.DEBUG),verbose:r("verbose",Rt.VERBOSE)}}var r1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},n1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},a1="diag",nr=function(){function t(){function e(n){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var i=nn("diag");if(i)return i[n].apply(i,n1([],r1(s),!1))}}var r=this,a=function(n,s){var o,i,l;if(s===void 0&&(s={logLevel:Rt.INFO}),n===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof s=="number"&&(s={logLevel:s});var d=nn("diag"),h=t1((i=s.logLevel)!==null&&i!==void 0?i:Rt.INFO,n);if(d&&!s.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+g),h.warn("Current logger will overwrite one already registered from "+g)}return ua("diag",h,r,!0)};r.setLogger=a,r.disable=function(){ca(a1,r)},r.createComponentLogger=function(n){return new e1(n)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),s1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},o1=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],a=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&a>=t.length&&(t=void 0),{value:t&&t[a++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},i1=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=s1(e,2),a=r[0],n=r[1];return[a,n]})},t.prototype.setEntry=function(e,r){var a=new t(this._entries);return a._entries.set(e,r),a},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,a=[],n=0;n<arguments.length;n++)a[n]=arguments[n];var s=new t(this._entries);try{for(var o=o1(a),i=o.next();!i.done;i=o.next()){var l=i.value;s._entries.delete(l)}}catch(u){e={error:u}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return s},t.prototype.clear=function(){return new t},t}();nr.instance();function l1(t){return t===void 0&&(t={}),new i1(new Map(Object.entries(t)))}function Md(t){return Symbol.for(t)}var u1=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(a){return r._currentContext.get(a)},r.setValue=function(a,n){var s=new t(r._currentContext);return s._currentContext.set(a,n),s},r.deleteValue=function(a){var n=new t(r._currentContext);return n._currentContext.delete(a),n}}return t}(),c1=new u1,an=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(a[s]=n[s])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),d1=function(){function t(){}return t.prototype.createGauge=function(e,r){return b1},t.prototype.createHistogram=function(e,r){return x1},t.prototype.createCounter=function(e,r){return w1},t.prototype.createUpDownCounter=function(e,r){return E1},t.prototype.createObservableGauge=function(e,r){return I1},t.prototype.createObservableCounter=function(e,r){return S1},t.prototype.createObservableUpDownCounter=function(e,r){return T1},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),cs=function(){function t(){}return t}(),p1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(cs),h1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(cs),f1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(cs),m1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(cs),ni=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),v1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ni),g1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ni),y1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ni),_1=new d1,w1=new p1,b1=new f1,x1=new m1,E1=new h1,S1=new v1,I1=new g1,T1=new y1,k1={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},P1={set:function(t,e,r){t!=null&&(t[e]=r)}},C1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},R1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},O1=function(){function t(){}return t.prototype.active=function(){return c1},t.prototype.with=function(e,r,a){for(var n=[],s=3;s<arguments.length;s++)n[s-3]=arguments[s];return r.call.apply(r,R1([a],C1(n),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),$1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},A1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},ai="context",N1=new O1,ds=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return ua(ai,e,nr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,a){for(var n,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(n=this._getContextManager()).with.apply(n,A1([e,r,a],$1(s),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return nn(ai)||N1},t.prototype.disable=function(){this._getContextManager().disable(),ca(ai,nr.instance())},t}(),si;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(si||(si={}));var Dd="0000000000000000",jd="00000000000000000000000000000000",M1={traceId:jd,spanId:Dd,traceFlags:si.NONE},pa=function(){function t(e){e===void 0&&(e=M1),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}(),oi=Md("OpenTelemetry Context Key SPAN");function ii(t){return t.getValue(oi)||void 0}function D1(){return ii(ds.getInstance().active())}function li(t,e){return t.setValue(oi,e)}function j1(t){return t.deleteValue(oi)}function L1(t,e){return li(t,new pa(e))}function Ld(t){var e;return(e=ii(t))===null||e===void 0?void 0:e.spanContext()}var z1=/^([0-9a-f]{32})$/i,U1=/^[0-9a-f]{16}$/i;function F1(t){return z1.test(t)&&t!==jd}function q1(t){return U1.test(t)&&t!==Dd}function zd(t){return F1(t.traceId)&&q1(t.spanId)}function Z1(t){return new pa(t)}var ui=ds.getInstance(),Ud=function(){function t(){}return t.prototype.startSpan=function(e,r,a){a===void 0&&(a=ui.active());var n=!!(r!=null&&r.root);if(n)return new pa;var s=a&&Ld(a);return V1(s)&&zd(s)?new pa(s):new pa},t.prototype.startActiveSpan=function(e,r,a,n){var s,o,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=a):(s=r,o=a,i=n);var l=o??ui.active(),u=this.startSpan(e,s,l),d=li(l,u);return ui.with(d,i,void 0,u)}},t}();function V1(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var B1=new Ud,H1=function(){function t(e,r,a,n){this._provider=e,this.name=r,this.version=a,this.options=n}return t.prototype.startSpan=function(e,r,a){return this._getTracer().startSpan(e,r,a)},t.prototype.startActiveSpan=function(e,r,a,n){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):B1},t}(),J1=function(){function t(){}return t.prototype.getTracer=function(e,r,a){return new Ud},t}(),W1=new J1,Fd=function(){function t(){}return t.prototype.getTracer=function(e,r,a){var n;return(n=this.getDelegateTracer(e,r,a))!==null&&n!==void 0?n:new H1(this,e,r,a)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:W1},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(e,r,a)},t}(),ps;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(ps||(ps={})),ds.getInstance(),nr.instance();var G1=function(){function t(){}return t.prototype.getMeter=function(e,r,a){return _1},t}(),K1=new G1,ci="metrics",Q1=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return ua(ci,e,nr.instance())},t.prototype.getMeterProvider=function(){return nn(ci)||K1},t.prototype.getMeter=function(e,r,a){return this.getMeterProvider().getMeter(e,r,a)},t.prototype.disable=function(){ca(ci,nr.instance())},t}();Q1.getInstance();var Y1=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),di=Md("OpenTelemetry Baggage Key");function qd(t){return t.getValue(di)||void 0}function X1(){return qd(ds.getInstance().active())}function ex(t,e){return t.setValue(di,e)}function tx(t){return t.deleteValue(di)}var pi="propagation",rx=new Y1,nx=function(){function t(){this.createBaggage=l1,this.getBaggage=qd,this.getActiveBaggage=X1,this.setBaggage=ex,this.deleteBaggage=tx}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return ua(pi,e,nr.instance())},t.prototype.inject=function(e,r,a){return a===void 0&&(a=P1),this._getGlobalPropagator().inject(e,r,a)},t.prototype.extract=function(e,r,a){return a===void 0&&(a=k1),this._getGlobalPropagator().extract(e,r,a)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){ca(pi,nr.instance())},t.prototype._getGlobalPropagator=function(){return nn(pi)||rx},t}();nx.getInstance();var hi="trace",ax=function(){function t(){this._proxyTracerProvider=new Fd,this.wrapSpanContext=Z1,this.isSpanContextValid=zd,this.deleteSpan=j1,this.getSpan=ii,this.getActiveSpan=D1,this.getSpanContext=Ld,this.setSpan=li,this.setSpanContext=L1}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=ua(hi,this._proxyTracerProvider,nr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return nn(hi)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){ca(hi,nr.instance()),this._proxyTracerProvider=new Fd},t}(),sx=ax.getInstance(),ox=Object.defineProperty,ix=(t,e)=>{for(var r in e)ox(t,r,{get:e[r],enumerable:!0})},Zd="AI_NoOutputSpecifiedError",Vd=`vercel.ai.error.${Zd}`,lx=Symbol.for(Vd),Bd,Hd=class extends he{constructor({message:t="No output specified."}={}){super({name:Zd,message:t}),this[Bd]=!0}static isInstance(t){return he.hasMarker(t,Vd)}};Bd=lx;function ux(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let a=`${e} The tool "${r}" is not supported by this model`;return t.details&&(a+=` - ${t.details}`),a}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var cx="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Jd=!1,Wd=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}Jd||(Jd=!0,console.info(cx));for(const r of t)console.warn(ux(r))}},Gd="AI_InvalidArgumentError",Kd=`vercel.ai.error.${Gd}`,dx=Symbol.for(Kd),Qd,ar=class extends he{constructor({parameter:t,value:e,message:r}){super({name:Gd,message:`Invalid argument for parameter ${t}: ${r}`}),this[Qd]=!0,this.parameter=t,this.value=e}static isInstance(t){return he.hasMarker(t,Kd)}};Qd=dx;var Yd="AI_InvalidToolInputError",Xd=`vercel.ai.error.${Yd}`,px=Symbol.for(Xd),ep,tp=class extends he{constructor({toolInput:t,toolName:e,cause:r,message:a=`Invalid input for tool ${e}: ${yn(r)}`}){super({name:Yd,message:a,cause:r}),this[ep]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return he.hasMarker(t,Xd)}};ep=px;var rp="AI_NoObjectGeneratedError",np=`vercel.ai.error.${rp}`,hx=Symbol.for(np),ap,sp=class extends he{constructor({message:t="No object generated.",cause:e,text:r,response:a,usage:n,finishReason:s}){super({name:rp,message:t,cause:e}),this[ap]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=s}static isInstance(t){return he.hasMarker(t,np)}};ap=hx;var op="AI_NoOutputGeneratedError",ip=`vercel.ai.error.${op}`,fx=Symbol.for(ip),lp,mx=class extends he{constructor({message:t="No output generated.",cause:e}={}){super({name:op,message:t,cause:e}),this[lp]=!0}static isInstance(t){return he.hasMarker(t,ip)}};lp=fx;var up="AI_NoSuchToolError",cp=`vercel.ai.error.${up}`,vx=Symbol.for(cp),dp,fi=class extends he{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:up,message:r}),this[dp]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return he.hasMarker(t,cp)}};dp=vx;var pp="AI_ToolCallRepairError",hp=`vercel.ai.error.${pp}`,gx=Symbol.for(hp),fp,yx=class extends he{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${yn(t)}`}){super({name:pp,message:r,cause:t}),this[fp]=!0,this.originalError=e}static isInstance(t){return he.hasMarker(t,hp)}};fp=gx;var _x=class extends he{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},mp="AI_InvalidMessageRoleError",vp=`vercel.ai.error.${mp}`,wx=Symbol.for(vp),gp,bx=class extends he{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:mp,message:e}),this[gp]=!0,this.role=t}static isInstance(t){return he.hasMarker(t,vp)}};gp=wx;var yp="AI_DownloadError",_p=`vercel.ai.error.${yp}`,xx=Symbol.for(_p),wp,mi=class extends he{constructor({url:t,statusCode:e,statusText:r,cause:a,message:n=a==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${a}`}){super({name:yp,message:n,cause:a}),this[wp]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return he.hasMarker(t,_p)}};wp=xx;var bp="AI_RetryError",xp=`vercel.ai.error.${bp}`,Ex=Symbol.for(xp),Ep,Sp=class extends he{constructor({message:t,reason:e,errors:r}){super({name:bp,message:t}),this[Ep]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return he.hasMarker(t,xp)}};Ep=Ex;function hs(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new _x({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return Sx().languageModel(t)}function Sx(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:Hb}var Ix=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],Tx=t=>{const e=typeof t=="string"?Qo(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function kx(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?Tx(t):t}function Px({data:t,signatures:e}){const r=kx(t),a=typeof r=="string"?Qo(r.substring(0,Math.min(r.length,24))):r;for(const n of e)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((s,o)=>s===null||a[o]===s))return n.mediaType}var Ip="5.0.76",Cx=async({url:t})=>{var e;const r=t.toString();try{const a=await fetch(r,{headers:aa({},`ai-sdk/${Ip}`,Vo())});if(!a.ok)throw new mi({url:r,statusCode:a.status,statusText:a.statusText});return{data:new Uint8Array(await a.arrayBuffer()),mediaType:(e=a.headers.get("content-type"))!=null?e:void 0}}catch(a){throw mi.isInstance(a)?a:new mi({url:r,cause:a})}},Rx=(t=Cx)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function Ox(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Tp=Ae([x(),Wa(Uint8Array),Wa(ArrayBuffer),p0(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function kp(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=Ox(t.toString());if(e==null||r==null)throw new he({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function $x(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Yo(new Uint8Array(t)):Yo(t)}async function Pp({prompt:t,supportedUrls:e,download:r=Rx()}){const a=await Nx(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(n=>Ax({message:n,downloadedAssets:a}))]}function Ax({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(a=>Mx(a,e)).filter(a=>a.type!=="text"||a.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).map(a=>{const n=a.providerOptions;switch(a.type){case"file":{const{data:s,mediaType:o}=kp(a.data);return{type:"file",data:s,filename:a.filename,mediaType:o??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:n}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(a=>({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:a.providerOptions})),providerOptions:t.providerOptions};default:{const a=r;throw new bx({role:a})}}}async function Nx(t,e,r){const a=t.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var o;const i=(o=s.mediaType)!=null?o:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&W0({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),n=await e(a);return Object.fromEntries(n.map((s,o)=>s==null?null:[a[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function Mx(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let a;const n=t.type;switch(n){case"image":a=t.image;break;case"file":a=t.data;break;default:throw new Error(`Unsupported part type: ${n}`)}const{data:s,mediaType:o}=kp(a);let i=o??t.mediaType,l=s;if(l instanceof URL){const u=e[l.toString()];u&&(l=u.data,i??(i=u.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=Px({data:l,signatures:Ix}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function vi({maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,seed:o,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new ar({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new ar({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new ar({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new ar({parameter:"topP",value:r,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new ar({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new ar({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new ar({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new ar({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,stopSequences:i,seed:o}}function Dx(t){return t!=null&&Object.keys(t).length>0}function Cp({tools:t,toolChoice:e,activeTools:r}){return Dx(t)?{tools:(r!=null?Object.entries(t).filter(([n])=>r.includes(n)):Object.entries(t)).map(([n,s])=>{const o=s.type;switch(o){case void 0:case"dynamic":case"function":return{type:"function",name:n,description:s.description,inputSchema:us(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:n,id:s.id,args:s.args};default:{const i=o;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var ha=Pc(()=>Ae([U_(),x(),U(),nt(),St(x(),ha),Y(ha)])),sr=St(x(),St(x(),ha)),Rp=P({type:H("text"),text:x(),providerOptions:sr.optional()}),jx=P({type:H("image"),image:Ae([Tp,Wa(URL)]),mediaType:x().optional(),providerOptions:sr.optional()}),Op=P({type:H("file"),data:Ae([Tp,Wa(URL)]),filename:x().optional(),mediaType:x(),providerOptions:sr.optional()}),Lx=P({type:H("reasoning"),text:x(),providerOptions:sr.optional()}),zx=P({type:H("tool-call"),toolCallId:x(),toolName:x(),input:Cr(),providerOptions:sr.optional(),providerExecuted:nt().optional()}),Ux=wn("type",[P({type:H("text"),value:x()}),P({type:H("json"),value:ha}),P({type:H("error-text"),value:x()}),P({type:H("error-json"),value:ha}),P({type:H("content"),value:Y(Ae([P({type:H("text"),text:x()}),P({type:H("media"),data:x(),mediaType:x()})]))})]),$p=P({type:H("tool-result"),toolCallId:x(),toolName:x(),output:Ux,providerOptions:sr.optional()}),Fx=P({role:H("system"),content:x(),providerOptions:sr.optional()}),qx=P({role:H("user"),content:Ae([x(),Y(Ae([Rp,jx,Op]))]),providerOptions:sr.optional()}),Zx=P({role:H("assistant"),content:Ae([x(),Y(Ae([Rp,Op,Lx,zx,$p]))]),providerOptions:sr.optional()}),Vx=P({role:H("tool"),content:Y($p),providerOptions:sr.optional()}),Bx=Ae([Fx,qx,Zx,Vx]);async function Ap(t){if(t.prompt==null&&t.messages==null)throw new Br({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Br({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Br({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Br({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Br({prompt:t,message:"messages must not be empty"});const r=await $r({value:e,schema:Y(Bx)});if(!r.success)throw new Br({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Np(t){return ri.isInstance(t)||bd.isInstance(t)?new he({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function In({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function Mp({model:t,settings:e,telemetry:r,headers:a}){var n;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((s,[o,i])=>(s[`ai.settings.${o}`]=i,s),{}),...Object.entries((n=r==null?void 0:r.metadata)!=null?n:{}).reduce((s,[o,i])=>(s[`ai.telemetry.metadata.${o}`]=i,s),{}),...Object.entries(a??{}).reduce((s,[o,i])=>(i!==void 0&&(s[`ai.request.headers.${o}`]=i),s),{})}}var Hx={startSpan(){return fs},startActiveSpan(t,e,r,a){if(typeof e=="function")return e(fs);if(typeof r=="function")return r(fs);if(typeof a=="function")return a(fs)}},fs={spanContext(){return Jx},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Jx={traceId:"",spanId:"",traceFlags:0};function Dp({isEnabled:t=!1,tracer:e}={}){return t?e||sx.getTracer("ai"):Hx}function Tn({name:t,tracer:e,attributes:r,fn:a,endWhenDone:n=!0}){return e.startActiveSpan(t,{attributes:r},async s=>{try{const o=await a(s);return n&&s.end(),o}catch(o){try{gi(s,o)}finally{s.end()}throw o}})}function gi(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:ps.ERROR,message:e.message})):t.setStatus({code:ps.ERROR})}function jt({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[a,n])=>{if(n==null)return r;if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const s=n.input();return s==null?r:{...r,[a]:s}}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const s=n.output();return s==null?r:{...r,[a]:s}}return{...r,[a]:n}},{})}function jp(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?$x(r.data):r.data}:r)})))}function Lp(t,e){return{inputTokens:fa(t.inputTokens,e.inputTokens),outputTokens:fa(t.outputTokens,e.outputTokens),totalTokens:fa(t.totalTokens,e.totalTokens),reasoningTokens:fa(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:fa(t.cachedInputTokens,e.cachedInputTokens)}}function fa(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function yi(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function Wx({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let a;const n=r["retry-after-ms"];if(n){const o=parseFloat(n);Number.isNaN(o)||(a=o)}const s=r["retry-after"];if(s&&a===void 0){const o=parseFloat(s);Number.isNaN(o)?a=Date.parse(s)-Date.now():a=o*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<e)?a:e}var Gx=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>zp(n,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:a});async function zp(t,{maxRetries:e,delayInMs:r,backoffFactor:a,abortSignal:n},s=[]){try{return await t()}catch(o){if(Yr(o)||e===0)throw o;const i=Zo(o),l=[...s,o],u=l.length;if(u>e)throw new Sp({message:`Failed after ${u} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Ue.isInstance(o)&&o.isRetryable===!0&&u<=e)return await Z0(Wx({error:o,exponentialBackoffDelay:r}),{abortSignal:n}),zp(t,{maxRetries:e,delayInMs:a*r,backoffFactor:a,abortSignal:n},l);throw u===1?o:new Sp({message:`Failed after ${u} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Up({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new ar({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new ar({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:Gx({maxRetries:r,abortSignal:e})}}function Fp(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var qp=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=Yo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Qo(this.base64Data)),this.uint8ArrayData}},Kx=class extends qp{constructor(t){super(t),this.type="file"}};async function Zp({toolCall:t,tools:e,repairToolCall:r,system:a,messages:n}){try{if(e==null)throw new fi({toolName:t.toolName});try{return await Vp({toolCall:t,tools:e})}catch(s){if(r==null||!(fi.isInstance(s)||tp.isInstance(s)))throw s;let o=null;try{o=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return us(l).jsonSchema},system:a,messages:n,error:s})}catch(i){throw new yx({cause:i,originalError:s})}if(o==null)throw s;return await Vp({toolCall:o,tools:e})}}catch(s){const o=await Xr({text:t.input}),i=o.success?o.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function Vp({toolCall:t,tools:e}){const r=t.toolName,a=e[r];if(a==null)throw new fi({toolName:t.toolName,availableTools:Object.keys(e)});const n=us(a.inputSchema),s=t.input.trim()===""?await $r({value:{},schema:n}):await Xr({text:t.input,schema:n});if(s.success===!1)throw new tp({toolName:r,toolInput:t.input,cause:s.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var Bp=class{constructor({content:t,finishReason:e,usage:r,warnings:a,request:n,response:s,providerMetadata:o}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=a,this.request=n,this.response=s,this.providerMetadata=o}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function _i(t){return({steps:e})=>e.length===t}async function Hp({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function wi({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:yn(t)}:r==="json"?{type:"error-json",value:Jp(t)}:e!=null&&e.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:Jp(t)}}function Jp(t){return t===void 0?null:t}function bi({content:t,tools:e}){const r=[],a=t.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:wi({tool:e==null?void 0:e[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:wi({tool:e==null?void 0:e[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});a.length>0&&r.push({role:"assistant",content:a});const n=t.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:wi({tool:e==null?void 0:e[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return n.length>0&&r.push({role:"tool",content:n}),r}var Qx=na({prefix:"aitxt",size:24});async function Yx({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:u=_i(1),experimental_output:d,experimental_telemetry:h,providerOptions:g,experimental_activeTools:c,activeTools:p=c,experimental_prepareStep:f,prepareStep:m=f,experimental_repairToolCall:v,experimental_download:w,experimental_context:y,_internal:{generateId:_=Qx,currentDate:E=()=>new Date}={},onStepFinish:I,...S}){const R=hs(t),$=yi(u),{maxRetries:z,retry:L}=Up({maxRetries:o,abortSignal:i}),F=vi(S),M=aa(l??{},`ai/${Ip}`),D=Mp({model:R,telemetry:h,headers:M,settings:{...F,maxRetries:z}}),K=await Ap({system:a,prompt:n,messages:s}),oe=Dp(h);try{return await Tn({name:"ai.generateText",attributes:jt({telemetry:h,attributes:{...In({operationId:"ai.generateText",telemetry:h}),...D,"ai.model.provider":R.provider,"ai.model.id":R.modelId,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:n,messages:s})}}}),tracer:oe,fn:async ie=>{var C,re,B,de,ae,ke,_e;const Pe=vi(S);let xe,ve=[],Re=[];const pt=[],Ne=[];do{const be=[...K.messages,...pt],se=await(m==null?void 0:m({model:R,steps:Ne,stepNumber:Ne.length,messages:be})),Se=hs((C=se==null?void 0:se.model)!=null?C:R),Ie=await Pp({prompt:{system:(re=se==null?void 0:se.system)!=null?re:K.system,messages:(B=se==null?void 0:se.messages)!=null?B:be},supportedUrls:await Se.supportedUrls,download:w}),{toolChoice:ye,tools:Xe}=Cp({tools:e,toolChoice:(de=se==null?void 0:se.toolChoice)!=null?de:r,activeTools:(ae=se==null?void 0:se.activeTools)!=null?ae:p});xe=await L(()=>{var pe;return Tn({name:"ai.generateText.doGenerate",attributes:jt({telemetry:h,attributes:{...In({operationId:"ai.generateText.doGenerate",telemetry:h}),...D,"ai.model.provider":Se.provider,"ai.model.id":Se.modelId,"ai.prompt.messages":{input:()=>jp(Ie)},"ai.prompt.tools":{input:()=>Xe==null?void 0:Xe.map(Be=>JSON.stringify(Be))},"ai.prompt.toolChoice":{input:()=>ye!=null?JSON.stringify(ye):void 0},"gen_ai.system":Se.provider,"gen_ai.request.model":Se.modelId,"gen_ai.request.frequency_penalty":S.frequencyPenalty,"gen_ai.request.max_tokens":S.maxOutputTokens,"gen_ai.request.presence_penalty":S.presencePenalty,"gen_ai.request.stop_sequences":S.stopSequences,"gen_ai.request.temperature":(pe=S.temperature)!=null?pe:void 0,"gen_ai.request.top_k":S.topK,"gen_ai.request.top_p":S.topP}}),tracer:oe,fn:async Be=>{var hr,Ft,mt,Yt,xt,qt,Sr,pn;const Ge=await Se.doGenerate({...Pe,tools:Xe,toolChoice:ye,responseFormat:d==null?void 0:d.responseFormat,prompt:Ie,providerOptions:g,abortSignal:i,headers:M}),Zt={id:(Ft=(hr=Ge.response)==null?void 0:hr.id)!=null?Ft:_(),timestamp:(Yt=(mt=Ge.response)==null?void 0:mt.timestamp)!=null?Yt:E(),modelId:(qt=(xt=Ge.response)==null?void 0:xt.modelId)!=null?qt:Se.modelId,headers:(Sr=Ge.response)==null?void 0:Sr.headers,body:(pn=Ge.response)==null?void 0:pn.body};return Be.setAttributes(jt({telemetry:h,attributes:{"ai.response.finishReason":Ge.finishReason,"ai.response.text":{output:()=>Fp(Ge.content)},"ai.response.toolCalls":{output:()=>{const Xt=Wp(Ge.content);return Xt==null?void 0:JSON.stringify(Xt)}},"ai.response.id":Zt.id,"ai.response.model":Zt.modelId,"ai.response.timestamp":Zt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ge.providerMetadata),"ai.usage.promptTokens":Ge.usage.inputTokens,"ai.usage.completionTokens":Ge.usage.outputTokens,"gen_ai.response.finish_reasons":[Ge.finishReason],"gen_ai.response.id":Zt.id,"gen_ai.response.model":Zt.modelId,"gen_ai.usage.input_tokens":Ge.usage.inputTokens,"gen_ai.usage.output_tokens":Ge.usage.outputTokens}})),{...Ge,response:Zt}}})});const Le=await Promise.all(xe.content.filter(pe=>pe.type==="tool-call").map(pe=>Zp({toolCall:pe,tools:e,repairToolCall:v,system:a,messages:be})));for(const pe of Le){if(pe.invalid)continue;const Be=e[pe.toolName];(Be==null?void 0:Be.onInputAvailable)!=null&&await Be.onInputAvailable({input:pe.input,toolCallId:pe.toolCallId,messages:be,abortSignal:i,experimental_context:y})}const J=Le.filter(pe=>pe.invalid&&pe.dynamic);Re=[];for(const pe of J)Re.push({type:"tool-error",toolCallId:pe.toolCallId,toolName:pe.toolName,input:pe.input,error:Zo(pe.error),dynamic:!0});ve=Le.filter(pe=>!pe.providerExecuted),e!=null&&Re.push(...await Xx({toolCalls:ve.filter(pe=>!pe.invalid),tools:e,tracer:oe,telemetry:h,messages:be,abortSignal:i,experimental_context:y}));const Me=tE({content:xe.content,toolCalls:Le,toolOutputs:Re});pt.push(...bi({content:Me,tools:e}));const ze=new Bp({content:Me,finishReason:xe.finishReason,usage:xe.usage,warnings:xe.warnings,providerMetadata:xe.providerMetadata,request:(ke=xe.request)!=null?ke:{},response:{...xe.response,messages:structuredClone(pt)}});Wd((_e=xe.warnings)!=null?_e:[]),Ne.push(ze),await(I==null?void 0:I(ze))}while(ve.length>0&&Re.length===ve.length&&!await Hp({stopConditions:$,steps:Ne}));ie.setAttributes(jt({telemetry:h,attributes:{"ai.response.finishReason":xe.finishReason,"ai.response.text":{output:()=>Fp(xe.content)},"ai.response.toolCalls":{output:()=>{const be=Wp(xe.content);return be==null?void 0:JSON.stringify(be)}},"ai.response.providerMetadata":JSON.stringify(xe.providerMetadata),"ai.usage.promptTokens":xe.usage.inputTokens,"ai.usage.completionTokens":xe.usage.outputTokens}}));const we=Ne[Ne.length-1];let bt;return we.finishReason==="stop"&&(bt=await(d==null?void 0:d.parseOutput({text:we.text},{response:we.response,usage:we.usage,finishReason:we.finishReason}))),new eE({steps:Ne,resolvedOutput:bt})}})}catch(ie){throw Np(ie)}}async function Xx({toolCalls:t,tools:e,tracer:r,telemetry:a,messages:n,abortSignal:s,experimental_context:o}){return(await Promise.all(t.map(async({toolCallId:l,toolName:u,input:d})=>{const h=e[u];if((h==null?void 0:h.execute)!=null)return Tn({name:"ai.toolCall",attributes:jt({telemetry:a,attributes:{...In({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":u,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(d)}}}),tracer:r,fn:async g=>{try{const c=Yc({execute:h.execute.bind(h),input:d,options:{toolCallId:l,messages:n,abortSignal:s,experimental_context:o}});let p;for await(const f of c)f.type==="final"&&(p=f.output);try{g.setAttributes(jt({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(p)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:u,input:d,output:p,dynamic:h.type==="dynamic"}}catch(c){return gi(g,c),{type:"tool-error",toolCallId:l,toolName:u,input:d,error:c,dynamic:h.type==="dynamic"}}}})}))).filter(l=>l!=null)}var eE=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>Lp(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new Hd;return this.resolvedOutput}};function Wp(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function tE({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(a=>{switch(a.type){case"text":case"reasoning":case"source":return a;case"file":return{type:"file",file:new qp(a)};case"tool-call":return e.find(n=>n.toolCallId===a.toolCallId);case"tool-result":{const n=e.find(s=>s.toolCallId===a.toolCallId);if(n==null)throw new Error(`Tool call ${a.toolCallId} not found.`);return a.isError?{type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,error:a.result,providerExecuted:!0,dynamic:n.dynamic}:{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,output:a.result,providerExecuted:!0,dynamic:n.dynamic}}}}),...r]}function ms(t,e){const r=new Headers(t??{});for(const[a,n]of Object.entries(e))r.has(a)||r.set(a,n);return r}function rE({status:t,statusText:e,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:ms(r,{"content-type":"text/plain; charset=utf-8"})})}function Gp({response:t,status:e,statusText:r,headers:a,stream:n}){t.writeHead(e??200,r,a);const s=n.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;t.write(l)||await new Promise(d=>{t.once("drain",d)})}}catch(i){throw i}finally{t.end()}})()}function nE({response:t,status:e,statusText:r,headers:a,textStream:n}){Gp({response:t,status:e,statusText:r,headers:Object.fromEntries(ms(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}var Kp=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
53
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new I2({message:a,statusCode:o,cause:s})}},bd="GatewayInvalidRequestError",ew=`vercel.ai.gateway.error.${bd}`,kd=Symbol.for(ew),Sd,Cd,tw=class extends(Cd=mt,Sd=kd,Cd){constructor({message:e="Invalid request",statusCode:t=400,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Sd]=!0,this.name=bd,this.type="invalid_request_error"}static isInstance(e){return mt.hasMarker(e)&&kd in e}},Td="GatewayRateLimitError",rw=`vercel.ai.gateway.error.${Td}`,$d=Symbol.for(rw),Ed,Id,nw=class extends(Id=mt,Ed=$d,Id){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Ed]=!0,this.name=Td,this.type="rate_limit_exceeded"}static isInstance(e){return mt.hasMarker(e)&&$d in e}},xd="GatewayModelNotFoundError",ow=`vercel.ai.gateway.error.${xd}`,Rd=Symbol.for(ow),sw=Br(()=>Er(T({modelId:v()}))),Pd,Od,Md=class extends(Od=mt,Pd=Rd,Od){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Pd]=!0,this.name=xd,this.type="model_not_found",this.modelId=r}static isInstance(e){return mt.hasMarker(e)&&Rd in e}},Nd="GatewayInternalServerError",aw=`vercel.ai.gateway.error.${Nd}`,Ad=Symbol.for(aw),qd,Ld,jd=class extends(Ld=mt,qd=Ad,Ld){constructor({message:e="Internal server error",statusCode:t=500,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[qd]=!0,this.name=Nd,this.type="internal_server_error"}static isInstance(e){return mt.hasMarker(e)&&Ad in e}},Ud="GatewayResponseError",iw=`vercel.ai.gateway.error.${Ud}`,zd=Symbol.for(iw),Dd,Zd,lw=class extends(Zd=mt,Dd=zd,Zd){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[Dd]=!0,this.name=Ud,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return mt.hasMarker(e)&&zd in e}};async function Fd({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){const s=await Tt({value:e,schema:cw});if(!s.success)return new lw({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:s.error,cause:n});const a=s.value,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return qa.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n});case"invalid_request_error":return new tw({message:l,statusCode:t,cause:n});case"rate_limit_exceeded":return new nw({message:l,statusCode:t,cause:n});case"model_not_found":{const c=await Tt({value:a.error.param,schema:sw});return new Md({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new jd({message:l,statusCode:t,cause:n});default:return new jd({message:l,statusCode:t,cause:n})}}var cw=Br(()=>Er(T({error:T({message:v(),type:v().nullish(),param:$e().nullish(),code:ne([v(),q()]).nullish()})})));function ur(e,t){var r;return mt.isInstance(e)?e:Pe.isInstance(e)?Fd({response:uw(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):Fd({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function uw(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Vd="ai-gateway-auth-method";async function Wr(e){const t=await Tt({value:e[Vd],schema:dw});return t.success?t.value:void 0}var dw=Br(()=>Er(ne([L("api-key"),L("oidc")]))),Hd=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Yu({url:`${this.config.baseURL}/config`,headers:await qt(this.config.headers()),successfulResponseHandler:Gr(pw),failedResponseHandler:$r({errorSchema:et(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await ur(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Yu({url:`${e.origin}/v1/credits`,headers:await qt(this.config.headers()),successfulResponseHandler:Gr(fw),failedResponseHandler:$r({errorSchema:et(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await ur(e)}}},pw=Br(()=>Er(T({models:A(T({id:v(),name:v(),description:v().nullish(),pricing:T({input:v(),output:v(),input_cache_read:v().nullish(),input_cache_write:v().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:T({specificationVersion:L("v2"),provider:v(),modelId:v()}),modelType:_e(["language","embedding","image"]).nullish()}))}))),fw=Br(()=>Er(T({balance:v(),total_used:v()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),hw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await qt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Jr({url:this.getUrl(),headers:Hr(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Gr(et()),failedResponseHandler:$r({errorSchema:et(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:r}}catch(s){throw await ur(s,await Wr(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await qt(this.config.headers());try{const{value:s,responseHeaders:a}=await Jr({url:this.getUrl(),headers:Hr(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:rd(et()),failedResponseHandler:$r({errorSchema:et(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await ur(s,await Wr(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},mw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await qt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Jr({url:this.getUrl(),headers:Hr(s,t??{},this.getModelConfigHeaders(),await qt(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Gr(gw),failedResponseHandler:$r({errorSchema:et(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await ur(a,await Wr(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},gw=Br(()=>Er(T({embeddings:A(A(q())),usage:T({tokens:q()}).nullish(),providerMetadata:ve(v(),ve(v(),$e())).optional()}))),vw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l;const c=await qt(this.config.headers());try{const{responseHeaders:u,value:g,rawValue:h}=await Jr({url:this.getUrl(),headers:Hr(c,a??{},this.getModelConfigHeaders(),await qt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...s&&{providerOptions:s}},successfulResponseHandler:Gr(yw),failedResponseHandler:$r({errorSchema:et(),errorToMessage:d=>d}),...i&&{abortSignal:i},fetch:this.config.fetch});return{images:g.images,warnings:(l=g.warnings)!=null?l:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw ur(u,await Wr(c))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},_w=T({images:A($e()).optional()}).catchall($e()),yw=T({images:A(v()),warnings:A(T({type:L("other"),message:v()})).optional(),providerMetadata:ve(v(),_w).optional()});async function ww(){var e;return(e=hd.getContext().headers)==null?void 0:e["x-vercel-id"]}var bw="2.0.18",kw="0.0.1";function Sw(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(r=cd(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const p=await Tw(e);if(p)return cr({Authorization:`Bearer ${p.token}`,"ai-gateway-protocol-version":kw,[Vd]:p.authMethod,...e.headers},`ai-sdk/gateway/${bw}`);throw qa.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const p=wo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),w=wo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=wo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const y=await ww();return{...p&&{"ai-o11y-deployment-id":p},...w&&{"ai-o11y-environment":w},...m&&{"ai-o11y-region":m},...y&&{"ai-o11y-request-id":y}}}},u=p=>new hw(p,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),g=async()=>{var p,w,m;const y=(m=(w=(p=e._internal)==null?void 0:p.currentDate)==null?void 0:w.call(p).getTime())!=null?m:Date.now();return(!n||y-a>s)&&(a=y,n=new Hd({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(_=>(o=_,_)).catch(async _=>{throw await ur(_,await Wr(await l()))})),o?Promise.resolve(o):n},h=async()=>new Hd({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async p=>{throw await ur(p,await Wr(await l()))}),d=function(p){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(p)};return d.getAvailableModels=g,d.getCredits=h,d.imageModel=p=>new vw(p,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),d.languageModel=u,d.textEmbeddingModel=p=>new mw(p,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),d}var Cw=Sw();async function Tw(e){const t=wo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await hd.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var $w=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Ir="1.9.0",Bd=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ew(e){var t=new Set([e]),r=new Set,n=e.match(Bd);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return r.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(Bd);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):s(l):o.minor<=u.minor?a(l):s(l)}}var Iw=Ew(Ir),xw=Ir.split(".")[0],Pn=Symbol.for("opentelemetry.js.api."+xw),On=$w;function Mn(e,t,r,n){var o;n===void 0&&(n=!1);var s=On[Pn]=(o=On[Pn])!==null&&o!==void 0?o:{version:Ir};if(!n&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}if(s.version!==Ir){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Ir);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Ir+"."),!0}function xr(e){var t,r,n=(t=On[Pn])===null||t===void 0?void 0:t.version;if(!(!n||!Iw(n)))return(r=On[Pn])===null||r===void 0?void 0:r[e]}function Nn(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Ir+".");var r=On[Pn];r&&delete r[e]}var Rw=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},Pw=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},Ow=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("verbose",this._namespace,t)},e})();function An(e,t,r){var n=xr("diag");if(n)return r.unshift(t),n[e].apply(n,Pw([],Rw(r),!1))}var gt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(gt||(gt={}));function Mw(e,t){e<gt.NONE?e=gt.NONE:e>gt.ALL&&(e=gt.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",gt.ERROR),warn:r("warn",gt.WARN),info:r("info",gt.INFO),debug:r("debug",gt.DEBUG),verbose:r("verbose",gt.VERBOSE)}}var Nw=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},Aw=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},qw="diag",Lt=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=xr("diag");if(i)return i[o].apply(i,Aw([],Nw(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:gt.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=xr("diag"),g=Mw((i=s.logLevel)!==null&&i!==void 0?i:gt.INFO,o);if(u&&!s.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+h),g.warn("Current logger will overwrite one already registered from "+h)}return Mn("diag",g,r,!0)};r.setLogger=n,r.disable=function(){Nn(qw,r)},r.createComponentLogger=function(o){return new Ow(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),Lw=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},jw=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Uw=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=Lw(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var a=jw(n),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();Lt.instance();function zw(e){return e===void 0&&(e={}),new Uw(new Map(Object.entries(e)))}function Jd(e){return Symbol.for(e)}var Dw=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var s=new e(r._currentContext);return s._currentContext.set(n,o),s},r.deleteValue=function(n){var o=new e(r._currentContext);return o._currentContext.delete(n),o}}return e})(),Zw=new Dw,Rr=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),Fw=(function(){function e(){}return e.prototype.createGauge=function(t,r){return Xw},e.prototype.createHistogram=function(t,r){return e3},e.prototype.createCounter=function(t,r){return Qw},e.prototype.createUpDownCounter=function(t,r){return t3},e.prototype.createObservableGauge=function(t,r){return n3},e.prototype.createObservableCounter=function(t,r){return r3},e.prototype.createObservableUpDownCounter=function(t,r){return o3},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Co=(function(){function e(){}return e})(),Vw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Co),Hw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Co),Bw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Co),Jw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Co),La=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Gw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(La),Ww=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(La),Kw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(La),Yw=new Fw,Qw=new Vw,Xw=new Bw,e3=new Jw,t3=new Hw,r3=new Gw,n3=new Ww,o3=new Kw,s3={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},a3={set:function(e,t,r){e!=null&&(e[t]=r)}},i3=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},l3=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},c3=(function(){function e(){}return e.prototype.active=function(){return Zw},e.prototype.with=function(t,r,n){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return r.call.apply(r,l3([n],i3(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),u3=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},d3=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},ja="context",p3=new c3,To=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Mn(ja,t,Lt.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,d3([t,r,n],u3(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return xr(ja)||p3},e.prototype.disable=function(){this._getContextManager().disable(),Nn(ja,Lt.instance())},e})(),Ua;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ua||(Ua={}));var Gd="0000000000000000",Wd="00000000000000000000000000000000",f3={traceId:Wd,spanId:Gd,traceFlags:Ua.NONE},qn=(function(){function e(t){t===void 0&&(t=f3),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e})(),za=Jd("OpenTelemetry Context Key SPAN");function Da(e){return e.getValue(za)||void 0}function h3(){return Da(To.getInstance().active())}function Za(e,t){return e.setValue(za,t)}function m3(e){return e.deleteValue(za)}function g3(e,t){return Za(e,new qn(t))}function Kd(e){var t;return(t=Da(e))===null||t===void 0?void 0:t.spanContext()}var v3=/^([0-9a-f]{32})$/i,_3=/^[0-9a-f]{16}$/i;function y3(e){return v3.test(e)&&e!==Wd}function w3(e){return _3.test(e)&&e!==Gd}function Yd(e){return y3(e.traceId)&&w3(e.spanId)}function b3(e){return new qn(e)}var Fa=To.getInstance(),Qd=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Fa.active());var o=!!r?.root;if(o)return new qn;var s=n&&Kd(n);return k3(s)&&Yd(s)?new qn(s):new qn},e.prototype.startActiveSpan=function(t,r,n,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=n):(s=r,a=n,i=o);var l=a??Fa.active(),c=this.startSpan(t,s,l),u=Za(l,c);return Fa.with(u,i,void 0,c)}},e})();function k3(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var S3=new Qd,C3=(function(){function e(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):S3},e})(),T3=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Qd},e})(),$3=new T3,Xd=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new C3(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:$3},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)},e})(),$o;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})($o||($o={})),To.getInstance(),Lt.instance();var E3=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return Yw},e})(),I3=new E3,Va="metrics",x3=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Mn(Va,t,Lt.instance())},e.prototype.getMeterProvider=function(){return xr(Va)||I3},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Nn(Va,Lt.instance())},e})();x3.getInstance();var R3=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Ha=Jd("OpenTelemetry Baggage Key");function ep(e){return e.getValue(Ha)||void 0}function P3(){return ep(To.getInstance().active())}function O3(e,t){return e.setValue(Ha,t)}function M3(e){return e.deleteValue(Ha)}var Ba="propagation",N3=new R3,A3=(function(){function e(){this.createBaggage=zw,this.getBaggage=ep,this.getActiveBaggage=P3,this.setBaggage=O3,this.deleteBaggage=M3}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Mn(Ba,t,Lt.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=a3),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=s3),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Nn(Ba,Lt.instance())},e.prototype._getGlobalPropagator=function(){return xr(Ba)||N3},e})();A3.getInstance();var Ja="trace",q3=(function(){function e(){this._proxyTracerProvider=new Xd,this.wrapSpanContext=b3,this.isSpanContextValid=Yd,this.deleteSpan=m3,this.getSpan=Da,this.getActiveSpan=h3,this.getSpanContext=Kd,this.setSpan=Za,this.setSpanContext=g3}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Mn(Ja,this._proxyTracerProvider,Lt.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return xr(Ja)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Nn(Ja,Lt.instance()),this._proxyTracerProvider=new Xd},e})(),L3=q3.getInstance(),j3=Object.defineProperty,U3=(e,t)=>{for(var r in t)j3(e,r,{get:t[r],enumerable:!0})},tp="AI_NoOutputSpecifiedError",rp=`vercel.ai.error.${tp}`,z3=Symbol.for(rp),np,op=class extends ue{constructor({message:e="No output specified."}={}){super({name:tp,message:e}),this[np]=!0}static isInstance(e){return ue.hasMarker(e,rp)}};np=z3;function D3(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let r=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"unsupported-tool":{const r="name"in e.tool?e.tool.name:"unknown tool";let n=`${t} The tool "${r}" is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var Z3="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",sp=!1,ap=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}sp||(sp=!0,console.info(Z3));for(const r of e)console.warn(D3(r))}},ip="AI_InvalidArgumentError",lp=`vercel.ai.error.${ip}`,F3=Symbol.for(lp),cp,jt=class extends ue{constructor({parameter:e,value:t,message:r}){super({name:ip,message:`Invalid argument for parameter ${e}: ${r}`}),this[cp]=!0,this.parameter=e,this.value=t}static isInstance(e){return ue.hasMarker(e,lp)}};cp=F3;var up="AI_InvalidToolInputError",dp=`vercel.ai.error.${up}`,V3=Symbol.for(dp),pp,fp=class extends ue{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Fr(r)}`}){super({name:up,message:n,cause:r}),this[pp]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ue.hasMarker(e,dp)}};pp=V3;var hp="AI_NoObjectGeneratedError",mp=`vercel.ai.error.${hp}`,H3=Symbol.for(mp),gp,vp=class extends ue{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:hp,message:e,cause:t}),this[gp]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ue.hasMarker(e,mp)}};gp=H3;var _p="AI_NoOutputGeneratedError",yp=`vercel.ai.error.${_p}`,B3=Symbol.for(yp),wp,J3=class extends ue{constructor({message:e="No output generated.",cause:t}={}){super({name:_p,message:e,cause:t}),this[wp]=!0}static isInstance(e){return ue.hasMarker(e,yp)}};wp=B3;var bp="AI_NoSuchToolError",kp=`vercel.ai.error.${bp}`,G3=Symbol.for(kp),Sp,Ga=class extends ue{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:bp,message:r}),this[Sp]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ue.hasMarker(e,kp)}};Sp=G3;var Cp="AI_ToolCallRepairError",Tp=`vercel.ai.error.${Cp}`,W3=Symbol.for(Tp),$p,K3=class extends ue{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Fr(e)}`}){super({name:Cp,message:r,cause:e}),this[$p]=!0,this.originalError=t}static isInstance(e){return ue.hasMarker(e,Tp)}};$p=W3;var Y3=class extends ue{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Ep="AI_InvalidMessageRoleError",Ip=`vercel.ai.error.${Ep}`,Q3=Symbol.for(Ip),xp,X3=class extends ue{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ep,message:t}),this[xp]=!0,this.role=e}static isInstance(e){return ue.hasMarker(e,Ip)}};xp=Q3;var Rp="AI_DownloadError",Pp=`vercel.ai.error.${Rp}`,eb=Symbol.for(Pp),Op,Wa=class extends ue{constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:Rp,message:o,cause:n}),this[Op]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ue.hasMarker(e,Pp)}};Op=eb;var Mp="AI_RetryError",Np=`vercel.ai.error.${Mp}`,tb=Symbol.for(Np),Ap,qp=class extends ue{constructor({message:e,reason:t,errors:r}){super({name:Mp,message:e}),this[Ap]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ue.hasMarker(e,Np)}};Ap=tb;function Eo(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new Y3({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return rb().languageModel(e)}function rb(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Cw}var nb=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],ob=e=>{const t=typeof e=="string"?Oa(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function sb(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?ob(e):e}function ab({data:e,signatures:t}){const r=sb(e),n=typeof r=="string"?Oa(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||n[a]===s))return o.mediaType}var Lp="5.0.106",ib=async({url:e})=>{var t;const r=e.toString();try{const n=await fetch(r,{headers:cr({},`ai-sdk/${Lp}`,xn())});if(!n.ok)throw new Wa({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(t=n.headers.get("content-type"))!=null?t:void 0}}catch(n){throw Wa.isInstance(n)?n:new Wa({url:r,cause:n})}},lb=(e=ib)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function cb(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var jp=ne([v(),_o(Uint8Array),_o(ArrayBuffer),Vu(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function Up(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:r}=cb(e.toString());if(t==null||r==null)throw new ue({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function ub(e){return typeof e=="string"?e:e instanceof ArrayBuffer?So(new Uint8Array(e)):So(e)}async function zp({prompt:e,supportedUrls:t,download:r=lb()}){const n=await pb(e.messages,r,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>db({message:o,downloadedAssets:n}))]}function db({message:e,downloadedAssets:t}){const r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(n=>fb(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=Up(n.data);return{type:"file",data:s,filename:n.filename,mediaType:a??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:e.providerOptions};default:{const n=r;throw new X3({role:n})}}}async function pb(e,t,r){const n=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const i=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&Z_({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,a)=>s==null?null:[n[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function fb(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=Up(n);let i=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=ab({data:l,signatures:nb}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function Ka({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new jt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new jt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new jt({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new jt({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new jt({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new jt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new jt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new jt({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function hb(e){return e!=null&&Object.keys(e).length>0}function Dp({tools:e,toolChoice:t,activeTools:r}){return hb(e)?{tools:(r!=null?Object.entries(e).filter(([o])=>r.includes(o)):Object.entries(e)).map(([o,s])=>{const a=s.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:ko(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var Ln=Fu(()=>ne([wa(),v(),q(),ce(),ve(v(),Ln),A(Ln)])),Ut=ve(v(),ve(v(),Ln)),Zp=T({type:L("text"),text:v(),providerOptions:Ut.optional()}),mb=T({type:L("image"),image:ne([jp,_o(URL)]),mediaType:v().optional(),providerOptions:Ut.optional()}),Fp=T({type:L("file"),data:ne([jp,_o(URL)]),filename:v().optional(),mediaType:v(),providerOptions:Ut.optional()}),gb=T({type:L("reasoning"),text:v(),providerOptions:Ut.optional()}),vb=T({type:L("tool-call"),toolCallId:v(),toolName:v(),input:$e(),providerOptions:Ut.optional(),providerExecuted:ce().optional()}),_b=Ze("type",[T({type:L("text"),value:v()}),T({type:L("json"),value:Ln}),T({type:L("error-text"),value:v()}),T({type:L("error-json"),value:Ln}),T({type:L("content"),value:A(ne([T({type:L("text"),text:v()}),T({type:L("media"),data:v(),mediaType:v()})]))})]),Vp=T({type:L("tool-result"),toolCallId:v(),toolName:v(),output:_b,providerOptions:Ut.optional()}),yb=T({role:L("system"),content:v(),providerOptions:Ut.optional()}),wb=T({role:L("user"),content:ne([v(),A(ne([Zp,mb,Fp]))]),providerOptions:Ut.optional()}),bb=T({role:L("assistant"),content:ne([v(),A(ne([Zp,Fp,gb,vb,Vp]))]),providerOptions:Ut.optional()}),kb=T({role:L("tool"),content:A(Vp),providerOptions:Ut.optional()}),Sb=ne([yb,wb,bb,kb]);async function Hp(e){if(e.prompt==null&&e.messages==null)throw new br({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new br({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new br({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new br({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new br({prompt:e,message:"messages must not be empty"});const r=await Tt({value:t,schema:A(Sb)});if(!r.success)throw new br({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:t,system:e.system}}function Bp(e){return qa.isInstance(e)||Md.isInstance(e)?new ue({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function Kr({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function Jp({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>(s[`ai.settings.${a}`]=i,s),{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(n??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var Cb={startSpan(){return Io},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Io);if(typeof r=="function")return r(Io);if(typeof n=="function")return n(Io)}},Io={spanContext(){return Tb},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Tb={traceId:"",spanId:"",traceFlags:0};function Gp({isEnabled:e=!1,tracer:t}={}){return e?t||L3.getTracer("ai"):Cb}function Yr({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:r},async s=>{try{const a=await n(s);return o&&s.end(),a}catch(a){try{Ya(s,a)}finally{s.end()}throw a}})}function Ya(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:$o.ERROR,message:t.message})):e.setStatus({code:$o.ERROR})}function wt({telemetry:e,attributes:t}){return e?.isEnabled!==!0?{}:Object.entries(t).reduce((r,[n,o])=>{if(o==null)return r;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)return r;const s=o.input();return s==null?r:{...r,[n]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)return r;const s=o.output();return s==null?r:{...r,[n]:s}}return{...r,[n]:o}},{})}function Wp(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?ub(r.data):r.data}:r)})))}function Kp(e,t){return{inputTokens:jn(e.inputTokens,t.inputTokens),outputTokens:jn(e.outputTokens,t.outputTokens),totalTokens:jn(e.totalTokens,t.totalTokens),reasoningTokens:jn(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:jn(e.cachedInputTokens,t.cachedInputTokens)}}function jn(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Qa(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function $b({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(n=a)}const s=r["retry-after"];if(s&&n===void 0){const a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var Eb=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>Yp(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Yp(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(Cr(a)||t===0)throw a;const i=Ta(a),l=[...s,a],c=l.length;if(c>t)throw new qp({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Pe.isInstance(a)&&a.isRetryable===!0&&c<=t)return await j_($b({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),Yp(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new qp({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Qp({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new jt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new jt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:Eb({maxRetries:r,abortSignal:t})}}function Xp(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var e0=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=So(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Oa(this.base64Data)),this.uint8ArrayData}},Ib=class extends e0{constructor(e){super(e),this.type="file"}};async function t0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){try{if(t==null)throw new Ga({toolName:e.toolName});try{return await r0({toolCall:e,tools:t})}catch(s){if(r==null||!(Ga.isInstance(s)||fp.isInstance(s)))throw s;let a=null;try{a=await r({toolCall:e,tools:t,inputSchema:({toolName:i})=>{const{inputSchema:l}=t[i];return ko(l).jsonSchema},system:n,messages:o,error:s})}catch(i){throw new K3({cause:i,originalError:s})}if(a==null)throw s;return await r0({toolCall:a,tools:t})}}catch(s){const a=await Tr({text:e.input}),i=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i,dynamic:!0,invalid:!0,error:s,providerMetadata:e.providerMetadata}}}async function r0({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null)throw new Ga({toolName:e.toolName,availableTools:Object.keys(t)});const o=ko(n.inputSchema),s=e.input.trim()===""?await Tt({value:{},schema:o}):await Tr({text:e.input,schema:o});if(s.success===!1)throw new fp({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var n0=class{constructor({content:e,finishReason:t,usage:r,warnings:n,request:o,response:s,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=r,this.warnings=n,this.request=o,this.response=s,this.providerMetadata=a}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function Xa(e){return({steps:t})=>t.length===e}async function o0({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}function ei({output:e,tool:t,errorMode:r}){return r==="text"?{type:"error-text",value:Fr(e)}:r==="json"?{type:"error-json",value:s0(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:s0(e)}}function s0(e){return e===void 0?null:e}function ti({content:e,tools:t}){const r=[],n=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:ei({tool:t?.[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:ei({tool:t?.[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:ei({tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"}),...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}}));return o.length>0&&r.push({role:"tool",content:o}),r}var xb=En({prefix:"aitxt",size:24});async function a0({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Xa(1),experimental_output:u,experimental_telemetry:g,providerOptions:h,experimental_activeTools:d,activeTools:p=d,experimental_prepareStep:w,prepareStep:m=w,experimental_repairToolCall:y,experimental_download:_,experimental_context:f,_internal:{generateId:b=xb,currentDate:k=()=>new Date}={},onStepFinish:S,...C}){const I=Eo(e),x=Qa(c),{maxRetries:M,retry:P}=Qp({maxRetries:a,abortSignal:i}),U=Ka(C),z=cr(l??{},`ai/${Lp}`),F=Jp({model:I,telemetry:g,headers:z,settings:{...U,maxRetries:M}}),te=await Hp({system:n,prompt:o,messages:s}),ie=Gp(g);try{return await Yr({name:"ai.generateText",attributes:wt({telemetry:g,attributes:{...Kr({operationId:"ai.generateText",telemetry:g}),...F,"ai.model.provider":I.provider,"ai.model.id":I.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:ie,fn:async se=>{var ee,pe,V,O,Z,j,E;const R=Ka(C);let $,H=[],G=[];const fe=[],ae=[];do{const B=[...te.messages,...fe],W=await m?.({model:I,steps:ae,stepNumber:ae.length,messages:B}),Y=Eo((ee=W?.model)!=null?ee:I),oe=await zp({prompt:{system:(pe=W?.system)!=null?pe:te.system,messages:(V=W?.messages)!=null?V:B},supportedUrls:await Y.supportedUrls,download:_}),{toolChoice:le,tools:Ne}=Dp({tools:t,toolChoice:(O=W?.toolChoice)!=null?O:r,activeTools:(Z=W?.activeTools)!=null?Z:p});$=await P(()=>{var be;return Yr({name:"ai.generateText.doGenerate",attributes:wt({telemetry:g,attributes:{...Kr({operationId:"ai.generateText.doGenerate",telemetry:g}),...F,"ai.model.provider":Y.provider,"ai.model.id":Y.modelId,"ai.prompt.messages":{input:()=>Wp(oe)},"ai.prompt.tools":{input:()=>Ne?.map(pt=>JSON.stringify(pt))},"ai.prompt.toolChoice":{input:()=>le!=null?JSON.stringify(le):void 0},"gen_ai.system":Y.provider,"gen_ai.request.model":Y.modelId,"gen_ai.request.frequency_penalty":C.frequencyPenalty,"gen_ai.request.max_tokens":C.maxOutputTokens,"gen_ai.request.presence_penalty":C.presencePenalty,"gen_ai.request.stop_sequences":C.stopSequences,"gen_ai.request.temperature":(be=C.temperature)!=null?be:void 0,"gen_ai.request.top_k":C.topK,"gen_ai.request.top_p":C.topP}}),tracer:ie,fn:async pt=>{var tr,ft,We,St,yr,wr,gn,aa;const He=await Y.doGenerate({...R,tools:Ne,toolChoice:le,responseFormat:u?.responseFormat,prompt:oe,providerOptions:h,abortSignal:i,headers:z}),rr={id:(ft=(tr=He.response)==null?void 0:tr.id)!=null?ft:b(),timestamp:(St=(We=He.response)==null?void 0:We.timestamp)!=null?St:k(),modelId:(wr=(yr=He.response)==null?void 0:yr.modelId)!=null?wr:Y.modelId,headers:(gn=He.response)==null?void 0:gn.headers,body:(aa=He.response)==null?void 0:aa.body};return pt.setAttributes(wt({telemetry:g,attributes:{"ai.response.finishReason":He.finishReason,"ai.response.text":{output:()=>Xp(He.content)},"ai.response.toolCalls":{output:()=>{const nr=i0(He.content);return nr==null?void 0:JSON.stringify(nr)}},"ai.response.id":rr.id,"ai.response.model":rr.modelId,"ai.response.timestamp":rr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(He.providerMetadata),"ai.usage.promptTokens":He.usage.inputTokens,"ai.usage.completionTokens":He.usage.outputTokens,"gen_ai.response.finish_reasons":[He.finishReason],"gen_ai.response.id":rr.id,"gen_ai.response.model":rr.modelId,"gen_ai.usage.input_tokens":He.usage.inputTokens,"gen_ai.usage.output_tokens":He.usage.outputTokens}})),{...He,response:rr}}})});const qe=await Promise.all($.content.filter(be=>be.type==="tool-call").map(be=>t0({toolCall:be,tools:t,repairToolCall:y,system:n,messages:B})));for(const be of qe){if(be.invalid)continue;const pt=t[be.toolName];pt?.onInputAvailable!=null&&await pt.onInputAvailable({input:be.input,toolCallId:be.toolCallId,messages:B,abortSignal:i,experimental_context:f})}const X=qe.filter(be=>be.invalid&&be.dynamic);G=[];for(const be of X)G.push({type:"tool-error",toolCallId:be.toolCallId,toolName:be.toolName,input:be.input,error:Ta(be.error),dynamic:!0});H=qe.filter(be=>!be.providerExecuted),t!=null&&G.push(...await Rb({toolCalls:H.filter(be=>!be.invalid),tools:t,tracer:ie,telemetry:g,messages:B,abortSignal:i,experimental_context:f}));const me=Ob({content:$.content,toolCalls:qe,toolOutputs:G});fe.push(...ti({content:me,tools:t}));const st=new n0({content:me,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(j=$.request)!=null?j:{},response:{...$.response,messages:structuredClone(fe)}});ap((E=$.warnings)!=null?E:[]),ae.push(st),await S?.(st)}while(H.length>0&&G.length===H.length&&!await o0({stopConditions:x,steps:ae}));se.setAttributes(wt({telemetry:g,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>Xp($.content)},"ai.response.toolCalls":{output:()=>{const B=i0($.content);return B==null?void 0:JSON.stringify(B)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const N=ae[ae.length-1];let D;return N.finishReason==="stop"&&(D=await u?.parseOutput({text:N.text},{response:N.response,usage:N.usage,finishReason:N.finishReason})),new Pb({steps:ae,resolvedOutput:D})}})}catch(se){throw Bp(se)}}async function Rb({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:c,input:u})=>{const g=t[c];if(g?.execute!=null)return Yr({name:"ai.toolCall",attributes:wt({telemetry:n,attributes:{...Kr({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async h=>{try{const d=ud({execute:g.execute.bind(g),input:u,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:a}});let p;for await(const w of d)w.type==="final"&&(p=w.output);try{h.setAttributes(wt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(p)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:p,dynamic:g.type==="dynamic"}}catch(d){return Ya(h,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:g.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Pb=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((e,t)=>Kp(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new op;return this.resolvedOutput}};function i0(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function Ob({content:e,toolCalls:t,toolOutputs:r}){return[...e.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new e0(n)};case"tool-call":return t.find(o=>o.toolCallId===n.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===n.toolCallId);if(o==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:o.input,error:n.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:o.input,output:n.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...r]}function xo(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function Mb({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:xo(r,{"content-type":"text/plain; charset=utf-8"})})}function l0({response:e,status:t,statusText:r,headers:n,stream:o}){e.writeHead(t??200,r,n);const s=o.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;e.write(l)||await new Promise(u=>{e.once("drain",u)})}}catch(i){throw i}finally{e.end()}})()}function Nb({response:e,status:t,statusText:r,headers:n,textStream:o}){l0({response:e,status:t,statusText:r,headers:Object.fromEntries(xo(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var c0=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
54
54
 
55
- `)},flush(t){t.enqueue(`data: [DONE]
55
+ `)},flush(e){e.enqueue(`data: [DONE]
56
56
 
57
- `)}})}},Qp={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function aE({status:t,statusText:e,headers:r,stream:a,consumeSseStream:n}){let s=a.pipeThrough(new Kp);if(n){const[o,i]=s.tee();s=o,n({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:ms(r,Qp)})}function sE({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return(r==null?void 0:r.role)==="assistant"?r.id:typeof e=="function"?e():e}function oE(t){return t.type.startsWith("data-")}function Yp(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)){const n=e[a];if(n===void 0)continue;const s=a in t?t[a]:void 0,o=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&i?r[a]=Yp(s,n):r[a]=n}return r}function iE(t){const e=["ROOT"];let r=-1,a=null;function n(l,u,d){switch(l){case'"':{r=u,e.pop(),e.push(d),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=u,a=u,e.pop(),e.push(d),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=u,e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"{":{r=u,e.pop(),e.push(d),e.push("INSIDE_OBJECT_START");break}case"[":{r=u,e.pop(),e.push(d),e.push("INSIDE_ARRAY_START");break}}}function s(l,u){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=u,e.pop();break}}}function o(l,u){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,e.pop();break}}}for(let l=0;l<t.length;l++){const u=t[l];switch(e[e.length-1]){case"ROOT":n(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{r=l,e.pop();break}default:{r=l,n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const h=t.substring(a,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';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":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const d=t.substring(a,t.length);"true".startsWith(d)?i+="true".slice(d.length):"false".startsWith(d)?i+="false".slice(d.length):"null".startsWith(d)&&(i+="null".slice(d.length))}}return i}async function Xp(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await Xr({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await Xr({text:iE(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function xi(t){return t.type.startsWith("tool-")}function eh(t){return t.type.split("-").slice(1).join("-")}function lE({lastMessage:t,messageId:e}){return{message:(t==null?void 0:t.role)==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function uE({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:s,onData:o}){return t.pipeThrough(new TransformStream({async transform(i,l){await a(async({state:u,write:d})=>{var h,g,c,p;function f(_){const I=u.message.parts.filter(xi).find(S=>S.toolCallId===_);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function m(_){const I=u.message.parts.filter(S=>S.type==="dynamic-tool").find(S=>S.toolCallId===_);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function v(_){var E;const I=u.message.parts.find($=>xi($)&&$.toolCallId===_.toolCallId),S=_,R=I;I!=null?(I.state=_.state,R.input=S.input,R.output=S.output,R.errorText=S.errorText,R.rawInput=S.rawInput,R.preliminary=S.preliminary,R.providerExecuted=(E=S.providerExecuted)!=null?E:I.providerExecuted,S.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=S.providerMetadata)):u.message.parts.push({type:`tool-${_.toolName}`,toolCallId:_.toolCallId,state:_.state,input:S.input,output:S.output,rawInput:S.rawInput,errorText:S.errorText,providerExecuted:S.providerExecuted,preliminary:S.preliminary,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}function w(_){var E;const I=u.message.parts.find($=>$.type==="dynamic-tool"&&$.toolCallId===_.toolCallId),S=_,R=I;I!=null?(I.state=_.state,R.toolName=_.toolName,R.input=S.input,R.output=S.output,R.errorText=S.errorText,R.rawInput=(E=S.rawInput)!=null?E:R.rawInput,R.preliminary=S.preliminary,S.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=S.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:_.toolName,toolCallId:_.toolCallId,state:_.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function y(_){if(_!=null){const E=u.message.metadata!=null?Yp(u.message.metadata,_):_;e!=null&&await Bo({value:E,schema:e}),u.message.metadata=E}}switch(i.type){case"text-start":{const _={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=_,u.message.parts.push(_),d();break}case"text-delta":{const _=u.activeTextParts[i.id];_.text+=i.delta,_.providerMetadata=(h=i.providerMetadata)!=null?h:_.providerMetadata,d();break}case"text-end":{const _=u.activeTextParts[i.id];_.state="done",_.providerMetadata=(g=i.providerMetadata)!=null?g:_.providerMetadata,delete u.activeTextParts[i.id],d();break}case"reasoning-start":{const _={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=_,u.message.parts.push(_),d();break}case"reasoning-delta":{const _=u.activeReasoningParts[i.id];_.text+=i.delta,_.providerMetadata=(c=i.providerMetadata)!=null?c:_.providerMetadata,d();break}case"reasoning-end":{const _=u.activeReasoningParts[i.id];_.providerMetadata=(p=i.providerMetadata)!=null?p:_.providerMetadata,_.state="done",delete u.activeReasoningParts[i.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),d();break}case"tool-input-start":{const _=u.message.parts.filter(xi);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:_.length,dynamic:i.dynamic},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):v({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),d();break}case"tool-input-delta":{const _=u.partialToolCalls[i.toolCallId];_.text+=i.inputTextDelta;const{value:E}=await Xp(_.text);_.dynamic?w({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:E}):v({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:E}),d();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):v({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):v({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d();break}case"tool-output-available":{if(i.dynamic){const _=m(i.toolCallId);w({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-available",input:_.input,output:i.output,preliminary:i.preliminary})}else{const _=f(i.toolCallId);v({toolCallId:i.toolCallId,toolName:eh(_),state:"output-available",input:_.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}d();break}case"tool-output-error":{if(i.dynamic){const _=m(i.toolCallId);w({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-error",input:_.input,errorText:i.errorText})}else{const _=f(i.toolCallId);v({toolCallId:i.toolCallId,toolName:eh(_),state:"output-error",input:_.input,rawInput:_.rawInput,errorText:i.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await y(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&d();break}case"finish":{await y(i.messageMetadata),i.messageMetadata!=null&&d();break}case"message-metadata":{await y(i.messageMetadata),i.messageMetadata!=null&&d();break}case"error":{n==null||n(new Error(i.errorText));break}default:if(oE(i)){(r==null?void 0:r[i.type])!=null&&await Bo({value:i.data,schema:r[i.type]});const _=i;if(_.transient){o==null||o(_);break}const E=_.id!=null?u.message.parts.find(I=>_.type===I.type&&_.id===I.id):void 0;E!=null?E.data=_.data:u.message.parts.push(_),o==null||o(_),d()}}l.enqueue(i)})}}))}function cE({messageId:t,originalMessages:e=[],onFinish:r,onError:a,stream:n}){let s=e==null?void 0:e[e.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:t=s.id;let o=!1;const i=n.pipeThrough(new TransformStream({transform(g,c){if(g.type==="start"){const p=g;p.messageId==null&&t!=null&&(p.messageId=t)}g.type==="abort"&&(o=!0),c.enqueue(g)}}));if(r==null)return i;const l=lE({lastMessage:s?structuredClone(s):void 0,messageId:t??""}),u=async g=>{await g({state:l,write:()=>{}})};let d=!1;const h=async()=>{if(d||!r)return;d=!0;const g=l.message.id===(s==null?void 0:s.id);await r({isAborted:o,isContinuation:g,responseMessage:l.message,messages:[...g?e.slice(0,-1):e,l.message]})};return uE({stream:i,runUpdateMessageJob:u,onError:a}).pipeThrough(new TransformStream({transform(g,c){c.enqueue(g)},async cancel(){await h()},async flush(){await h()}}))}function dE({response:t,status:e,statusText:r,headers:a,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new Kp);if(s){const[i,l]=o.tee();o=i,s({stream:l})}Gp({response:t,status:e,statusText:r,headers:Object.fromEntries(ms(a,Qp).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function vs(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let a=!1;async function n(s){var o;a=!0;try{s&&await((o=r.cancel)==null?void 0:o.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(a)return{done:!0,value:void 0};const{done:s,value:o}=await r.read();return s?(await n(!0),{done:!0,value:void 0}):{done:!1,value:o}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(s){throw await n(!0),s}}},e}async function pE({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:a}=await r.read();if(a)break}}catch(a){e==null||e(a)}finally{r.releaseLock()}}function th(){let t,e;return{promise:new Promise((a,n)=>{t=a,e=n}),resolve:t,reject:e}}function hE(){let t=[],e=null,r=!1,a=th();const n=()=>{r=!0,a.resolve(),t.forEach(o=>o.cancel()),t=[],e==null||e.close()},s=async()=>{if(r&&t.length===0){e==null||e.close();return}if(t.length===0)return a=th(),await a.promise,s();try{const{value:o,done:i}=await t[0].read();i?(t.shift(),t.length>0?await s():r&&(e==null||e.close())):e==null||e.enqueue(o)}catch(o){e==null||e.error(o),t.shift(),n()}};return{stream:new ReadableStream({start(o){e=o},pull:s,async cancel(){for(const o of t)await o.cancel();t=[],r=!0}}),addStream:o=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(o.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),t.length===0&&(e==null||e.close())},terminate:n}}var gs=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}};function fE(){var t,e;return(e=(t=globalThis==null?void 0:globalThis.performance)==null?void 0:t.now())!=null?e:Date.now()}function mE({tools:t,generatorStream:e,tracer:r,telemetry:a,system:n,messages:s,abortSignal:o,repairToolCall:i,experimental_context:l}){let u=null;const d=new ReadableStream({start(v){u=v}}),h=new Set,g=new Map;let c=!1,p;function f(){c&&h.size===0&&(p!=null&&u.enqueue(p),u.close())}const m=new TransformStream({async transform(v,w){const y=v.type;switch(y){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{w.enqueue(v);break}case"file":{w.enqueue({type:"file",file:new Kx({data:v.data,mediaType:v.mediaType})});break}case"finish":{p={type:"finish",finishReason:v.finishReason,usage:v.usage,providerMetadata:v.providerMetadata};break}case"tool-call":{try{const _=await Zp({toolCall:v,tools:t,repairToolCall:i,system:n,messages:s});if(w.enqueue(_),_.invalid){u.enqueue({type:"tool-error",toolCallId:_.toolCallId,toolName:_.toolName,input:_.input,error:Zo(_.error),dynamic:!0});break}const E=t[_.toolName];if(g.set(_.toolCallId,_.input),E.onInputAvailable!=null&&await E.onInputAvailable({input:_.input,toolCallId:_.toolCallId,messages:s,abortSignal:o,experimental_context:l}),E.execute!=null&&_.providerExecuted!==!0){const I=V0();h.add(I),Tn({name:"ai.toolCall",attributes:jt({telemetry:a,attributes:{...In({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":_.toolName,"ai.toolCall.id":_.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(_.input)}}}),tracer:r,fn:async S=>{let R;try{const $=Yc({execute:E.execute.bind(E),input:_.input,options:{toolCallId:_.toolCallId,messages:s,abortSignal:o,experimental_context:l}});for await(const z of $)u.enqueue({..._,type:"tool-result",output:z.output,...z.type==="preliminary"&&{preliminary:!0}}),z.type==="final"&&(R=z.output)}catch($){gi(S,$),u.enqueue({..._,type:"tool-error",error:$}),h.delete(I),f();return}h.delete(I),f();try{S.setAttributes(jt({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(R)}}}))}catch{}}})}}catch(_){u.enqueue({type:"error",error:_})}break}case"tool-result":{const _=v.toolName;v.isError?u.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:_,input:g.get(v.toolCallId),providerExecuted:v.providerExecuted,error:v.result}):w.enqueue({type:"tool-result",toolCallId:v.toolCallId,toolName:_,input:g.get(v.toolCallId),output:v.result,providerExecuted:v.providerExecuted});break}default:{const _=y;throw new Error(`Unhandled chunk type: ${_}`)}}},flush(){c=!0,f()}});return new ReadableStream({async start(v){return Promise.all([e.pipeThrough(m).pipeTo(new WritableStream({write(w){v.enqueue(w)},close(){}})),d.pipeTo(new WritableStream({write(w){v.enqueue(w)},close(){v.close()}}))])}})}var vE=na({prefix:"aitxt",size:24});function gE({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:u=_i(1),experimental_output:d,experimental_telemetry:h,prepareStep:g,providerOptions:c,experimental_activeTools:p,activeTools:f=p,experimental_repairToolCall:m,experimental_transform:v,experimental_download:w,includeRawChunks:y=!1,onChunk:_,onError:E=({error:D})=>{console.error(D)},onFinish:I,onAbort:S,onStepFinish:R,experimental_context:$,_internal:{now:z=fE,generateId:L=vE,currentDate:F=()=>new Date}={},...M}){return new _E({model:hs(t),telemetry:h,headers:l,settings:M,maxRetries:o,abortSignal:i,system:a,prompt:n,messages:s,tools:e,toolChoice:r,transforms:yi(v),activeTools:f,repairToolCall:m,stopConditions:yi(u),output:d,providerOptions:c,prepareStep:g,includeRawChunks:y,onChunk:_,onError:E,onFinish:I,onAbort:S,onStepFinish:R,now:z,currentDate:F,generateId:L,experimental_context:$,download:w})}function yE(t){if(!t)return new TransformStream({transform(o,i){i.enqueue({part:o,partialOutput:void 0})}});let e,r="",a="",n="";function s({controller:o,partialOutput:i=void 0}){o.enqueue({part:{type:"text-delta",id:e,text:a},partialOutput:i}),a=""}return new TransformStream({async transform(o,i){if(o.type==="finish-step"&&a.length>0&&s({controller:i}),o.type!=="text-delta"&&o.type!=="text-start"&&o.type!=="text-end"){i.enqueue({part:o,partialOutput:void 0});return}if(e==null)e=o.id;else if(o.id!==e){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-start"){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-end"){a.length>0&&s({controller:i}),i.enqueue({part:o,partialOutput:void 0});return}r+=o.text,a+=o.text;const l=await t.parsePartial({text:r});if(l!=null){const u=JSON.stringify(l.partial);u!==n&&(s({controller:i,partialOutput:l.partial}),n=u)}}})}var _E=class{constructor({model:t,telemetry:e,headers:r,settings:a,maxRetries:n,abortSignal:s,system:o,prompt:i,messages:l,tools:u,toolChoice:d,transforms:h,activeTools:g,repairToolCall:c,stopConditions:p,output:f,providerOptions:m,prepareStep:v,includeRawChunks:w,now:y,currentDate:_,generateId:E,onChunk:I,onError:S,onFinish:R,onAbort:$,onStepFinish:z,experimental_context:L,download:F}){this._totalUsage=new gs,this._finishReason=new gs,this._steps=new gs,this.output=f,this.includeRawChunks=w,this.tools=u;let M,D=[];const K=[];let oe,ie,C={},re=[];const B=[];let de,ae={},ke={};const _e=new TransformStream({async transform(se,Se){var Ie,ye,Xe,Le;Se.enqueue(se);const{part:J}=se;if((J.type==="text-delta"||J.type==="reasoning-delta"||J.type==="source"||J.type==="tool-call"||J.type==="tool-result"||J.type==="tool-input-start"||J.type==="tool-input-delta"||J.type==="raw")&&await(I==null?void 0:I({chunk:J})),J.type==="error"&&await S({error:Np(J.error)}),J.type==="text-start"&&(ae[J.id]={type:"text",text:"",providerMetadata:J.providerMetadata},D.push(ae[J.id])),J.type==="text-delta"){const Me=ae[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`text part ${J.id} not found`},partialOutput:void 0});return}Me.text+=J.text,Me.providerMetadata=(Ie=J.providerMetadata)!=null?Ie:Me.providerMetadata}if(J.type==="text-end"){const Me=ae[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`text part ${J.id} not found`},partialOutput:void 0});return}Me.providerMetadata=(ye=J.providerMetadata)!=null?ye:Me.providerMetadata,delete ae[J.id]}if(J.type==="reasoning-start"&&(ke[J.id]={type:"reasoning",text:"",providerMetadata:J.providerMetadata},D.push(ke[J.id])),J.type==="reasoning-delta"){const Me=ke[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`reasoning part ${J.id} not found`},partialOutput:void 0});return}Me.text+=J.text,Me.providerMetadata=(Xe=J.providerMetadata)!=null?Xe:Me.providerMetadata}if(J.type==="reasoning-end"){const Me=ke[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`reasoning part ${J.id} not found`},partialOutput:void 0});return}Me.providerMetadata=(Le=J.providerMetadata)!=null?Le:Me.providerMetadata,delete ke[J.id]}if(J.type==="file"&&D.push({type:"file",file:J.file}),J.type==="source"&&D.push(J),J.type==="tool-call"&&D.push(J),J.type==="tool-result"&&!J.preliminary&&D.push(J),J.type==="tool-error"&&D.push(J),J.type==="start-step"&&(C=J.request,re=J.warnings),J.type==="finish-step"){const Me=bi({content:D,tools:u}),ze=new Bp({content:D,finishReason:J.finishReason,usage:J.usage,warnings:re,request:C,response:{...J.response,messages:[...K,...Me]},providerMetadata:J.providerMetadata});await(z==null?void 0:z(ze)),Wd(re),B.push(ze),D=[],ke={},ae={},K.push(...Me),M.resolve()}J.type==="finish"&&(ie=J.totalUsage,oe=J.finishReason)},async flush(se){try{if(B.length===0){const Xe=new mx({message:"No output generated. Check the stream for errors."});be._finishReason.reject(Xe),be._totalUsage.reject(Xe),be._steps.reject(Xe);return}const Se=oe??"unknown",Ie=ie??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};be._finishReason.resolve(Se),be._totalUsage.resolve(Ie),be._steps.resolve(B);const ye=B[B.length-1];await(R==null?void 0:R({finishReason:Se,totalUsage:Ie,usage:ye.usage,content:ye.content,text:ye.text,reasoningText:ye.reasoningText,reasoning:ye.reasoning,files:ye.files,sources:ye.sources,toolCalls:ye.toolCalls,staticToolCalls:ye.staticToolCalls,dynamicToolCalls:ye.dynamicToolCalls,toolResults:ye.toolResults,staticToolResults:ye.staticToolResults,dynamicToolResults:ye.dynamicToolResults,request:ye.request,response:ye.response,warnings:ye.warnings,providerMetadata:ye.providerMetadata,steps:B})),de.setAttributes(jt({telemetry:e,attributes:{"ai.response.finishReason":Se,"ai.response.text":{output:()=>ye.text},"ai.response.toolCalls":{output:()=>{var Xe;return(Xe=ye.toolCalls)!=null&&Xe.length?JSON.stringify(ye.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ye.providerMetadata),"ai.usage.inputTokens":Ie.inputTokens,"ai.usage.outputTokens":Ie.outputTokens,"ai.usage.totalTokens":Ie.totalTokens,"ai.usage.reasoningTokens":Ie.reasoningTokens,"ai.usage.cachedInputTokens":Ie.cachedInputTokens}}))}catch(Se){se.error(Se)}finally{de.end()}}}),Pe=hE();this.addStream=Pe.addStream,this.closeStream=Pe.close;const xe=Pe.stream.getReader();let ve=new ReadableStream({async start(se){se.enqueue({type:"start"})},async pull(se){function Se(){$==null||$({steps:B}),se.enqueue({type:"abort"}),se.close()}try{const{done:Ie,value:ye}=await xe.read();if(Ie){se.close();return}if(s!=null&&s.aborted){Se();return}se.enqueue(ye)}catch(Ie){Yr(Ie)&&(s!=null&&s.aborted)?Se():se.error(Ie)}},cancel(se){return Pe.stream.cancel(se)}});for(const se of h)ve=ve.pipeThrough(se({tools:u,stopStream(){Pe.terminate()}}));this.baseStream=ve.pipeThrough(yE(f)).pipeThrough(_e);const{maxRetries:Re,retry:pt}=Up({maxRetries:n,abortSignal:s}),Ne=Dp(e),we=vi(a),bt=Mp({model:t,telemetry:e,headers:r,settings:{...we,maxRetries:Re}}),be=this;Tn({name:"ai.streamText",attributes:jt({telemetry:e,attributes:{...In({operationId:"ai.streamText",telemetry:e}),...bt,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:l})}}}),tracer:Ne,endWhenDone:!1,fn:async se=>{de=se;async function Se({currentStep:Ie,responseMessages:ye,usage:Xe}){var Le,J,Me,ze,pe;const Be=be.includeRawChunks;M=new gs;const hr=await Ap({system:o,prompt:i,messages:l}),Ft=[...hr.messages,...ye],mt=await(v==null?void 0:v({model:t,steps:B,stepNumber:B.length,messages:Ft})),Yt=hs((Le=mt==null?void 0:mt.model)!=null?Le:t),xt=await Pp({prompt:{system:(J=mt==null?void 0:mt.system)!=null?J:hr.system,messages:(Me=mt==null?void 0:mt.messages)!=null?Me:Ft},supportedUrls:await Yt.supportedUrls,download:F}),{toolChoice:qt,tools:Sr}=Cp({tools:u,toolChoice:(ze=mt==null?void 0:mt.toolChoice)!=null?ze:d,activeTools:(pe=mt==null?void 0:mt.activeTools)!=null?pe:g}),{result:{stream:pn,response:Ge,request:Zt},doStreamSpan:Xt,startTimestampMs:Ra}=await pt(()=>Tn({name:"ai.streamText.doStream",attributes:jt({telemetry:e,attributes:{...In({operationId:"ai.streamText.doStream",telemetry:e}),...bt,"ai.model.provider":Yt.provider,"ai.model.id":Yt.modelId,"ai.prompt.messages":{input:()=>jp(xt)},"ai.prompt.tools":{input:()=>Sr==null?void 0:Sr.map(ue=>JSON.stringify(ue))},"ai.prompt.toolChoice":{input:()=>qt!=null?JSON.stringify(qt):void 0},"gen_ai.system":Yt.provider,"gen_ai.request.model":Yt.modelId,"gen_ai.request.frequency_penalty":we.frequencyPenalty,"gen_ai.request.max_tokens":we.maxOutputTokens,"gen_ai.request.presence_penalty":we.presencePenalty,"gen_ai.request.stop_sequences":we.stopSequences,"gen_ai.request.temperature":we.temperature,"gen_ai.request.top_k":we.topK,"gen_ai.request.top_p":we.topP}}),tracer:Ne,endWhenDone:!1,fn:async ue=>({startTimestampMs:y(),doStreamSpan:ue,result:await Yt.doStream({...we,tools:Sr,toolChoice:qt,responseFormat:f==null?void 0:f.responseFormat,prompt:xt,providerOptions:m,abortSignal:s,headers:r,includeRawChunks:Be})})})),Vt=mE({tools:u,generatorStream:pn,tracer:Ne,telemetry:e,system:o,messages:Ft,repairToolCall:c,abortSignal:s,experimental_context:L}),Kl=Zt??{},Un=[],Oa=[];let $a;const Aa={};let qr="unknown",ht={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},Na,Ma=!0,Bt={id:E(),timestamp:_(),modelId:t.modelId},Fn="";be.addStream(Vt.pipeThrough(new TransformStream({async transform(ue,ct){var Zr,hn,fn,T;if(ue.type==="stream-start"){$a=ue.warnings;return}if(Ma){const k=y()-Ra;Ma=!1,Xt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":k}),Xt.setAttributes({"ai.response.msToFirstChunk":k}),ct.enqueue({type:"start-step",request:Kl,warnings:$a??[]})}const b=ue.type;switch(b){case"text-start":case"text-end":{ct.enqueue(ue);break}case"text-delta":{ue.delta.length>0&&(ct.enqueue({type:"text-delta",id:ue.id,text:ue.delta,providerMetadata:ue.providerMetadata}),Fn+=ue.delta);break}case"reasoning-start":case"reasoning-end":{ct.enqueue(ue);break}case"reasoning-delta":{ct.enqueue({type:"reasoning-delta",id:ue.id,text:ue.delta,providerMetadata:ue.providerMetadata});break}case"tool-call":{ct.enqueue(ue),Un.push(ue);break}case"tool-result":{ct.enqueue(ue),ue.preliminary||Oa.push(ue);break}case"tool-error":{ct.enqueue(ue),Oa.push(ue);break}case"response-metadata":{Bt={id:(Zr=ue.id)!=null?Zr:Bt.id,timestamp:(hn=ue.timestamp)!=null?hn:Bt.timestamp,modelId:(fn=ue.modelId)!=null?fn:Bt.modelId};break}case"finish":{ht=ue.usage,qr=ue.finishReason,Na=ue.providerMetadata;const k=y()-Ra;Xt.addEvent("ai.stream.finish"),Xt.setAttributes({"ai.response.msToFinish":k,"ai.response.avgOutputTokensPerSecond":1e3*((T=ht.outputTokens)!=null?T:0)/k});break}case"file":{ct.enqueue(ue);break}case"source":{ct.enqueue(ue);break}case"tool-input-start":{Aa[ue.id]=ue.toolName;const k=u==null?void 0:u[ue.toolName];(k==null?void 0:k.onInputStart)!=null&&await k.onInputStart({toolCallId:ue.id,messages:Ft,abortSignal:s,experimental_context:L}),ct.enqueue({...ue,dynamic:(k==null?void 0:k.type)==="dynamic"});break}case"tool-input-end":{delete Aa[ue.id],ct.enqueue(ue);break}case"tool-input-delta":{const k=Aa[ue.id],A=u==null?void 0:u[k];(A==null?void 0:A.onInputDelta)!=null&&await A.onInputDelta({inputTextDelta:ue.delta,toolCallId:ue.id,messages:Ft,abortSignal:s,experimental_context:L}),ct.enqueue(ue);break}case"error":{ct.enqueue(ue),qr="error";break}case"raw":{Be&&ct.enqueue(ue);break}default:{const k=b;throw new Error(`Unknown chunk type: ${k}`)}}},async flush(ue){const ct=Un.length>0?JSON.stringify(Un):void 0;try{Xt.setAttributes(jt({telemetry:e,attributes:{"ai.response.finishReason":qr,"ai.response.text":{output:()=>Fn},"ai.response.toolCalls":{output:()=>ct},"ai.response.id":Bt.id,"ai.response.model":Bt.modelId,"ai.response.timestamp":Bt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Na),"ai.usage.inputTokens":ht.inputTokens,"ai.usage.outputTokens":ht.outputTokens,"ai.usage.totalTokens":ht.totalTokens,"ai.usage.reasoningTokens":ht.reasoningTokens,"ai.usage.cachedInputTokens":ht.cachedInputTokens,"gen_ai.response.finish_reasons":[qr],"gen_ai.response.id":Bt.id,"gen_ai.response.model":Bt.modelId,"gen_ai.usage.input_tokens":ht.inputTokens,"gen_ai.usage.output_tokens":ht.outputTokens}}))}catch{}finally{Xt.end()}ue.enqueue({type:"finish-step",finishReason:qr,usage:ht,providerMetadata:Na,response:{...Bt,headers:Ge==null?void 0:Ge.headers}});const Zr=Lp(Xe,ht);await M.promise;const hn=Un.filter(T=>T.providerExecuted!==!0),fn=Oa.filter(T=>T.providerExecuted!==!0);if(hn.length>0&&fn.length===hn.length&&!await Hp({stopConditions:p,steps:B})){ye.push(...bi({content:B[B.length-1].content,tools:u}));try{await Se({currentStep:Ie+1,responseMessages:ye,usage:Zr})}catch(T){ue.enqueue({type:"error",error:T}),be.closeStream()}}else ue.enqueue({type:"finish",finishReason:qr,totalUsage:Zr}),be.closeStream()}})))}await Se({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(se=>{be.addStream(new ReadableStream({start(Se){Se.enqueue({type:"error",error:se}),Se.close()}})),be.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return vs(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return vs(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await pE({stream:this.fullStream,onError:t==null?void 0:t.onError})}catch(r){(e=t==null?void 0:t.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new Hd;return vs(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:s=!1,sendStart:o=!0,sendFinish:i=!0,onError:l=yn}={}){const u=e!=null?sE({originalMessages:t,responseMessageId:e}):void 0,d={},h=c=>{var p,f;const m=d[c];return((f=(p=this.tools)==null?void 0:p[m])==null?void 0:f.type)==="dynamic"?!0:void 0},g=this.fullStream.pipeThrough(new TransformStream({transform:async(c,p)=>{const f=a==null?void 0:a({part:c}),m=c.type;switch(m){case"text-start":{p.enqueue({type:"text-start",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"text-delta":{p.enqueue({type:"text-delta",id:c.id,delta:c.text,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"text-end":{p.enqueue({type:"text-end",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-start":{p.enqueue({type:"reasoning-start",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-delta":{n&&p.enqueue({type:"reasoning-delta",id:c.id,delta:c.text,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-end":{p.enqueue({type:"reasoning-end",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"file":{p.enqueue({type:"file",mediaType:c.file.mediaType,url:`data:${c.file.mediaType};base64,${c.file.base64}`});break}case"source":{s&&c.sourceType==="url"&&p.enqueue({type:"source-url",sourceId:c.id,url:c.url,title:c.title,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}}),s&&c.sourceType==="document"&&p.enqueue({type:"source-document",sourceId:c.id,mediaType:c.mediaType,title:c.title,filename:c.filename,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"tool-input-start":{d[c.id]=c.toolName;const v=h(c.id);p.enqueue({type:"tool-input-start",toolCallId:c.id,toolName:c.toolName,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"tool-input-delta":{p.enqueue({type:"tool-input-delta",toolCallId:c.id,inputTextDelta:c.delta});break}case"tool-call":{d[c.toolCallId]=c.toolName;const v=h(c.toolCallId);c.invalid?p.enqueue({type:"tool-input-error",toolCallId:c.toolCallId,toolName:c.toolName,input:c.input,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{},...v!=null?{dynamic:v}:{},errorText:l(c.error)}):p.enqueue({type:"tool-input-available",toolCallId:c.toolCallId,toolName:c.toolName,input:c.input,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{},...v!=null?{dynamic:v}:{}});break}case"tool-result":{const v=h(c.toolCallId);p.enqueue({type:"tool-output-available",toolCallId:c.toolCallId,output:c.output,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.preliminary!=null?{preliminary:c.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{const v=h(c.toolCallId);p.enqueue({type:"tool-output-error",toolCallId:c.toolCallId,errorText:l(c.error),...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"error":{p.enqueue({type:"error",errorText:l(c.error)});break}case"start-step":{p.enqueue({type:"start-step"});break}case"finish-step":{p.enqueue({type:"finish-step"});break}case"start":{o&&p.enqueue({type:"start",...f!=null?{messageMetadata:f}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&p.enqueue({type:"finish",...f!=null?{messageMetadata:f}:{}});break}case"abort":{p.enqueue(c);break}case"tool-input-end":break;case"raw":break;default:{const v=m;throw new Error(`Unknown chunk type: ${v}`)}}f!=null&&m!=="start"&&m!=="finish"&&p.enqueue({type:"message-metadata",messageMetadata:f})}}));return vs(cE({stream:g,messageId:u??(e==null?void 0:e()),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:u,...d}={}){dE({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:u}),...d})}pipeTextStreamToResponse(t,e){nE({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l,...u}={}){return aE({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l}),...u})}toTextStreamResponse(t){return rE({textStream:this.textStream,...t})}};na({prefix:"aiobj",size:24}),na({prefix:"aiobj",size:24});var wE={};ix(wE,{object:()=>xE,text:()=>bE});var bE=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),xE=({schema:t})=>{const e=us(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const a=await Xp(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value};default:{const n=a.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},a){const n=await Xr({text:r});if(!n.success)throw new sp({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await $r({value:n.value,schema:e});if(!s.success)throw new sp({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value}}},EE=_n({name:x(),version:x()}),Ei=_n({_meta:at(P({}).loose())}),ma=Ei,SE=P({method:x(),params:at(Ei)}),IE=_n({experimental:at(P({}).loose()),logging:at(P({}).loose()),prompts:at(_n({listChanged:at(nt())})),resources:at(_n({subscribe:at(nt()),listChanged:at(nt())})),tools:at(_n({listChanged:at(nt())}))});ma.extend({protocolVersion:x(),capabilities:IE,serverInfo:EE,instructions:at(x())});var TE=ma.extend({nextCursor:at(x())}),kE=P({name:x(),description:at(x()),inputSchema:P({type:H("object"),properties:at(P({}).loose())}).loose()}).loose();TE.extend({tools:Y(kE)});var PE=P({type:H("text"),text:x()}).loose(),CE=P({type:H("image"),data:wc(),mimeType:x()}).loose(),rh=P({uri:x(),mimeType:at(x())}).loose(),RE=rh.extend({text:x()}),OE=rh.extend({blob:wc()}),$E=P({type:H("resource"),resource:Ae([RE,OE])}).loose();ma.extend({content:Y(Ae([PE,CE,$E])),isError:nt().default(!1).optional()}).or(ma.extend({toolResult:Cr()}));var ys="2.0",AE=P({jsonrpc:H(ys),id:Ae([x(),U().int()])}).merge(SE).strict(),NE=P({jsonrpc:H(ys),id:Ae([x(),U().int()]),result:ma}).strict(),ME=P({jsonrpc:H(ys),id:Ae([x(),U().int()]),error:P({code:U().int(),message:x(),data:at(Cr())})}).strict(),DE=P({jsonrpc:H(ys)}).merge(P({method:x(),params:at(Ei)})).strict();Ae([AE,DE,NE,ME]);const _s="2025-06-18",jE=[_s,"2025-03-26","2024-11-05","2024-10-07"],ws="2.0",nh=_t([O(),dt().int()]),ah=O(),LE=W({progressToken:q(nh)}).passthrough(),Lt=W({_meta:q(LE)}).passthrough(),It=W({method:O(),params:q(Lt)}),va=W({_meta:q(W({}).passthrough())}).passthrough(),or=W({method:O(),params:q(va)}),zt=W({_meta:q(W({}).passthrough())}).passthrough(),bs=_t([O(),dt().int()]),sh=W({jsonrpc:me(ws),id:bs}).merge(It).strict(),oh=t=>sh.safeParse(t).success,ih=W({jsonrpc:me(ws)}).merge(or).strict(),zE=t=>ih.safeParse(t).success,lh=W({jsonrpc:me(ws),id:bs,result:zt}).strict(),Si=t=>lh.safeParse(t).success;var ir;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(ir||(ir={}));const uh=W({jsonrpc:me(ws),id:bs,error:W({code:dt().int(),message:O(),data:q(ea())})}).strict(),UE=t=>uh.safeParse(t).success,sn=_t([sh,ih,lh,uh]),on=zt.strict(),Ii=or.extend({method:me("notifications/cancelled"),params:va.extend({requestId:bs,reason:O().optional()})}),ga=W({name:O(),title:q(O())}).passthrough(),ch=ga.extend({version:O()}),FE=W({experimental:q(W({}).passthrough()),sampling:q(W({}).passthrough()),elicitation:q(W({}).passthrough()),roots:q(W({listChanged:q(lt())}).passthrough())}).passthrough(),qE=It.extend({method:me("initialize"),params:Lt.extend({protocolVersion:O(),capabilities:FE,clientInfo:ch})}),ZE=W({experimental:q(W({}).passthrough()),logging:q(W({}).passthrough()),completions:q(W({}).passthrough()),prompts:q(W({listChanged:q(lt())}).passthrough()),resources:q(W({subscribe:q(lt()),listChanged:q(lt())}).passthrough()),tools:q(W({listChanged:q(lt())}).passthrough())}).passthrough(),dh=zt.extend({protocolVersion:O(),capabilities:ZE,serverInfo:ch,instructions:q(O())}),ph=or.extend({method:me("notifications/initialized")}),VE=t=>ph.safeParse(t).success,Ti=It.extend({method:me("ping")}),BE=W({progress:dt(),total:q(dt()),message:q(O())}).passthrough(),ki=or.extend({method:me("notifications/progress"),params:va.merge(BE).extend({progressToken:nh})}),xs=It.extend({params:Lt.extend({cursor:q(ah)}).optional()}),Es=zt.extend({nextCursor:q(ah)}),hh=W({uri:O(),mimeType:q(O()),_meta:q(W({}).passthrough())}).passthrough(),fh=hh.extend({text:O()}),Pi=O().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),mh=hh.extend({blob:Pi}),vh=ga.extend({uri:O(),description:q(O()),mimeType:q(O()),_meta:q(W({}).passthrough())}),HE=ga.extend({uriTemplate:O(),description:q(O()),mimeType:q(O()),_meta:q(W({}).passthrough())}),JE=xs.extend({method:me("resources/list")}),gh=Es.extend({resources:ee(vh)}),WE=xs.extend({method:me("resources/templates/list")}),yh=Es.extend({resourceTemplates:ee(HE)}),GE=It.extend({method:me("resources/read"),params:Lt.extend({uri:O()})}),_h=zt.extend({contents:ee(_t([fh,mh]))}),wh=or.extend({method:me("notifications/resources/list_changed")}),KE=It.extend({method:me("resources/subscribe"),params:Lt.extend({uri:O()})}),QE=It.extend({method:me("resources/unsubscribe"),params:Lt.extend({uri:O()})}),bh=or.extend({method:me("notifications/resources/updated"),params:va.extend({uri:O()})}),YE=W({name:O(),description:q(O()),required:q(lt())}).passthrough(),XE=ga.extend({description:q(O()),arguments:q(ee(YE)),_meta:q(W({}).passthrough())}),eS=xs.extend({method:me("prompts/list")}),xh=Es.extend({prompts:ee(XE)}),tS=It.extend({method:me("prompts/get"),params:Lt.extend({name:O(),arguments:q(ta(O()))})}),Ci=W({type:me("text"),text:O(),_meta:q(W({}).passthrough())}).passthrough(),Ri=W({type:me("image"),data:Pi,mimeType:O(),_meta:q(W({}).passthrough())}).passthrough(),Oi=W({type:me("audio"),data:Pi,mimeType:O(),_meta:q(W({}).passthrough())}).passthrough(),rS=W({type:me("resource"),resource:_t([fh,mh]),_meta:q(W({}).passthrough())}).passthrough(),nS=vh.extend({type:me("resource_link")}),Eh=_t([Ci,Ri,Oi,nS,rS]),aS=W({role:xr(["user","assistant"]),content:Eh}).passthrough(),Sh=zt.extend({description:q(O()),messages:ee(aS)}),Ih=or.extend({method:me("notifications/prompts/list_changed")}),sS=W({title:q(O()),readOnlyHint:q(lt()),destructiveHint:q(lt()),idempotentHint:q(lt()),openWorldHint:q(lt())}).passthrough(),oS=ga.extend({description:q(O()),inputSchema:W({type:me("object"),properties:q(W({}).passthrough()),required:q(ee(O()))}).passthrough(),outputSchema:q(W({type:me("object"),properties:q(W({}).passthrough()),required:q(ee(O()))}).passthrough()),annotations:q(sS),_meta:q(W({}).passthrough())}),iS=xs.extend({method:me("tools/list")}),Th=Es.extend({tools:ee(oS)}),Ss=zt.extend({content:ee(Eh).default([]),structuredContent:W({}).passthrough().optional(),isError:q(lt())});Ss.or(zt.extend({toolResult:ea()}));const lS=It.extend({method:me("tools/call"),params:Lt.extend({name:O(),arguments:q(ta(ea()))})}),kh=or.extend({method:me("notifications/tools/list_changed")}),Ph=xr(["debug","info","notice","warning","error","critical","alert","emergency"]),uS=It.extend({method:me("logging/setLevel"),params:Lt.extend({level:Ph})}),Ch=or.extend({method:me("notifications/message"),params:va.extend({level:Ph,logger:q(O()),data:ea()})}),cS=W({name:O().optional()}).passthrough(),dS=W({hints:q(ee(cS)),costPriority:q(dt().min(0).max(1)),speedPriority:q(dt().min(0).max(1)),intelligencePriority:q(dt().min(0).max(1))}).passthrough(),pS=W({role:xr(["user","assistant"]),content:_t([Ci,Ri,Oi])}).passthrough(),Rh=It.extend({method:me("sampling/createMessage"),params:Lt.extend({messages:ee(pS),systemPrompt:q(O()),includeContext:q(xr(["none","thisServer","allServers"])),temperature:q(dt()),maxTokens:dt().int(),stopSequences:q(ee(O())),metadata:q(W({}).passthrough()),modelPreferences:q(dS)})}),Oh=zt.extend({model:O(),stopReason:q(xr(["endTurn","stopSequence","maxTokens"]).or(O())),role:xr(["user","assistant"]),content:q0("type",[Ci,Ri,Oi])}),hS=W({type:me("boolean"),title:q(O()),description:q(O()),default:q(lt())}).passthrough(),fS=W({type:me("string"),title:q(O()),description:q(O()),minLength:q(dt()),maxLength:q(dt()),format:q(xr(["email","uri","date","date-time"]))}).passthrough(),mS=W({type:xr(["number","integer"]),title:q(O()),description:q(O()),minimum:q(dt()),maximum:q(dt())}).passthrough(),vS=W({type:me("string"),title:q(O()),description:q(O()),enum:ee(O()),enumNames:q(ee(O()))}).passthrough(),gS=_t([hS,fS,mS,vS]),$h=It.extend({method:me("elicitation/create"),params:Lt.extend({message:O(),requestedSchema:W({type:me("object"),properties:ta(O(),gS),required:q(ee(O()))}).passthrough()})}),Ah=zt.extend({action:xr(["accept","decline","cancel"]),content:q(ta(O(),ea()))}),yS=W({type:me("ref/resource"),uri:O()}).passthrough(),_S=W({type:me("ref/prompt"),name:O()}).passthrough(),wS=It.extend({method:me("completion/complete"),params:Lt.extend({ref:_t([_S,yS]),argument:W({name:O(),value:O()}).passthrough(),context:q(W({arguments:q(ta(O(),O()))}))})}),Nh=zt.extend({completion:W({values:ee(O()).max(100),total:q(dt().int()),hasMore:q(lt())}).passthrough()}),bS=W({uri:O().startsWith("file://"),name:q(O()),_meta:q(W({}).passthrough())}).passthrough(),Mh=It.extend({method:me("roots/list")}),Dh=zt.extend({roots:ee(bS)}),xS=or.extend({method:me("notifications/roots/list_changed")});_t([Ti,qE,wS,uS,tS,eS,JE,WE,GE,KE,QE,lS,iS]),_t([Ii,ki,ph,xS]),_t([on,Oh,Ah,Dh]),_t([Ti,Rh,$h,Mh]),_t([Ii,ki,Ch,bh,wh,kh,Ih]),_t([on,dh,Nh,Sh,xh,gh,yh,_h,Ss,Th]);class Nr extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}}let $i;$i=globalThis.crypto;async function ES(t){return(await $i).getRandomValues(new Uint8Array(t))}async function SS(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const a=await ES(t);for(let n=0;n<t;n++){const s=a[n]%e.length;r+=e[s]}return r}async function IS(t){return await SS(t)}async function TS(t){const e=await(await $i).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function kS(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await IS(t),r=await TS(e);return{code_verifier:e,code_challenge:r}}const PS=W({resource:O().url(),authorization_servers:ee(O().url()).optional(),jwks_uri:O().url().optional(),scopes_supported:ee(O()).optional(),bearer_methods_supported:ee(O()).optional(),resource_signing_alg_values_supported:ee(O()).optional(),resource_name:O().optional(),resource_documentation:O().optional(),resource_policy_uri:O().url().optional(),resource_tos_uri:O().url().optional(),tls_client_certificate_bound_access_tokens:lt().optional(),authorization_details_types_supported:ee(O()).optional(),dpop_signing_alg_values_supported:ee(O()).optional(),dpop_bound_access_tokens_required:lt().optional()}).passthrough(),jh=W({issuer:O(),authorization_endpoint:O(),token_endpoint:O(),registration_endpoint:O().optional(),scopes_supported:ee(O()).optional(),response_types_supported:ee(O()),response_modes_supported:ee(O()).optional(),grant_types_supported:ee(O()).optional(),token_endpoint_auth_methods_supported:ee(O()).optional(),token_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),service_documentation:O().optional(),revocation_endpoint:O().optional(),revocation_endpoint_auth_methods_supported:ee(O()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),introspection_endpoint:O().optional(),introspection_endpoint_auth_methods_supported:ee(O()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),code_challenge_methods_supported:ee(O()).optional()}).passthrough(),CS=W({issuer:O(),authorization_endpoint:O(),token_endpoint:O(),userinfo_endpoint:O().optional(),jwks_uri:O(),registration_endpoint:O().optional(),scopes_supported:ee(O()).optional(),response_types_supported:ee(O()),response_modes_supported:ee(O()).optional(),grant_types_supported:ee(O()).optional(),acr_values_supported:ee(O()).optional(),subject_types_supported:ee(O()),id_token_signing_alg_values_supported:ee(O()),id_token_encryption_alg_values_supported:ee(O()).optional(),id_token_encryption_enc_values_supported:ee(O()).optional(),userinfo_signing_alg_values_supported:ee(O()).optional(),userinfo_encryption_alg_values_supported:ee(O()).optional(),userinfo_encryption_enc_values_supported:ee(O()).optional(),request_object_signing_alg_values_supported:ee(O()).optional(),request_object_encryption_alg_values_supported:ee(O()).optional(),request_object_encryption_enc_values_supported:ee(O()).optional(),token_endpoint_auth_methods_supported:ee(O()).optional(),token_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),display_values_supported:ee(O()).optional(),claim_types_supported:ee(O()).optional(),claims_supported:ee(O()).optional(),service_documentation:O().optional(),claims_locales_supported:ee(O()).optional(),ui_locales_supported:ee(O()).optional(),claims_parameter_supported:lt().optional(),request_parameter_supported:lt().optional(),request_uri_parameter_supported:lt().optional(),require_request_uri_registration:lt().optional(),op_policy_uri:O().optional(),op_tos_uri:O().optional()}).passthrough().merge(jh.pick({code_challenge_methods_supported:!0})),Lh=W({access_token:O(),id_token:O().optional(),token_type:O(),expires_in:dt().optional(),scope:O().optional(),refresh_token:O().optional()}).strip(),RS=W({error:O(),error_description:O().optional(),error_uri:O().optional()}),OS=W({redirect_uris:ee(O()).refine(t=>t.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:O().optional(),grant_types:ee(O()).optional(),response_types:ee(O()).optional(),client_name:O().optional(),client_uri:O().optional(),logo_uri:O().optional(),scope:O().optional(),contacts:ee(O()).optional(),tos_uri:O().optional(),policy_uri:O().optional(),jwks_uri:O().optional(),jwks:F0().optional(),software_id:O().optional(),software_version:O().optional(),software_statement:O().optional()}).strip(),$S=W({client_id:O(),client_secret:O().optional(),client_id_issued_at:dt().optional(),client_secret_expires_at:dt().optional()}).strip(),AS=OS.merge($S);W({error:O(),error_description:O().optional()}).strip(),W({token:O(),token_type_hint:O().optional()}).strip();function NS(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function MS({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),a=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==a.origin||r.pathname.length<a.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(s)}class ft extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Ai extends ft{}Ai.errorCode="invalid_request";class Is extends ft{}Is.errorCode="invalid_client";class Ts extends ft{}Ts.errorCode="invalid_grant";class ks extends ft{}ks.errorCode="unauthorized_client";class Ni extends ft{}Ni.errorCode="unsupported_grant_type";class Mi extends ft{}Mi.errorCode="invalid_scope";class Di extends ft{}Di.errorCode="access_denied";class kn extends ft{}kn.errorCode="server_error";class ji extends ft{}ji.errorCode="temporarily_unavailable";class Li extends ft{}Li.errorCode="unsupported_response_type";class zi extends ft{}zi.errorCode="unsupported_token_type";class Ui extends ft{}Ui.errorCode="invalid_token";class Fi extends ft{}Fi.errorCode="method_not_allowed";class qi extends ft{}qi.errorCode="too_many_requests";class Zi extends ft{}Zi.errorCode="invalid_client_metadata";class Vi extends ft{}Vi.errorCode="insufficient_scope";const DS={[Ai.errorCode]:Ai,[Is.errorCode]:Is,[Ts.errorCode]:Ts,[ks.errorCode]:ks,[Ni.errorCode]:Ni,[Mi.errorCode]:Mi,[Di.errorCode]:Di,[kn.errorCode]:kn,[ji.errorCode]:ji,[Li.errorCode]:Li,[zi.errorCode]:zi,[Ui.errorCode]:Ui,[Fi.errorCode]:Fi,[qi.errorCode]:qi,[Zi.errorCode]:Zi,[Vi.errorCode]:Vi};class Gt extends Error{constructor(e){super(e??"Unauthorized")}}function zh(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Uh(t,e,r,a){const{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":jS(n,s,r);return;case"client_secret_post":LS(n,s,a);return;case"none":zS(n,a);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function jS(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${a}`)}function LS(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function zS(t,e){e.set("client_id",t)}async function Bi(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const a=RS.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:o}=a,i=DS[n]||kn;return new i(s||"",o)}catch(a){const n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${a}. Raw body: ${r}`;return new kn(n)}}async function Pn(t,e){var r,a;try{return await Hi(t,e)}catch(n){if(n instanceof Is||n instanceof ks)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Hi(t,e);if(n instanceof Ts)return await((a=t.invalidateCredentials)===null||a===void 0?void 0:a.call(t,"tokens")),await Hi(t,e);throw n}}async function Hi(t,{serverUrl:e,authorizationCode:r,scope:a,resourceMetadataUrl:n,fetchFn:s}){let o,i;try{o=await FS(e,{resourceMetadataUrl:n},s),o.authorization_servers&&o.authorization_servers.length>0&&(i=o.authorization_servers[0])}catch{}i||(i=e);const l=await US(e,t,o),u=await HS(i,{fetchFn:s});let d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const f=await KS(i,{metadata:u,clientMetadata:t.clientMetadata});await t.saveClientInformation(f),d=f}if(r!==void 0){const f=await t.codeVerifier(),m=await WS(i,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:f,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(m),"AUTHORIZED"}const h=await t.tokens();if(h!=null&&h.refresh_token)try{const f=await GS(i,{metadata:u,clientInformation:d,refreshToken:h.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication});return await t.saveTokens(f),"AUTHORIZED"}catch(f){if(!(!(f instanceof ft)||f instanceof kn))throw f}const g=t.state?await t.state():void 0,{authorizationUrl:c,codeVerifier:p}=await JS(i,{metadata:u,clientInformation:d,state:g,redirectUrl:t.redirectUrl,scope:a||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(p),await t.redirectToAuthorization(c),"REDIRECT"}async function US(t,e,r){const a=NS(t);if(e.validateResourceURL)return await e.validateResourceURL(a,r==null?void 0:r.resource);if(r){if(!MS({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function Ji(t){const e=t.headers.get("WWW-Authenticate");if(!e)return;const[r,a]=e.split(" ");if(r.toLowerCase()!=="bearer"||!a)return;const s=/resource_metadata="([^"]*)"/.exec(e);if(s)try{return new URL(s[1])}catch{return}}async function FS(t,e,r=fetch){const a=await VS(t,"oauth-protected-resource",r,{protocolVersion:e==null?void 0:e.protocolVersion,metadataUrl:e==null?void 0:e.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return PS.parse(await a.json())}async function Wi(t,e,r=fetch){try{return await r(t,{headers:e})}catch(a){if(a instanceof TypeError)return e?Wi(t,void 0,r):void 0;throw a}}function qS(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Fh(t,e,r=fetch){return await Wi(t,{"MCP-Protocol-Version":e},r)}function ZS(t,e){return!t||t.status===404&&e!=="/"}async function VS(t,e,r,a){var n,s;const o=new URL(t),i=(n=a==null?void 0:a.protocolVersion)!==null&&n!==void 0?n:_s;let l;if(a!=null&&a.metadataUrl)l=new URL(a.metadataUrl);else{const d=qS(e,o.pathname);l=new URL(d,(s=a==null?void 0:a.metadataServerUrl)!==null&&s!==void 0?s:o),l.search=o.search}let u=await Fh(l,i,r);if(!(a!=null&&a.metadataUrl)&&ZS(u,o.pathname)){const d=new URL(`/.well-known/${e}`,o);u=await Fh(d,i,r)}return u}function BS(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),a;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),a}async function HS(t,{fetchFn:e=fetch,protocolVersion:r=_s}={}){var a;const n={"MCP-Protocol-Version":r},s=BS(t);for(const{url:o,type:i}of s){const l=await Wi(o,n,e);if(!l)throw new Error(`CORS error trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`);if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}if(i==="oauth")return jh.parse(await l.json());{const u=CS.parse(await l.json());if(!(!((a=u.code_challenge_methods_supported)===null||a===void 0)&&a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${o}: does not support S256 code challenge method required by MCP specification`);return u}}}async function JS(t,{metadata:e,clientInformation:r,redirectUrl:a,scope:n,state:s,resource:o}){const i="code",l="S256";let u;if(e){if(u=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",t);const d=await kS(),h=d.code_verifier,g=d.code_challenge;return u.searchParams.set("response_type",i),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",g),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(a)),s&&u.searchParams.set("state",s),n&&u.searchParams.set("scope",n),n!=null&&n.includes("offline_access")&&u.searchParams.append("prompt","consent"),o&&u.searchParams.set("resource",o.href),{authorizationUrl:u,codeVerifier:h}}async function WS(t,{metadata:e,clientInformation:r,authorizationCode:a,codeVerifier:n,redirectUri:s,resource:o,addClientAuthentication:i,fetchFn:l}){var u;const d="authorization_code",h=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e!=null&&e.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const g=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),c=new URLSearchParams({grant_type:d,code:a,code_verifier:n,redirect_uri:String(s)});if(i)i(g,c,t,e);else{const f=(u=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],m=zh(r,f);Uh(m,r,g,c)}o&&c.set("resource",o.href);const p=await(l??fetch)(h,{method:"POST",headers:g,body:c});if(!p.ok)throw await Bi(p);return Lh.parse(await p.json())}async function GS(t,{metadata:e,clientInformation:r,refreshToken:a,resource:n,addClientAuthentication:s,fetchFn:o}){var i;const l="refresh_token";let u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",t);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:l,refresh_token:a});if(s)s(d,h,t,e);else{const c=(i=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],p=zh(r,c);Uh(p,r,d,h)}n&&h.set("resource",n.href);const g=await(o??fetch)(u,{method:"POST",headers:d,body:h});if(!g.ok)throw await Bi(g);return Lh.parse({refresh_token:a,...await g.json()})}async function KS(t,{metadata:e,clientMetadata:r,fetchFn:a}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);const s=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Bi(s);return AS.parse(await s.json())}class qh extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Gi(t){}function Zh(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=Gi,onError:r=Gi,onRetry:a=Gi,onComment:n}=t;let s="",o=!0,i,l="",u="";function d(f){const m=o?f.replace(/^\xEF\xBB\xBF/,""):f,[v,w]=QS(`${s}${m}`);for(const y of v)h(y);s=w,o=!1}function h(f){if(f===""){c();return}if(f.startsWith(":")){n&&n(f.slice(f.startsWith(": ")?2:1));return}const m=f.indexOf(":");if(m!==-1){const v=f.slice(0,m),w=f[m+1]===" "?2:1,y=f.slice(m+w);g(v,y,f);return}g(f,"",f)}function g(f,m,v){switch(f){case"event":u=m;break;case"data":l=`${l}${m}
58
- `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?a(parseInt(m,10)):r(new qh(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:v}));break;default:r(new qh(`Unknown field "${f.length>20?`${f.slice(0,20)}…`:f}"`,{type:"unknown-field",field:f,value:m,line:v}));break}}function c(){l.length>0&&e({id:i,event:u||void 0,data:l.endsWith(`
59
- `)?l.slice(0,-1):l}),i=void 0,l="",u=""}function p(f={}){s&&f.consume&&h(s),o=!0,i=void 0,l="",u="",s=""}return{feed:d,reset:p}}function QS(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
60
- `,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
61
- `&&a++}}return[e,r]}class Vh extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=Zh({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}}const YS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Ki extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Ps{constructor(e,r){var a;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch,this._sessionId=r==null?void 0:r.sessionId,this._reconnectionOptions=(a=r==null?void 0:r.reconnectionOptions)!==null&&a!==void 0?a:YS}async _authThenStart(){var e;if(!this._authProvider)throw new Gt("No auth provider");let r;try{r=await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Gt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const a=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...a})}async _startOrAuthSse(e){var r,a,n;const{resumptionToken:s}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),s&&o.set("last-event-id",s);const i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:o,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Ki(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(a,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var a;const n=this._reconnectionOptions.maxRetries;if(n>0&&r>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,a){if(!e)return;const{onresumptiontoken:n,replayMessageId:s}=r;let o;(async()=>{var l,u,d,h;try{const g=e.pipeThrough(new TextDecoderStream).pipeThrough(new Vh).getReader();for(;;){const{value:c,done:p}=await g.read();if(p)break;if(c.id&&(o=c.id,n==null||n(c.id)),!c.event||c.event==="message")try{const f=sn.parse(JSON.parse(c.data));s!==void 0&&Si(f)&&(f.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,f)}catch(f){(u=this.onerror)===null||u===void 0||u.call(this,f)}}}catch(g){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${g}`)),a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:s},0)}catch(c){(h=this.onerror)===null||h===void 0||h.call(this,new Error(`Failed to reconnect: ${c instanceof Error?c.message:String(c)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Gt("No auth provider");if(await Pn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var a,n,s,o;try{const{resumptionToken:i,onresumptiontoken:l}=r||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:oh(e)?e.id:void 0}).catch(m=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,m)});return}const u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},h=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),g=h.headers.get("mcp-session-id");if(g&&(this._sessionId=g),!h.ok){if(h.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ji(h),await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt;return this.send(e)}const m=await h.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${m}`)}if(h.status===202){VE(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,m)});return}const p=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,f=h.headers.get("content-type");if(p)if(f!=null&&f.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:l},!1);else if(f!=null&&f.includes("application/json")){const m=await h.json(),v=Array.isArray(m)?m.map(w=>sn.parse(w)):[sn.parse(m)];for(const w of v)(s=this.onmessage)===null||s===void 0||s.call(this,w)}else throw new Ki(-1,`Unexpected content type: ${f}`)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,a;if(this._sessionId)try{const n=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!o.ok&&o.status!==405)throw new Ki(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(n){throw(a=this.onerror)===null||a===void 0||a.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}class Cs{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new Cs,r=new Cs;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(var e;this._messageQueue.length>0;){const r=this._messageQueue.shift();(e=this.onmessage)===null||e===void 0||e.call(this,r.message,r.extra)}}async close(){var e;const r=this._otherTransport;this._otherTransport=void 0,await(r==null?void 0:r.close()),(e=this.onclose)===null||e===void 0||e.call(this)}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r==null?void 0:r.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r==null?void 0:r.authInfo}})}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ut(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function ya(t){return Object.fromEntries([...t.headers])}var XS=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new vo({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},Ot=XS();function Qi(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var eI=["fetch failed","failed to fetch"];function tI({error:t,url:e,requestBodyValues:r}){if(Qi(t))return t;if(t instanceof TypeError&&eI.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Ue({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function rI(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function Bh({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:a}){if(typeof t=="string")return t;if(t!=null)throw new La({message:`${a} API key must be a string.`});if(typeof process>"u")throw new La({message:`${a} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new La({message:`${a} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new La({message:`${a} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}var nI=/"__proto__"\s*:/,aI=/"constructor"\s*:/;function sI(t){const e=JSON.parse(t);return e===null||typeof e!="object"||nI.test(t)===!1&&aI.test(t)===!1?e:oI(e)}function oI(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function Yi(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return sI(t)}finally{Error.stackTraceLimit=e}}var Xi=Symbol.for("vercel.ai.validator");function iI(t){return{[Xi]:!0,validate:t}}function lI(t){return typeof t=="object"&&t!==null&&Xi in t&&t[Xi]===!0&&"validate"in t}function uI(t){return lI(t)?t:cI(t)}function cI(t){return iI(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new er({value:e,cause:r.issues})}})}async function dI({value:t,schema:e}){const r=await _a({value:t,schema:e});if(!r.success)throw er.wrap({value:t,cause:r.error});return r.value}async function _a({value:t,schema:e}){const r=uI(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:er.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:er.wrap({value:t,cause:a}),rawValue:t}}}async function pI({text:t,schema:e}){try{const r=Yi(t);return e==null?r:dI({value:r,schema:e})}catch(r){throw Tr.isInstance(r)||er.isInstance(r)?r:new Tr({text:t,cause:r})}}async function Hh({text:t,schema:e}){try{const r=Yi(t);return e==null?{success:!0,value:r,rawValue:r}:await _a({value:r,schema:e})}catch(r){return{success:!1,error:Tr.isInstance(r)?r:new Tr({text:t,cause:r}),rawValue:void 0}}}function Rs(t){try{return Yi(t),!0}catch{return!1}}function hI({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Vh).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await Hh({text:r,schema:e}))}}))}async function lr({provider:t,providerOptions:e,schema:r}){if((e==null?void 0:e[t])==null)return;const a=await _a({value:e[t],schema:r});if(!a.success)throw new vo({argument:"providerOptions",message:`invalid ${t} provider options`,cause:a.error});return a.value}var fI=()=>globalThis.fetch,Kt=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>Jh({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),mI=async({url:t,headers:e,formData:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>Jh({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),Jh=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=fI()})=>{try{const i=await o(t,{method:"POST",headers:rI(e),body:r.content,signal:s}),l=ya(i);if(!i.ok){let u;try{u=await n({response:i,url:t,requestBodyValues:r.values})}catch(d){throw Qi(d)||Ue.isInstance(d)?d:new Ue({message:"Failed to process error response",cause:d,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw u.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(u){throw u instanceof Error&&(Qi(u)||Ue.isInstance(u))?u:new Ue({message:"Failed to process successful response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw tI({error:i,url:t,requestBodyValues:r.values})}};function b2(t){return t}function el({id:t,name:e,inputSchema:r}){return({execute:a,outputSchema:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l,...u})=>({type:"provider-defined",id:t,name:e,args:u,inputSchema:r,outputSchema:n,execute:a,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l})}var Wh=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=ya(a);if(o.trim()==="")return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await pI({text:o,schema:t});return{responseHeaders:i,value:new Ue({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},Os=t=>async({response:e})=>{const r=ya(e);if(e.body==null)throw new su({});return{responseHeaders:r,value:hI({stream:e.body,schema:t})}},ln=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await Hh({text:n,schema:t}),o=ya(e);if(!s.success)throw new Ue({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},vI=()=>async({response:t,url:e,requestBodyValues:r})=>{const a=ya(t);if(!t.body)throw new Ue({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0});try{const n=await t.arrayBuffer();return{responseHeaders:a,value:new Uint8Array(n)}}catch(n){throw new Ue({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0,cause:n})}},{btoa:gI,atob:yI}=globalThis;function _I(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=yI(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function wI(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return gI(e)}function un(t){return t instanceof Uint8Array?wI(t):t}function Gh(t){return t==null?void 0:t.replace(/\/$/,"")}var tl=P({error:P({message:x(),type:x().nullish(),param:Mt().nullish(),code:Ae([x(),U()]).nullish()})}),ur=Wh({errorSchema:tl,errorToMessage:t=>t.error.message});function bI({prompt:t,systemMessageMode:e="system"}){const r=[],a=[];for(const{role:n,content:s}of t)switch(n){case"system":{switch(e){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const o=e;throw new Error(`Unsupported system message mode: ${o}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((o,i)=>{var l,u,d;switch(o.type){case"text":return{type:"text",text:o.text};case"file":if(o.mediaType.startsWith("image/")){const h=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${h};base64,${un(o.data)}`,detail:(u=(l=o.providerOptions)==null?void 0:l.openai)==null?void 0:u.imageDetail}}}else if(o.mediaType.startsWith("audio/")){if(o.data instanceof URL)throw new Nt({functionality:"audio file parts with URLs"});switch(o.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:un(o.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:un(o.data),format:"mp3"}};default:throw new Nt({functionality:`audio content parts with media type ${o.mediaType}`})}}else if(o.mediaType==="application/pdf"){if(o.data instanceof URL)throw new Nt({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof o.data=="string"&&o.data.startsWith("file-")?{file_id:o.data}:{filename:(d=o.filename)!=null?d:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${un(o.data)}`}}}else throw new Nt({functionality:`file part media type ${o.mediaType}`})}})});break}case"assistant":{let o="";const i=[];for(const l of s)switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const o of s){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:o.toolCallId,content:l})}break}default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return{messages:r,warnings:a}}function Kh({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Qh(t){switch(t){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 xI=P({logitBias:St(m0(),U()).optional(),logprobs:Ae([nt(),U()]).optional(),parallelToolCalls:nt().optional(),user:x().optional(),reasoningEffort:vt(["minimal","low","medium","high"]).optional(),maxCompletionTokens:U().optional(),store:nt().optional(),metadata:St(x().max(64),x().max(512)).optional(),prediction:St(x(),Mt()).optional(),structuredOutputs:nt().optional(),serviceTier:vt(["auto","flex","priority"]).optional(),strictJsonSchema:nt().optional(),textVerbosity:vt(["low","medium","high"]).optional(),promptCacheKey:x().optional(),safetyIdentifier:x().optional()}),Yh=P({key:x(),type:vt(["eq","ne","gt","gte","lt","lte"]),value:Ae([x(),U(),nt()])}),Xh=P({type:vt(["and","or"]),filters:Y(Ae([Yh,Pc(()=>Xh)]))}),EI=Ae([Yh,Xh]),ef=P({vectorStoreIds:Y(x()).optional(),maxNumResults:U().optional(),ranking:P({ranker:vt(["auto","default-2024-08-21"]).optional()}).optional(),filters:EI.optional()}),SI=el({id:"openai.file_search",name:"file_search",inputSchema:P({query:x()})}),tf=P({searchContextSize:vt(["low","medium","high"]).optional(),userLocation:P({type:H("approximate"),country:x().optional(),city:x().optional(),region:x().optional(),timezone:x().optional()}).optional()}),II=el({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:P({})});function TI({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:a}){t=t!=null&&t.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const i of t)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?a:void 0}});break;case"provider-defined":switch(i.id){case"openai.file_search":{const l=ef.parse(i.args);s.push({type:"file_search",vector_store_ids:l.vectorStoreIds,max_num_results:l.maxNumResults,ranking_options:l.ranking?{ranker:l.ranking.ranker}:void 0,filters:l.filters});break}case"openai.web_search_preview":{const l=tf.parse(i.args);s.push({type:"web_search_preview",search_context_size:l.searchContextSize,user_location:l.userLocation});break}default:n.push({type:"unsupported-tool",tool:i});break}break;default:n.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:n};default:{const i=o;throw new Nt({functionality:`tool choice type: ${i}`})}}}var kI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,seed:u,tools:d,toolChoice:h,providerOptions:g}){var c,p,f,m;const v=[],w=(c=await lr({provider:"openai",providerOptions:g,schema:xI}))!=null?c:{},y=(p=w.structuredOutputs)!=null?p:!0;n!=null&&v.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!y&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:_,warnings:E}=bI({prompt:t,systemMessageMode:$I(this.modelId)});v.push(...E);const I=(f=w.strictJsonSchema)!=null?f:!1,S={model:this.modelId,logit_bias:w.logitBias,logprobs:w.logprobs===!0||typeof w.logprobs=="number"?!0:void 0,top_logprobs:typeof w.logprobs=="number"?w.logprobs:typeof w.logprobs=="boolean"&&w.logprobs?0:void 0,user:w.user,parallel_tool_calls:w.parallelToolCalls,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(l==null?void 0:l.type)==="json"?y&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:I,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:u,verbosity:w.textVerbosity,max_completion_tokens:w.maxCompletionTokens,store:w.store,metadata:w.metadata,prediction:w.prediction,reasoning_effort:w.reasoningEffort,service_tier:w.serviceTier,prompt_cache_key:w.promptCacheKey,safety_identifier:w.safetyIdentifier,messages:_};nf(this.modelId)?(S.temperature!=null&&(S.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,v.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,v.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),S.presence_penalty!=null&&(S.presence_penalty=void 0,v.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),S.logit_bias!=null&&(S.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),S.logprobs!=null&&(S.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"})),S.top_logprobs!=null&&(S.top_logprobs=void 0,v.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),S.max_tokens!=null&&(S.max_completion_tokens==null&&(S.max_completion_tokens=S.max_tokens),S.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&S.temperature!=null&&(S.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w.serviceTier==="flex"&&!RI(this.modelId)&&(v.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),S.service_tier=void 0),w.serviceTier==="priority"&&!OI(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"}),S.service_tier=void 0);const{tools:R,toolChoice:$,toolWarnings:z}=TI({tools:d,toolChoice:h,structuredOutputs:y,strictJsonSchema:I});return{args:{...S,tools:R,tool_choice:$},warnings:[...v,...z]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,h,g,c,p;const{args:f,warnings:m}=await this.getArgs(t),{responseHeaders:v,value:w,rawValue:y}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:f,failedResponseHandler:ur,successfulResponseHandler:ln(PI),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=w.choices[0],E=[],I=_.message.content;I!=null&&I.length>0&&E.push({type:"text",text:I});for(const z of(e=_.message.tool_calls)!=null?e:[])E.push({type:"tool-call",toolCallId:(r=z.id)!=null?r:Ot(),toolName:z.function.name,input:z.function.arguments});for(const z of(a=_.message.annotations)!=null?a:[])E.push({type:"source",sourceType:"url",id:Ot(),url:z.url,title:z.title});const S=(n=w.usage)==null?void 0:n.completion_tokens_details,R=(s=w.usage)==null?void 0:s.prompt_tokens_details,$={openai:{}};return(S==null?void 0:S.accepted_prediction_tokens)!=null&&($.openai.acceptedPredictionTokens=S==null?void 0:S.accepted_prediction_tokens),(S==null?void 0:S.rejected_prediction_tokens)!=null&&($.openai.rejectedPredictionTokens=S==null?void 0:S.rejected_prediction_tokens),((o=_.logprobs)==null?void 0:o.content)!=null&&($.openai.logprobs=_.logprobs.content),{content:E,finishReason:Qh(_.finish_reason),usage:{inputTokens:(l=(i=w.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(d=(u=w.usage)==null?void 0:u.completion_tokens)!=null?d:void 0,totalTokens:(g=(h=w.usage)==null?void 0:h.total_tokens)!=null?g:void 0,reasoningTokens:(c=S==null?void 0:S.reasoning_tokens)!=null?c:void 0,cachedInputTokens:(p=R==null?void 0:R.cached_tokens)!=null?p:void 0},request:{body:f},response:{...Kh(w),headers:v,body:y},warnings:m,providerMetadata:$}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:a,failedResponseHandler:ur,successfulResponseHandler:Os(CI),abortSignal:t.abortSignal,fetch:this.config.fetch}),o=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,d=!1;const h={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,c){var p,f,m,v,w,y,_,E,I,S,R,$,z,L,F,M,D,K,oe,ie,C,re,B,de;if(t.includeRawChunks&&c.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){i="error",c.enqueue({type:"error",error:g.error});return}const ae=g.value;if("error"in ae){i="error",c.enqueue({type:"error",error:ae.error});return}u&&(u=!1,c.enqueue({type:"response-metadata",...Kh(ae)})),ae.usage!=null&&(l.inputTokens=(p=ae.usage.prompt_tokens)!=null?p:void 0,l.outputTokens=(f=ae.usage.completion_tokens)!=null?f:void 0,l.totalTokens=(m=ae.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(w=(v=ae.usage.completion_tokens_details)==null?void 0:v.reasoning_tokens)!=null?w:void 0,l.cachedInputTokens=(_=(y=ae.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?_:void 0,((E=ae.usage.completion_tokens_details)==null?void 0:E.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(I=ae.usage.completion_tokens_details)==null?void 0:I.accepted_prediction_tokens),((S=ae.usage.completion_tokens_details)==null?void 0:S.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(R=ae.usage.completion_tokens_details)==null?void 0:R.rejected_prediction_tokens));const ke=ae.choices[0];if((ke==null?void 0:ke.finish_reason)!=null&&(i=Qh(ke.finish_reason)),(($=ke==null?void 0:ke.logprobs)==null?void 0:$.content)!=null&&(h.openai.logprobs=ke.logprobs.content),(ke==null?void 0:ke.delta)==null)return;const _e=ke.delta;if(_e.content!=null&&(d||(c.enqueue({type:"text-start",id:"0"}),d=!0),c.enqueue({type:"text-delta",id:"0",delta:_e.content})),_e.tool_calls!=null)for(const Pe of _e.tool_calls){const xe=Pe.index;if(o[xe]==null){if(Pe.type!=="function")throw new Zn({data:Pe,message:"Expected 'function' type."});if(Pe.id==null)throw new Zn({data:Pe,message:"Expected 'id' to be a string."});if(((z=Pe.function)==null?void 0:z.name)==null)throw new Zn({data:Pe,message:"Expected 'function.name' to be a string."});c.enqueue({type:"tool-input-start",id:Pe.id,toolName:Pe.function.name}),o[xe]={id:Pe.id,type:"function",function:{name:Pe.function.name,arguments:(L=Pe.function.arguments)!=null?L:""},hasFinished:!1};const Re=o[xe];((F=Re.function)==null?void 0:F.name)!=null&&((M=Re.function)==null?void 0:M.arguments)!=null&&(Re.function.arguments.length>0&&c.enqueue({type:"tool-input-delta",id:Re.id,delta:Re.function.arguments}),Rs(Re.function.arguments)&&(c.enqueue({type:"tool-input-end",id:Re.id}),c.enqueue({type:"tool-call",toolCallId:(D=Re.id)!=null?D:Ot(),toolName:Re.function.name,input:Re.function.arguments}),Re.hasFinished=!0));continue}const ve=o[xe];ve.hasFinished||(((K=Pe.function)==null?void 0:K.arguments)!=null&&(ve.function.arguments+=(ie=(oe=Pe.function)==null?void 0:oe.arguments)!=null?ie:""),c.enqueue({type:"tool-input-delta",id:ve.id,delta:(C=Pe.function.arguments)!=null?C:""}),((re=ve.function)==null?void 0:re.name)!=null&&((B=ve.function)==null?void 0:B.arguments)!=null&&Rs(ve.function.arguments)&&(c.enqueue({type:"tool-input-end",id:ve.id}),c.enqueue({type:"tool-call",toolCallId:(de=ve.id)!=null?de:Ot(),toolName:ve.function.name,input:ve.function.arguments}),ve.hasFinished=!0))}if(_e.annotations!=null)for(const Pe of _e.annotations)c.enqueue({type:"source",sourceType:"url",id:Ot(),url:Pe.url,title:Pe.title})},flush(g){d&&g.enqueue({type:"text-end",id:"0"}),g.enqueue({type:"finish",finishReason:i,usage:l,...h!=null?{providerMetadata:h}:{}})}})),request:{body:a},response:{headers:n}}}},rf=P({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:P({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:P({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish(),PI=P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({message:P({role:H("assistant").nullish(),content:x().nullish(),tool_calls:Y(P({id:x().nullish(),type:H("function"),function:P({name:x(),arguments:x()})})).nullish(),annotations:Y(P({type:H("url_citation"),start_index:U(),end_index:U(),url:x(),title:x()})).nullish()}),index:U(),logprobs:P({content:Y(P({token:x(),logprob:U(),top_logprobs:Y(P({token:x(),logprob:U()}))})).nullish()}).nullish(),finish_reason:x().nullish()})),usage:rf}),CI=Ae([P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({delta:P({role:vt(["assistant"]).nullish(),content:x().nullish(),tool_calls:Y(P({index:U(),id:x().nullish(),type:H("function").nullish(),function:P({name:x().nullish(),arguments:x().nullish()})})).nullish(),annotations:Y(P({type:H("url_citation"),start_index:U(),end_index:U(),url:x(),title:x()})).nullish()}).nullish(),logprobs:P({content:Y(P({token:x(),logprob:U(),top_logprobs:Y(P({token:x(),logprob:U()}))})).nullish()}).nullish(),finish_reason:x().nullish(),index:U()})),usage:rf}),tl]);function nf(t){return(t.startsWith("o")||t.startsWith("gpt-5"))&&!t.startsWith("gpt-5-chat")}function RI(t){return t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")}function OI(t){return t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini")}function $I(t){var e,r;return nf(t)?(r=(e=AI[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var AI={"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 NI({prompt:t,user:e="user",assistant:r="assistant"}){let a="";t[0].role==="system"&&(a+=`${t[0].content}
57
+ `)}})}},u0={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Ab({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new c0);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:xo(r,u0)})}function qb({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function Lb(e){return e.type.startsWith("data-")}function d0(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?r[n]=d0(s,o):r[n]=o}return r}function jb(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),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":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,l+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';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":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function p0(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Tr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Tr({text:jb(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function ri(e){return e.type.startsWith("tool-")}function f0(e){return e.type.split("-").slice(1).join("-")}function Ub({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function zb({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var g,h,d,p;function w(b){const S=c.message.parts.filter(ri).find(C=>C.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function m(b){const S=c.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function y(b){var k;const S=c.message.parts.find(x=>ri(x)&&x.toolCallId===b.toolCallId),C=b,I=S;S!=null?(S.state=b.state,I.input=C.input,I.output=C.output,I.errorText=C.errorText,I.rawInput=C.rawInput,I.preliminary=C.preliminary,I.providerExecuted=(k=C.providerExecuted)!=null?k:S.providerExecuted,C.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=C.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}function _(b){var k,S;const C=c.message.parts.find(M=>M.type==="dynamic-tool"&&M.toolCallId===b.toolCallId),I=b,x=C;C!=null?(C.state=b.state,x.toolName=b.toolName,x.input=I.input,x.output=I.output,x.errorText=I.errorText,x.rawInput=(k=I.rawInput)!=null?k:x.rawInput,x.preliminary=I.preliminary,x.providerExecuted=(S=I.providerExecuted)!=null?S:C.providerExecuted,I.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=I.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,providerExecuted:I.providerExecuted,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}async function f(b){if(b!=null){const k=c.message.metadata!=null?d0(c.message.metadata,b):b;t!=null&&await Ea({value:k,schema:t}),c.message.metadata=k}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(g=i.providerMetadata)!=null?g:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[i.id];b.state="done",b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[i.id];b.providerMetadata=(p=i.providerMetadata)!=null?p:b.providerMetadata,b.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(ri);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:k}=await p0(b.text);b.dynamic?_({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}):y({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}),u();break}case"tool-input-available":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:f0(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:f0(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await f(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await f(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await f(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(Lb(i)){r?.[i.type]!=null&&await Ea({value:i.data,schema:r[i.type]});const b=i;if(b.transient){a?.(b);break}const k=b.id!=null?c.message.parts.find(S=>b.type===S.type&&b.id===S.id):void 0;k!=null?k.data=b.data:c.message.parts.push(b),a?.(b),u()}}l.enqueue(i)})}}))}function Db({messageId:e,originalMessages:t=[],onFinish:r,onError:n,stream:o}){let s=t?.[t.length-1];s?.role!=="assistant"?s=void 0:e=s.id;let a=!1;const i=o.pipeThrough(new TransformStream({transform(h,d){if(h.type==="start"){const p=h;p.messageId==null&&e!=null&&(p.messageId=e)}h.type==="abort"&&(a=!0),d.enqueue(h)}}));if(r==null)return i;const l=Ub({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),c=async h=>{await h({state:l,write:()=>{}})};let u=!1;const g=async()=>{if(u||!r)return;u=!0;const h=l.message.id===s?.id;await r({isAborted:a,isContinuation:h,responseMessage:l.message,messages:[...h?t.slice(0,-1):t,l.message],finishReason:l.finishReason})};return zb({stream:i,runUpdateMessageJob:c,onError:n}).pipeThrough(new TransformStream({transform(h,d){d.enqueue(h)},async cancel(){await g()},async flush(){await g()}}))}function Zb({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new c0);if(s){const[i,l]=a.tee();a=i,s({stream:l})}l0({response:e,status:t,statusText:r,headers:Object.fromEntries(xo(n,u0).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Ro(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var a;n=!0;try{s&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:a}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function Fb({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function h0(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Vb(){let e=[],t=null,r=!1,n=h0();const o=()=>{r=!0,n.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=h0(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length>0?await s():r&&t?.close()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function Hb(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function Bb({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(y){c=y}}),g=new Set,h=new Map;let d=!1,p;function w(){d&&g.size===0&&(p!=null&&c.enqueue(p),c.close())}const m=new TransformStream({async transform(y,_){const f=y.type;switch(f){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{_.enqueue(y);break}case"file":{_.enqueue({type:"file",file:new Ib({data:y.data,mediaType:y.mediaType})});break}case"finish":{p={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const b=await t0({toolCall:y,tools:e,repairToolCall:i,system:o,messages:s});if(_.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Ta(b.error),dynamic:!0});break}const k=e[b.toolName];if(h.set(b.toolCallId,b.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:s,abortSignal:a,experimental_context:l}),k.execute!=null&&b.providerExecuted!==!0){const S=In();g.add(S),Yr({name:"ai.toolCall",attributes:wt({telemetry:n,attributes:{...Kr({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async C=>{let I;try{const x=ud({execute:k.execute.bind(k),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:a,experimental_context:l}});for await(const M of x)c.enqueue({...b,type:"tool-result",output:M.output,...M.type==="preliminary"&&{preliminary:!0}}),M.type==="final"&&(I=M.output)}catch(x){Ya(C,x),c.enqueue({...b,type:"tool-error",error:x}),g.delete(S),w();return}g.delete(S),w();try{C.setAttributes(wt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(I)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=y.toolName;y.isError?c.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):_.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const b=f;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,w()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(m).pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){}})),u.pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){y.close()}}))])}})}var Jb=En({prefix:"aitxt",size:24});function ni({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Xa(1),experimental_output:u,experimental_telemetry:g,prepareStep:h,providerOptions:d,experimental_activeTools:p,activeTools:w=p,experimental_repairToolCall:m,experimental_transform:y,experimental_download:_,includeRawChunks:f=!1,onChunk:b,onError:k=({error:F})=>{console.error(F)},onFinish:S,onAbort:C,onStepFinish:I,experimental_context:x,_internal:{now:M=Hb,generateId:P=Jb,currentDate:U=()=>new Date}={},...z}){return new Wb({model:Eo(e),telemetry:g,headers:l,settings:z,maxRetries:a,abortSignal:i,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Qa(y),activeTools:w,repairToolCall:m,stopConditions:Qa(c),output:u,providerOptions:d,prepareStep:h,includeRawChunks:f,onChunk:b,onError:k,onFinish:S,onAbort:C,onStepFinish:I,now:M,currentDate:U,generateId:P,experimental_context:x,download:_})}function Gb(e){if(!e)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let t,r="",n="",o="";function s({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&n.length>0&&s({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&s({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text;const l=await e.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==o&&(s({controller:i,partialOutput:l.partial}),o=c)}}})}var Wb=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,system:a,prompt:i,messages:l,tools:c,toolChoice:u,transforms:g,activeTools:h,repairToolCall:d,stopConditions:p,output:w,providerOptions:m,prepareStep:y,includeRawChunks:_,now:f,currentDate:b,generateId:k,onChunk:S,onError:C,onFinish:I,onAbort:x,onStepFinish:M,experimental_context:P,download:U}){this._totalUsage=new yo,this._finishReason=new yo,this._steps=new yo,this.output=w,this.includeRawChunks=_,this.tools=c;let z,F=[];const te=[];let ie,se,ee={},pe=[];const V=[];let O,Z={},j={};const E=new TransformStream({async transform(W,Y){var oe,le,Ne,qe;Y.enqueue(W);const{part:X}=W;if((X.type==="text-delta"||X.type==="reasoning-delta"||X.type==="source"||X.type==="tool-call"||X.type==="tool-result"||X.type==="tool-input-start"||X.type==="tool-input-delta"||X.type==="raw")&&await S?.({chunk:X}),X.type==="error"&&await C({error:Bp(X.error)}),X.type==="text-start"&&(Z[X.id]={type:"text",text:"",providerMetadata:X.providerMetadata},F.push(Z[X.id])),X.type==="text-delta"){const me=Z[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}me.text+=X.text,me.providerMetadata=(oe=X.providerMetadata)!=null?oe:me.providerMetadata}if(X.type==="text-end"){const me=Z[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}me.providerMetadata=(le=X.providerMetadata)!=null?le:me.providerMetadata,delete Z[X.id]}if(X.type==="reasoning-start"&&(j[X.id]={type:"reasoning",text:"",providerMetadata:X.providerMetadata},F.push(j[X.id])),X.type==="reasoning-delta"){const me=j[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}me.text+=X.text,me.providerMetadata=(Ne=X.providerMetadata)!=null?Ne:me.providerMetadata}if(X.type==="reasoning-end"){const me=j[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}me.providerMetadata=(qe=X.providerMetadata)!=null?qe:me.providerMetadata,delete j[X.id]}if(X.type==="file"&&F.push({type:"file",file:X.file}),X.type==="source"&&F.push(X),X.type==="tool-call"&&F.push(X),X.type==="tool-result"&&!X.preliminary&&F.push(X),X.type==="tool-error"&&F.push(X),X.type==="start-step"&&(ee=X.request,pe=X.warnings),X.type==="finish-step"){const me=ti({content:F,tools:c}),st=new n0({content:F,finishReason:X.finishReason,usage:X.usage,warnings:pe,request:ee,response:{...X.response,messages:[...te,...me]},providerMetadata:X.providerMetadata});await M?.(st),ap(pe),V.push(st),F=[],j={},Z={},te.push(...me),z.resolve()}X.type==="finish"&&(se=X.totalUsage,ie=X.finishReason)},async flush(W){try{if(V.length===0){const Ne=new J3({message:"No output generated. Check the stream for errors."});B._finishReason.reject(Ne),B._totalUsage.reject(Ne),B._steps.reject(Ne);return}const Y=ie??"unknown",oe=se??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};B._finishReason.resolve(Y),B._totalUsage.resolve(oe),B._steps.resolve(V);const le=V[V.length-1];await I?.({finishReason:Y,totalUsage:oe,usage:le.usage,content:le.content,text:le.text,reasoningText:le.reasoningText,reasoning:le.reasoning,files:le.files,sources:le.sources,toolCalls:le.toolCalls,staticToolCalls:le.staticToolCalls,dynamicToolCalls:le.dynamicToolCalls,toolResults:le.toolResults,staticToolResults:le.staticToolResults,dynamicToolResults:le.dynamicToolResults,request:le.request,response:le.response,warnings:le.warnings,providerMetadata:le.providerMetadata,steps:V}),O.setAttributes(wt({telemetry:t,attributes:{"ai.response.finishReason":Y,"ai.response.text":{output:()=>le.text},"ai.response.toolCalls":{output:()=>{var Ne;return(Ne=le.toolCalls)!=null&&Ne.length?JSON.stringify(le.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(le.providerMetadata),"ai.usage.inputTokens":oe.inputTokens,"ai.usage.outputTokens":oe.outputTokens,"ai.usage.totalTokens":oe.totalTokens,"ai.usage.reasoningTokens":oe.reasoningTokens,"ai.usage.cachedInputTokens":oe.cachedInputTokens}}))}catch(Y){W.error(Y)}finally{O.end()}}}),R=Vb();this.addStream=R.addStream,this.closeStream=R.close;const $=R.stream.getReader();let H=new ReadableStream({async start(W){W.enqueue({type:"start"})},async pull(W){function Y(){x?.({steps:V}),W.enqueue({type:"abort"}),W.close()}try{const{done:oe,value:le}=await $.read();if(oe){W.close();return}if(s?.aborted){Y();return}W.enqueue(le)}catch(oe){Cr(oe)&&s?.aborted?Y():W.error(oe)}},cancel(W){return R.stream.cancel(W)}});for(const W of g)H=H.pipeThrough(W({tools:c,stopStream(){R.terminate()}}));this.baseStream=H.pipeThrough(Gb(w)).pipeThrough(E);const{maxRetries:G,retry:fe}=Qp({maxRetries:o,abortSignal:s}),ae=Gp(t),N=Ka(n),D=Jp({model:e,telemetry:t,headers:r,settings:{...N,maxRetries:G}}),B=this;Yr({name:"ai.streamText",attributes:wt({telemetry:t,attributes:{...Kr({operationId:"ai.streamText",telemetry:t}),...D,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:ae,endWhenDone:!1,fn:async W=>{O=W;async function Y({currentStep:oe,responseMessages:le,usage:Ne}){var qe,X,me,st,be;const pt=B.includeRawChunks;z=new yo;const tr=await Hp({system:a,prompt:i,messages:l}),ft=[...tr.messages,...le],We=await y?.({model:e,steps:V,stepNumber:V.length,messages:ft}),St=Eo((qe=We?.model)!=null?qe:e),yr=await zp({prompt:{system:(X=We?.system)!=null?X:tr.system,messages:(me=We?.messages)!=null?me:ft},supportedUrls:await St.supportedUrls,download:U}),{toolChoice:wr,tools:gn}=Dp({tools:c,toolChoice:(st=We?.toolChoice)!=null?st:u,activeTools:(be=We?.activeTools)!=null?be:h}),{result:{stream:aa,response:He,request:rr},doStreamSpan:nr,startTimestampMs:k2}=await fe(()=>Yr({name:"ai.streamText.doStream",attributes:wt({telemetry:t,attributes:{...Kr({operationId:"ai.streamText.doStream",telemetry:t}),...D,"ai.model.provider":St.provider,"ai.model.id":St.modelId,"ai.prompt.messages":{input:()=>Wp(yr)},"ai.prompt.tools":{input:()=>gn?.map(he=>JSON.stringify(he))},"ai.prompt.toolChoice":{input:()=>wr!=null?JSON.stringify(wr):void 0},"gen_ai.system":St.provider,"gen_ai.request.model":St.modelId,"gen_ai.request.frequency_penalty":N.frequencyPenalty,"gen_ai.request.max_tokens":N.maxOutputTokens,"gen_ai.request.presence_penalty":N.presencePenalty,"gen_ai.request.stop_sequences":N.stopSequences,"gen_ai.request.temperature":N.temperature,"gen_ai.request.top_k":N.topK,"gen_ai.request.top_p":N.topP}}),tracer:ae,endWhenDone:!1,fn:async he=>({startTimestampMs:f(),doStreamSpan:he,result:await St.doStream({...N,tools:gn,toolChoice:wr,responseFormat:w?.responseFormat,prompt:yr,providerOptions:m,abortSignal:s,headers:r,includeRawChunks:pt})})})),hC=Bb({tools:c,generatorStream:aa,tracer:ae,telemetry:t,system:a,messages:ft,repairToolCall:d,abortSignal:s,experimental_context:P}),mC=rr??{},ia=[],ec=[];let tc;const rc={};let vn="unknown",Nt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},nc,S2=!0,Bt={id:k(),timestamp:b(),modelId:e.modelId},C2="";B.addStream(hC.pipeThrough(new TransformStream({async transform(he,Ke){var so,ao,la,or;if(he.type==="stream-start"){tc=he.warnings;return}if(S2){const at=f()-k2;S2=!1,nr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":at}),nr.setAttributes({"ai.response.msToFirstChunk":at}),Ke.enqueue({type:"start-step",request:mC,warnings:tc??[]})}const T2=he.type;switch(T2){case"text-start":case"text-end":{Ke.enqueue(he);break}case"text-delta":{he.delta.length>0&&(Ke.enqueue({type:"text-delta",id:he.id,text:he.delta,providerMetadata:he.providerMetadata}),C2+=he.delta);break}case"reasoning-start":case"reasoning-end":{Ke.enqueue(he);break}case"reasoning-delta":{Ke.enqueue({type:"reasoning-delta",id:he.id,text:he.delta,providerMetadata:he.providerMetadata});break}case"tool-call":{Ke.enqueue(he),ia.push(he);break}case"tool-result":{Ke.enqueue(he),he.preliminary||ec.push(he);break}case"tool-error":{Ke.enqueue(he),ec.push(he);break}case"response-metadata":{Bt={id:(so=he.id)!=null?so:Bt.id,timestamp:(ao=he.timestamp)!=null?ao:Bt.timestamp,modelId:(la=he.modelId)!=null?la:Bt.modelId};break}case"finish":{Nt=he.usage,vn=he.finishReason,nc=he.providerMetadata;const at=f()-k2;nr.addEvent("ai.stream.finish"),nr.setAttributes({"ai.response.msToFinish":at,"ai.response.avgOutputTokensPerSecond":1e3*((or=Nt.outputTokens)!=null?or:0)/at});break}case"file":{Ke.enqueue(he);break}case"source":{Ke.enqueue(he);break}case"tool-input-start":{rc[he.id]=he.toolName;const at=c?.[he.toolName];at?.onInputStart!=null&&await at.onInputStart({toolCallId:he.id,messages:ft,abortSignal:s,experimental_context:P}),Ke.enqueue({...he,dynamic:at?.type==="dynamic"});break}case"tool-input-end":{delete rc[he.id],Ke.enqueue(he);break}case"tool-input-delta":{const at=rc[he.id],oc=c?.[at];oc?.onInputDelta!=null&&await oc.onInputDelta({inputTextDelta:he.delta,toolCallId:he.id,messages:ft,abortSignal:s,experimental_context:P}),Ke.enqueue(he);break}case"error":{Ke.enqueue(he),vn="error";break}case"raw":{pt&&Ke.enqueue(he);break}default:{const at=T2;throw new Error(`Unknown chunk type: ${at}`)}}},async flush(he){const Ke=ia.length>0?JSON.stringify(ia):void 0;try{nr.setAttributes(wt({telemetry:t,attributes:{"ai.response.finishReason":vn,"ai.response.text":{output:()=>C2},"ai.response.toolCalls":{output:()=>Ke},"ai.response.id":Bt.id,"ai.response.model":Bt.modelId,"ai.response.timestamp":Bt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(nc),"ai.usage.inputTokens":Nt.inputTokens,"ai.usage.outputTokens":Nt.outputTokens,"ai.usage.totalTokens":Nt.totalTokens,"ai.usage.reasoningTokens":Nt.reasoningTokens,"ai.usage.cachedInputTokens":Nt.cachedInputTokens,"gen_ai.response.finish_reasons":[vn],"gen_ai.response.id":Bt.id,"gen_ai.response.model":Bt.modelId,"gen_ai.usage.input_tokens":Nt.inputTokens,"gen_ai.usage.output_tokens":Nt.outputTokens}}))}catch{}finally{nr.end()}he.enqueue({type:"finish-step",finishReason:vn,usage:Nt,providerMetadata:nc,response:{...Bt,headers:He?.headers}});const so=Kp(Ne,Nt);await z.promise;const ao=ia.filter(or=>or.providerExecuted!==!0),la=ec.filter(or=>or.providerExecuted!==!0);if(ao.length>0&&la.length===ao.length&&!await o0({stopConditions:p,steps:V})){le.push(...ti({content:V[V.length-1].content,tools:c}));try{await Y({currentStep:oe+1,responseMessages:le,usage:so})}catch(or){he.enqueue({type:"error",error:or}),B.closeStream()}}else he.enqueue({type:"finish",finishReason:vn,totalUsage:so}),B.closeStream()}})))}await Y({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(W=>{B.addStream(new ReadableStream({start(Y){Y.enqueue({type:"error",error:W}),Y.close()}})),B.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ro(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ro(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Fb({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new op;return Ro(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=Fr}={}){const c=t!=null?qb({originalMessages:e,responseMessageId:t}):void 0,u={},g=d=>{var p,w;const m=u[d];return((w=(p=this.tools)==null?void 0:p[m])==null?void 0:w.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(d,p)=>{const w=n?.({part:d}),m=d.type;switch(m){case"text-start":{p.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{p.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{p.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{p.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{o&&p.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{p.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{p.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{s&&d.sourceType==="url"&&p.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),s&&d.sourceType==="document"&&p.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const y=g(d.id);p.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{p.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const y=g(d.toolCallId);d.invalid?p.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(d.error)}):p.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=g(d.toolCallId);p.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=g(d.toolCallId);p.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{p.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{p.enqueue({type:"start-step"});break}case"finish-step":{p.enqueue({type:"finish-step"});break}case"start":{a&&p.enqueue({type:"start",...w!=null?{messageMetadata:w}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&p.enqueue({type:"finish",finishReason:d.finishReason,...w!=null?{messageMetadata:w}:{}});break}case"abort":{p.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const y=m;throw new Error(`Unknown chunk type: ${y}`)}}w!=null&&m!=="start"&&m!=="finish"&&p.enqueue({type:"message-metadata",messageMetadata:w})}}));return Ro(Db({stream:h,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){Zb({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){Nb({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...c}={}){return Ab({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return Mb({textStream:this.textStream,...e})}};En({prefix:"aiobj",size:24}),En({prefix:"aiobj",size:24});var Kb={};U3(Kb,{object:()=>Qb,text:()=>Yb});var Yb=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Qb=({schema:e})=>{const t=ko(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await p0(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const o=n.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:r},n){const o=await Tr({text:r});if(!o.success)throw new vp({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const s=await Tt({value:o.value,schema:t});if(!s.success)throw new vp({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return s.value}}};let oi;oi=globalThis.crypto;async function Xb(e){return(await oi).getRandomValues(new Uint8Array(e))}async function e9(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await Xb(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function t9(e){return await e9(e)}async function r9(e){const t=await(await oi).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function m0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await t9(e),r=await r9(t);return{code_verifier:t,code_challenge:r}}var n9="AI_MCPClientError",g0=`vercel.ai.error.${n9}`,o9=Symbol.for(g0),v0,_0,Ie=class extends(_0=ue,v0=o9,_0){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[v0]=!0,this.data=n,this.code=o}static isInstance(e){return ue.hasMarker(e,g0)}},Qr="2025-06-18",s9=[Qr,"2025-03-26","2024-11-05"],a9=ze({name:v(),version:v()}),Po=ze({_meta:K(T({}).loose())}),Gt=Po,y0=T({method:v(),params:K(Po)}),w0=T({applyDefaults:K(ce())}).loose(),i9=ze({experimental:K(T({}).loose()),logging:K(T({}).loose()),prompts:K(ze({listChanged:K(ce())})),resources:K(ze({subscribe:K(ce()),listChanged:K(ce())})),tools:K(ze({listChanged:K(ce())})),elicitation:K(w0)});T({elicitation:K(w0)}).loose();var l9=Gt.extend({protocolVersion:v(),capabilities:i9,serverInfo:a9,instructions:K(v())}),si=Gt.extend({nextCursor:K(v())}),c9=T({name:v(),description:K(v()),inputSchema:T({type:L("object"),properties:K(T({}).loose())}).loose()}).loose(),u9=si.extend({tools:A(c9)}),b0=T({type:L("text"),text:v()}).loose(),k0=T({type:L("image"),data:Au(),mimeType:v()}).loose(),d9=T({uri:v(),name:v(),title:K(v()),description:K(v()),mimeType:K(v()),size:K(q())}).loose(),p9=si.extend({resources:A(d9)}),S0=T({uri:v(),name:K(v()),title:K(v()),mimeType:K(v())}).loose(),C0=S0.extend({text:v()}),T0=S0.extend({blob:Au()}),$0=T({type:L("resource"),resource:ne([C0,T0])}).loose(),f9=Gt.extend({content:A(ne([b0,k0,$0])),isError:ce().default(!1).optional()}).or(Gt.extend({toolResult:$e()})),h9=T({uriTemplate:v(),name:v(),title:K(v()),description:K(v()),mimeType:K(v())}).loose(),m9=Gt.extend({resourceTemplates:A(h9)}),g9=Gt.extend({contents:A(ne([C0,T0]))}),v9=T({name:v(),description:K(v()),required:K(ce())}).loose(),_9=T({name:v(),title:K(v()),description:K(v()),arguments:K(A(v9))}).loose(),y9=si.extend({prompts:A(_9)}),w9=T({role:ne([L("user"),L("assistant")]),content:ne([b0,k0,$0])}).loose(),b9=Gt.extend({description:K(v()),messages:A(w9)}),k9=Po.extend({message:v(),requestedSchema:$e()}),E0=y0.extend({method:L("elicitation/create"),params:k9}),S9=Gt.extend({action:ne([L("accept"),L("decline"),L("cancel")]),content:K(ve(v(),$e()))}),Oo="2.0",C9=T({jsonrpc:L(Oo),id:ne([v(),q().int()])}).merge(y0).strict(),T9=T({jsonrpc:L(Oo),id:ne([v(),q().int()]),result:Gt}).strict(),$9=T({jsonrpc:L(Oo),id:ne([v(),q().int()]),error:T({code:q().int(),message:v(),data:K($e())})}).strict(),E9=T({jsonrpc:L(Oo)}).merge(T({method:v(),params:K(Po)})).strict(),Un=ne([C9,E9,T9,$9]),I0=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",x0=T({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:q().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),lt=v().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bu.custom,message:"URL must be parseable",fatal:!0}),Vc}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),I9=T({resource:v().url(),authorization_servers:A(lt).optional(),jwks_uri:v().url().optional(),scopes_supported:A(v()).optional(),bearer_methods_supported:A(v()).optional(),resource_signing_alg_values_supported:A(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ce().optional(),authorization_details_types_supported:A(v()).optional(),dpop_signing_alg_values_supported:A(v()).optional(),dpop_bound_access_tokens_required:ce().optional()}).passthrough(),R0=T({issuer:v(),authorization_endpoint:lt,token_endpoint:lt,registration_endpoint:lt.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),grant_types_supported:A(v()).optional(),code_challenge_methods_supported:A(v()),token_endpoint_auth_methods_supported:A(v()).optional(),token_endpoint_auth_signing_alg_values_supported:A(v()).optional()}).passthrough(),x9=T({issuer:v(),authorization_endpoint:lt,token_endpoint:lt,userinfo_endpoint:lt.optional(),jwks_uri:lt,registration_endpoint:lt.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),grant_types_supported:A(v()).optional(),subject_types_supported:A(v()),id_token_signing_alg_values_supported:A(v()),claims_supported:A(v()).optional(),token_endpoint_auth_methods_supported:A(v()).optional()}).passthrough(),R9=x9.merge(R0.pick({code_challenge_methods_supported:!0})),P9=T({client_id:v(),client_secret:v().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional()}).strip(),O9=T({redirect_uris:A(lt),token_endpoint_auth_method:v().optional(),grant_types:A(v()).optional(),response_types:A(v()).optional(),client_name:v().optional(),client_uri:lt.optional(),logo_uri:lt.optional(),scope:v().optional(),contacts:A(v()).optional(),tos_uri:lt.optional(),policy_uri:v().optional(),jwks_uri:lt.optional(),jwks:et().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),M9=T({error:v(),error_description:v().optional(),error_uri:v().optional()}),N9=O9.merge(P9),A9="AI_MCPClientOAuthError",P0=`vercel.ai.error.${A9}`,q9=Symbol.for(P0),O0,M0,zn=class extends(M0=ue,O0=q9,M0){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[O0]=!0}static isInstance(e){return ue.hasMarker(e,P0)}},Xr=class extends zn{};Xr.errorCode="server_error";var Mo=class extends zn{};Mo.errorCode="invalid_client";var No=class extends zn{};No.errorCode="invalid_grant";var Ao=class extends zn{};Ao.errorCode="unauthorized_client";var L9={[Xr.errorCode]:Xr,[Mo.errorCode]:Mo,[No.errorCode]:No,[Ao.errorCode]:Ao};function j9(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function U9({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var qo=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Lo(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const s=/resource_metadata="([^"]*)"/,a=r.match(s);if(a)try{return new URL(a[1])}catch{return}}function z9(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function ai(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?ai(e,void 0,r):void 0;throw n}}async function N0(e,t,r=fetch){return await ai(e,{"MCP-Protocol-Version":t},r)}function D9(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Z9(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:Qr;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=z9(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await N0(l,i,r);if(!n?.metadataUrl&&D9(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await N0(u,i,r)}return c}async function F9(e,t,r=fetch){const n=await Z9(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return I9.parse(await n.json())}function V9(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function H9(e,{fetchFn:t=fetch,protocolVersion:r=Qr}={}){var n;const o={"MCP-Protocol-Version":r},s=V9(e);for(const{url:a,type:i}of s){const l=await ai(a,o,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return R0.parse(await l.json());{const c=R9.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function B9(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){const i="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",e);const u=await m0(),g=u.code_verifier,h=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",h),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:g}}function A0(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function q0(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":J9(o,s,r);return;case"client_secret_post":G9(o,s,n);return;case"none":W9(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function J9(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function G9(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function W9(e,t){t.set("client_id",e)}async function ii(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=M9.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=L9[o]||Xr;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Xr({message:o})}}async function K9(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",g=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(h,d,e,t);else{const w=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],m=A0(r,w);q0(m,r,h,d)}a&&d.set("resource",a.href);const p=await(l??fetch)(g,{method:"POST",headers:h,body:d});if(!p.ok)throw await ii(p);return x0.parse(await p.json())}async function Y9(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),g=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,g,e,t);else{const d=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],p=A0(r,d);q0(p,r,u,g)}o&&g.set("resource",o.href);const h=await(a??fetch)(c,{method:"POST",headers:u,body:g});if(!h.ok)throw await ii(h);return x0.parse({refresh_token:n,...await h.json()})}async function Q9(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await ii(s);return N9.parse(await s.json())}async function jo(e,t){var r,n;try{return await li(e,t)}catch(o){if(o instanceof Mo||o instanceof Ao)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await li(e,t);if(o instanceof No)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await li(e,t);throw o}}async function X9(e,t,r){const n=j9(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!U9({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function li(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await F9(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await X9(t,e,a),c=await H9(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const w=await Q9(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(w),u=w}if(r!==void 0){const w=await e.codeVerifier(),m=await K9(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:w,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}const g=await e.tokens();if(g?.refresh_token)try{const w=await Y9(i,{metadata:c,clientInformation:u,refreshToken:g.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof zn)||w instanceof Xr))throw w}const h=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:p}=await B9(i,{metadata:c,clientInformation:u,state:h,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(p),await e.redirectToAuthorization(d),"REDIRECT"}var e4=class{constructor({url:e,headers:t,authProvider:r}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Qr};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return cr(t,`ai-sdk/${I0}`,xn())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Lo(u);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new qo;return(s=this.onerror)==null||s.call(this,w),t(w)}}catch(p){return(a=this.onerror)==null||a.call(this,p),t(p)}return r(!0)}if(!u.ok||!u.body){let p=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(p+=". This server does not support SSE transport. Try using `http` transport instead");const w=new Ie({message:p});return(i=this.onerror)==null||i.call(this,w),t(w)}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader(),d=async()=>{var p,w,m;try{for(;;){const{done:y,value:_}=await h.read();if(y){if(this.connected)throw this.connected=!1,new Ie({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:f,data:b}=_;if(f==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new Ie({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(f==="message")try{const k=Un.parse(JSON.parse(b));(p=this.onmessage)==null||p.call(this,k)}catch(k){const S=new Ie({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(w=this.onerror)==null||w.call(this,S)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(m=this.onerror)==null||m.call(this,y),t(y)}};this.sseConnection={close:()=>h.cancel()},d()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Ie({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},g=await fetch(t,u);if(g.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Lo(g);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new qo;(s=this.onerror)==null||s.call(this,d);return}}catch(h){(a=this.onerror)==null||a.call(this,h);return}return r(!0)}if(!g.ok){const h=await g.text().catch(()=>null),d=new Ie({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${g.status}): ${h}`});(i=this.onerror)==null||i.call(this,d);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},t4=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Qr};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return cr(t,`ai-sdk/${I0}`,xn())}async start(){if(this.abortController)throw new Ie({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,a,i,l,c;try{const g={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},h=await fetch(this.url,g),d=h.headers.get("mcp-session-id");if(d&&(this.sessionId=d),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Lo(h);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new qo}catch(m){throw(o=this.onerror)==null||o.call(this,m),m}return t(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const m=await h.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${m}`;h.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const _=new Ie({message:y});throw(s=this.onerror)==null||s.call(this,_),_}const p=h.headers.get("content-type")||"";if(p.includes("application/json")){const m=await h.json(),y=Array.isArray(m)?m.map(_=>Un.parse(_)):[Un.parse(m)];for(const _ of y)(a=this.onmessage)==null||a.call(this,_);return}if(p.includes("text/event-stream")){if(!h.body){const f=new Ie({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,f),f}const y=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader();(async()=>{var f,b,k;try{for(;;){const{done:S,value:C}=await y.read();if(S)return;const{event:I,data:x}=C;if(I==="message")try{const M=Un.parse(JSON.parse(x));(f=this.onmessage)==null||f.call(this,M)}catch(M){const P=new Ie({message:"MCP HTTP Transport Error: Failed to parse message",cause:M});(b=this.onerror)==null||b.call(this,P)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const w=new Ie({message:`MCP HTTP Transport Error: Unexpected content type: ${p}`});throw(l=this.onerror)==null||l.call(this,w),w}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Ie({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await fetch(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Lo(c);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new qo;(n=this.onerror)==null||n.call(this,w);return}}catch(p){(o=this.onerror)==null||o.call(this,p);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const p=new Ie({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,p);return}const h=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader(),d=async()=>{var p,w,m,y;try{for(;;){const{done:_,value:f}=await h.read();if(_)return;const{event:b,data:k,id:S}=f;if(S&&(this.lastInboundEventId=S),b==="message")try{const C=Un.parse(JSON.parse(k));(p=this.onmessage)==null||p.call(this,C)}catch(C){const I=new Ie({message:"MCP HTTP Transport Error: Failed to parse message",cause:C});(w=this.onerror)==null||w.call(this,I)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(m=this.onerror)==null||m.call(this,_),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,d()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function r4(e){switch(e.type){case"sse":return new e4(e);case"http":return new t4(e);default:throw new Ie({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function n4(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var o4="1.0.0";async function s4(e){const t=new a4(e);return await t.init(),t}var a4=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=o4,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},n4(e)?this.transport=e:this.transport=r4(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new Ie({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Qr,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:l9});if(e===void 0)throw new Ie({message:"Server sent invalid initialize result"});if(!s9.includes(e.protocolVersion))throw new Ie({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Ie({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Ie({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Ie({message:"Server does not support prompts"});break;default:throw new Ie({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Ie({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s?.aborted)return o(new Ie({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const g=new Ie({message:"Failed to parse server response",cause:u});o(g)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:u9,options:t})}catch(r){throw r}}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:f9,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:p9,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:g9,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:m9,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:y9,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:b9,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const r={};try{const n=await this.listTools();for(const{name:o,description:s,inputSchema:a}of n.tools){if(e!=="automatic"&&!(o in e))continue;const i=this,l=async(u,g)=>{var h;return(h=g?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:o,args:u,options:g})},c=e==="automatic"?td({description:s,inputSchema:Rn({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};r[o]=c}return r}catch(n){throw n}}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==E0)throw new Ie({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=E0.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=S9.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new Ie({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new Ie({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Ie({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function Uo(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function L0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Uo(t.headers),...Uo(n.headers)}:t.headers};return e(r,o)}:e}const zo="2025-11-25",i4=[zo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Wt="io.modelcontextprotocol/related-task",Do="2.0",zt=Vu(e=>e!==null&&(typeof e=="object"||typeof e=="function")),j0=ne([v(),q().int()]),U0=v(),l4=ze({ttl:ne([q(),wa()]).optional(),pollInterval:q().optional()}),ci=ze({taskId:v()}),c4=ze({progressToken:j0.optional(),[Wt]:ci.optional()}),ct=ze({task:l4.optional(),_meta:c4.optional()}),Be=T({method:v(),params:ct.optional()}),Pr=ze({_meta:T({[Wt]:K(ci)}).passthrough().optional()}),bt=T({method:v(),params:Pr.optional()}),Ye=ze({_meta:ze({[Wt]:ci.optional()}).optional()}),Zo=ne([v(),q().int()]),z0=T({jsonrpc:L(Do),id:Zo,...Be.shape}).strict(),ui=e=>z0.safeParse(e).success,D0=T({jsonrpc:L(Do),...bt.shape}).strict(),u4=e=>D0.safeParse(e).success,Z0=T({jsonrpc:L(Do),id:Zo,result:Ye}).strict(),Dn=e=>Z0.safeParse(e).success;var ge;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ge||(ge={}));const F0=T({jsonrpc:L(Do),id:Zo,error:T({code:q().int(),message:v(),data:K($e())})}).strict(),d4=e=>F0.safeParse(e).success,Or=ne([z0,D0,Z0,F0]),Mr=Ye.strict(),p4=Pr.extend({requestId:Zo,reason:v().optional()}),di=bt.extend({method:L("notifications/cancelled"),params:p4}),f4=T({src:v(),mimeType:v().optional(),sizes:A(v()).optional()}),Zn=T({icons:A(f4).optional()}),en=T({name:v(),title:v().optional()}),V0=en.extend({...en.shape,...Zn.shape,version:v(),websiteUrl:v().optional()}),h4=ba(T({applyDefaults:ce().optional()}),ve(v(),$e())),m4=Hu(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ba(T({form:h4.optional(),url:zt.optional()}),ve(v(),$e()).optional())),g4=T({list:K(T({}).passthrough()),cancel:K(T({}).passthrough()),requests:K(T({sampling:K(T({createMessage:K(T({}).passthrough())}).passthrough()),elicitation:K(T({create:K(T({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),v4=T({list:K(T({}).passthrough()),cancel:K(T({}).passthrough()),requests:K(T({tools:K(T({call:K(T({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),_4=T({experimental:ve(v(),zt).optional(),sampling:T({context:zt.optional(),tools:zt.optional()}).optional(),elicitation:m4.optional(),roots:T({listChanged:ce().optional()}).optional(),tasks:K(g4)}),y4=ct.extend({protocolVersion:v(),capabilities:_4,clientInfo:V0}),w4=Be.extend({method:L("initialize"),params:y4}),b4=T({experimental:ve(v(),zt).optional(),logging:zt.optional(),completions:zt.optional(),prompts:K(T({listChanged:K(ce())})),resources:T({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:T({listChanged:ce().optional()}).optional(),tasks:K(v4)}).passthrough(),H0=Ye.extend({protocolVersion:v(),capabilities:b4,serverInfo:V0,instructions:v().optional()}),B0=bt.extend({method:L("notifications/initialized")}),k4=e=>B0.safeParse(e).success,pi=Be.extend({method:L("ping")}),S4=T({progress:q(),total:K(q()),message:K(v())}),C4=T({...Pr.shape,...S4.shape,progressToken:j0}),fi=bt.extend({method:L("notifications/progress"),params:C4}),T4=ct.extend({cursor:U0.optional()}),Fn=Be.extend({params:T4.optional()}),Vn=Ye.extend({nextCursor:K(U0)}),Hn=T({taskId:v(),status:_e(["working","input_required","completed","failed","cancelled"]),ttl:ne([q(),wa()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:K(q()),statusMessage:K(v())}),Bn=Ye.extend({task:Hn}),$4=Pr.merge(Hn),Fo=bt.extend({method:L("notifications/tasks/status"),params:$4}),hi=Be.extend({method:L("tasks/get"),params:ct.extend({taskId:v()})}),mi=Ye.merge(Hn),gi=Be.extend({method:L("tasks/result"),params:ct.extend({taskId:v()})}),vi=Fn.extend({method:L("tasks/list")}),_i=Vn.extend({tasks:A(Hn)}),E4=Be.extend({method:L("tasks/cancel"),params:ct.extend({taskId:v()})}),I4=Ye.merge(Hn),J0=T({uri:v(),mimeType:K(v()),_meta:ve(v(),$e()).optional()}),G0=J0.extend({text:v()}),yi=v().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),W0=J0.extend({blob:yi}),tn=T({audience:A(_e(["user","assistant"])).optional(),priority:q().min(0).max(1).optional(),lastModified:Ru({offset:!0}).optional()}),K0=T({...en.shape,...Zn.shape,uri:v(),description:K(v()),mimeType:K(v()),annotations:tn.optional(),_meta:K(ze({}))}),x4=T({...en.shape,...Zn.shape,uriTemplate:v(),description:K(v()),mimeType:K(v()),annotations:tn.optional(),_meta:K(ze({}))}),R4=Fn.extend({method:L("resources/list")}),Y0=Vn.extend({resources:A(K0)}),P4=Fn.extend({method:L("resources/templates/list")}),Q0=Vn.extend({resourceTemplates:A(x4)}),wi=ct.extend({uri:v()}),O4=wi,M4=Be.extend({method:L("resources/read"),params:O4}),X0=Ye.extend({contents:A(ne([G0,W0]))}),ef=bt.extend({method:L("notifications/resources/list_changed")}),N4=wi,A4=Be.extend({method:L("resources/subscribe"),params:N4}),q4=wi,L4=Be.extend({method:L("resources/unsubscribe"),params:q4}),j4=Pr.extend({uri:v()}),tf=bt.extend({method:L("notifications/resources/updated"),params:j4}),U4=T({name:v(),description:K(v()),required:K(ce())}),z4=T({...en.shape,...Zn.shape,description:K(v()),arguments:K(A(U4)),_meta:K(ze({}))}),D4=Fn.extend({method:L("prompts/list")}),rf=Vn.extend({prompts:A(z4)}),Z4=ct.extend({name:v(),arguments:ve(v(),v()).optional()}),F4=Be.extend({method:L("prompts/get"),params:Z4}),bi=T({type:L("text"),text:v(),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),ki=T({type:L("image"),data:yi,mimeType:v(),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),Si=T({type:L("audio"),data:yi,mimeType:v(),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),V4=T({type:L("tool_use"),name:v(),id:v(),input:T({}).passthrough(),_meta:K(T({}).passthrough())}).passthrough(),H4=T({type:L("resource"),resource:ne([G0,W0]),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),B4=K0.extend({type:L("resource_link")}),Ci=ne([bi,ki,Si,B4,H4]),J4=T({role:_e(["user","assistant"]),content:Ci}),nf=Ye.extend({description:K(v()),messages:A(J4)}),of=bt.extend({method:L("notifications/prompts/list_changed")}),G4=T({title:v().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),W4=T({taskSupport:_e(["required","optional","forbidden"]).optional()}),sf=T({...en.shape,...Zn.shape,description:v().optional(),inputSchema:T({type:L("object"),properties:ve(v(),zt).optional(),required:A(v()).optional()}).catchall($e()),outputSchema:T({type:L("object"),properties:ve(v(),zt).optional(),required:A(v()).optional()}).catchall($e()).optional(),annotations:K(G4),execution:K(W4),_meta:ve(v(),$e()).optional()}),K4=Fn.extend({method:L("tools/list")}),af=Vn.extend({tools:A(sf)}),Jn=Ye.extend({content:A(Ci).default([]),structuredContent:ve(v(),$e()).optional(),isError:K(ce())});Jn.or(Ye.extend({toolResult:$e()}));const Y4=ct.extend({name:v(),arguments:K(ve(v(),$e()))}),Q4=Be.extend({method:L("tools/call"),params:Y4}),lf=bt.extend({method:L("notifications/tools/list_changed")}),cf=_e(["debug","info","notice","warning","error","critical","alert","emergency"]),X4=ct.extend({level:cf}),e6=Be.extend({method:L("logging/setLevel"),params:X4}),t6=Pr.extend({level:cf,logger:v().optional(),data:$e()}),uf=bt.extend({method:L("notifications/message"),params:t6}),r6=T({name:v().optional()}),n6=T({hints:K(A(r6)),costPriority:K(q().min(0).max(1)),speedPriority:K(q().min(0).max(1)),intelligencePriority:K(q().min(0).max(1))}),o6=T({mode:K(_e(["auto","required","none"]))}),s6=T({type:L("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:A(Ci).default([]),structuredContent:T({}).passthrough().optional(),isError:K(ce()),_meta:K(T({}).passthrough())}).passthrough(),a6=Ze("type",[bi,ki,Si]),Vo=Ze("type",[bi,ki,Si,V4,s6]),i6=T({role:_e(["user","assistant"]),content:ne([Vo,A(Vo)]),_meta:K(T({}).passthrough())}).passthrough(),l6=ct.extend({messages:A(i6),modelPreferences:n6.optional(),systemPrompt:v().optional(),includeContext:_e(["none","thisServer","allServers"]).optional(),temperature:q().optional(),maxTokens:q().int(),stopSequences:A(v()).optional(),metadata:zt.optional(),tools:K(A(sf)),toolChoice:K(o6)}),Ti=Be.extend({method:L("sampling/createMessage"),params:l6}),$i=Ye.extend({model:v(),stopReason:K(_e(["endTurn","stopSequence","maxTokens"]).or(v())),role:_e(["user","assistant"]),content:a6}),c6=Ye.extend({model:v(),stopReason:K(_e(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:_e(["user","assistant"]),content:ne([Vo,A(Vo)])}),u6=T({type:L("boolean"),title:v().optional(),description:v().optional(),default:ce().optional()}),d6=T({type:L("string"),title:v().optional(),description:v().optional(),minLength:q().optional(),maxLength:q().optional(),format:_e(["email","uri","date","date-time"]).optional(),default:v().optional()}),p6=T({type:_e(["number","integer"]),title:v().optional(),description:v().optional(),minimum:q().optional(),maximum:q().optional(),default:q().optional()}),f6=T({type:L("string"),title:v().optional(),description:v().optional(),enum:A(v()),default:v().optional()}),h6=T({type:L("string"),title:v().optional(),description:v().optional(),oneOf:A(T({const:v(),title:v()})),default:v().optional()}),m6=T({type:L("string"),title:v().optional(),description:v().optional(),enum:A(v()),enumNames:A(v()).optional(),default:v().optional()}),g6=ne([f6,h6]),v6=T({type:L("array"),title:v().optional(),description:v().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({type:L("string"),enum:A(v())}),default:A(v()).optional()}),_6=T({type:L("array"),title:v().optional(),description:v().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({anyOf:A(T({const:v(),title:v()}))}),default:A(v()).optional()}),y6=ne([v6,_6]),w6=ne([m6,g6,y6]),b6=ne([w6,u6,d6,p6]),k6=ct.extend({mode:L("form").optional(),message:v(),requestedSchema:T({type:L("object"),properties:ve(v(),b6),required:A(v()).optional()})}),S6=ct.extend({mode:L("url"),message:v(),elicitationId:v(),url:v().url()}),C6=ne([k6,S6]),Ei=Be.extend({method:L("elicitation/create"),params:C6}),T6=Pr.extend({elicitationId:v()}),$6=bt.extend({method:L("notifications/elicitation/complete"),params:T6}),Ii=Ye.extend({action:_e(["accept","decline","cancel"]),content:Hu(e=>e===null?void 0:e,ve(v(),ne([v(),q(),ce(),A(v())])).optional())}),E6=T({type:L("ref/resource"),uri:v()}),I6=T({type:L("ref/prompt"),name:v()}),x6=ct.extend({ref:ne([I6,E6]),argument:T({name:v(),value:v()}),context:T({arguments:ve(v(),v()).optional()}).optional()}),R6=Be.extend({method:L("completion/complete"),params:x6}),df=Ye.extend({completion:ze({values:A(v()).max(100),total:K(q().int()),hasMore:K(ce())})}),P6=T({uri:v().startsWith("file://"),name:v().optional(),_meta:ve(v(),$e()).optional()}),pf=Be.extend({method:L("roots/list")}),ff=Ye.extend({roots:A(P6)}),O6=bt.extend({method:L("notifications/roots/list_changed")});ne([pi,w4,R6,e6,F4,D4,R4,P4,M4,A4,L4,Q4,K4,hi,gi,vi]),ne([di,fi,B0,O6,Fo]),ne([Mr,$i,c6,Ii,ff,mi,_i,Bn]),ne([pi,Ti,Ei,pf,hi,gi,vi]),ne([di,fi,uf,tf,ef,lf,of,Fo,$6]),ne([Mr,H0,df,nf,rf,Y0,Q0,X0,Jn,af,mi,_i,Bn]);class de extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===ge.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new M6(o.elicitations,r)}return new de(t,r,n)}}class M6 extends de{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ge.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){var t,r;return(r=(t=this.data)===null||t===void 0?void 0:t.elicitations)!==null&&r!==void 0?r:[]}}const Je=Wv().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bu.custom,message:"URL must be parseable",fatal:!0}),Vc}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),N6=ze({resource:v().url(),authorization_servers:A(Je).optional(),jwks_uri:v().url().optional(),scopes_supported:A(v()).optional(),bearer_methods_supported:A(v()).optional(),resource_signing_alg_values_supported:A(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ce().optional(),authorization_details_types_supported:A(v()).optional(),dpop_signing_alg_values_supported:A(v()).optional(),dpop_bound_access_tokens_required:ce().optional()}),hf=ze({issuer:v(),authorization_endpoint:Je,token_endpoint:Je,registration_endpoint:Je.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),response_modes_supported:A(v()).optional(),grant_types_supported:A(v()).optional(),token_endpoint_auth_methods_supported:A(v()).optional(),token_endpoint_auth_signing_alg_values_supported:A(v()).optional(),service_documentation:Je.optional(),revocation_endpoint:Je.optional(),revocation_endpoint_auth_methods_supported:A(v()).optional(),revocation_endpoint_auth_signing_alg_values_supported:A(v()).optional(),introspection_endpoint:v().optional(),introspection_endpoint_auth_methods_supported:A(v()).optional(),introspection_endpoint_auth_signing_alg_values_supported:A(v()).optional(),code_challenge_methods_supported:A(v()).optional(),client_id_metadata_document_supported:ce().optional()}),A6=ze({issuer:v(),authorization_endpoint:Je,token_endpoint:Je,userinfo_endpoint:Je.optional(),jwks_uri:Je,registration_endpoint:Je.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),response_modes_supported:A(v()).optional(),grant_types_supported:A(v()).optional(),acr_values_supported:A(v()).optional(),subject_types_supported:A(v()),id_token_signing_alg_values_supported:A(v()),id_token_encryption_alg_values_supported:A(v()).optional(),id_token_encryption_enc_values_supported:A(v()).optional(),userinfo_signing_alg_values_supported:A(v()).optional(),userinfo_encryption_alg_values_supported:A(v()).optional(),userinfo_encryption_enc_values_supported:A(v()).optional(),request_object_signing_alg_values_supported:A(v()).optional(),request_object_encryption_alg_values_supported:A(v()).optional(),request_object_encryption_enc_values_supported:A(v()).optional(),token_endpoint_auth_methods_supported:A(v()).optional(),token_endpoint_auth_signing_alg_values_supported:A(v()).optional(),display_values_supported:A(v()).optional(),claim_types_supported:A(v()).optional(),claims_supported:A(v()).optional(),service_documentation:v().optional(),claims_locales_supported:A(v()).optional(),ui_locales_supported:A(v()).optional(),claims_parameter_supported:ce().optional(),request_parameter_supported:ce().optional(),request_uri_parameter_supported:ce().optional(),require_request_uri_registration:ce().optional(),op_policy_uri:Je.optional(),op_tos_uri:Je.optional(),client_id_metadata_document_supported:ce().optional()}),q6=T({...A6.shape,...hf.pick({code_challenge_methods_supported:!0}).shape}),L6=T({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:Ju().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),j6=T({error:v(),error_description:v().optional(),error_uri:v().optional()}),mf=Je.optional().or(L("").transform(()=>{})),U6=T({redirect_uris:A(Je),token_endpoint_auth_method:v().optional(),grant_types:A(v()).optional(),response_types:A(v()).optional(),client_name:v().optional(),client_uri:Je.optional(),logo_uri:mf,scope:v().optional(),contacts:A(v()).optional(),tos_uri:mf,policy_uri:v().optional(),jwks_uri:Je.optional(),jwks:et().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),z6=T({client_id:v(),client_secret:v().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional()}).strip(),D6=U6.merge(z6);T({error:v(),error_description:v().optional()}).strip(),T({token:v(),token_type_hint:v().optional()}).strip();function Z6(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function F6({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class Ve extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class xi extends Ve{}xi.errorCode="invalid_request";class Ho extends Ve{}Ho.errorCode="invalid_client";class Bo extends Ve{}Bo.errorCode="invalid_grant";class Jo extends Ve{}Jo.errorCode="unauthorized_client";class Ri extends Ve{}Ri.errorCode="unsupported_grant_type";class Pi extends Ve{}Pi.errorCode="invalid_scope";class Oi extends Ve{}Oi.errorCode="access_denied";class rn extends Ve{}rn.errorCode="server_error";class Mi extends Ve{}Mi.errorCode="temporarily_unavailable";class Ni extends Ve{}Ni.errorCode="unsupported_response_type";class Ai extends Ve{}Ai.errorCode="unsupported_token_type";class qi extends Ve{}qi.errorCode="invalid_token";class Li extends Ve{}Li.errorCode="method_not_allowed";class ji extends Ve{}ji.errorCode="too_many_requests";class Go extends Ve{}Go.errorCode="invalid_client_metadata";class Ui extends Ve{}Ui.errorCode="insufficient_scope";class zi extends Ve{}zi.errorCode="invalid_target";const V6={[xi.errorCode]:xi,[Ho.errorCode]:Ho,[Bo.errorCode]:Bo,[Jo.errorCode]:Jo,[Ri.errorCode]:Ri,[Pi.errorCode]:Pi,[Oi.errorCode]:Oi,[rn.errorCode]:rn,[Mi.errorCode]:Mi,[Ni.errorCode]:Ni,[Ai.errorCode]:Ai,[qi.errorCode]:qi,[Li.errorCode]:Li,[ji.errorCode]:ji,[Go.errorCode]:Go,[Ui.errorCode]:Ui,[zi.errorCode]:zi};class kt extends Error{constructor(t){super(t??"Unauthorized")}}function H6(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Di="code",Zi="S256";function B6(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&H6(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function J6(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":G6(o,s,r);return;case"client_secret_post":W6(o,s,n);return;case"none":K6(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function G6(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function W6(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function K6(e,t){t.set("client_id",e)}async function gf(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=j6.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=V6[o]||rn;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new rn(o)}}async function Nr(e,t){var r,n;try{return await Fi(e,t)}catch(o){if(o instanceof Ho||o instanceof Jo)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"all")),await Fi(e,t);if(o instanceof Bo)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"tokens")),await Fi(e,t);throw o}}async function Fi(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){var a,i;let l,c;try{l=await X6(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",t));const u=await Q6(t,e,l),g=await o5(c,{fetchFn:s});let h=await Promise.resolve(e.clientInformation());if(!h){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const _=g?.client_id_metadata_document_supported===!0,f=e.clientMetadataUrl;if(f&&!Y6(f))throw new Go(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${f}`);if(_&&f)h={client_id:f},await((a=e.saveClientInformation)===null||a===void 0?void 0:a.call(e,h));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const k=await c5(c,{metadata:g,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(k),h=k}}const d=!e.redirectUrl;if(r!==void 0||d){const _=await l5(e,c,{metadata:g,resource:u,authorizationCode:r,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const _=await i5(c,{metadata:g,clientInformation:h,refreshToken:p.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof Ve)||_ instanceof rn))throw _}const w=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await s5(c,{metadata:g,clientInformation:h,state:w,redirectUrl:e.redirectUrl,scope:n||((i=l?.scopes_supported)===null||i===void 0?void 0:i.join(" "))||e.clientMetadata.scope,resource:u});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function Y6(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Q6(e,t,r){const n=Z6(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!F6({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Wo(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Vi(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=Vi(e,"scope")||void 0,i=Vi(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function Vi(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function X6(e,t,r=fetch){var n,o;const s=await r5(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!s||s.status===404)throw await((n=s?.body)===null||n===void 0?void 0:n.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!s.ok)throw await((o=s.body)===null||o===void 0?void 0:o.cancel()),new Error(`HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`);return N6.parse(await s.json())}async function Hi(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Hi(e,void 0,r):void 0;throw n}}function e5(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function vf(e,t,r=fetch){return await Hi(e,{"MCP-Protocol-Version":t},r)}function t5(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function r5(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!==null&&o!==void 0?o:zo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=e5(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:a),l.search=a.search}let c=await vf(l,i,r);if(!n?.metadataUrl&&t5(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await vf(u,i,r)}return c}function n5(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function o5(e,{fetchFn:t=fetch,protocolVersion:r=zo}={}){var n;const o={"MCP-Protocol-Version":r,Accept:"application/json"},s=n5(e);for(const{url:a,type:i}of s){const l=await Hi(a,o,t);if(l){if(!l.ok){if(await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?hf.parse(await l.json()):q6.parse(await l.json())}}}async function s5(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Di))throw new Error(`Incompatible auth server: does not support response type ${Di}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Zi))throw new Error(`Incompatible auth server: does not support code challenge method ${Zi}`)}else i=new URL("/authorize",e);const l=await m0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Di),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Zi),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function a5(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function _f(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){var i;const l=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,l,t);else if(n){const g=(i=t?.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],h=B6(n,g);J6(h,n,c,r)}const u=await(a??fetch)(l,{method:"POST",headers:c,body:r});if(!u.ok)throw await gf(u);return L6.parse(await u.json())}async function i5(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await _f(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function l5(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();i=a5(o,c,e.redirectUrl)}const l=await e.clientInformation();return _f(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function c5(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await gf(s);return D6.parse(await s.json())}const u5={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class nn extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Ko{constructor(t,r){var n;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=L0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:u5}async _authThenStart(){var t;if(!this._authProvider)throw new kt("No auth provider");let r;try{r=await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(t=this.onerror)===null||t===void 0||t.call(this,n),n}if(r!=="AUTHORIZED")throw new kt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const r={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(r.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Uo((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...r,...n})}async _startOrAuthSse(t){var r,n,o,s;const{resumptionToken:a}=t;try{const i=await this._commonHeaders();i.set("Accept","text/event-stream"),a&&i.set("last-event-id",a);const l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:i,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((o=l.body)===null||o===void 0?void 0:o.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new nn(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,t,!0)}catch(i){throw(s=this.onerror)===null||s===void 0||s.call(this,i),i}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){var n;const o=this._reconnectionOptions.maxRetries;if(r>=o){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,r+1)})},s)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{var u,g,h,d;try{const p=t.pipeThrough(new TextDecoderStream).pipeThrough(new Vr({onRetry:y=>{this._serverRetryMs=y}})).getReader();for(;;){const{value:y,done:_}=await p.read();if(_)break;if(y.id&&(a=y.id,i=!0,o?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{const f=Or.parse(JSON.parse(y.data));Dn(f)&&(l=!0,s!==void 0&&(f.id=s)),(u=this.onmessage)===null||u===void 0||u.call(this,f)}catch(f){(g=this.onerror)===null||g===void 0||g.call(this,f)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(p){if((h=this.onerror)===null||h===void 0||h.call(this,new Error(`SSE stream disconnected: ${p}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(y){(d=this.onerror)===null||d===void 0||d.call(this,new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new kt("No auth provider");if(await Nr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt("Failed to authorize")}async close(){var t,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)===null||t===void 0||t.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(t,r){var n,o,s,a,i,l,c;try{const{resumptionToken:u,onresumptiontoken:g}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:ui(t)?t.id:void 0}).catch(f=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,f)});return}const h=await this._commonHeaders();h.set("content-type","application/json"),h.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:h,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},p=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,d),w=p.headers.get("mcp-session-id");if(w&&(this._sessionId=w),!p.ok){const f=await p.text().catch(()=>null);if(p.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new nn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:b,scope:k}=Wo(p);if(this._resourceMetadataUrl=b,this._scope=k,await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(p.status===403&&this._authProvider){const{resourceMetadataUrl:b,scope:k,error:S}=Wo(p);if(S==="insufficient_scope"){const C=p.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===C)throw new nn(403,"Server returned 403 after trying upscoping");if(k&&(this._scope=k),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=C??void 0,await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new kt;return this.send(t)}}throw new nn(p.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,p.status===202){await((s=p.body)===null||s===void 0?void 0:s.cancel()),k4(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,f)});return}const y=(Array.isArray(t)?t:[t]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,_=p.headers.get("content-type");if(y)if(_?.includes("text/event-stream"))this._handleSseStream(p.body,{onresumptiontoken:g},!1);else if(_?.includes("application/json")){const f=await p.json(),b=Array.isArray(f)?f.map(k=>Or.parse(k)):[Or.parse(f)];for(const k of b)(a=this.onmessage)===null||a===void 0||a.call(this,k)}else throw await((i=p.body)===null||i===void 0?void 0:i.cancel()),new nn(-1,`Unexpected content type: ${_}`);else await((l=p.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var t,r,n,o;if(this._sessionId)try{const s=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:s,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,a);if(await((n=i.body)===null||n===void 0?void 0:n.cancel()),!i.ok&&i.status!==405)throw new nn(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class Yo{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Yo,r=new Yo;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(var t;this._messageQueue.length>0;){const r=this._messageQueue.shift();(t=this.onmessage)===null||t===void 0||t.call(this,r.message,r.extra)}}async close(){var t;const r=this._otherTransport;this._otherTransport=void 0,await r?.close(),(t=this.onclose)===null||t===void 0||t.call(this)}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}function Dt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Gn(e){return Object.fromEntries([...e.headers])}var d5=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new io({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},It=d5();function Bi(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var p5=["fetch failed","failed to fetch"];function f5({error:e,url:t,requestBodyValues:r}){if(Bi(e))return e;if(e instanceof TypeError&&p5.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Pe({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function h5(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function m5(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function yf(e,...t){const r=new Headers(m5(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var g5="3.0.19";function v5({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ar({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ar({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ar({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ar({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function _5({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function y5(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var w5=/"__proto__"\s*:/,b5=/"constructor"\s*:/;function wf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||w5.test(e)===!1&&b5.test(e)===!1?t:k5(t)}function k5(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){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 o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Ji(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return wf(e)}try{return wf(e)}finally{Error.stackTraceLimit=t}}var Qo=Symbol.for("vercel.ai.validator");function S5(e){return{[Qo]:!0,validate:e}}function C5(e){return typeof e=="object"&&e!==null&&Qo in e&&e[Qo]===!0&&"validate"in e}function rt(e){let t;return()=>(t==null&&(t=e()),t)}function T5(e){return C5(e)?e:typeof e=="function"?e():$5(e)}function $5(e){return S5(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new At({value:t,cause:r.issues})}})}async function dr({value:e,schema:t}){const r=await Gi({value:e,schema:t});if(!r.success)throw At.wrap({value:e,cause:r.error});return r.value}async function Gi({value:e,schema:t}){const r=T5(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:At.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:At.wrap({value:e,cause:n}),rawValue:e}}}async function E5({text:e,schema:t}){try{const r=Ji(e);return t==null?r:dr({value:r,schema:t})}catch(r){throw sr.isInstance(r)||At.isInstance(r)?r:new sr({text:e,cause:r})}}async function bf({text:e,schema:t}){try{const r=Ji(e);return t==null?{success:!0,value:r,rawValue:r}:await Gi({value:r,schema:t})}catch(r){return{success:!1,error:sr.isInstance(r)?r:new sr({text:e,cause:r}),rawValue:void 0}}}function kf(e){try{return Ji(e),!0}catch{return!1}}function I5({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await bf({text:r,schema:t}))}}))}async function pr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Gi({value:t[e],schema:r});if(!n.success)throw new io({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var x5=()=>globalThis.fetch,Kt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Sf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),R5=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Sf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Sf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=x5()})=>{try{const i=await a(e,{method:"POST",headers:yf(t,`ai-sdk/provider-utils/${g5}`,h5()),body:r.content,signal:s}),l=Gn(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Bi(u)||Pe.isInstance(u)?u:new Pe({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Bi(c)||Pe.isInstance(c))?c:new Pe({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw f5({error:i,url:e,requestBodyValues:r.values})}};function _C(e){return e}function on({id:e,name:t,inputSchema:r,outputSchema:n}){return({execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:r,outputSchema:n,execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}var P5=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Gn(n);if(a.trim()==="")return{responseHeaders:i,value:new Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await E5({text:a,schema:e});return{responseHeaders:i,value:new Pe({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Wi=e=>async({response:t})=>{const r=Gn(t);if(t.body==null)throw new fc({});return{responseHeaders:r,value:I5({stream:t.body,schema:e})}},sn=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await bf({text:o,schema:e}),a=Gn(t);if(!s.success)throw new Pe({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},O5=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Gn(e);if(!e.body)throw new Pe({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new Pe({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function Xo(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const r in t)t[r]=Xo(t[r])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>Xo(t)):e.items=Xo(e.items)),e}var M5=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},N5=Symbol("Let zodToJsonSchema decide on which parser to use"),Cf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},A5=e=>typeof e=="string"?{...Cf,name:e}:{...Cf,...e};function vt(){return{}}function q5(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==Q.ZodAny&&(s.items=xe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function L5(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function j5(){return{type:"boolean"}}function Tf(e,t){return xe(e.type._def,t)}var U5=(e,t)=>xe(e.innerType._def,t);function $f(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>$f(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return z5(e)}}var z5=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function D5(e,t){return{...xe(e.innerType._def,t),default:e.defaultValue()}}function Z5(e,t){return t.effectStrategy==="input"?xe(e.schema._def,t):vt()}function F5(e){return{type:"string",enum:Array.from(e.values)}}var V5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function H5(e,t){const r=[xe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),xe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(V5(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}n.push(s)}}),n.length?{allOf:n}:void 0}function B5(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Ki=void 0,xt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ki===void 0&&(Ki=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ki),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ef(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Rt(r,"email",n.message,t);break;case"format:idn-email":Rt(r,"idn-email",n.message,t);break;case"pattern:zod":nt(r,xt.email,n.message,t);break}break;case"url":Rt(r,"uri",n.message,t);break;case"uuid":Rt(r,"uuid",n.message,t);break;case"regex":nt(r,n.regex,n.message,t);break;case"cuid":nt(r,xt.cuid,n.message,t);break;case"cuid2":nt(r,xt.cuid2,n.message,t);break;case"startsWith":nt(r,RegExp(`^${Yi(n.value,t)}`),n.message,t);break;case"endsWith":nt(r,RegExp(`${Yi(n.value,t)}$`),n.message,t);break;case"datetime":Rt(r,"date-time",n.message,t);break;case"date":Rt(r,"date",n.message,t);break;case"time":Rt(r,"time",n.message,t);break;case"duration":Rt(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{nt(r,RegExp(Yi(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Rt(r,"ipv4",n.message,t),n.version!=="v4"&&Rt(r,"ipv6",n.message,t);break}case"base64url":nt(r,xt.base64url,n.message,t);break;case"jwt":nt(r,xt.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&nt(r,xt.ipv4Cidr,n.message,t),n.version!=="v4"&&nt(r,xt.ipv6Cidr,n.message,t);break}case"emoji":nt(r,xt.emoji(),n.message,t);break;case"ulid":{nt(r,xt.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Rt(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{nt(r,xt.base64,n.message,t);break}}break}case"nanoid":nt(r,xt.nanoid,n.message,t)}return r}function Yi(e,t){return t.patternStrategy==="escape"?G5(e):e}var J5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function G5(e){let t="";for(let r=0;r<e.length;r++)J5.has(e[r])||(t+="\\"),t+=e[r];return t}function Rt(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function nt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:If(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=If(t,n)}function If(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
58
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
59
+ ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
60
+ `:`[${o[c]}\r
61
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}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 s}function xf(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Q.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Ef(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Q.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=Tf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function W5(e,t){if(t.mapStrategy==="record")return xf(e,t);const r=xe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||vt(),n=xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||vt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function K5(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Y5(){return{not:vt()}}function Q5(){return{type:"null"}}var Qi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function X5(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Qi&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Qi[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return e8(e,t)}var e8=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>xe(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function t8(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Qi[e.innerType._def.typeName],"null"]};const r=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function r8(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function n8(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=s8(i),c=xe(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=o8(e,t);return s!==void 0&&(r.additionalProperties=s),r}function o8(e,t){if(e.catchall._def.typeName!=="ZodNever")return xe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function s8(e){try{return e.isOptional()}catch{return!0}}var a8=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return xe(e.innerType._def,t);const n=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:vt()},n]}:vt()},i8=(e,t)=>{if(t.pipeStrategy==="input")return xe(e.in._def,t);if(t.pipeStrategy==="output")return xe(e.out._def,t);const r=xe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=xe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function l8(e,t){return xe(e.type._def,t)}function c8(e,t){const n={type:"array",uniqueItems:!0,items:xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function u8(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:xe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function d8(){return{not:vt()}}function p8(){return vt()}var f8=(e,t)=>xe(e.innerType._def,t),h8=(e,t,r)=>{switch(t){case Q.ZodString:return Ef(e,r);case Q.ZodNumber:return r8(e);case Q.ZodObject:return n8(e,r);case Q.ZodBigInt:return L5(e);case Q.ZodBoolean:return j5();case Q.ZodDate:return $f(e,r);case Q.ZodUndefined:return d8();case Q.ZodNull:return Q5();case Q.ZodArray:return q5(e,r);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return X5(e,r);case Q.ZodIntersection:return H5(e,r);case Q.ZodTuple:return u8(e,r);case Q.ZodRecord:return xf(e,r);case Q.ZodLiteral:return B5(e);case Q.ZodEnum:return F5(e);case Q.ZodNativeEnum:return K5(e);case Q.ZodNullable:return t8(e,r);case Q.ZodOptional:return a8(e,r);case Q.ZodMap:return W5(e,r);case Q.ZodSet:return c8(e,r);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return l8(e,r);case Q.ZodNaN:case Q.ZodNever:return Y5();case Q.ZodEffects:return Z5(e,r);case Q.ZodAny:return vt();case Q.ZodUnknown:return p8();case Q.ZodDefault:return D5(e,r);case Q.ZodBranded:return Tf(e,r);case Q.ZodReadonly:return f8(e,r);case Q.ZodCatch:return U5(e,r);case Q.ZodPipeline:return i8(e,r);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(n=>{})()}};function xe(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==N5)return l}if(o&&!r){const l=m8(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=h8(e,e.typeName,t),i=typeof a=="function"?xe(a(),t):a;if(i&&g8(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var m8=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:M5(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),vt()):t.$refStrategy==="seen"?vt():void 0}},g8=(e,t,r)=>(e.description&&(r.description=e.description),r),v8=e=>{const t=A5(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},_8=(e,t)=>{var r;const n=v8(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,g])=>{var h;return{...c,[u]:(h=xe(g._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:vt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=xe(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:vt(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},y8=_8;function w8(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rf(()=>y8(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function b8(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rf(()=>Xo(xu(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await _a(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function k8(e){return"_zod"in e}function Ce(e,t){return k8(e)?b8(e):w8(e)}var S8=Symbol.for("vercel.ai.schema");function Qe(e){let t;return()=>(t==null&&(t=e()),t)}function Rf(e,{validate:t}={}){return{[S8]:!0,_type:void 0,[Qo]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}var{btoa:C8,atob:T8}=globalThis;function $8(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=T8(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function E8(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return C8(t)}function an(e){return e instanceof Uint8Array?E8(e):e}function I8(e){return e?.replace(/\/$/,"")}var Xi=T({error:T({message:v(),type:v().nullish(),param:et().nullish(),code:ne([v(),q()]).nullish()})}),Zt=P5({errorSchema:Xi,errorToMessage:e=>e.error.message});function Pf(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=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"),n=!(e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("chatgpt-4o")||e.startsWith("gpt-5-chat")),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function x8({prompt:e,systemMessageMode:t="system"}){const r=[],n=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((a,i)=>{var l,c,u;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const g=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${g};base64,${an(a.data)}`,detail:(c=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Ct({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:an(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:an(a.data),format:"mp3"}};default:throw new Ct({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Ct({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(u=a.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${an(a.data)}`}}}else throw new Ct({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of s)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of s){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:r,warnings:n}}function el({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function Of(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 R8=rt(()=>Ce(T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({message:T({role:L("assistant").nullish(),content:v().nullish(),tool_calls:A(T({id:v().nullish(),type:L("function"),function:T({name:v(),arguments:v()})})).nullish(),annotations:A(T({type:L("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:v(),title:v()})})).nullish()}),index:q(),logprobs:T({content:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}))),P8=rt(()=>Ce(ne([T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({delta:T({role:_e(["assistant"]).nullish(),content:v().nullish(),tool_calls:A(T({index:q(),id:v().nullish(),type:L("function").nullish(),function:T({name:v().nullish(),arguments:v().nullish()})})).nullish(),annotations:A(T({type:L("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:v(),title:v()})})).nullish()}).nullish(),logprobs:T({content:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish()}).nullish(),finish_reason:v().nullish(),index:q()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}),Xi]))),O8=rt(()=>Ce(T({logitBias:ve(Ju(),q()).optional(),logprobs:ne([ce(),q()]).optional(),parallelToolCalls:ce().optional(),user:v().optional(),reasoningEffort:_e(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:q().optional(),store:ce().optional(),metadata:ve(v().max(64),v().max(512)).optional(),prediction:ve(v(),et()).optional(),structuredOutputs:ce().optional(),serviceTier:_e(["auto","flex","priority","default"]).optional(),strictJsonSchema:ce().optional(),textVerbosity:_e(["low","medium","high"]).optional(),promptCacheKey:v().optional(),promptCacheRetention:_e(["in_memory","24h"]).optional(),safetyIdentifier:v().optional()})));function M8({tools:e,toolChoice:t,structuredOutputs:r,strictJsonSchema:n}){e=e?.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const i of e)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?n:void 0}});break;default:o.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:s,toolChoice:a,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const i=a;throw new Ct({functionality:`tool choice type: ${i}`})}}}var N8=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:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:g,providerOptions:h}){var d,p,w,m;const y=[],_=(d=await pr({provider:"openai",providerOptions:h,schema:O8}))!=null?d:{},f=(p=_.structuredOutputs)!=null?p:!0,b=Pf(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!f&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:k,warnings:S}=x8({prompt:e,systemMessageMode:b.systemMessageMode});y.push(...S);const C=(w=_.strictJsonSchema)!=null?w:!1,I={model:this.modelId,logit_bias:_.logitBias,logprobs:_.logprobs===!0||typeof _.logprobs=="number"?!0:void 0,top_logprobs:typeof _.logprobs=="number"?_.logprobs:typeof _.logprobs=="boolean"&&_.logprobs?0:void 0,user:_.user,parallel_tool_calls:_.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?f&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:C,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:_.textVerbosity,max_completion_tokens:_.maxCompletionTokens,store:_.store,metadata:_.metadata,prediction:_.prediction,reasoning_effort:_.reasoningEffort,service_tier:_.serviceTier,prompt_cache_key:_.promptCacheKey,prompt_cache_retention:_.promptCacheRetention,safety_identifier:_.safetyIdentifier,messages:k};b.isReasoningModel?((_.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(I.temperature!=null&&(I.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,y.push({type:"other",message:"logprobs is not supported for reasoning models"}))),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,y.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,y.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,y.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,y.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&I.temperature!=null&&(I.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),_.serviceTier==="flex"&&!b.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),_.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(y.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"}),I.service_tier=void 0);const{tools:x,toolChoice:M,toolWarnings:P}=M8({tools:u,toolChoice:g,structuredOutputs:f,strictJsonSchema:C});return{args:{...I,tools:x,tool_choice:M},warnings:[...y,...P]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,h,d,p;const{args:w,warnings:m}=await this.getArgs(e),{responseHeaders:y,value:_,rawValue:f}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:w,failedResponseHandler:Zt,successfulResponseHandler:sn(R8),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=_.choices[0],k=[],S=b.message.content;S!=null&&S.length>0&&k.push({type:"text",text:S});for(const M of(t=b.message.tool_calls)!=null?t:[])k.push({type:"tool-call",toolCallId:(r=M.id)!=null?r:It(),toolName:M.function.name,input:M.function.arguments});for(const M of(n=b.message.annotations)!=null?n:[])k.push({type:"source",sourceType:"url",id:It(),url:M.url_citation.url,title:M.url_citation.title});const C=(o=_.usage)==null?void 0:o.completion_tokens_details,I=(s=_.usage)==null?void 0:s.prompt_tokens_details,x={openai:{}};return C?.accepted_prediction_tokens!=null&&(x.openai.acceptedPredictionTokens=C?.accepted_prediction_tokens),C?.rejected_prediction_tokens!=null&&(x.openai.rejectedPredictionTokens=C?.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(x.openai.logprobs=b.logprobs.content),{content:k,finishReason:Of(b.finish_reason),usage:{inputTokens:(l=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=_.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(h=(g=_.usage)==null?void 0:g.total_tokens)!=null?h:void 0,reasoningTokens:(d=C?.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(p=I?.cached_tokens)!=null?p:void 0},request:{body:w},response:{...el(_),headers:y,body:f},warnings:m,providerMetadata:x}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:n,failedResponseHandler:Zt,successfulResponseHandler:Wi(P8),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,u=!1;const g={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:r})},transform(h,d){var p,w,m,y,_,f,b,k,S,C,I,x,M,P,U,z,F,te,ie,se,ee,pe,V,O;if(e.includeRawChunks&&d.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){i="error",d.enqueue({type:"error",error:h.error});return}const Z=h.value;if("error"in Z){i="error",d.enqueue({type:"error",error:Z.error});return}if(!c){const R=el(Z);Object.values(R).some(Boolean)&&(c=!0,d.enqueue({type:"response-metadata",...el(Z)}))}Z.usage!=null&&(l.inputTokens=(p=Z.usage.prompt_tokens)!=null?p:void 0,l.outputTokens=(w=Z.usage.completion_tokens)!=null?w:void 0,l.totalTokens=(m=Z.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(_=(y=Z.usage.completion_tokens_details)==null?void 0:y.reasoning_tokens)!=null?_:void 0,l.cachedInputTokens=(b=(f=Z.usage.prompt_tokens_details)==null?void 0:f.cached_tokens)!=null?b:void 0,((k=Z.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(g.openai.acceptedPredictionTokens=(S=Z.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((C=Z.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens)!=null&&(g.openai.rejectedPredictionTokens=(I=Z.usage.completion_tokens_details)==null?void 0:I.rejected_prediction_tokens));const j=Z.choices[0];if(j?.finish_reason!=null&&(i=Of(j.finish_reason)),((x=j?.logprobs)==null?void 0:x.content)!=null&&(g.openai.logprobs=j.logprobs.content),j?.delta==null)return;const E=j.delta;if(E.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:E.content})),E.tool_calls!=null)for(const R of E.tool_calls){const $=R.index;if(a[$]==null){if(R.type!=="function")throw new _n({data:R,message:"Expected 'function' type."});if(R.id==null)throw new _n({data:R,message:"Expected 'id' to be a string."});if(((M=R.function)==null?void 0:M.name)==null)throw new _n({data:R,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:R.id,toolName:R.function.name}),a[$]={id:R.id,type:"function",function:{name:R.function.name,arguments:(P=R.function.arguments)!=null?P:""},hasFinished:!1};const G=a[$];((U=G.function)==null?void 0:U.name)!=null&&((z=G.function)==null?void 0:z.arguments)!=null&&(G.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:G.id,delta:G.function.arguments}),kf(G.function.arguments)&&(d.enqueue({type:"tool-input-end",id:G.id}),d.enqueue({type:"tool-call",toolCallId:(F=G.id)!=null?F:It(),toolName:G.function.name,input:G.function.arguments}),G.hasFinished=!0));continue}const H=a[$];H.hasFinished||(((te=R.function)==null?void 0:te.arguments)!=null&&(H.function.arguments+=(se=(ie=R.function)==null?void 0:ie.arguments)!=null?se:""),d.enqueue({type:"tool-input-delta",id:H.id,delta:(ee=R.function.arguments)!=null?ee:""}),((pe=H.function)==null?void 0:pe.name)!=null&&((V=H.function)==null?void 0:V.arguments)!=null&&kf(H.function.arguments)&&(d.enqueue({type:"tool-input-end",id:H.id}),d.enqueue({type:"tool-call",toolCallId:(O=H.id)!=null?O:It(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}if(E.annotations!=null)for(const R of E.annotations)d.enqueue({type:"source",sourceType:"url",id:It(),url:R.url_citation.url,title:R.url_citation.title})},flush(h){u&&h.enqueue({type:"text-end",id:"0"}),h.enqueue({type:"finish",finishReason:i,usage:l,...g!=null?{providerMetadata:g}:{}})}})),request:{body:n},response:{headers:o}}}};function A8({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
62
62
 
63
- `,t=t.slice(1));for(const{role:n,content:s}of t)switch(n){case"system":throw new Br({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");a+=`${e}:
64
- ${o}
63
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new br({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${t}:
64
+ ${a}
65
65
 
66
- `;break}case"assistant":{const o=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Nt({functionality:"tool-call messages"})}}).join("");a+=`${r}:
67
- ${o}
66
+ `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Ct({functionality:"tool-call messages"})}}).join("");n+=`${r}:
67
+ ${a}
68
68
 
69
- `;break}case"tool":throw new Nt({functionality:"tool messages"});default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return a+=`${r}:
70
- `,{prompt:a,stopSequences:[`
71
- ${e}:`]}}function af({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function sf(t){switch(t){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 of=P({echo:nt().optional(),logitBias:St(x(),U()).optional(),suffix:x().optional(),user:x().optional(),logprobs:Ae([nt(),U()]).optional()}),MI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,tools:u,toolChoice:d,seed:h,providerOptions:g}){const c=[],p={...await lr({provider:"openai",providerOptions:g,schema:of}),...await lr({provider:this.providerOptionsName,providerOptions:g,schema:of})};n!=null&&c.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&c.push({type:"unsupported-setting",setting:"tools"}),d!=null&&c.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&c.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:f,stopSequences:m}=NI({prompt:t}),v=[...m??[],...i??[]];return{args:{model:this.modelId,echo:p.echo,logit_bias:p.logitBias,logprobs:(p==null?void 0:p.logprobs)===!0?0:(p==null?void 0:p.logprobs)===!1||p==null?void 0:p.logprobs,suffix:p.suffix,user:p.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,seed:h,prompt:f,stop:v.length>0?v:void 0},warnings:c}}async doGenerate(t){var e,r,a;const{args:n,warnings:s}=await this.getArgs(t),{responseHeaders:o,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:n,failedResponseHandler:ur,successfulResponseHandler:ln(DI),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=i.choices[0],d={openai:{}};return u.logprobs!=null&&(d.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(a=i.usage)==null?void 0:a.total_tokens},finishReason:sf(u.finish_reason),request:{body:n},response:{...af(i),headers:o,body:l},providerMetadata:d,warnings:s}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:a,failedResponseHandler:ur,successfulResponseHandler:Os(jI),abortSignal:t.abortSignal,fetch:this.config.fetch});let o="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){o="error",h.enqueue({type:"error",error:d.error});return}const g=d.value;if("error"in g){o="error",h.enqueue({type:"error",error:g.error});return}u&&(u=!1,h.enqueue({type:"response-metadata",...af(g)}),h.enqueue({type:"text-start",id:"0"})),g.usage!=null&&(l.inputTokens=g.usage.prompt_tokens,l.outputTokens=g.usage.completion_tokens,l.totalTokens=g.usage.total_tokens);const c=g.choices[0];(c==null?void 0:c.finish_reason)!=null&&(o=sf(c.finish_reason)),(c==null?void 0:c.logprobs)!=null&&(i.openai.logprobs=c.logprobs),(c==null?void 0:c.text)!=null&&c.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:c.text})},flush(d){u||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:o,providerMetadata:i,usage:l})}})),request:{body:a},response:{headers:n}}}},lf=P({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()}),DI=P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({text:x(),finish_reason:x(),logprobs:P({tokens:Y(x()),token_logprobs:Y(U()),top_logprobs:Y(St(x(),U())).nullish()}).nullish()})),usage:lf.nullish()}),jI=Ae([P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({text:x(),finish_reason:x().nullish(),index:U(),logprobs:P({tokens:Y(x()),token_logprobs:Y(U()),top_logprobs:Y(St(x(),U())).nullish()}).nullish()})),usage:lf.nullish()}),tl]),LI=P({dimensions:U().optional(),user:x().optional()}),zI=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;if(t.length>this.maxEmbeddingsPerCall)throw new iv({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const s=(n=await lr({provider:"openai",providerOptions:a,schema:LI}))!=null?n:{},{responseHeaders:o,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ut(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:ur,successfulResponseHandler:ln(UI),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:o,body:l}}}},UI=P({data:Y(P({embedding:Y(U())})),usage:P({prompt_tokens:U()}).nullish()}),FI={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},qI=new Set(["gpt-image-1"]),ZI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=FI[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:a,seed:n,providerOptions:s,headers:o,abortSignal:i}){var l,u,d,h;const g=[];a!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),n!=null&&g.push({type:"unsupported-setting",setting:"seed"});const c=(d=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?d:new Date,{value:p,responseHeaders:f}=await Kt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ut(this.config.headers(),o),body:{model:this.modelId,prompt:t,n:e,size:r,...(h=s.openai)!=null?h:{},...qI.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:ur,successfulResponseHandler:ln(VI),abortSignal:i,fetch:this.config.fetch});return{images:p.data.map(m=>m.b64_json),warnings:g,response:{timestamp:c,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:p.data.map(m=>m.revised_prompt?{revisedPrompt:m.revised_prompt}:null)}}}}},VI=P({data:Y(P({b64_json:x(),revised_prompt:x().optional()}))}),BI=P({container:Ae([x(),P({fileIds:Y(x()).optional()})]).optional()}),HI=el({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:P({})}),JI={codeInterpreter:HI,fileSearch:SI,webSearchPreview:II};function uf(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function WI({prompt:t,systemMessageMode:e,fileIdPrefixes:r}){var a,n,s,o,i,l;const u=[],d=[];for(const{role:h,content:g}of t)switch(h){case"system":{switch(e){case"system":{u.push({role:"system",content:g});break}case"developer":{u.push({role:"developer",content:g});break}case"remove":{d.push({type:"other",message:"system messages are removed for this model"});break}default:{const c=e;throw new Error(`Unsupported system message mode: ${c}`)}}break}case"user":{u.push({role:"user",content:g.map((c,p)=>{var f,m,v;switch(c.type){case"text":return{type:"input_text",text:c.text};case"file":if(c.mediaType.startsWith("image/")){const w=c.mediaType==="image/*"?"image/jpeg":c.mediaType;return{type:"input_image",...c.data instanceof URL?{image_url:c.data.toString()}:typeof c.data=="string"&&uf(c.data,r)?{file_id:c.data}:{image_url:`data:${w};base64,${un(c.data)}`},detail:(m=(f=c.providerOptions)==null?void 0:f.openai)==null?void 0:m.imageDetail}}else if(c.mediaType==="application/pdf"){if(c.data instanceof URL)throw new Nt({functionality:"PDF file parts with URLs"});return{type:"input_file",...typeof c.data=="string"&&uf(c.data,r)?{file_id:c.data}:{filename:(v=c.filename)!=null?v:`part-${p}.pdf`,file_data:`data:application/pdf;base64,${un(c.data)}`}}}else throw new Nt({functionality:`file part media type ${c.mediaType}`})}})});break}case"assistant":{const c={};for(const p of g)switch(p.type){case"text":{u.push({role:"assistant",content:[{type:"output_text",text:p.text}],id:(s=(n=(a=p.providerOptions)==null?void 0:a.openai)==null?void 0:n.itemId)!=null?s:void 0});break}case"tool-call":{if(p.providerExecuted)break;u.push({type:"function_call",call_id:p.toolCallId,name:p.toolName,arguments:JSON.stringify(p.input),id:(l=(i=(o=p.providerOptions)==null?void 0:o.openai)==null?void 0:i.itemId)!=null?l:void 0});break}case"tool-result":{d.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break}case"reasoning":{const f=await lr({provider:"openai",providerOptions:p.providerOptions,schema:GI}),m=f==null?void 0:f.itemId;if(m!=null){const v=c[m],w=[];p.text.length>0?w.push({type:"summary_text",text:p.text}):v!==void 0&&d.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(p)}.`}),v===void 0?(c[m]={type:"reasoning",id:m,encrypted_content:f==null?void 0:f.reasoningEncryptedContent,summary:w},u.push(c[m])):v.summary.push(...w)}else d.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(p)}.`});break}}break}case"tool":{for(const c of g){const p=c.output;let f;switch(p.type){case"text":case"error-text":f=p.value;break;case"content":case"json":case"error-json":f=JSON.stringify(p.value);break}u.push({type:"function_call_output",call_id:c.toolCallId,output:f})}break}default:{const c=h;throw new Error(`Unsupported role: ${c}`)}}return{messages:u,warnings:d}}var GI=P({itemId:x().nullish(),reasoningEncryptedContent:x().nullish()});function cf({finishReason:t,hasToolCalls:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}function KI({tools:t,toolChoice:e,strictJsonSchema:r}){t=t!=null&&t.length?t:void 0;const a=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const n=[];for(const o of t)switch(o.type){case"function":n.push({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:r});break;case"provider-defined":{switch(o.id){case"openai.file_search":{const i=ef.parse(o.args);n.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker}:void 0,filters:i.filters});break}case"openai.web_search_preview":{const i=tf.parse(o.args);n.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=BI.parse(o.args);n.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}default:{a.push({type:"unsupported-tool",tool:o});break}}break}default:a.push({type:"unsupported-tool",tool:o});break}if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:a};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:a};case"tool":return{tools:n,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="web_search_preview"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:a};default:{const o=s;throw new Nt({functionality:`tool choice type: ${o}`})}}}var df=20,pf=Y(P({token:x(),logprob:U(),top_logprobs:Y(P({token:x(),logprob:U()}))})),QI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:a,topK:n,presencePenalty:s,frequencyPenalty:o,seed:i,prompt:l,providerOptions:u,tools:d,toolChoice:h,responseFormat:g}){var c,p;const f=[],m=_T(this.modelId);n!=null&&f.push({type:"unsupported-setting",setting:"topK"}),i!=null&&f.push({type:"unsupported-setting",setting:"seed"}),s!=null&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),o!=null&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&f.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:v,warnings:w}=await WI({prompt:l,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});f.push(...w);const y=await lr({provider:"openai",providerOptions:u,schema:wT}),_=(c=y==null?void 0:y.strictJsonSchema)!=null?c:!1,E=typeof(y==null?void 0:y.logprobs)=="number"?y==null?void 0:y.logprobs:(y==null?void 0:y.logprobs)===!0?df:void 0,I=E?Array.isArray(y==null?void 0:y.include)?[...y==null?void 0:y.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:y==null?void 0:y.include,S={model:this.modelId,input:v,temperature:e,top_p:a,max_output_tokens:t,...((g==null?void 0:g.type)==="json"||(y==null?void 0:y.textVerbosity))&&{text:{...(g==null?void 0:g.type)==="json"&&{format:g.schema!=null?{type:"json_schema",strict:_,name:(p=g.name)!=null?p:"response",description:g.description,schema:g.schema}:{type:"json_object"}},...(y==null?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},metadata:y==null?void 0:y.metadata,parallel_tool_calls:y==null?void 0:y.parallelToolCalls,previous_response_id:y==null?void 0:y.previousResponseId,store:y==null?void 0:y.store,user:y==null?void 0:y.user,instructions:y==null?void 0:y.instructions,service_tier:y==null?void 0:y.serviceTier,include:I,prompt_cache_key:y==null?void 0:y.promptCacheKey,safety_identifier:y==null?void 0:y.safetyIdentifier,top_logprobs:E,...m.isReasoningModel&&((y==null?void 0:y.reasoningEffort)!=null||(y==null?void 0:y.reasoningSummary)!=null)&&{reasoning:{...(y==null?void 0:y.reasoningEffort)!=null&&{effort:y.reasoningEffort},...(y==null?void 0:y.reasoningSummary)!=null&&{summary:y.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:"auto"}};m.isReasoningModel?(S.temperature!=null&&(S.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((y==null?void 0:y.reasoningEffort)!=null&&f.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(y==null?void 0:y.reasoningSummary)!=null&&f.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(y==null?void 0:y.serviceTier)==="flex"&&!m.supportsFlexProcessing&&(f.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete S.service_tier),(y==null?void 0:y.serviceTier)==="priority"&&!m.supportsPriorityProcessing&&(f.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete S.service_tier);const{tools:R,toolChoice:$,toolWarnings:z}=KI({tools:d,toolChoice:h,strictJsonSchema:_});return{args:{...S,tools:R,tool_choice:$},warnings:[...f,...z]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,h,g,c,p,f,m,v;const{args:w,warnings:y}=await this.getArgs(t),_=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:E,value:I,rawValue:S}=await Kt({url:_,headers:Ut(this.config.headers(),t.headers),body:w,failedResponseHandler:ur,successfulResponseHandler:ln(P({id:x(),created_at:U(),error:P({code:x(),message:x()}).nullish(),model:x(),output:Y(wn("type",[P({type:H("message"),role:H("assistant"),id:x(),content:Y(P({type:H("output_text"),text:x(),logprobs:pf.nullish(),annotations:Y(wn("type",[P({type:H("url_citation"),start_index:U(),end_index:U(),url:x(),title:x()}),P({type:H("file_citation"),start_index:U(),end_index:U(),file_id:x(),quote:x()})]))}))}),P({type:H("function_call"),call_id:x(),name:x(),arguments:x(),id:x()}),P({type:H("web_search_call"),id:x(),status:x().optional(),action:P({type:H("search"),query:x().optional()}).nullish()}),P({type:H("computer_call"),id:x(),status:x().optional()}),P({type:H("file_search_call"),id:x(),status:x().optional(),queries:Y(x()).nullish(),results:Y(P({attributes:P({file_id:x(),filename:x(),score:U(),text:x()})})).nullish()}),P({type:H("reasoning"),id:x(),encrypted_content:x().nullish(),summary:Y(P({type:H("summary_text"),text:x()}))})])),incomplete_details:P({reason:x()}).nullable(),usage:hf})),abortSignal:t.abortSignal,fetch:this.config.fetch});if(I.error)throw new Ue({message:I.error.message,url:_,requestBodyValues:w,statusCode:400,responseHeaders:E,responseBody:S,isRetryable:!1});const R=[],$=[];for(const L of I.output)switch(L.type){case"reasoning":{L.summary.length===0&&L.summary.push({type:"summary_text",text:""});for(const F of L.summary)R.push({type:"reasoning",text:F.text,providerMetadata:{openai:{itemId:L.id,reasoningEncryptedContent:(e=L.encrypted_content)!=null?e:null}}});break}case"message":{for(const F of L.content){(a=(r=t.providerOptions)==null?void 0:r.openai)!=null&&a.logprobs&&F.logprobs&&$.push(F.logprobs),R.push({type:"text",text:F.text,providerMetadata:{openai:{itemId:L.id}}});for(const M of F.annotations)M.type==="url_citation"?R.push({type:"source",sourceType:"url",id:(o=(s=(n=this.config).generateId)==null?void 0:s.call(n))!=null?o:Ot(),url:M.url,title:M.title}):M.type==="file_citation"&&R.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:Ot(),mediaType:"text/plain",title:M.quote,filename:M.file_id})}break}case"function_call":{R.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:L.arguments,providerMetadata:{openai:{itemId:L.id}}});break}case"web_search_call":{R.push({type:"tool-call",toolCallId:L.id,toolName:"web_search_preview",input:(h=(d=L.action)==null?void 0:d.query)!=null?h:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:L.id,toolName:"web_search_preview",result:{status:L.status||"completed",...((g=L.action)==null?void 0:g.query)&&{query:L.action.query}},providerExecuted:!0});break}case"computer_call":{R.push({type:"tool-call",toolCallId:L.id,toolName:"computer_use",input:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:L.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:L.status||"completed"},providerExecuted:!0});break}case"file_search_call":{R.push({type:"tool-call",toolCallId:L.id,toolName:"file_search",input:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:L.id,toolName:"file_search",result:{type:"file_search_tool_result",status:L.status||"completed",...L.queries&&{queries:L.queries},...L.results&&{results:L.results}},providerExecuted:!0});break}}const z={openai:{responseId:I.id}};return $.length>0&&(z.openai.logprobs=$),{content:R,finishReason:cf({finishReason:(c=I.incomplete_details)==null?void 0:c.reason,hasToolCalls:R.some(L=>L.type==="tool-call")}),usage:{inputTokens:I.usage.input_tokens,outputTokens:I.usage.output_tokens,totalTokens:I.usage.input_tokens+I.usage.output_tokens,reasoningTokens:(f=(p=I.usage.output_tokens_details)==null?void 0:p.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(v=(m=I.usage.input_tokens_details)==null?void 0:m.cached_tokens)!=null?v:void 0},request:{body:w},response:{id:I.id,timestamp:new Date(I.created_at*1e3),modelId:I.model,headers:E,body:S},providerMetadata:z,warnings:y}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{responseHeaders:a,value:n}=await Kt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:ur,successfulResponseHandler:Os(lT),abortSignal:t.abortSignal,fetch:this.config.fetch}),s=this;let o="unknown";const i={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=null;const d={};let h=!1;const g={};return{stream:n.pipeThrough(new TransformStream({start(c){c.enqueue({type:"stream-start",warnings:r})},transform(c,p){var f,m,v,w,y,_,E,I,S,R,$,z,L,F,M,D,K,oe,ie;if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:c.rawValue}),!c.success){o="error",p.enqueue({type:"error",error:c.error});return}const C=c.value;if(mf(C))C.item.type==="function_call"?(d[C.output_index]={toolName:C.item.name,toolCallId:C.item.call_id},p.enqueue({type:"tool-input-start",id:C.item.call_id,toolName:C.item.name})):C.item.type==="web_search_call"?(d[C.output_index]={toolName:"web_search_preview",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"web_search_preview"})):C.item.type==="computer_call"?(d[C.output_index]={toolName:"computer_use",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"computer_use"})):C.item.type==="file_search_call"?(d[C.output_index]={toolName:"file_search",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"file_search"})):C.item.type==="message"?p.enqueue({type:"text-start",id:C.item.id,providerMetadata:{openai:{itemId:C.item.id}}}):fT(C)&&(g[C.item.id]={encryptedContent:C.item.encrypted_content,summaryParts:[0]},p.enqueue({type:"reasoning-start",id:`${C.item.id}:0`,providerMetadata:{openai:{itemId:C.item.id,reasoningEncryptedContent:(f=C.item.encrypted_content)!=null?f:null}}}));else if(ff(C)){if(C.item.type==="function_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.call_id}),p.enqueue({type:"tool-call",toolCallId:C.item.call_id,toolName:C.item.name,input:C.item.arguments,providerMetadata:{openai:{itemId:C.item.id}}});else if(C.item.type==="web_search_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"web_search_preview",input:(v=(m=C.item.action)==null?void 0:m.query)!=null?v:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:C.item.status||"completed",...((w=C.item.action)==null?void 0:w.query)&&{query:C.item.action.query}},providerExecuted:!0});else if(C.item.type==="computer_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:C.item.status||"completed"},providerExecuted:!0});else if(C.item.type==="file_search_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"file_search",input:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:C.item.status||"completed",...C.item.queries&&{queries:C.item.queries},...C.item.results&&{results:C.item.results}},providerExecuted:!0});else if(C.item.type==="message")p.enqueue({type:"text-end",id:C.item.id});else if(cT(C)){const re=g[C.item.id];for(const B of re.summaryParts)p.enqueue({type:"reasoning-end",id:`${C.item.id}:${B}`,providerMetadata:{openai:{itemId:C.item.id,reasoningEncryptedContent:(y=C.item.encrypted_content)!=null?y:null}}});delete g[C.item.id]}}else if(hT(C)){const re=d[C.output_index];re!=null&&p.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:C.delta})}else pT(C)?(u=C.response.id,p.enqueue({type:"response-metadata",id:C.response.id,timestamp:new Date(C.response.created_at*1e3),modelId:C.response.model})):uT(C)?(p.enqueue({type:"text-delta",id:C.item_id,delta:C.delta}),C.logprobs&&l.push(C.logprobs)):vT(C)?C.summary_index>0&&((_=g[C.item_id])==null||_.summaryParts.push(C.summary_index),p.enqueue({type:"reasoning-start",id:`${C.item_id}:${C.summary_index}`,providerMetadata:{openai:{itemId:C.item_id,reasoningEncryptedContent:(I=(E=g[C.item_id])==null?void 0:E.encryptedContent)!=null?I:null}}})):gT(C)?p.enqueue({type:"reasoning-delta",id:`${C.item_id}:${C.summary_index}`,delta:C.delta,providerMetadata:{openai:{itemId:C.item_id}}}):dT(C)?(o=cf({finishReason:(S=C.response.incomplete_details)==null?void 0:S.reason,hasToolCalls:h}),i.inputTokens=C.response.usage.input_tokens,i.outputTokens=C.response.usage.output_tokens,i.totalTokens=C.response.usage.input_tokens+C.response.usage.output_tokens,i.reasoningTokens=($=(R=C.response.usage.output_tokens_details)==null?void 0:R.reasoning_tokens)!=null?$:void 0,i.cachedInputTokens=(L=(z=C.response.usage.input_tokens_details)==null?void 0:z.cached_tokens)!=null?L:void 0):mT(C)?C.annotation.type==="url_citation"?p.enqueue({type:"source",sourceType:"url",id:(D=(M=(F=s.config).generateId)==null?void 0:M.call(F))!=null?D:Ot(),url:C.annotation.url,title:C.annotation.title}):C.annotation.type==="file_citation"&&p.enqueue({type:"source",sourceType:"document",id:(ie=(oe=(K=s.config).generateId)==null?void 0:oe.call(K))!=null?ie:Ot(),mediaType:"text/plain",title:C.annotation.quote,filename:C.annotation.file_id}):yT(C)&&p.enqueue({type:"error",error:C})},flush(c){const p={openai:{responseId:u}};l.length>0&&(p.openai.logprobs=l),c.enqueue({type:"finish",finishReason:o,usage:i,providerMetadata:p})}})),request:{body:e},response:{headers:a}}}},hf=P({input_tokens:U(),input_tokens_details:P({cached_tokens:U().nullish()}).nullish(),output_tokens:U(),output_tokens_details:P({reasoning_tokens:U().nullish()}).nullish()}),YI=P({type:H("response.output_text.delta"),item_id:x(),delta:x(),logprobs:pf.nullish()}),XI=P({type:H("error"),code:x(),message:x(),param:x().nullish(),sequence_number:U()}),eT=P({type:vt(["response.completed","response.incomplete"]),response:P({incomplete_details:P({reason:x()}).nullish(),usage:hf})}),tT=P({type:H("response.created"),response:P({id:x(),created_at:U(),model:x()})}),rT=P({type:H("response.output_item.added"),output_index:U(),item:wn("type",[P({type:H("message"),id:x()}),P({type:H("reasoning"),id:x(),encrypted_content:x().nullish()}),P({type:H("function_call"),id:x(),call_id:x(),name:x(),arguments:x()}),P({type:H("web_search_call"),id:x(),status:x(),action:P({type:H("search"),query:x().optional()}).nullish()}),P({type:H("computer_call"),id:x(),status:x()}),P({type:H("file_search_call"),id:x(),status:x(),queries:Y(x()).nullish(),results:Y(P({attributes:P({file_id:x(),filename:x(),score:U(),text:x()})})).optional()})])}),nT=P({type:H("response.output_item.done"),output_index:U(),item:wn("type",[P({type:H("message"),id:x()}),P({type:H("reasoning"),id:x(),encrypted_content:x().nullish()}),P({type:H("function_call"),id:x(),call_id:x(),name:x(),arguments:x(),status:H("completed")}),P({type:H("web_search_call"),id:x(),status:H("completed"),action:P({type:H("search"),query:x().optional()}).nullish()}),P({type:H("computer_call"),id:x(),status:H("completed")}),P({type:H("file_search_call"),id:x(),status:H("completed"),queries:Y(x()).nullish(),results:Y(P({attributes:P({file_id:x(),filename:x(),score:U(),text:x()})})).nullish()})])}),aT=P({type:H("response.function_call_arguments.delta"),item_id:x(),output_index:U(),delta:x()}),sT=P({type:H("response.output_text.annotation.added"),annotation:wn("type",[P({type:H("url_citation"),url:x(),title:x()}),P({type:H("file_citation"),file_id:x(),quote:x()})])}),oT=P({type:H("response.reasoning_summary_part.added"),item_id:x(),summary_index:U()}),iT=P({type:H("response.reasoning_summary_text.delta"),item_id:x(),summary_index:U(),delta:x()}),lT=Ae([YI,eT,tT,rT,nT,aT,sT,oT,iT,XI,P({type:x()}).loose()]);function uT(t){return t.type==="response.output_text.delta"}function ff(t){return t.type==="response.output_item.done"}function cT(t){return ff(t)&&t.item.type==="reasoning"}function dT(t){return t.type==="response.completed"||t.type==="response.incomplete"}function pT(t){return t.type==="response.created"}function hT(t){return t.type==="response.function_call_arguments.delta"}function mf(t){return t.type==="response.output_item.added"}function fT(t){return mf(t)&&t.item.type==="reasoning"}function mT(t){return t.type==="response.output_text.annotation.added"}function vT(t){return t.type==="response.reasoning_summary_part.added"}function gT(t){return t.type==="response.reasoning_summary_text.delta"}function yT(t){return t.type==="error"}function _T(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),a={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:e,supportsPriorityProcessing:r};return t.startsWith("gpt-5-chat")?{...a,isReasoningModel:!1}:t.startsWith("o")||t.startsWith("gpt-5")||t.startsWith("codex-")||t.startsWith("computer-use")?t.startsWith("o1-mini")||t.startsWith("o1-preview")?{...a,isReasoningModel:!0,systemMessageMode:"remove"}:{...a,isReasoningModel:!0,systemMessageMode:"developer"}:{...a,isReasoningModel:!1}}var wT=P({metadata:Mt().nullish(),parallelToolCalls:nt().nullish(),previousResponseId:x().nullish(),store:nt().nullish(),user:x().nullish(),reasoningEffort:x().nullish(),strictJsonSchema:nt().nullish(),instructions:x().nullish(),reasoningSummary:x().nullish(),serviceTier:vt(["auto","flex","priority"]).nullish(),include:Y(vt(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:vt(["low","medium","high"]).nullish(),promptCacheKey:x().nullish(),safetyIdentifier:x().nullish(),logprobs:Ae([nt(),U().min(1).max(df)]).optional()}),bT=P({instructions:x().nullish(),speed:U().min(.25).max(4).default(1).nullish()}),xT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:a,instructions:n,language:s,providerOptions:o}){const i=[],l=await lr({provider:"openai",providerOptions:o,schema:bT}),u={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:a,instructions:n};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?u.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const d={};for(const h in d){const g=d[h];g!==void 0&&(u[h]=g)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(t){var e,r,a;const n=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{requestBody:s,warnings:o}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:u}=await Kt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:s,failedResponseHandler:ur,successfulResponseHandler:vI(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:o,request:{body:JSON.stringify(s)},response:{timestamp:n,modelId:this.modelId,headers:l,body:u}}}},ET=P({include:Y(x()).optional(),language:x().optional(),prompt:x().optional(),temperature:U().min(0).max(1).default(0).optional(),timestampGranularities:Y(vt(["word","segment"])).default(["segment"]).optional()}),vf={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"},ST=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const a=[],n=await lr({provider:"openai",providerOptions:r,schema:ET}),s=new FormData,o=t instanceof Uint8Array?new Blob([t]):new Blob([_I(t)]);if(s.append("model",this.modelId),s.append("file",new File([o],"audio",{type:e})),n){const i={include:n.include,language:n.language,prompt:n.prompt,response_format:"verbose_json",temperature:n.temperature,timestamp_granularities:n.timestampGranularities};for(const[l,u]of Object.entries(i))u!=null&&s.append(l,String(u))}return{formData:s,warnings:a}}async doGenerate(t){var e,r,a,n,s,o,i,l;const u=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{formData:d,warnings:h}=await this.getArgs(t),{value:g,responseHeaders:c,rawValue:p}=await mI({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),formData:d,failedResponseHandler:ur,successfulResponseHandler:ln(IT),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=g.language!=null&&g.language in vf?vf[g.language]:void 0;return{text:g.text,segments:(i=(o=(n=g.segments)==null?void 0:n.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?o:(s=g.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:f,durationInSeconds:(l=g.duration)!=null?l:void 0,warnings:h,response:{timestamp:u,modelId:this.modelId,headers:c,body:p}}}},IT=P({text:x(),language:x().nullish(),duration:U().nullish(),words:Y(P({word:x(),start:U(),end:U()})).nullish(),segments:Y(P({id:U(),seek:U(),start:U(),end:U(),text:x(),tokens:Y(U()),temperature:U(),avg_logprob:U(),compression_ratio:U(),no_speech_prob:U()})).nullish()});function gf(t={}){var e,r;const a=(e=Gh(t.baseURL))!=null?e:"https://api.openai.com/v1",n=(r=t.name)!=null?r:"openai",s=()=>({Authorization:`Bearer ${Bh({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers}),o=f=>new kI(f,{provider:`${n}.chat`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),i=f=>new MI(f,{provider:`${n}.completion`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),l=f=>new zI(f,{provider:`${n}.embedding`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),u=f=>new ZI(f,{provider:`${n}.image`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),d=f=>new ST(f,{provider:`${n}.transcription`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),h=f=>new xT(f,{provider:`${n}.speech`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),g=f=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return c(f)},c=f=>new QI(f,{provider:`${n}.responses`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch,fileIdPrefixes:["file-"]}),p=function(f){return g(f)};return p.languageModel=g,p.chat=o,p.completion=i,p.responses=c,p.embedding=l,p.textEmbedding=l,p.textEmbeddingModel=l,p.image=u,p.imageModel=u,p.transcription=d,p.transcriptionModel=d,p.speech=h,p.speechModel=h,p.tools=JI,p}gf();function wa(t){var e,r;return(r=(e=t==null?void 0:t.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function TT(t){const e=[];for(const{role:r,content:a,...n}of t){const s=wa({...n});switch(r){case"system":{e.push({role:"system",content:a,...s});break}case"user":{if(a.length===1&&a[0].type==="text"){e.push({role:"user",content:a[0].text,...wa(a[0])});break}e.push({role:"user",content:a.map(o=>{const i=wa(o);switch(o.type){case"text":return{type:"text",text:o.text,...i};case"file":if(o.mediaType.startsWith("image/")){const l=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${l};base64,${un(o.data)}`},...i}}else throw new Nt({functionality:`file part media type ${o.mediaType}`})}}),...s});break}case"assistant":{let o="";const i=[];for(const l of a){const u=wa(l);switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}e.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const o of a){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=wa(o);e.push({role:"tool",tool_call_id:o.toolCallId,content:l,...u})}break}default:{const o=r;throw new Error(`Unsupported role: ${o}`)}}}return e}function yf({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function _f(t){switch(t){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 wf=P({user:x().optional(),reasoningEffort:x().optional()}),kT=P({error:P({message:x(),type:x().nullish(),param:Mt().nullish(),code:Ae([x(),U()]).nullish()})}),PT={errorSchema:kT,errorToMessage:t=>t.error.message};function CT({tools:t,toolChoice:e}){t=t!=null&&t.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const a=[];for(const s of t)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):a.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(e==null)return{tools:a,toolChoice:void 0,toolWarnings:r};const n=e.type;switch(n){case"auto":case"none":case"required":return{tools:a,toolChoice:n,toolWarnings:r};case"tool":return{tools:a,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const s=n;throw new Nt({functionality:`tool choice type: ${s}`})}}}var RT=class{constructor(t,e){this.specificationVersion="v2";var r,a;this.modelId=t,this.config=e;const n=(r=e.errorStructure)!=null?r:PT;this.chunkSchema=$T(n.errorSchema),this.failedResponseHandler=Wh(n),this.supportsStructuredOutputs=(a=e.supportsStructuredOutputs)!=null?a:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,providerOptions:i,stopSequences:l,responseFormat:u,seed:d,toolChoice:h,tools:g}){var c,p,f;const m=[],v=Object.assign((c=await lr({provider:"openai-compatible",providerOptions:i,schema:wf}))!=null?c:{},(p=await lr({provider:this.providerOptionsName,providerOptions:i,schema:wf}))!=null?p:{});n!=null&&m.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:w,toolChoice:y,toolWarnings:_}=CT({tools:g,toolChoice:h});return{args:{model:this.modelId,user:v.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(f=u.name)!=null?f:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:d,...i==null?void 0:i[this.providerOptionsName],reasoning_effort:v.reasoningEffort,messages:TT(t),tools:w,tool_choice:y},warnings:[...m,..._]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,h,g,c,p,f,m,v;const{args:w,warnings:y}=await this.getArgs({...t}),_=JSON.stringify(w),{responseHeaders:E,value:I,rawValue:S}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:w,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:ln(OT),abortSignal:t.abortSignal,fetch:this.config.fetch}),R=I.choices[0],$=[],z=R.message.content;z!=null&&z.length>0&&$.push({type:"text",text:z});const L=(e=R.message.reasoning_content)!=null?e:R.message.reasoning;if(L!=null&&L.length>0&&$.push({type:"reasoning",text:L}),R.message.tool_calls!=null)for(const D of R.message.tool_calls)$.push({type:"tool-call",toolCallId:(r=D.id)!=null?r:Ot(),toolName:D.function.name,input:D.function.arguments});const F={[this.providerOptionsName]:{},...await((n=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:n.call(a,{parsedBody:S}))},M=(s=I.usage)==null?void 0:s.completion_tokens_details;return(M==null?void 0:M.accepted_prediction_tokens)!=null&&(F[this.providerOptionsName].acceptedPredictionTokens=M==null?void 0:M.accepted_prediction_tokens),(M==null?void 0:M.rejected_prediction_tokens)!=null&&(F[this.providerOptionsName].rejectedPredictionTokens=M==null?void 0:M.rejected_prediction_tokens),{content:$,finishReason:_f(R.finish_reason),usage:{inputTokens:(i=(o=I.usage)==null?void 0:o.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=I.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(h=(d=I.usage)==null?void 0:d.total_tokens)!=null?h:void 0,reasoningTokens:(p=(c=(g=I.usage)==null?void 0:g.completion_tokens_details)==null?void 0:c.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(v=(m=(f=I.usage)==null?void 0:f.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?v:void 0},providerMetadata:F,request:{body:_},response:{...yf(I),headers:E,body:S},warnings:y}}async doStream(t){var e;const{args:r,warnings:a}=await this.getArgs({...t}),n={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:o,value:i}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Os(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const d={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const g=this.providerOptionsName;let c=!1,p=!1;return{stream:i.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:a})},transform(f,m){var v,w,y,_,E,I,S,R,$,z,L,F,M;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){u="error",m.enqueue({type:"error",error:f.error});return}const D=f.value;if(s==null||s.processChunk(f.rawValue),"error"in D){u="error",m.enqueue({type:"error",error:D.error.message});return}if(h&&(h=!1,m.enqueue({type:"response-metadata",...yf(D)})),D.usage!=null){const{prompt_tokens:C,completion_tokens:re,total_tokens:B,prompt_tokens_details:de,completion_tokens_details:ae}=D.usage;d.promptTokens=C??void 0,d.completionTokens=re??void 0,d.totalTokens=B??void 0,(ae==null?void 0:ae.reasoning_tokens)!=null&&(d.completionTokensDetails.reasoningTokens=ae==null?void 0:ae.reasoning_tokens),(ae==null?void 0:ae.accepted_prediction_tokens)!=null&&(d.completionTokensDetails.acceptedPredictionTokens=ae==null?void 0:ae.accepted_prediction_tokens),(ae==null?void 0:ae.rejected_prediction_tokens)!=null&&(d.completionTokensDetails.rejectedPredictionTokens=ae==null?void 0:ae.rejected_prediction_tokens),(de==null?void 0:de.cached_tokens)!=null&&(d.promptTokensDetails.cachedTokens=de==null?void 0:de.cached_tokens)}const K=D.choices[0];if((K==null?void 0:K.finish_reason)!=null&&(u=_f(K.finish_reason)),(K==null?void 0:K.delta)==null)return;const oe=K.delta,ie=(v=oe.reasoning_content)!=null?v:oe.reasoning;if(ie&&(c||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),c=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ie})),oe.content&&(p||(m.enqueue({type:"text-start",id:"txt-0"}),p=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:oe.content})),oe.tool_calls!=null)for(const C of oe.tool_calls){const re=C.index;if(l[re]==null){if(C.id==null)throw new Zn({data:C,message:"Expected 'id' to be a string."});if(((w=C.function)==null?void 0:w.name)==null)throw new Zn({data:C,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:C.id,toolName:C.function.name}),l[re]={id:C.id,type:"function",function:{name:C.function.name,arguments:(y=C.function.arguments)!=null?y:""},hasFinished:!1};const de=l[re];((_=de.function)==null?void 0:_.name)!=null&&((E=de.function)==null?void 0:E.arguments)!=null&&(de.function.arguments.length>0&&m.enqueue({type:"tool-input-start",id:de.id,toolName:de.function.name}),Rs(de.function.arguments)&&(m.enqueue({type:"tool-input-end",id:de.id}),m.enqueue({type:"tool-call",toolCallId:(I=de.id)!=null?I:Ot(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const B=l[re];B.hasFinished||(((S=C.function)==null?void 0:S.arguments)!=null&&(B.function.arguments+=($=(R=C.function)==null?void 0:R.arguments)!=null?$:""),m.enqueue({type:"tool-input-delta",id:B.id,delta:(z=C.function.arguments)!=null?z:""}),((L=B.function)==null?void 0:L.name)!=null&&((F=B.function)==null?void 0:F.arguments)!=null&&Rs(B.function.arguments)&&(m.enqueue({type:"tool-input-end",id:B.id}),m.enqueue({type:"tool-call",toolCallId:(M=B.id)!=null?M:Ot(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}},flush(f){var m,v,w,y,_,E;c&&f.enqueue({type:"reasoning-end",id:"reasoning-0"}),p&&f.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(R=>!R.hasFinished))f.enqueue({type:"tool-input-end",id:S.id}),f.enqueue({type:"tool-call",toolCallId:(m=S.id)!=null?m:Ot(),toolName:S.function.name,input:S.function.arguments});const I={[g]:{},...s==null?void 0:s.buildMetadata()};d.completionTokensDetails.acceptedPredictionTokens!=null&&(I[g].acceptedPredictionTokens=d.completionTokensDetails.acceptedPredictionTokens),d.completionTokensDetails.rejectedPredictionTokens!=null&&(I[g].rejectedPredictionTokens=d.completionTokensDetails.rejectedPredictionTokens),f.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(v=d.promptTokens)!=null?v:void 0,outputTokens:(w=d.completionTokens)!=null?w:void 0,totalTokens:(y=d.totalTokens)!=null?y:void 0,reasoningTokens:(_=d.completionTokensDetails.reasoningTokens)!=null?_:void 0,cachedInputTokens:(E=d.promptTokensDetails.cachedTokens)!=null?E:void 0},providerMetadata:I})}})),request:{body:n},response:{headers:o}}}},bf=P({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:P({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:P({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish(),OT=P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({message:P({role:H("assistant").nullish(),content:x().nullish(),reasoning_content:x().nullish(),reasoning:x().nullish(),tool_calls:Y(P({id:x().nullish(),function:P({name:x(),arguments:x()})})).nullish()}),finish_reason:x().nullish()})),usage:bf}),$T=t=>Ae([P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({delta:P({role:vt(["assistant"]).nullish(),content:x().nullish(),reasoning_content:x().nullish(),reasoning:x().nullish(),tool_calls:Y(P({index:U(),id:x().nullish(),function:P({name:x().nullish(),arguments:x().nullish()})})).nullish()}).nullish(),finish_reason:x().nullish()})),usage:bf}),t]);P({echo:nt().optional(),logitBias:St(x(),U()).optional(),suffix:x().optional(),user:x().optional()});var AT=P({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()});P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({text:x(),finish_reason:x()})),usage:AT.nullish()}),P({dimensions:U().optional(),user:x().optional()}),P({data:Y(P({embedding:Y(U())})),usage:P({prompt_tokens:U()}).nullish(),providerMetadata:St(x(),St(x(),Mt())).optional()}),P({data:Y(P({b64_json:x()}))});var xf=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},NT={extractMetadata:async({parsedBody:t})=>{const e=await _a({value:t,schema:MT});return!e.success||e.value.usage==null?void 0:xf(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,a;const n=await _a({value:e,schema:DT});n.success&&((a=(r=n.value.choices)==null?void 0:r[0])==null?void 0:a.finish_reason)==="stop"&&n.value.usage&&(t=n.value.usage)},buildMetadata:()=>xf(t)}}},Ef=P({prompt_cache_hit_tokens:U().nullish(),prompt_cache_miss_tokens:U().nullish()}),MT=P({usage:Ef.nullish()}),DT=P({choices:Y(P({finish_reason:x().nullish()})).nullish(),usage:Ef.nullish()});function Sf(t={}){var e;const r=Gh((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),a=()=>({Authorization:`Bearer ${Bh({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers}),n=o=>new RT(o,{provider:"deepseek.chat",url:({path:i})=>`${r}${i}`,headers:a,fetch:t.fetch,metadataExtractor:NT}),s=o=>n(o);return s.languageModel=n,s.chat=n,s.textEmbeddingModel=o=>{throw new go({modelId:o,modelType:"textEmbeddingModel"})},s.imageModel=o=>{throw new go({modelId:o,modelType:"imageModel"})},s}Sf();const jT=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},a=>{a.forEach(n=>{chrome.tabs.sendMessage(n.id,{type:t,data:e,direction:r,tabId:n.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},LT=(t,e,r,a)=>{const n=(s,o,i)=>{if(s.type===t&&s.direction===r){const{data:l}=s;e(l,o,i),i(o)}};return chrome.runtime.onMessage.addListener(n),()=>chrome.runtime.onMessage.removeListener(n)};class zT{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=LT("mcp-server-to-client",r=>{var a;try{if(r.sessionId!==this.targetSessionId)return;const n=sn.parse(r.mcpMessage);(a=this.onmessage)==null||a.call(this,n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const a=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!a,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const n=a.tabIds[a.tabIds.length-1];jT("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const UT=6e4;class FT{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Ii,r=>{const a=this._requestHandlerAbortControllers.get(r.params.requestId);a==null||a.abort(r.params.reason)}),this.setNotificationHandler(ki,r=>{this._onprogress(r)}),this.setRequestHandler(Ti,r=>({}))}_setupTimeout(e,r,a,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Nr(ir.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,a,n;this._transport=e;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o==null||o(l),this._onerror(l)};const i=(n=this._transport)===null||n===void 0?void 0:n.onmessage;this._transport.onmessage=(l,u)=>{i==null||i(l,u),Si(l)||UE(l)?this._onresponse(l):oh(l)?this._onrequest(l,u):zE(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);const a=new Nr(ir.ConnectionClosed,"Connection closed");for(const n of r.values())n(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){var a,n,s,o;const i=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler;if(i===void 0){(n=this._transport)===null||n===void 0||n.send({jsonrpc:"2.0",id:e.id,error:{code:ir.MethodNotFound,message:"Method not found"}}).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);const u={signal:l.signal,sessionId:(s=this._transport)===null||s===void 0?void 0:s.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:d=>this.notification(d,{relatedRequestId:e.id}),sendRequest:(d,h,g)=>this.request(d,h,{...g,relatedRequestId:e.id}),authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo};Promise.resolve().then(()=>i(e,u)).then(d=>{var h;if(!l.signal.aborted)return(h=this._transport)===null||h===void 0?void 0:h.send({result:d,jsonrpc:"2.0",id:e.id})},d=>{var h,g;if(!l.signal.aborted)return(h=this._transport)===null||h===void 0?void 0:h.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:ir.InternalError,message:(g=d.message)!==null&&g!==void 0?g:"Internal error"}})}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...a}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}s(a)}_onresponse(e){const r=Number(e.id),a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Si(e))a(e);else{const n=new Nr(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){const{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var u,d,h,g,c,p;if(!this._transport){l(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=a==null?void 0:a.signal)===null||d===void 0||d.throwIfAborted();const f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};a!=null&&a.onprogress&&(this._progressHandlers.set(f,a.onprogress),m.params={...e.params,_meta:{...((h=e.params)===null||h===void 0?void 0:h._meta)||{},progressToken:f}});const v=_=>{var E;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(E=this._transport)===null||E===void 0||E.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(_)};this._responseHandlers.set(f,_=>{var E;if(!(!((E=a==null?void 0:a.signal)===null||E===void 0)&&E.aborted)){if(_ instanceof Error)return l(_);try{const I=r.parse(_.result);i(I)}catch(I){l(I)}}}),(g=a==null?void 0:a.signal)===null||g===void 0||g.addEventListener("abort",()=>{var _;v((_=a==null?void 0:a.signal)===null||_===void 0?void 0:_.reason)});const w=(c=a==null?void 0:a.timeout)!==null&&c!==void 0?c:UT,y=()=>v(new Nr(ir.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(f,w,a==null?void 0:a.maxTotalTimeout,y,(p=a==null?void 0:a.resetTimeoutOnProgress)!==null&&p!==void 0?p:!1),this._transport.send(m,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async notification(e,r){var a,n;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((n=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&n!==void 0?n:[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const u={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(u,r).catch(d=>this._onerror(d))});return}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){const a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,s)=>Promise.resolve(r(e.parse(n),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function qT(t,e){return Object.entries(e).reduce((r,[a,n])=>(n&&typeof n=="object"?r[a]=r[a]?{...r[a],...n}:n:r[a]=n,r),{...t})}var rl={exports:{}};/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */(function(t,e){(function(r,a){a(e)})(ab,function(r){function a(){for(var T=arguments.length,b=Array(T),k=0;k<T;k++)b[k]=arguments[k];if(b.length>1){b[0]=b[0].slice(0,-1);for(var A=b.length-1,N=1;N<A;++N)b[N]=b[N].slice(1,-1);return b[A]=b[A].slice(1),b.join("")}else return b[0]}function n(T){return"(?:"+T+")"}function s(T){return T===void 0?"undefined":T===null?"null":Object.prototype.toString.call(T).split(" ").pop().split("]").shift().toLowerCase()}function o(T){return T.toUpperCase()}function i(T){return T!=null?T instanceof Array?T:typeof T.length!="number"||T.split||T.setInterval||T.call?[T]:Array.prototype.slice.call(T):[]}function l(T,b){var k=T;if(b)for(var A in b)k[A]=b[A];return k}function u(T){var b="[A-Za-z]",k="[0-9]",A=a(k,"[A-Fa-f]"),N=n(n("%[EFef]"+A+"%"+A+A+"%"+A+A)+"|"+n("%[89A-Fa-f]"+A+"%"+A+A)+"|"+n("%"+A+A)),ne="[\\:\\/\\?\\#\\[\\]\\@]",le="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Oe=a(ne,le),He=T?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",tt=T?"[\\uE000-\\uF8FF]":"[]",Ce=a(b,k,"[\\-\\.\\_\\~]",He);n(b+a(b,k,"[\\+\\-\\.]")+"*"),n(n(N+"|"+a(Ce,le,"[\\:]"))+"*");var Ze=n(n("25[0-5]")+"|"+n("2[0-4]"+k)+"|"+n("1"+k+k)+"|"+n("0?[1-9]"+k)+"|0?0?"+k),rt=n(Ze+"\\."+Ze+"\\."+Ze+"\\."+Ze),fe=n(A+"{1,4}"),Ke=n(n(fe+"\\:"+fe)+"|"+rt),ot=n(n(fe+"\\:")+"{6}"+Ke),Qe=n("\\:\\:"+n(fe+"\\:")+"{5}"+Ke),Vr=n(n(fe)+"?\\:\\:"+n(fe+"\\:")+"{4}"+Ke),fr=n(n(n(fe+"\\:")+"{0,1}"+fe)+"?\\:\\:"+n(fe+"\\:")+"{3}"+Ke),mr=n(n(n(fe+"\\:")+"{0,2}"+fe)+"?\\:\\:"+n(fe+"\\:")+"{2}"+Ke),qn=n(n(n(fe+"\\:")+"{0,3}"+fe)+"?\\:\\:"+fe+"\\:"+Ke),mn=n(n(n(fe+"\\:")+"{0,4}"+fe)+"?\\:\\:"+Ke),Ht=n(n(n(fe+"\\:")+"{0,5}"+fe)+"?\\:\\:"+fe),vr=n(n(n(fe+"\\:")+"{0,6}"+fe)+"?\\:\\:"),vn=n([ot,Qe,Vr,fr,mr,qn,mn,Ht,vr].join("|")),Ir=n(n(Ce+"|"+N)+"+");n("[vV]"+A+"+\\."+a(Ce,le,"[\\:]")+"+"),n(n(N+"|"+a(Ce,le))+"*");var Da=n(N+"|"+a(Ce,le,"[\\:\\@]"));return n(n(N+"|"+a(Ce,le,"[\\@]"))+"+"),n(n(Da+"|"+a("[\\/\\?]",tt))+"*"),{NOT_SCHEME:new RegExp(a("[^]",b,k,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(a("[^\\%\\:]",Ce,le),"g"),NOT_HOST:new RegExp(a("[^\\%\\[\\]\\:]",Ce,le),"g"),NOT_PATH:new RegExp(a("[^\\%\\/\\:\\@]",Ce,le),"g"),NOT_PATH_NOSCHEME:new RegExp(a("[^\\%\\/\\@]",Ce,le),"g"),NOT_QUERY:new RegExp(a("[^\\%]",Ce,le,"[\\:\\@\\/\\?]",tt),"g"),NOT_FRAGMENT:new RegExp(a("[^\\%]",Ce,le,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(a("[^]",Ce,le),"g"),UNRESERVED:new RegExp(Ce,"g"),OTHER_CHARS:new RegExp(a("[^\\%]",Ce,Oe),"g"),PCT_ENCODED:new RegExp(N,"g"),IPV4ADDRESS:new RegExp("^("+rt+")$"),IPV6ADDRESS:new RegExp("^\\[?("+vn+")"+n(n("\\%25|\\%(?!"+A+"{2})")+"("+Ir+")")+"?\\]?$")}}var d=u(!1),h=u(!0),g=function(){function T(b,k){var A=[],N=!0,ne=!1,le=void 0;try{for(var Oe=b[Symbol.iterator](),He;!(N=(He=Oe.next()).done)&&(A.push(He.value),!(k&&A.length===k));N=!0);}catch(tt){ne=!0,le=tt}finally{try{!N&&Oe.return&&Oe.return()}finally{if(ne)throw le}}return A}return function(b,k){if(Array.isArray(b))return b;if(Symbol.iterator in Object(b))return T(b,k);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),c=function(T){if(Array.isArray(T)){for(var b=0,k=Array(T.length);b<T.length;b++)k[b]=T[b];return k}else return Array.from(T)},p=2147483647,f=36,m=1,v=26,w=38,y=700,_=72,E=128,I="-",S=/^xn--/,R=/[^\0-\x7E]/,$=/[\x2E\u3002\uFF0E\uFF61]/g,z={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=f-m,F=Math.floor,M=String.fromCharCode;function D(T){throw new RangeError(z[T])}function K(T,b){for(var k=[],A=T.length;A--;)k[A]=b(T[A]);return k}function oe(T,b){var k=T.split("@"),A="";k.length>1&&(A=k[0]+"@",T=k[1]),T=T.replace($,".");var N=T.split("."),ne=K(N,b).join(".");return A+ne}function ie(T){for(var b=[],k=0,A=T.length;k<A;){var N=T.charCodeAt(k++);if(N>=55296&&N<=56319&&k<A){var ne=T.charCodeAt(k++);(ne&64512)==56320?b.push(((N&1023)<<10)+(ne&1023)+65536):(b.push(N),k--)}else b.push(N)}return b}var C=function(b){return String.fromCodePoint.apply(String,c(b))},re=function(b){return b-48<10?b-22:b-65<26?b-65:b-97<26?b-97:f},B=function(b,k){return b+22+75*(b<26)-((k!=0)<<5)},de=function(b,k,A){var N=0;for(b=A?F(b/y):b>>1,b+=F(b/k);b>L*v>>1;N+=f)b=F(b/L);return F(N+(L+1)*b/(b+w))},ae=function(b){var k=[],A=b.length,N=0,ne=E,le=_,Oe=b.lastIndexOf(I);Oe<0&&(Oe=0);for(var He=0;He<Oe;++He)b.charCodeAt(He)>=128&&D("not-basic"),k.push(b.charCodeAt(He));for(var tt=Oe>0?Oe+1:0;tt<A;){for(var Ce=N,Ze=1,rt=f;;rt+=f){tt>=A&&D("invalid-input");var fe=re(b.charCodeAt(tt++));(fe>=f||fe>F((p-N)/Ze))&&D("overflow"),N+=fe*Ze;var Ke=rt<=le?m:rt>=le+v?v:rt-le;if(fe<Ke)break;var ot=f-Ke;Ze>F(p/ot)&&D("overflow"),Ze*=ot}var Qe=k.length+1;le=de(N-Ce,Qe,Ce==0),F(N/Qe)>p-ne&&D("overflow"),ne+=F(N/Qe),N%=Qe,k.splice(N++,0,ne)}return String.fromCodePoint.apply(String,k)},ke=function(b){var k=[];b=ie(b);var A=b.length,N=E,ne=0,le=_,Oe=!0,He=!1,tt=void 0;try{for(var Ce=b[Symbol.iterator](),Ze;!(Oe=(Ze=Ce.next()).done);Oe=!0){var rt=Ze.value;rt<128&&k.push(M(rt))}}catch(ja){He=!0,tt=ja}finally{try{!Oe&&Ce.return&&Ce.return()}finally{if(He)throw tt}}var fe=k.length,Ke=fe;for(fe&&k.push(I);Ke<A;){var ot=p,Qe=!0,Vr=!1,fr=void 0;try{for(var mr=b[Symbol.iterator](),qn;!(Qe=(qn=mr.next()).done);Qe=!0){var mn=qn.value;mn>=N&&mn<ot&&(ot=mn)}}catch(ja){Vr=!0,fr=ja}finally{try{!Qe&&mr.return&&mr.return()}finally{if(Vr)throw fr}}var Ht=Ke+1;ot-N>F((p-ne)/Ht)&&D("overflow"),ne+=(ot-N)*Ht,N=ot;var vr=!0,vn=!1,Ir=void 0;try{for(var Da=b[Symbol.iterator](),Zm;!(vr=(Zm=Da.next()).done);vr=!0){var Vm=Zm.value;if(Vm<N&&++ne>p&&D("overflow"),Vm==N){for(var ho=ne,fo=f;;fo+=f){var mo=fo<=le?m:fo>=le+v?v:fo-le;if(ho<mo)break;var Bm=ho-mo,Hm=f-mo;k.push(M(B(mo+Bm%Hm,0))),ho=F(Bm/Hm)}k.push(M(B(ho,0))),le=de(ne,Ht,Ke==fe),ne=0,++Ke}}}catch(ja){vn=!0,Ir=ja}finally{try{!vr&&Da.return&&Da.return()}finally{if(vn)throw Ir}}++ne,++N}return k.join("")},_e=function(b){return oe(b,function(k){return S.test(k)?ae(k.slice(4).toLowerCase()):k})},Pe=function(b){return oe(b,function(k){return R.test(k)?"xn--"+ke(k):k})},xe={version:"2.1.0",ucs2:{decode:ie,encode:C},decode:ae,encode:ke,toASCII:Pe,toUnicode:_e},ve={};function Re(T){var b=T.charCodeAt(0),k=void 0;return b<16?k="%0"+b.toString(16).toUpperCase():b<128?k="%"+b.toString(16).toUpperCase():b<2048?k="%"+(b>>6|192).toString(16).toUpperCase()+"%"+(b&63|128).toString(16).toUpperCase():k="%"+(b>>12|224).toString(16).toUpperCase()+"%"+(b>>6&63|128).toString(16).toUpperCase()+"%"+(b&63|128).toString(16).toUpperCase(),k}function pt(T){for(var b="",k=0,A=T.length;k<A;){var N=parseInt(T.substr(k+1,2),16);if(N<128)b+=String.fromCharCode(N),k+=3;else if(N>=194&&N<224){if(A-k>=6){var ne=parseInt(T.substr(k+4,2),16);b+=String.fromCharCode((N&31)<<6|ne&63)}else b+=T.substr(k,6);k+=6}else if(N>=224){if(A-k>=9){var le=parseInt(T.substr(k+4,2),16),Oe=parseInt(T.substr(k+7,2),16);b+=String.fromCharCode((N&15)<<12|(le&63)<<6|Oe&63)}else b+=T.substr(k,9);k+=9}else b+=T.substr(k,3),k+=3}return b}function Ne(T,b){function k(A){var N=pt(A);return N.match(b.UNRESERVED)?N:A}return T.scheme&&(T.scheme=String(T.scheme).replace(b.PCT_ENCODED,k).toLowerCase().replace(b.NOT_SCHEME,"")),T.userinfo!==void 0&&(T.userinfo=String(T.userinfo).replace(b.PCT_ENCODED,k).replace(b.NOT_USERINFO,Re).replace(b.PCT_ENCODED,o)),T.host!==void 0&&(T.host=String(T.host).replace(b.PCT_ENCODED,k).toLowerCase().replace(b.NOT_HOST,Re).replace(b.PCT_ENCODED,o)),T.path!==void 0&&(T.path=String(T.path).replace(b.PCT_ENCODED,k).replace(T.scheme?b.NOT_PATH:b.NOT_PATH_NOSCHEME,Re).replace(b.PCT_ENCODED,o)),T.query!==void 0&&(T.query=String(T.query).replace(b.PCT_ENCODED,k).replace(b.NOT_QUERY,Re).replace(b.PCT_ENCODED,o)),T.fragment!==void 0&&(T.fragment=String(T.fragment).replace(b.PCT_ENCODED,k).replace(b.NOT_FRAGMENT,Re).replace(b.PCT_ENCODED,o)),T}function we(T){return T.replace(/^0*(.*)/,"$1")||"0"}function bt(T,b){var k=T.match(b.IPV4ADDRESS)||[],A=g(k,2),N=A[1];return N?N.split(".").map(we).join("."):T}function be(T,b){var k=T.match(b.IPV6ADDRESS)||[],A=g(k,3),N=A[1],ne=A[2];if(N){for(var le=N.toLowerCase().split("::").reverse(),Oe=g(le,2),He=Oe[0],tt=Oe[1],Ce=tt?tt.split(":").map(we):[],Ze=He.split(":").map(we),rt=b.IPV4ADDRESS.test(Ze[Ze.length-1]),fe=rt?7:8,Ke=Ze.length-fe,ot=Array(fe),Qe=0;Qe<fe;++Qe)ot[Qe]=Ce[Qe]||Ze[Ke+Qe]||"";rt&&(ot[fe-1]=bt(ot[fe-1],b));var Vr=ot.reduce(function(Ht,vr,vn){if(!vr||vr==="0"){var Ir=Ht[Ht.length-1];Ir&&Ir.index+Ir.length===vn?Ir.length++:Ht.push({index:vn,length:1})}return Ht},[]),fr=Vr.sort(function(Ht,vr){return vr.length-Ht.length})[0],mr=void 0;if(fr&&fr.length>1){var qn=ot.slice(0,fr.index),mn=ot.slice(fr.index+fr.length);mr=qn.join(":")+"::"+mn.join(":")}else mr=ot.join(":");return ne&&(mr+="%"+ne),mr}else return T}var se=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Se="".match(/(){0}/)[1]===void 0;function Ie(T){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k={},A=b.iri!==!1?h:d;b.reference==="suffix"&&(T=(b.scheme?b.scheme+":":"")+"//"+T);var N=T.match(se);if(N){Se?(k.scheme=N[1],k.userinfo=N[3],k.host=N[4],k.port=parseInt(N[5],10),k.path=N[6]||"",k.query=N[7],k.fragment=N[8],isNaN(k.port)&&(k.port=N[5])):(k.scheme=N[1]||void 0,k.userinfo=T.indexOf("@")!==-1?N[3]:void 0,k.host=T.indexOf("//")!==-1?N[4]:void 0,k.port=parseInt(N[5],10),k.path=N[6]||"",k.query=T.indexOf("?")!==-1?N[7]:void 0,k.fragment=T.indexOf("#")!==-1?N[8]:void 0,isNaN(k.port)&&(k.port=T.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?N[4]:void 0)),k.host&&(k.host=be(bt(k.host,A),A)),k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&!k.path&&k.query===void 0?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",b.reference&&b.reference!=="suffix"&&b.reference!==k.reference&&(k.error=k.error||"URI is not a "+b.reference+" reference.");var ne=ve[(b.scheme||k.scheme||"").toLowerCase()];if(!b.unicodeSupport&&(!ne||!ne.unicodeSupport)){if(k.host&&(b.domainHost||ne&&ne.domainHost))try{k.host=xe.toASCII(k.host.replace(A.PCT_ENCODED,pt).toLowerCase())}catch(le){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+le}Ne(k,d)}else Ne(k,A);ne&&ne.parse&&ne.parse(k,b)}else k.error=k.error||"URI can not be parsed.";return k}function ye(T,b){var k=b.iri!==!1?h:d,A=[];return T.userinfo!==void 0&&(A.push(T.userinfo),A.push("@")),T.host!==void 0&&A.push(be(bt(String(T.host),k),k).replace(k.IPV6ADDRESS,function(N,ne,le){return"["+ne+(le?"%25"+le:"")+"]"})),(typeof T.port=="number"||typeof T.port=="string")&&(A.push(":"),A.push(String(T.port))),A.length?A.join(""):void 0}var Xe=/^\.\.?\//,Le=/^\/\.(\/|$)/,J=/^\/\.\.(\/|$)/,Me=/^\/?(?:.|\n)*?(?=\/|$)/;function ze(T){for(var b=[];T.length;)if(T.match(Xe))T=T.replace(Xe,"");else if(T.match(Le))T=T.replace(Le,"/");else if(T.match(J))T=T.replace(J,"/"),b.pop();else if(T==="."||T==="..")T="";else{var k=T.match(Me);if(k){var A=k[0];T=T.slice(A.length),b.push(A)}else throw new Error("Unexpected dot segment condition")}return b.join("")}function pe(T){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=b.iri?h:d,A=[],N=ve[(b.scheme||T.scheme||"").toLowerCase()];if(N&&N.serialize&&N.serialize(T,b),T.host&&!k.IPV6ADDRESS.test(T.host)){if(b.domainHost||N&&N.domainHost)try{T.host=b.iri?xe.toUnicode(T.host):xe.toASCII(T.host.replace(k.PCT_ENCODED,pt).toLowerCase())}catch(Oe){T.error=T.error||"Host's domain name can not be converted to "+(b.iri?"Unicode":"ASCII")+" via punycode: "+Oe}}Ne(T,k),b.reference!=="suffix"&&T.scheme&&(A.push(T.scheme),A.push(":"));var ne=ye(T,b);if(ne!==void 0&&(b.reference!=="suffix"&&A.push("//"),A.push(ne),T.path&&T.path.charAt(0)!=="/"&&A.push("/")),T.path!==void 0){var le=T.path;!b.absolutePath&&(!N||!N.absolutePath)&&(le=ze(le)),ne===void 0&&(le=le.replace(/^\/\//,"/%2F")),A.push(le)}return T.query!==void 0&&(A.push("?"),A.push(T.query)),T.fragment!==void 0&&(A.push("#"),A.push(T.fragment)),A.join("")}function Be(T,b){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},A=arguments[3],N={};return A||(T=Ie(pe(T,k),k),b=Ie(pe(b,k),k)),k=k||{},!k.tolerant&&b.scheme?(N.scheme=b.scheme,N.userinfo=b.userinfo,N.host=b.host,N.port=b.port,N.path=ze(b.path||""),N.query=b.query):(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0?(N.userinfo=b.userinfo,N.host=b.host,N.port=b.port,N.path=ze(b.path||""),N.query=b.query):(b.path?(b.path.charAt(0)==="/"?N.path=ze(b.path):((T.userinfo!==void 0||T.host!==void 0||T.port!==void 0)&&!T.path?N.path="/"+b.path:T.path?N.path=T.path.slice(0,T.path.lastIndexOf("/")+1)+b.path:N.path=b.path,N.path=ze(N.path)),N.query=b.query):(N.path=T.path,b.query!==void 0?N.query=b.query:N.query=T.query),N.userinfo=T.userinfo,N.host=T.host,N.port=T.port),N.scheme=T.scheme),N.fragment=b.fragment,N}function hr(T,b,k){var A=l({scheme:"null"},k);return pe(Be(Ie(T,A),Ie(b,A),A,!0),A)}function Ft(T,b){return typeof T=="string"?T=pe(Ie(T,b),b):s(T)==="object"&&(T=Ie(pe(T,b),b)),T}function mt(T,b,k){return typeof T=="string"?T=pe(Ie(T,k),k):s(T)==="object"&&(T=pe(T,k)),typeof b=="string"?b=pe(Ie(b,k),k):s(b)==="object"&&(b=pe(b,k)),T===b}function Yt(T,b){return T&&T.toString().replace(!b||!b.iri?d.ESCAPE:h.ESCAPE,Re)}function xt(T,b){return T&&T.toString().replace(!b||!b.iri?d.PCT_ENCODED:h.PCT_ENCODED,pt)}var qt={scheme:"http",domainHost:!0,parse:function(b,k){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b},serialize:function(b,k){var A=String(b.scheme).toLowerCase()==="https";return(b.port===(A?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}},Sr={scheme:"https",domainHost:qt.domainHost,parse:qt.parse,serialize:qt.serialize};function pn(T){return typeof T.secure=="boolean"?T.secure:String(T.scheme).toLowerCase()==="wss"}var Ge={scheme:"ws",domainHost:!0,parse:function(b,k){var A=b;return A.secure=pn(A),A.resourceName=(A.path||"/")+(A.query?"?"+A.query:""),A.path=void 0,A.query=void 0,A},serialize:function(b,k){if((b.port===(pn(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){var A=b.resourceName.split("?"),N=g(A,2),ne=N[0],le=N[1];b.path=ne&&ne!=="/"?ne:void 0,b.query=le,b.resourceName=void 0}return b.fragment=void 0,b}},Zt={scheme:"wss",domainHost:Ge.domainHost,parse:Ge.parse,serialize:Ge.serialize},Xt={},Ra="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Vt="[0-9A-Fa-f]",Kl=n(n("%[EFef]"+Vt+"%"+Vt+Vt+"%"+Vt+Vt)+"|"+n("%[89A-Fa-f]"+Vt+"%"+Vt+Vt)+"|"+n("%"+Vt+Vt)),Un="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Oa="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",$a=a(Oa,'[\\"\\\\]'),Aa="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",qr=new RegExp(Ra,"g"),ht=new RegExp(Kl,"g"),Na=new RegExp(a("[^]",Un,"[\\.]",'[\\"]',$a),"g"),Ma=new RegExp(a("[^]",Ra,Aa),"g"),Bt=Ma;function Fn(T){var b=pt(T);return b.match(qr)?b:T}var ue={scheme:"mailto",parse:function(b,k){var A=b,N=A.to=A.path?A.path.split(","):[];if(A.path=void 0,A.query){for(var ne=!1,le={},Oe=A.query.split("&"),He=0,tt=Oe.length;He<tt;++He){var Ce=Oe[He].split("=");switch(Ce[0]){case"to":for(var Ze=Ce[1].split(","),rt=0,fe=Ze.length;rt<fe;++rt)N.push(Ze[rt]);break;case"subject":A.subject=xt(Ce[1],k);break;case"body":A.body=xt(Ce[1],k);break;default:ne=!0,le[xt(Ce[0],k)]=xt(Ce[1],k);break}}ne&&(A.headers=le)}A.query=void 0;for(var Ke=0,ot=N.length;Ke<ot;++Ke){var Qe=N[Ke].split("@");if(Qe[0]=xt(Qe[0]),k.unicodeSupport)Qe[1]=xt(Qe[1],k).toLowerCase();else try{Qe[1]=xe.toASCII(xt(Qe[1],k).toLowerCase())}catch(Vr){A.error=A.error||"Email address's domain name can not be converted to ASCII via punycode: "+Vr}N[Ke]=Qe.join("@")}return A},serialize:function(b,k){var A=b,N=i(b.to);if(N){for(var ne=0,le=N.length;ne<le;++ne){var Oe=String(N[ne]),He=Oe.lastIndexOf("@"),tt=Oe.slice(0,He).replace(ht,Fn).replace(ht,o).replace(Na,Re),Ce=Oe.slice(He+1);try{Ce=k.iri?xe.toUnicode(Ce):xe.toASCII(xt(Ce,k).toLowerCase())}catch(Ke){A.error=A.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Ke}N[ne]=tt+"@"+Ce}A.path=N.join(",")}var Ze=b.headers=b.headers||{};b.subject&&(Ze.subject=b.subject),b.body&&(Ze.body=b.body);var rt=[];for(var fe in Ze)Ze[fe]!==Xt[fe]&&rt.push(fe.replace(ht,Fn).replace(ht,o).replace(Ma,Re)+"="+Ze[fe].replace(ht,Fn).replace(ht,o).replace(Bt,Re));return rt.length&&(A.query=rt.join("&")),A}},ct=/^([^\:]+)\:(.*)/,Zr={scheme:"urn",parse:function(b,k){var A=b.path&&b.path.match(ct),N=b;if(A){var ne=k.scheme||N.scheme||"urn",le=A[1].toLowerCase(),Oe=A[2],He=ne+":"+(k.nid||le),tt=ve[He];N.nid=le,N.nss=Oe,N.path=void 0,tt&&(N=tt.parse(N,k))}else N.error=N.error||"URN can not be parsed.";return N},serialize:function(b,k){var A=k.scheme||b.scheme||"urn",N=b.nid,ne=A+":"+(k.nid||N),le=ve[ne];le&&(b=le.serialize(b,k));var Oe=b,He=b.nss;return Oe.path=(N||k.nid)+":"+He,Oe}},hn=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,fn={scheme:"urn:uuid",parse:function(b,k){var A=b;return A.uuid=A.nss,A.nss=void 0,!k.tolerant&&(!A.uuid||!A.uuid.match(hn))&&(A.error=A.error||"UUID is not valid."),A},serialize:function(b,k){var A=b;return A.nss=(b.uuid||"").toLowerCase(),A}};ve[qt.scheme]=qt,ve[Sr.scheme]=Sr,ve[Ge.scheme]=Ge,ve[Zt.scheme]=Zt,ve[ue.scheme]=ue,ve[Zr.scheme]=Zr,ve[fn.scheme]=fn,r.SCHEMES=ve,r.pctEncChar=Re,r.pctDecChars=pt,r.parse=Ie,r.removeDotSegments=ze,r.serialize=pe,r.resolveComponents=Be,r.resolve=hr,r.normalize=Ft,r.equal=mt,r.escapeComponent=Yt,r.unescapeComponent=xt,Object.defineProperty(r,"__esModule",{value:!0})})})(rl,rl.exports);var ZT=rl.exports,nl=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var a,n,s;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(n=a;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),a=s.length,a!==Object.keys(r).length)return!1;for(n=a;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=a;n--!==0;){var o=s[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},VT=function(e){for(var r=0,a=e.length,n=0,s;n<a;)r++,s=e.charCodeAt(n++),s>=55296&&s<=56319&&n<a&&(s=e.charCodeAt(n),(s&64512)==56320&&n++);return r},Cn={copy:BT,checkDataType:al,checkDataTypes:HT,coerceToTypes:JT,toHash:sl,getProperty:ol,escapeQuotes:il,equal:nl,ucs2length:VT,varOccurences:KT,varReplace:QT,schemaHasRules:YT,schemaHasRulesExcept:XT,schemaUnknownRules:ek,toQuotedString:ll,getPathExpr:tk,getPath:rk,getData:sk,unescapeFragment:ok,unescapeJsonPointer:cl,escapeFragment:ik,escapeJsonPointer:ul};function BT(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function al(t,e,r,a){var n=a?" !== ":" === ",s=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(t){case"null":return e+n+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+s+"typeof "+e+n+'"object"'+s+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+n+'"number"'+s+i+"("+e+" % 1)"+s+e+n+e+(r?s+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+n+'"'+t+'"'+(r?s+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+n+'"'+t+'"'}}function HT(t,e,r){switch(t.length){case 1:return al(t[0],e,r,!0);default:var a="",n=sl(t);n.array&&n.object&&(a=n.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer;for(var s in n)a+=(a?" && ":"")+al(s,e,r,!0);return a}}var If=sl(["string","number","integer","boolean","null"]);function JT(t,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var n=e[a];(If[n]||t==="array"&&n==="array")&&(r[r.length]=n)}if(r.length)return r}else{if(If[e])return[e];if(t==="array"&&e==="array")return["array"]}}function sl(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var WT=/^[a-z$_][a-z$_0-9]*$/i,GT=/'|\\/g;function ol(t){return typeof t=="number"?"["+t+"]":WT.test(t)?"."+t:"['"+il(t)+"']"}function il(t){return t.replace(GT,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function KT(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function QT(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function YT(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function XT(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var a in t)if(a!=r&&e[a])return!0}function ek(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function ll(t){return"'"+il(t)+"'"}function tk(t,e,r,a){var n=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return Tf(t,n)}function rk(t,e,r){var a=ll(r?"/"+ul(e):ol(e));return Tf(t,a)}var nk=/^\/(?:[^~]|~0|~1)*$/,ak=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function sk(t,e,r){var a,n,s,o;if(t==="")return"rootData";if(t[0]=="/"){if(!nk.test(t))throw new Error("Invalid JSON-pointer: "+t);n=t,s="rootData"}else{if(o=t.match(ak),!o)throw new Error("Invalid JSON-pointer: "+t);if(a=+o[1],n=o[2],n=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(s="data"+(e-a||""),!n)return s}for(var i=s,l=n.split("/"),u=0;u<l.length;u++){var d=l[u];d&&(s+=ol(cl(d)),i+=" && "+s)}return i}function Tf(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function ok(t){return cl(decodeURIComponent(t))}function ik(t){return encodeURIComponent(ul(t))}function ul(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function cl(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var lk=Cn,kf=uk;function uk(t){lk.copy(t,this)}var Pf={exports:{}},Mr=Pf.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};$s(e,a,n,t,"",t)};Mr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},Mr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Mr.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Mr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function $s(t,e,r,a,n,s,o,i,l,u){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,u);for(var d in a){var h=a[d];if(Array.isArray(h)){if(d in Mr.arrayKeywords)for(var g=0;g<h.length;g++)$s(t,e,r,h[g],n+"/"+d+"/"+g,s,n,d,a,g)}else if(d in Mr.propsKeywords){if(h&&typeof h=="object")for(var c in h)$s(t,e,r,h[c],n+"/"+d+"/"+ck(c),s,n,d,a,c)}else(d in Mr.keywords||t.allKeys&&!(d in Mr.skipKeywords))&&$s(t,e,r,h,n+"/"+d,s,n,d,a)}r(a,n,s,o,i,l,u)}}function ck(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var dk=Pf.exports,ba=ZT,Cf=nl,As=Cn,Ns=kf,pk=dk,dl=Dr;Dr.normalizeId=jr,Dr.fullPath=Ds,Dr.url=js,Dr.ids=gk,Dr.inlineRef=pl,Dr.schema=Ms;function Dr(t,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return Dr.call(this,t,e,a);if(a=a||this._schemas[r],a instanceof Ns)return pl(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var n=Ms.call(this,e,r),s,o,i;return n&&(s=n.schema,e=n.root,i=n.baseId),s instanceof Ns?o=s.validate||t.call(this,s.schema,e,void 0,i):s!==void 0&&(o=pl(s,this._opts.inlineRefs)?s:t.call(this,s,e,void 0,i)),o}function Ms(t,e){var r=ba.parse(e),a=Of(r),n=Ds(this._getId(t.schema));if(Object.keys(t.schema).length===0||a!==n){var s=jr(a),o=this._refs[s];if(typeof o=="string")return hk.call(this,t,o,r);if(o instanceof Ns)o.validate||this._compile(o),t=o;else if(o=this._schemas[s],o instanceof Ns){if(o.validate||this._compile(o),s==jr(e))return{schema:o,root:t,baseId:n};t=o}else return;if(!t.schema)return;n=Ds(this._getId(t.schema))}return Rf.call(this,r,n,t.schema,t)}function hk(t,e,r){var a=Ms.call(this,t,e);if(a){var n=a.schema,s=a.baseId;t=a.root;var o=this._getId(n);return o&&(s=js(s,o)),Rf.call(this,r,s,n,t)}}var fk=As.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Rf(t,e,r,a){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var n=t.fragment.split("/"),s=1;s<n.length;s++){var o=n[s];if(o){if(o=As.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!fk[o]&&(i=this._getId(r),i&&(e=js(e,i)),r.$ref)){var l=js(e,r.$ref),u=Ms.call(this,a,l);u&&(r=u.schema,a=u.root,e=u.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var mk=As.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function pl(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return hl(t);if(e)return fl(t)<=e}function hl(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!hl(e))return!1}else for(var a in t)if(a=="$ref"||(e=t[a],typeof e=="object"&&!hl(e)))return!1;return!0}function fl(t){var e=0,r;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if(r=t[a],typeof r=="object"&&(e+=fl(r)),e==1/0)return 1/0}else for(var n in t){if(n=="$ref")return 1/0;if(mk[n])e++;else if(r=t[n],typeof r=="object"&&(e+=fl(r)+1),e==1/0)return 1/0}return e}function Ds(t,e){e!==!1&&(t=jr(t));var r=ba.parse(t);return Of(r)}function Of(t){return ba.serialize(t).split("#")[0]+"#"}var vk=/#\/?$/;function jr(t){return t?t.replace(vk,""):""}function js(t,e){return e=jr(e),ba.resolve(t,e)}function gk(t){var e=jr(this._getId(t)),r={"":e},a={"":Ds(e,!1)},n={},s=this;return pk(t,{allKeys:!0},function(o,i,l,u,d,h,g){if(i!==""){var c=s._getId(o),p=r[u],f=a[u]+"/"+d;if(g!==void 0&&(f+="/"+(typeof g=="number"?g:As.escapeFragment(g))),typeof c=="string"){c=p=jr(p?ba.resolve(p,c):c);var m=s._refs[c];if(typeof m=="string"&&(m=s._refs[m]),m&&m.schema){if(!Cf(o,m.schema))throw new Error('id "'+c+'" resolves to more than one schema')}else if(c!=jr(f))if(c[0]=="#"){if(n[c]&&!Cf(o,n[c]))throw new Error('id "'+c+'" resolves to more than one schema');n[c]=o}else s._refs[c]=f}r[i]=p,a[i]=f}}),n}var ml=dl,vl={Validation:$f(yk),MissingRef:$f(gl)};function yk(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}gl.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function gl(t,e,r){this.message=r||gl.message(t,e),this.missingRef=ml.url(t,e),this.missingSchema=ml.normalizeId(ml.fullPath(this.missingRef))}function $f(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Af=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&function(s){return function(o){return function(i,l){var u={key:i,value:o[i]},d={key:l,value:o[l]};return s(u,d)}}}(e.cmp),n=[];return function s(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i<o.length;i++)i&&(l+=","),l+=s(o[i])||"null";return l+"]"}if(o===null)return"null";if(n.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=n.push(o)-1,d=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<d.length;i++){var h=d[i],g=s(o[h]);g&&(l&&(l+=","),l+=JSON.stringify(h)+":"+g)}return n.splice(u,1),"{"+l+"}"}}(t)},Nf=function(e,r,a){var n="",s=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var u="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(u);else throw new Error(u)}}if(e.isTop&&(n+=" var validate = ",s&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",d=e.level,h=e.dataLevel,g=e.schema[r],c=e.schemaPath+e.util.getProperty(r),p=e.errSchemaPath+"/"+r,E=!e.opts.allErrors,R,f="data"+(h||""),_="valid"+d;if(e.schema===!1){e.isTop?E=!0:n+=" var "+_+" = false; ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s?n+=" return data; ":n+=" validate.errors = null; return true; ":n+=" var "+_+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var w=e.isTop,d=e.level=0,h=e.dataLevel=0,f="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var y="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{var d=e.level,h=e.dataLevel,f="data"+(h||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),s&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+d+" = errors;"}var _="valid"+d,E=!e.opts.allErrors,I="",S="",R,$=e.schema.type,z=Array.isArray($);if($&&e.opts.nullable&&e.schema.nullable===!0&&(z?$.indexOf("null")==-1&&($=$.concat("null")):$!="null"&&($=[$,"null"],z=!0)),z&&$.length==1&&($=$[0],z=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),$){if(e.opts.coerceTypes)var L=e.util.coerceToTypes(e.opts.coerceTypes,$);var F=e.RULES.types[$];if(L||z||F===!0||F&&!Le(F)){var c=e.schemaPath+".type",p=e.errSchemaPath+"/type",c=e.schemaPath+".type",p=e.errSchemaPath+"/type",M=z?"checkDataTypes":"checkDataType";if(n+=" if ("+e.util[M]($,f,e.opts.strictNumbers,!0)+") { ",L){var D="dataType"+d,K="coerced"+d;n+=" var "+D+" = typeof "+f+"; var "+K+" = undefined; ",e.opts.coerceTypes=="array"&&(n+=" if ("+D+" == 'object' && Array.isArray("+f+") && "+f+".length == 1) { "+f+" = "+f+"[0]; "+D+" = typeof "+f+"; if ("+e.util.checkDataType(e.schema.type,f,e.opts.strictNumbers)+") "+K+" = "+f+"; } "),n+=" if ("+K+" !== undefined) ; ";var oe=L;if(oe)for(var ie,C=-1,re=oe.length-1;C<re;)ie=oe[C+=1],ie=="string"?n+=" else if ("+D+" == 'number' || "+D+" == 'boolean') "+K+" = '' + "+f+"; else if ("+f+" === null) "+K+" = ''; ":ie=="number"||ie=="integer"?(n+=" else if ("+D+" == 'boolean' || "+f+" === null || ("+D+" == 'string' && "+f+" && "+f+" == +"+f+" ",ie=="integer"&&(n+=" && !("+f+" % 1)"),n+=")) "+K+" = +"+f+"; "):ie=="boolean"?n+=" else if ("+f+" === 'false' || "+f+" === 0 || "+f+" === null) "+K+" = false; else if ("+f+" === 'true' || "+f+" === 1) "+K+" = true; ":ie=="null"?n+=" else if ("+f+" === '' || "+f+" === 0 || "+f+" === false) "+K+" = null; ":e.opts.coerceTypes=="array"&&ie=="array"&&(n+=" else if ("+D+" == 'string' || "+D+" == 'number' || "+D+" == 'boolean' || "+f+" == null) "+K+" = ["+f+"]; ");n+=" else { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",z?n+=""+$.join(","):n+=""+$,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",z?n+=""+$.join(","):n+=""+$,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+K+" !== undefined) { ";var B=h?"data"+(h-1||""):"parentData",de=h?e.dataPathArr[h]:"parentDataProperty";n+=" "+f+" = "+K+"; ",h||(n+="if ("+B+" !== undefined)"),n+=" "+B+"["+de+"] = "+K+"; } "}else{var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",z?n+=""+$.join(","):n+=""+$,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",z?n+=""+$.join(","):n+=""+$,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!o)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",E&&(n+=" } if (errors === ",w?n+="0":n+="errs_"+d,n+=") { ",S+="}");else{var ae=e.RULES;if(ae){for(var F,ke=-1,_e=ae.length-1;ke<_e;)if(F=ae[ke+=1],Le(F)){if(F.type&&(n+=" if ("+e.util.checkDataType(F.type,f,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(F.type=="object"&&e.schema.properties){var g=e.schema.properties,Pe=Object.keys(g),xe=Pe;if(xe)for(var ve,Re=-1,pt=xe.length-1;Re<pt;){ve=xe[Re+=1];var Ne=g[ve];if(Ne.default!==void 0){var we=f+e.util.getProperty(ve);if(e.compositeRule){if(e.opts.strictDefaults){var y="default is ignored for: "+we;if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}}else n+=" if ("+we+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+we+" === null || "+we+" === '' "),n+=" ) "+we+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(Ne.default)+" ":n+=" "+JSON.stringify(Ne.default)+" ",n+="; "}}}else if(F.type=="array"&&Array.isArray(e.schema.items)){var bt=e.schema.items;if(bt){for(var Ne,C=-1,be=bt.length-1;C<be;)if(Ne=bt[C+=1],Ne.default!==void 0){var we=f+"["+C+"]";if(e.compositeRule){if(e.opts.strictDefaults){var y="default is ignored for: "+we;if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}}else n+=" if ("+we+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+we+" === null || "+we+" === '' "),n+=" ) "+we+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(Ne.default)+" ":n+=" "+JSON.stringify(Ne.default)+" ",n+="; "}}}}var se=F.rules;if(se){for(var Se,Ie=-1,ye=se.length-1;Ie<ye;)if(Se=se[Ie+=1],J(Se)){var Xe=Se.code(e,Se.keyword,F.type);Xe&&(n+=" "+Xe+" ",E&&(I+="}"))}}if(E&&(n+=" "+I+" ",I=""),F.type&&(n+=" } ",$&&$===F.type&&!L)){n+=" else { ";var c=e.schemaPath+".type",p=e.errSchemaPath+"/type",m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",z?n+=""+$.join(","):n+=""+$,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",z?n+=""+$.join(","):n+=""+$,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}E&&(n+=" if (errors === ",w?n+="0":n+="errs_"+d,n+=") { ",S+="}")}}}E&&(n+=" "+S+" "),w?(s?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+_+" = errors === errs_"+d+";";function Le(ze){for(var pe=ze.rules,Be=0;Be<pe.length;Be++)if(J(pe[Be]))return!0}function J(ze){return e.schema[ze.keyword]!==void 0||ze.implements&&Me(ze)}function Me(ze){for(var pe=ze.implements,Be=0;Be<pe.length;Be++)if(e.schema[pe[Be]]!==void 0)return!0}return n},Ls=dl,zs=Cn,Mf=vl,_k=Af,Df=Nf,wk=zs.ucs2length,bk=nl,xk=Mf.Validation,Ek=yl;function yl(t,e,r,a){var n=this,s=this._opts,o=[void 0],i={},l=[],u={},d=[],h={},g=[];e=e||{schema:t,refVal:o,refs:i};var c=Sk.call(this,t,e,a),p=this._compilations[c.index];if(c.compiling)return p.callValidate=y;var f=this._formats,m=this.RULES;try{var v=_(t,e,r,a);p.validate=v;var w=p.callValidate;return w&&(w.schema=v.schema,w.errors=null,w.refs=v.refs,w.refVal=v.refVal,w.root=v.root,w.$async=v.$async,s.sourceCode&&(w.source=v.source)),v}finally{Ik.call(this,t,e,a)}function y(){var M=p.validate,D=M.apply(this,arguments);return y.errors=M.errors,D}function _(M,D,K,oe){var ie=!D||D&&D.schema==M;if(D.schema!=e.schema)return yl.call(n,M,D,K,oe);var C=M.$async===!0,re=Df({isTop:!0,schema:M,isRoot:ie,baseId:oe,root:D,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Mf.MissingRef,RULES:m,validate:Df,util:zs,resolve:Ls,resolveRef:E,usePattern:z,useDefault:L,useCustomRule:F,opts:s,formats:f,logger:n.logger,self:n});re=Us(o,Pk)+Us(l,Tk)+Us(d,kk)+Us(g,Ck)+re,s.processCode&&(re=s.processCode(re,M));var B;try{var de=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",re);B=de(n,m,f,e,o,d,g,bk,wk,xk),o[0]=B}catch(ae){throw n.logger.error("Error compiling schema, function code:",re),ae}return B.schema=M,B.errors=null,B.refs=i,B.refVal=o,B.root=ie?B:D,C&&(B.$async=!0),s.sourceCode===!0&&(B.source={code:re,patterns:l,defaults:d}),B}function E(M,D,K){D=Ls.url(M,D);var oe=i[D],ie,C;if(oe!==void 0)return ie=o[oe],C="refVal["+oe+"]",$(ie,C);if(!K&&e.refs){var re=e.refs[D];if(re!==void 0)return ie=e.refVal[re],C=I(D,ie),$(ie,C)}C=I(D);var B=Ls.call(n,_,e,D);if(B===void 0){var de=r&&r[D];de&&(B=Ls.inlineRef(de,s.inlineRefs)?de:yl.call(n,de,e,r,M))}if(B===void 0)S(D);else return R(D,B),$(B,C)}function I(M,D){var K=o.length;return o[K]=D,i[M]=K,"refVal"+K}function S(M){delete i[M]}function R(M,D){var K=i[M];o[K]=D}function $(M,D){return typeof M=="object"||typeof M=="boolean"?{code:D,schema:M,inline:!0}:{code:D,$async:M&&!!M.$async}}function z(M){var D=u[M];return D===void 0&&(D=u[M]=l.length,l[D]=M),"pattern"+D}function L(M){switch(typeof M){case"boolean":case"number":return""+M;case"string":return zs.toQuotedString(M);case"object":if(M===null)return"null";var D=_k(M),K=h[D];return K===void 0&&(K=h[D]=d.length,d[K]=M),"default"+K}}function F(M,D,K,oe){if(n._opts.validateSchema!==!1){var ie=M.definition.dependencies;if(ie&&!ie.every(function(xe){return Object.prototype.hasOwnProperty.call(K,xe)}))throw new Error("parent schema must have all required keywords: "+ie.join(","));var C=M.definition.validateSchema;if(C){var re=C(D);if(!re){var B="keyword schema is invalid: "+n.errorsText(C.errors);if(n._opts.validateSchema=="log")n.logger.error(B);else throw new Error(B)}}}var de=M.definition.compile,ae=M.definition.inline,ke=M.definition.macro,_e;if(de)_e=de.call(n,D,K,oe);else if(ke)_e=ke.call(n,D,K,oe),s.validateSchema!==!1&&n.validateSchema(_e,!0);else if(ae)_e=ae.call(n,oe,M.keyword,D,K);else if(_e=M.definition.validate,!_e)return;if(_e===void 0)throw new Error('custom keyword "'+M.keyword+'"failed to compile');var Pe=g.length;return g[Pe]=_e,{code:"customRule"+Pe,validate:_e}}}function Sk(t,e,r){var a=jf.call(this,t,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:t,root:e,baseId:r},{index:a,compiling:!1})}function Ik(t,e,r){var a=jf.call(this,t,e,r);a>=0&&this._compilations.splice(a,1)}function jf(t,e,r){for(var a=0;a<this._compilations.length;a++){var n=this._compilations[a];if(n.schema==t&&n.root==e&&n.baseId==r)return a}return-1}function Tk(t,e){return"var pattern"+t+" = new RegExp("+zs.toQuotedString(e[t])+");"}function kk(t){return"var default"+t+" = defaults["+t+"];"}function Pk(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function Ck(t){return"var customRule"+t+" = customRules["+t+"];"}function Us(t,e){if(!t.length)return"";for(var r="",a=0;a<t.length;a++)r+=e(a,t);return r}var Lf={exports:{}},Fs=Lf.exports=function(){this._cache={}};Fs.prototype.put=function(e,r){this._cache[e]=r},Fs.prototype.get=function(e){return this._cache[e]},Fs.prototype.del=function(e){delete this._cache[e]},Fs.prototype.clear=function(){this._cache={}};var Rk=Lf.exports,Ok=Cn,$k=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ak=[0,31,28,31,30,31,30,31,31,30,31,30,31],Nk=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,zf=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Mk=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Dk=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Uf=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Ff=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,qf=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Zf=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Vf=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Bf=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,jk=qs;function qs(t){return t=t=="full"?"full":"fast",Ok.copy(qs[t])}qs.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":Uf,url:Ff,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:zf,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:Wf,uuid:qf,"json-pointer":Zf,"json-pointer-uri-fragment":Vf,"relative-json-pointer":Bf},qs.full={date:Hf,time:Jf,"date-time":Uk,uri:qk,"uri-reference":Dk,"uri-template":Uf,url:Ff,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:zf,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:Wf,uuid:qf,"json-pointer":Zf,"json-pointer-uri-fragment":Vf,"relative-json-pointer":Bf};function Lk(t){return t%4===0&&(t%100!==0||t%400===0)}function Hf(t){var e=t.match($k);if(!e)return!1;var r=+e[1],a=+e[2],n=+e[3];return a>=1&&a<=12&&n>=1&&n<=(a==2&&Lk(r)?29:Ak[a])}function Jf(t,e){var r=t.match(Nk);if(!r)return!1;var a=r[1],n=r[2],s=r[3],o=r[5];return(a<=23&&n<=59&&s<=59||a==23&&n==59&&s==60)&&(!e||o)}var zk=/t|\s/i;function Uk(t){var e=t.split(zk);return e.length==2&&Hf(e[0])&&Jf(e[1],!0)}var Fk=/\/|:/;function qk(t){return Fk.test(t)&&Mk.test(t)}var Zk=/[^\\]\\Z/;function Wf(t){if(Zk.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}var Vk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(o||""),h="valid"+s,g,c;if(i=="#"||i=="#/")e.isRoot?(g=e.async,c="validate"):(g=e.root.schema.$async===!0,c="root.refVal[0]");else{var p=e.resolveRef(e.baseId,i,e.isRoot);if(p===void 0){var f=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(f);var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(n+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(n+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(n+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(f),u&&(n+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,f)}else if(p.inline){var w=e.util.copy(e);w.level++;var y="valid"+w.level;w.schema=p.schema,w.schemaPath="",w.errSchemaPath=i;var _=e.validate(w).replace(/validate\.schema/g,p.code);n+=" "+_+" ",u&&(n+=" if ("+y+") { ")}else g=p.$async===!0||e.async&&p.$async!==!1,c=p.code}if(c){var m=m||[];m.push(n),n="",e.opts.passContext?n+=" "+c+".call(this, ":n+=" "+c+"( ",n+=" "+d+", (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var E=o?"data"+(o-1||""):"parentData",I=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+E+" , "+I+", rootData) ";var S=n;if(n=m.pop(),g){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(n+=" var "+h+"; "),n+=" try { await "+S+"; ",u&&(n+=" "+h+" = true; "),n+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(n+=" "+h+" = false; "),n+=" } ",u&&(n+=" if ("+h+") { ")}else n+=" if (!"+S+") { if (vErrors === null) vErrors = "+c+".errors; else vErrors = vErrors.concat("+c+".errors); errors = vErrors.length; } ",u&&(n+=" else { ")}return n},Bk=function(e,r,a){var n=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u=e.util.copy(e),d="";u.level++;var h="valid"+u.level,g=u.baseId,c=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m<v;)f=p[m+=1],(e.opts.strictKeywords?typeof f=="object"&&Object.keys(f).length>0||f===!1:e.util.schemaHasRules(f,e.RULES.all))&&(c=!1,u.schema=f,u.schemaPath=o+"["+m+"]",u.errSchemaPath=i+"/"+m,n+=" "+e.validate(u)+" ",u.baseId=g,l&&(n+=" if ("+h+") { ",d+="}"));return l&&(c?n+=" if (true) { ":n+=" "+d.slice(0,-1)+" "),n},Hk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=i.every(function(R){return e.opts.strictKeywords?typeof R=="object"&&Object.keys(R).length>0||R===!1:e.util.schemaHasRules(R,e.RULES.all)});if(v){var w=p.baseId;n+=" var "+c+" = errors; var "+g+" = false; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=i;if(_)for(var E,I=-1,S=_.length-1;I<S;)E=_[I+=1],p.schema=E,p.schemaPath=l+"["+I+"]",p.errSchemaPath=u+"/"+I,n+=" "+e.validate(p)+" ",p.baseId=w,n+=" "+g+" = "+g+" || "+m+"; if (!"+g+") { ",f+="}";e.compositeRule=p.compositeRule=y,n+=" "+f+" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else d&&(n+=" if (true) { ");return n},Jk=function(e,r,a){var n=" ",s=e.schema[r],o=e.errSchemaPath+"/"+r;e.opts.allErrors;var i=e.util.toQuotedString(s);return e.opts.$comment===!0?n+=" console.log("+i+");":typeof e.opts.$comment=="function"&&(n+=" self._opts.$comment("+i+", "+e.util.toQuotedString(o)+", validate.root.schema);"),n},Wk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),c||(n+=" var schema"+s+" = validate.schema"+l+";"),n+="var "+g+" = equal("+h+", schema"+s+"); if (!"+g+") { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var f=n;return n=p.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+f+"]); ":n+=" validate.errors = ["+f+"]; return false; ":n+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",d&&(n+=" else { "),n},Gk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,w=p.dataLevel=e.dataLevel+1,y="data"+w,_=e.baseId,E=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(n+="var "+c+" = errors;var "+g+";",E){var I=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=i,p.schemaPath=l,p.errSchemaPath=u,n+=" var "+m+" = false; for (var "+v+" = 0; "+v+" < "+h+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var S=h+"["+v+"]";p.dataPathArr[w]=v;var R=e.validate(p);p.baseId=_,e.util.varOccurences(R,y)<2?n+=" "+e.util.varReplace(R,y,S)+" ":n+=" var "+y+" = "+S+"; "+R+" ",n+=" if ("+m+") break; } ",e.compositeRule=p.compositeRule=I,n+=" "+f+" if (!"+m+") {"}else n+=" if ("+h+".length == 0) {";var $=$||[];$.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var z=n;return n=$.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+z+"]); ":n+=" validate.errors = ["+z+"]; return false; ":n+=" var err = "+z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",E&&(n+=" errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},Kk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e),p="";c.level++;var f="valid"+c.level,m={},v={},w=e.opts.ownProperties;for(I in i)if(I!="__proto__"){var y=i[I],_=Array.isArray(y)?v:m;_[I]=y}n+="var "+g+" = errors;";var E=e.errorPath;n+="var missing"+s+";";for(var I in v)if(_=v[I],_.length){if(n+=" if ( "+h+e.util.getProperty(I)+" !== undefined ",w&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(I)+"') "),d){n+=" && ( ";var S=_;if(S)for(var R,$=-1,z=S.length-1;$<z;){R=S[$+=1],$&&(n+=" || ");var L=e.util.getProperty(R),F=h+L;n+=" ( ( "+F+" === undefined ",w&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(R)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?R:L)+") ) "}n+=")) { ";var M="missing"+s,D="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,M,!0):E+" + "+M);var K=K||[];K.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(I)+"', missingProperty: '"+D+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(_.length==1?_[0]:_.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",_.length==1?n+="property "+e.util.escapeQuotes(_[0]):n+="properties "+e.util.escapeQuotes(_.join(", ")),n+=" when property "+e.util.escapeQuotes(I)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var oe=n;n=K.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+oe+"]); ":n+=" validate.errors = ["+oe+"]; return false; ":n+=" var err = "+oe+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var ie=_;if(ie)for(var R,C=-1,re=ie.length-1;C<re;){R=ie[C+=1];var L=e.util.getProperty(R),D=e.util.escapeQuotes(R),F=h+L;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(E,R,e.opts.jsonPointers)),n+=" if ( "+F+" === undefined ",w&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(R)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(I)+"', missingProperty: '"+D+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(_.length==1?_[0]:_.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",_.length==1?n+="property "+e.util.escapeQuotes(_[0]):n+="properties "+e.util.escapeQuotes(_.join(", ")),n+=" when property "+e.util.escapeQuotes(I)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",d&&(p+="}",n+=" else { ")}e.errorPath=E;var B=c.baseId;for(var I in m){var y=m[I];(e.opts.strictKeywords?typeof y=="object"&&Object.keys(y).length>0||y===!1:e.util.schemaHasRules(y,e.RULES.all))&&(n+=" "+f+" = true; if ( "+h+e.util.getProperty(I)+" !== undefined ",w&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(I)+"') "),n+=") { ",c.schema=y,c.schemaPath=l+e.util.getProperty(I),c.errSchemaPath=u+"/"+e.util.escapeFragment(I),n+=" "+e.validate(c)+" ",c.baseId=B,n+=" } ",d&&(n+=" if ("+f+") { ",p+="}"))}return d&&(n+=" "+p+" if ("+g+" == errors) {"),n},Qk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var p="i"+s,f="schema"+s;c||(n+=" var "+f+" = validate.schema"+l+";"),n+="var "+g+";",c&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=""+g+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+h+", "+f+"["+p+"])) { "+g+" = true; break; }",c&&(n+=" } "),n+=" if (!"+g+") { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",d&&(n+=" else { "),n},Yk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||"");if(e.opts.format===!1)return d&&(n+=" if (true) { "),n;var g=e.opts.$data&&i&&i.$data,c;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var p=e.opts.unknownFormats,f=Array.isArray(p);if(g){var m="format"+s,v="isObject"+s,w="formatType"+s;n+=" var "+m+" = formats["+c+"]; var "+v+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+w+" = "+v+" && "+m+".type || 'string'; if ("+v+") { ",e.async&&(n+=" var async"+s+" = "+m+".async; "),n+=" "+m+" = "+m+".validate; } if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'string') || "),n+=" (",p!="ignore"&&(n+=" ("+c+" && !"+m+" ",f&&(n+=" && self._opts.unknownFormats.indexOf("+c+") == -1 "),n+=") || "),n+=" ("+m+" && "+w+" == '"+a+"' && !(typeof "+m+" == 'function' ? ",e.async?n+=" (async"+s+" ? await "+m+"("+h+") : "+m+"("+h+")) ":n+=" "+m+"("+h+") ",n+=" : "+m+".test("+h+"))))) {"}else{var m=e.formats[i];if(!m){if(p=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(n+=" if (true) { "),n;if(f&&p.indexOf(i)>=0)return d&&(n+=" if (true) { "),n;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var v=typeof m=="object"&&!(m instanceof RegExp)&&m.validate,w=v&&m.type||"string";if(v){var y=m.async===!0;m=m.validate}if(w!=a)return d&&(n+=" if (true) { "),n;if(y){if(!e.async)throw new Error("async format in sync schema");var _="formats"+e.util.getProperty(i)+".validate";n+=" if (!(await "+_+"("+h+"))) { "}else{n+=" if (! ";var _="formats"+e.util.getProperty(i);v&&(_+=".validate"),typeof m=="function"?n+=" "+_+"("+h+") ":n+=" "+_+".test("+h+") ",n+=") { "}}var E=E||[];E.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",g?n+=""+c:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match format "`,g?n+="' + "+c+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var I=n;return n=E.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+I+"]); ":n+=" validate.errors = ["+I+"]; return false; ":n+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { "),n},Xk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m=e.schema.then,v=e.schema.else,w=m!==void 0&&(e.opts.strictKeywords?typeof m=="object"&&Object.keys(m).length>0||m===!1:e.util.schemaHasRules(m,e.RULES.all)),y=v!==void 0&&(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all)),_=p.baseId;if(w||y){var E;p.createErrors=!1,p.schema=i,p.schemaPath=l,p.errSchemaPath=u,n+=" var "+c+" = errors; var "+g+" = true; ";var I=e.compositeRule;e.compositeRule=p.compositeRule=!0,n+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,n+=" errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=I,w?(n+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(p)+" ",p.baseId=_,n+=" "+g+" = "+f+"; ",w&&y?(E="ifClause"+s,n+=" var "+E+" = 'then'; "):E="'then'",n+=" } ",y&&(n+=" else { ")):n+=" if (!"+f+") { ",y&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(p)+" ",p.baseId=_,n+=" "+g+" = "+f+"; ",w&&y?(E="ifClause"+s,n+=" var "+E+" = 'else'; "):E="'else'",n+=" } "),n+=" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+E+" } ",e.opts.messages!==!1&&(n+=` , message: 'should match "' + `+E+` + '" schema' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } ",d&&(n+=" else { ")}else d&&(n+=" if (true) { ");return n},eP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,w=p.dataLevel=e.dataLevel+1,y="data"+w,_=e.baseId;if(n+="var "+c+" = errors;var "+g+";",Array.isArray(i)){var E=e.schema.additionalItems;if(E===!1){n+=" "+g+" = "+h+".length <= "+i.length+"; ";var I=u;u=e.errSchemaPath+"/additionalItems",n+=" if (!"+g+") { ";var S=S||[];S.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var R=n;n=S.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+R+"]); ":n+=" validate.errors = ["+R+"]; return false; ":n+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u=I,d&&(f+="}",n+=" else { ")}var $=i;if($){for(var z,L=-1,F=$.length-1;L<F;)if(z=$[L+=1],e.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:e.util.schemaHasRules(z,e.RULES.all)){n+=" "+m+" = true; if ("+h+".length > "+L+") { ";var M=h+"["+L+"]";p.schema=z,p.schemaPath=l+"["+L+"]",p.errSchemaPath=u+"/"+L,p.errorPath=e.util.getPathExpr(e.errorPath,L,e.opts.jsonPointers,!0),p.dataPathArr[w]=L;var D=e.validate(p);p.baseId=_,e.util.varOccurences(D,y)<2?n+=" "+e.util.varReplace(D,y,M)+" ":n+=" var "+y+" = "+M+"; "+D+" ",n+=" } ",d&&(n+=" if ("+m+") { ",f+="}")}}if(typeof E=="object"&&(e.opts.strictKeywords?typeof E=="object"&&Object.keys(E).length>0||E===!1:e.util.schemaHasRules(E,e.RULES.all))){p.schema=E,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+m+" = true; if ("+h+".length > "+i.length+") { for (var "+v+" = "+i.length+"; "+v+" < "+h+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var M=h+"["+v+"]";p.dataPathArr[w]=v;var D=e.validate(p);p.baseId=_,e.util.varOccurences(D,y)<2?n+=" "+e.util.varReplace(D,y,M)+" ":n+=" var "+y+" = "+M+"; "+D+" ",d&&(n+=" if (!"+m+") break; "),n+=" } } ",d&&(n+=" if ("+m+") { ",f+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){p.schema=i,p.schemaPath=l,p.errSchemaPath=u,n+=" for (var "+v+" = 0; "+v+" < "+h+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var M=h+"["+v+"]";p.dataPathArr[w]=v;var D=e.validate(p);p.baseId=_,e.util.varOccurences(D,y)<2?n+=" "+e.util.varReplace(D,y,M)+" ":n+=" var "+y+" = "+M+"; "+D+" ",d&&(n+=" if (!"+m+") break; "),n+=" }"}return d&&(n+=" "+f+" if ("+c+" == errors) {"),n},Gf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,_,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var p=r=="maximum",f=p?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[f],v=e.opts.$data&&m&&m.$data,w=p?"<":">",y=p?">":"<",_=void 0;if(!(g||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(v||m===void 0||typeof m=="number"||typeof m=="boolean"))throw new Error(f+" must be number or boolean");if(v){var E=e.util.getData(m.$data,o,e.dataPathArr),I="exclusive"+s,S="exclType"+s,R="exclIsNumber"+s,$="op"+s,z="' + "+$+" + '";n+=" var schemaExcl"+s+" = "+E+"; ",E="schemaExcl"+s,n+=" var "+I+"; var "+S+" = typeof "+E+"; if ("+S+" != 'boolean' && "+S+" != 'undefined' && "+S+" != 'number') { ";var _=f,L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+S+" == 'number' ? ( ("+I+" = "+c+" === undefined || "+E+" "+w+"= "+c+") ? "+h+" "+y+"= "+E+" : "+h+" "+y+" "+c+" ) : ( ("+I+" = "+E+" === true) ? "+h+" "+y+"= "+c+" : "+h+" "+y+" "+c+" ) || "+h+" !== "+h+") { var op"+s+" = "+I+" ? '"+w+"' : '"+w+"='; ",i===void 0&&(_=f,u=e.errSchemaPath+"/"+f,c=E,g=v)}else{var R=typeof m=="number",z=w;if(R&&g){var $="'"+z+"'";n+=" if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" ( "+c+" === undefined || "+m+" "+w+"= "+c+" ? "+h+" "+y+"= "+m+" : "+h+" "+y+" "+c+" ) || "+h+" !== "+h+") { "}else{R&&i===void 0?(I=!0,_=f,u=e.errSchemaPath+"/"+f,c=m,y+="="):(R&&(c=Math[p?"min":"max"](m,i)),m===(R?c:!0)?(I=!0,_=f,u=e.errSchemaPath+"/"+f,y+="="):(I=!1,z+="="));var $="'"+z+"'";n+=" if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+h+" "+y+" "+c+" || "+h+" !== "+h+") { "}}_=_||r;var L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+$+", limit: "+c+", exclusive: "+I+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be "+z+" ",g?n+="' + "+c:n+=""+c+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;return n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { "),n},Kf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var p=r=="maxItems"?">":"<";n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+h+".length "+p+" "+c+") { ";var f=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxItems"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+c+" + '":n+=""+i,n+=" items' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},Qf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var p=r=="maxLength"?">":"<";n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),e.opts.unicode===!1?n+=" "+h+".length ":n+=" ucs2length("+h+") ",n+=" "+p+" "+c+") { ";var f=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be ",r=="maxLength"?n+="longer":n+="shorter",n+=" than ",g?n+="' + "+c+" + '":n+=""+i,n+=" characters' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},Yf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var p=r=="maxProperties"?">":"<";n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" Object.keys("+h+").length "+p+" "+c+") { ";var f=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxProperties"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+c+" + '":n+=""+i,n+=" properties' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},tP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");n+="var division"+s+";if (",g&&(n+=" "+c+" !== undefined && ( typeof "+c+" != 'number' || "),n+=" (division"+s+" = "+h+" / "+c+", ",e.opts.multipleOfPrecision?n+=" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":n+=" division"+s+" !== parseInt(division"+s+") ",n+=" ) ",g&&(n+=" ) "),n+=" ) { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be multiple of ",g?n+="' + "+c:n+=""+c+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var f=n;return n=p.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+f+"]); ":n+=" validate.errors = ["+f+"]; return false; ":n+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},rP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e);c.level++;var p="valid"+c.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){c.schema=i,c.schemaPath=l,c.errSchemaPath=u,n+=" var "+g+" = errors; ";var f=e.compositeRule;e.compositeRule=c.compositeRule=!0,c.createErrors=!1;var m;c.opts.allErrors&&(m=c.opts.allErrors,c.opts.allErrors=!1),n+=" "+e.validate(c)+" ",c.createErrors=!0,m&&(c.opts.allErrors=m),e.compositeRule=c.compositeRule=f,n+=" if ("+p+") { ";var v=v||[];v.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var w=n;n=v.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+w+"]); ":n+=" validate.errors = ["+w+"]; return false; ":n+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+g+"; if (vErrors !== null) { if ("+g+") vErrors.length = "+g+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(n+=" if (false) { ");return n},nP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=p.baseId,w="prevValid"+s,y="passingSchemas"+s;n+="var "+c+" = errors , "+w+" = false , "+g+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var E=i;if(E)for(var I,S=-1,R=E.length-1;S<R;)I=E[S+=1],(e.opts.strictKeywords?typeof I=="object"&&Object.keys(I).length>0||I===!1:e.util.schemaHasRules(I,e.RULES.all))?(p.schema=I,p.schemaPath=l+"["+S+"]",p.errSchemaPath=u+"/"+S,n+=" "+e.validate(p)+" ",p.baseId=v):n+=" var "+m+" = true; ",S&&(n+=" if ("+m+" && "+w+") { "+g+" = false; "+y+" = ["+y+", "+S+"]; } else { ",f+="}"),n+=" if ("+m+") { "+g+" = "+w+" = true; "+y+" = "+S+"; }";return e.compositeRule=p.compositeRule=_,n+=""+f+"if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+y+" } ",e.opts.messages!==!1&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+="} else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},aP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var p=g?"(new RegExp("+c+"))":e.usePattern(i);n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'string') || "),n+=" !"+p+".test("+h+") ) { ";var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",g?n+=""+c:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match pattern "`,g?n+="' + "+c+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var m=n;return n=f.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},sP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e),p="";c.level++;var f="valid"+c.level,m="key"+s,v="idx"+s,w=c.dataLevel=e.dataLevel+1,y="data"+w,_="dataProperties"+s,E=Object.keys(i||{}).filter(C),I=e.schema.patternProperties||{},S=Object.keys(I).filter(C),R=e.schema.additionalProperties,$=E.length||S.length,z=R===!1,L=typeof R=="object"&&Object.keys(R).length,F=e.opts.removeAdditional,M=z||L||F,D=e.opts.ownProperties,K=e.baseId,oe=e.schema.required;if(oe&&!(e.opts.$data&&oe.$data)&&oe.length<e.opts.loopRequired)var ie=e.util.toHash(oe);function C(mt){return mt!=="__proto__"}if(n+="var "+g+" = errors;var "+f+" = true;",D&&(n+=" var "+_+" = undefined;"),M){if(D?n+=" "+_+" = "+_+" || Object.keys("+h+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":n+=" for (var "+m+" in "+h+") { ",$){if(n+=" var isAdditional"+s+" = !(false ",E.length)if(E.length>8)n+=" || validate.schema"+l+".hasOwnProperty("+m+") ";else{var re=E;if(re)for(var B,de=-1,ae=re.length-1;de<ae;)B=re[de+=1],n+=" || "+m+" == "+e.util.toQuotedString(B)+" "}if(S.length){var ke=S;if(ke)for(var _e,Pe=-1,xe=ke.length-1;Pe<xe;)_e=ke[Pe+=1],n+=" || "+e.usePattern(_e)+".test("+m+") "}n+=" ); if (isAdditional"+s+") { "}if(F=="all")n+=" delete "+h+"["+m+"]; ";else{var ve=e.errorPath,Re="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),z)if(F)n+=" delete "+h+"["+m+"]; ";else{n+=" "+f+" = false; ";var pt=u;u=e.errSchemaPath+"/additionalProperties";var Ne=Ne||[];Ne.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { additionalProperty: '"+Re+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is an invalid additional property":n+="should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var we=n;n=Ne.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+we+"]); ":n+=" validate.errors = ["+we+"]; return false; ":n+=" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,d&&(n+=" break; ")}else if(L)if(F=="failing"){n+=" var "+g+" = errors; ";var bt=e.compositeRule;e.compositeRule=c.compositeRule=!0,c.schema=R,c.schemaPath=e.schemaPath+".additionalProperties",c.errSchemaPath=e.errSchemaPath+"/additionalProperties",c.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var be=h+"["+m+"]";c.dataPathArr[w]=m;var se=e.validate(c);c.baseId=K,e.util.varOccurences(se,y)<2?n+=" "+e.util.varReplace(se,y,be)+" ":n+=" var "+y+" = "+be+"; "+se+" ",n+=" if (!"+f+") { errors = "+g+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+h+"["+m+"]; } ",e.compositeRule=c.compositeRule=bt}else{c.schema=R,c.schemaPath=e.schemaPath+".additionalProperties",c.errSchemaPath=e.errSchemaPath+"/additionalProperties",c.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var be=h+"["+m+"]";c.dataPathArr[w]=m;var se=e.validate(c);c.baseId=K,e.util.varOccurences(se,y)<2?n+=" "+e.util.varReplace(se,y,be)+" ":n+=" var "+y+" = "+be+"; "+se+" ",d&&(n+=" if (!"+f+") break; ")}e.errorPath=ve}$&&(n+=" } "),n+=" } ",d&&(n+=" if ("+f+") { ",p+="}")}var Se=e.opts.useDefaults&&!e.compositeRule;if(E.length){var Ie=E;if(Ie)for(var B,ye=-1,Xe=Ie.length-1;ye<Xe;){B=Ie[ye+=1];var Le=i[B];if(e.opts.strictKeywords?typeof Le=="object"&&Object.keys(Le).length>0||Le===!1:e.util.schemaHasRules(Le,e.RULES.all)){var J=e.util.getProperty(B),be=h+J,Me=Se&&Le.default!==void 0;c.schema=Le,c.schemaPath=l+J,c.errSchemaPath=u+"/"+e.util.escapeFragment(B),c.errorPath=e.util.getPath(e.errorPath,B,e.opts.jsonPointers),c.dataPathArr[w]=e.util.toQuotedString(B);var se=e.validate(c);if(c.baseId=K,e.util.varOccurences(se,y)<2){se=e.util.varReplace(se,y,be);var ze=be}else{var ze=y;n+=" var "+y+" = "+be+"; "}if(Me)n+=" "+se+" ";else{if(ie&&ie[B]){n+=" if ( "+ze+" === undefined ",D&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),n+=") { "+f+" = false; ";var ve=e.errorPath,pt=u,pe=e.util.escapeQuotes(B);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(ve,B,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var Ne=Ne||[];Ne.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+pe+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+pe+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var we=n;n=Ne.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+we+"]); ":n+=" validate.errors = ["+we+"]; return false; ":n+=" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,e.errorPath=ve,n+=" } else { "}else d?(n+=" if ( "+ze+" === undefined ",D&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),n+=") { "+f+" = true; } else { "):(n+=" if ("+ze+" !== undefined ",D&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),n+=" ) { ");n+=" "+se+" } "}}d&&(n+=" if ("+f+") { ",p+="}")}}if(S.length){var Be=S;if(Be)for(var _e,hr=-1,Ft=Be.length-1;hr<Ft;){_e=Be[hr+=1];var Le=I[_e];if(e.opts.strictKeywords?typeof Le=="object"&&Object.keys(Le).length>0||Le===!1:e.util.schemaHasRules(Le,e.RULES.all)){c.schema=Le,c.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(_e),c.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(_e),D?n+=" "+_+" = "+_+" || Object.keys("+h+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":n+=" for (var "+m+" in "+h+") { ",n+=" if ("+e.usePattern(_e)+".test("+m+")) { ",c.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var be=h+"["+m+"]";c.dataPathArr[w]=m;var se=e.validate(c);c.baseId=K,e.util.varOccurences(se,y)<2?n+=" "+e.util.varReplace(se,y,be)+" ":n+=" var "+y+" = "+be+"; "+se+" ",d&&(n+=" if (!"+f+") break; "),n+=" } ",d&&(n+=" else "+f+" = true; "),n+=" } ",d&&(n+=" if ("+f+") { ",p+="}")}}}return d&&(n+=" "+p+" if ("+g+" == errors) {"),n},oP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e),p="";c.level++;var f="valid"+c.level;if(n+="var "+g+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){c.schema=i,c.schemaPath=l,c.errSchemaPath=u;var m="key"+s,v="idx"+s,w="i"+s,y="' + "+m+" + '",_=c.dataLevel=e.dataLevel+1,E="data"+_,I="dataProperties"+s,S=e.opts.ownProperties,R=e.baseId;S&&(n+=" var "+I+" = undefined; "),S?n+=" "+I+" = "+I+" || Object.keys("+h+"); for (var "+v+"=0; "+v+"<"+I+".length; "+v+"++) { var "+m+" = "+I+"["+v+"]; ":n+=" for (var "+m+" in "+h+") { ",n+=" var startErrs"+s+" = errors; ";var $=m,z=e.compositeRule;e.compositeRule=c.compositeRule=!0;var L=e.validate(c);c.baseId=R,e.util.varOccurences(L,E)<2?n+=" "+e.util.varReplace(L,E,$)+" ":n+=" var "+E+" = "+$+"; "+L+" ",e.compositeRule=c.compositeRule=z,n+=" if (!"+f+") { for (var "+w+"=startErrs"+s+"; "+w+"<errors; "+w+"++) { vErrors["+w+"].propertyName = "+m+"; } var err = ",e.createErrors!==!1?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { propertyName: '"+y+"' } ",e.opts.messages!==!1&&(n+=" , message: 'property name \\'"+y+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),d&&(n+=" break; "),n+=" } }"}return d&&(n+=" "+p+" if ("+g+" == errors) {"),n},iP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var p="schema"+s;if(!c)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],m=i;if(m)for(var v,w=-1,y=m.length-1;w<y;){v=m[w+=1];var _=e.schema.properties[v];_&&(e.opts.strictKeywords?typeof _=="object"&&Object.keys(_).length>0||_===!1:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=v)}}else var f=i;if(c||f.length){var E=e.errorPath,I=c||f.length>=e.opts.loopRequired,S=e.opts.ownProperties;if(d)if(n+=" var missing"+s+"; ",I){c||(n+=" var "+p+" = validate.schema"+l+"; ");var R="i"+s,$="schema"+s+"["+R+"]",z="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),n+=" var "+g+" = true; ",c&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=" for (var "+R+" = 0; "+R+" < "+p+".length; "+R+"++) { "+g+" = "+h+"["+p+"["+R+"]] !== undefined ",S&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", "+p+"["+R+"]) "),n+="; if (!"+g+") break; } ",c&&(n+=" } "),n+=" if (!"+g+") { ";var L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var M=f;if(M)for(var D,R=-1,K=M.length-1;R<K;){D=M[R+=1],R&&(n+=" || ");var oe=e.util.getProperty(D),ie=h+oe;n+=" ( ( "+ie+" === undefined ",S&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(D)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?D:oe)+") ) "}n+=") { ";var $="missing"+s,z="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,$,!0):E+" + "+$);var L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(I){c||(n+=" var "+p+" = validate.schema"+l+"; ");var R="i"+s,$="schema"+s+"["+R+"]",z="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),c&&(n+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),n+=" for (var "+R+" = 0; "+R+" < "+p+".length; "+R+"++) { if ("+h+"["+p+"["+R+"]] === undefined ",S&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", "+p+"["+R+"]) "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",c&&(n+=" } ")}else{var C=f;if(C)for(var D,re=-1,B=C.length-1;re<B;){D=C[re+=1];var oe=e.util.getProperty(D),z=e.util.escapeQuotes(D),ie=h+oe;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(E,D,e.opts.jsonPointers)),n+=" if ( "+ie+" === undefined ",S&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(D)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=E}else d&&(n+=" if (true) {");return n},lP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data,p;if(c?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+s):p=i,(i||c)&&e.opts.uniqueItems!==!1){c&&(n+=" var "+g+"; if ("+p+" === false || "+p+" === undefined) "+g+" = true; else if (typeof "+p+" != 'boolean') "+g+" = false; else { "),n+=" var i = "+h+".length , "+g+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,m=Array.isArray(f);if(!f||f=="object"||f=="array"||m&&(f.indexOf("object")>=0||f.indexOf("array")>=0))n+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+h+"[i], "+h+"[j])) { "+g+" = false; break outer; } } } ";else{n+=" var itemIndices = {}, item; for (;i--;) { var item = "+h+"[i]; ";var v="checkDataType"+(m?"s":"");n+=" if ("+e.util[v](f,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(n+=` if (typeof item == 'string') item = '"' + item; `),n+=" if (typeof itemIndices[item] == 'number') { "+g+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}n+=" } ",c&&(n+=" } "),n+=" if (!"+g+") { ";var w=w||[];w.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(n+=" , schema: ",c?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var y=n;n=w.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+y+"]); ":n+=" validate.errors = ["+y+"]; return false; ":n+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { ")}else d&&(n+=" if (true) { ");return n},uP={$ref:Vk,allOf:Bk,anyOf:Hk,$comment:Jk,const:Wk,contains:Gk,dependencies:Kk,enum:Qk,format:Yk,if:Xk,items:eP,maximum:Gf,minimum:Gf,maxItems:Kf,minItems:Kf,maxLength:Qf,minLength:Qf,maxProperties:Yf,minProperties:Yf,multipleOf:tP,not:rP,oneOf:nP,pattern:aP,properties:sP,propertyNames:oP,required:iP,uniqueItems:lP,validate:Nf},Xf=uP,_l=Cn.toHash,cP=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],n=["number","integer","string","array","object","boolean","null"];return e.all=_l(r),e.types=_l(n),e.forEach(function(s){s.rules=s.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(d){r.push(d),e.all[d]=!0})}r.push(o);var u=e.all[o]={keyword:o,code:Xf[o],implements:i};return u}),e.all.$comment={keyword:"$comment",code:Xf.$comment},s.type&&(e.types[s.type]=s)}),e.keywords=_l(r.concat(a)),e.custom={},e},em=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],dP=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var a=e[r].split("/"),n=t,s;for(s=1;s<a.length;s++)n=n[a[s]];for(s=0;s<em.length;s++){var o=em[s],i=n[o];i&&(n[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t},pP=vl.MissingRef,hP=tm;function tm(t,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var n=s(t).then(function(){var i=a._addSchema(t,void 0,e);return i.validate||o(i)});return r&&n.then(function(i){r(null,i)},r),n;function s(i){var l=i.$schema;return l&&!a.getSchema(l)?tm.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(u){if(u instanceof pP)return l(u);throw u}function l(u){var d=u.missingSchema;if(c(d))throw new Error("Schema "+d+" is loaded but "+u.missingRef+" cannot be resolved");var h=a._loadingSchemas[d];return h||(h=a._loadingSchemas[d]=a._opts.loadSchema(d),h.then(g,g)),h.then(function(p){if(!c(d))return s(p).then(function(){c(d)||a.addSchema(p,d,void 0,e)})}).then(function(){return o(i)});function g(){delete a._loadingSchemas[d]}function c(p){return a._refs[p]||a._schemas[p]}}}}var fP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h,g="data"+(o||""),c="valid"+s,p="errs__"+s,f=e.opts.$data&&i&&i.$data,m;f?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+s):m=i;var v=this,w="definition"+s,y=v.definition,_="",E,I,S,R,$;if(f&&y.$data){$="keywordValidate"+s;var z=y.validateSchema;n+=" var "+w+" = RULES.custom['"+r+"'].definition; var "+$+" = "+w+".validate;"}else{if(R=e.useCustomRule(v,i,e.schema,e),!R)return;m="validate.schema"+l,$=R.code,E=y.compile,I=y.inline,S=y.macro}var L=$+".errors",F="i"+s,M="ruleErr"+s,D=y.async;if(D&&!e.async)throw new Error("async keyword in sync schema");if(I||S||(n+=""+L+" = null;"),n+="var "+p+" = errors;var "+c+";",f&&y.$data&&(_+="}",n+=" if ("+m+" === undefined) { "+c+" = true; } else { ",z&&(_+="}",n+=" "+c+" = "+w+".validateSchema("+m+"); if ("+c+") { ")),I)y.statements?n+=" "+R.validate+" ":n+=" "+c+" = "+R.validate+"; ";else if(S){var K=e.util.copy(e),_="";K.level++;var oe="valid"+K.level;K.schema=R.validate,K.schemaPath="";var ie=e.compositeRule;e.compositeRule=K.compositeRule=!0;var C=e.validate(K).replace(/validate\.schema/g,$);e.compositeRule=K.compositeRule=ie,n+=" "+C}else{var re=re||[];re.push(n),n="",n+=" "+$+".call( ",e.opts.passContext?n+="this":n+="self",E||y.schema===!1?n+=" , "+g+" ":n+=" , "+m+" , "+g+" , validate.schema"+e.schemaPath+" ",n+=" , (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var B=o?"data"+(o-1||""):"parentData",de=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+B+" , "+de+" , rootData ) ";var ae=n;n=re.pop(),y.errors===!1?(n+=" "+c+" = ",D&&(n+="await "),n+=""+ae+"; "):D?(L="customErrors"+s,n+=" var "+L+" = null; try { "+c+" = await "+ae+"; } catch (e) { "+c+" = false; if (e instanceof ValidationError) "+L+" = e.errors; else throw e; } "):n+=" "+L+" = null; "+c+" = "+ae+"; "}if(y.modifying&&(n+=" if ("+B+") "+g+" = "+B+"["+de+"];"),n+=""+_,y.valid)d&&(n+=" if (true) { ");else{n+=" if ( ",y.valid===void 0?(n+=" !",S?n+=""+oe:n+=""+c):n+=" "+!y.valid+" ",n+=") { ",h=v.keyword;var re=re||[];re.push(n),n="";var re=re||[];re.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+v.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+v.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var ke=n;n=re.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+ke+"]); ":n+=" validate.errors = ["+ke+"]; return false; ":n+=" var err = "+ke+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var _e=n;n=re.pop(),I?y.errors?y.errors!="full"&&(n+=" for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+M+" = vErrors["+F+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+M+".schemaPath === undefined) { "+M+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(n+=" "+M+".schema = "+m+"; "+M+".data = "+g+"; "),n+=" } "):y.errors===!1?n+=" "+_e+" ":(n+=" if ("+p+" == errors) { "+_e+" } else { for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+M+" = vErrors["+F+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+M+".schemaPath === undefined) { "+M+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(n+=" "+M+".schema = "+m+"; "+M+".data = "+g+"; "),n+=" } } "):S?(n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+v.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+v.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; ")):y.errors===!1?n+=" "+_e+" ":(n+=" if (Array.isArray("+L+")) { if (vErrors === null) vErrors = "+L+"; else vErrors = vErrors.concat("+L+"); errors = vErrors.length; for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+M+" = vErrors["+F+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; "+M+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(n+=" "+M+".schema = "+m+"; "+M+".data = "+g+"; "),n+=" } } else { "+_e+" } "),n+=" } ",d&&(n+=" else { ")}return n};const rm={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var nm=rm,mP={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:nm.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:nm.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},vP=/^[a-z_$][a-z0-9_$-]*$/i,gP=fP,yP=mP,_P={add:wP,get:bP,remove:xP,validate:wl};function wP(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!vP.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var n=0;n<a.length;n++)o(t,a[n],e);else o(t,a,e);var s=e.metaSchema;s&&(e.$data&&this._opts.$data&&(s={anyOf:[s,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(s,!0))}r.keywords[t]=r.all[t]=!0;function o(i,l,u){for(var d,h=0;h<r.length;h++){var g=r[h];if(g.type==l){d=g;break}}d||(d={type:l,rules:[]},r.push(d));var c={keyword:i,definition:u,custom:!0,code:gP,implements:u.implements};d.rules.push(c),r.custom[i]=c}return this}function bP(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function xP(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var a=e[r].rules,n=0;n<a.length;n++)if(a[n].keyword==t){a.splice(n,1);break}return this}function wl(t,e){wl.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(yP,!0);if(r(t))return!0;if(wl.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}const EP={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var am=Ek,cn=dl,SP=Rk,sm=kf,IP=Af,TP=jk,kP=cP,om=dP,im=Cn,PP=et;et.prototype.validate=RP,et.prototype.compile=OP,et.prototype.addSchema=$P,et.prototype.addMetaSchema=AP,et.prototype.validateSchema=NP,et.prototype.getSchema=DP,et.prototype.removeSchema=LP,et.prototype.addFormat=HP,et.prototype.errorsText=BP,et.prototype._addSchema=zP,et.prototype._compile=UP,et.prototype.compileAsync=hP;var Zs=_P;et.prototype.addKeyword=Zs.add,et.prototype.getKeyword=Zs.get,et.prototype.removeKeyword=Zs.remove,et.prototype.validateKeyword=Zs.validate;var lm=vl;et.ValidationError=lm.Validation,et.MissingRefError=lm.MissingRef,et.$dataMetaSchema=om;var Vs="http://json-schema.org/draft-07/schema",um=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],CP=["/properties"];function et(t){if(!(this instanceof et))return new et(t);t=this._opts=im.copy(t)||{},YP(this),this._schemas={},this._refs={},this._fragments={},this._formats=TP(t.format),this._cache=t.cache||new SP,this._loadingSchemas={},this._compilations=[],this.RULES=kP(),this._getId=FP(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=IP),this._metaOpts=QP(this),t.formats&&GP(this),t.keywords&&KP(this),JP(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),WP(this)}function RP(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var a=this._addSchema(t);r=a.validate||this._compile(a)}var n=r(e);return r.$async!==!0&&(this.errors=r.errors),n}function OP(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function $P(t,e,r,a){if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.addSchema(t[n],void 0,r,a);return this}var s=this._getId(t);if(s!==void 0&&typeof s!="string")throw new Error("schema id must be string");return e=cn.normalizeId(e||s),dm(this,e),this._schemas[e]=this._addSchema(t,r,a,!0),this}function AP(t,e,r){return this.addSchema(t,e,r,!0),this}function NP(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||MP(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,t);if(!a&&e){var n="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(n);else throw new Error(n)}return a}function MP(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(Vs)?Vs:void 0,t._opts.defaultMeta}function DP(t){var e=cm(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return jP(this,t)}}function jP(t,e){var r=cn.schema.call(t,{schema:{}},e);if(r){var a=r.schema,n=r.root,s=r.baseId,o=am.call(t,a,n,void 0,s);return t._fragments[e]=new sm({ref:e,fragment:!0,schema:a,root:n,baseId:s,validate:o}),o}}function cm(t,e){return e=cn.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function LP(t){if(t instanceof RegExp)return Bs(this,this._schemas,t),Bs(this,this._refs,t),this;switch(typeof t){case"undefined":return Bs(this,this._schemas),Bs(this,this._refs),this._cache.clear(),this;case"string":var e=cm(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,a=r?r(t):t;this._cache.del(a);var n=this._getId(t);n&&(n=cn.normalizeId(n),delete this._schemas[n],delete this._refs[n])}return this}function Bs(t,e,r){for(var a in e){var n=e[a];!n.meta&&(!r||r.test(a))&&(t._cache.del(n.cacheKey),delete e[a])}}function zP(t,e,r,a){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var n=this._opts.serialize,s=n?n(t):t,o=this._cache.get(s);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=cn.normalizeId(this._getId(t));i&&a&&dm(this,i);var l=this._opts.validateSchema!==!1&&!e,u;l&&!(u=i&&i==cn.normalizeId(t.$schema))&&this.validateSchema(t,!0);var d=cn.ids.call(this,t),h=new sm({id:i,schema:t,localRefs:d,cacheKey:s,meta:r});return i[0]!="#"&&a&&(this._refs[i]=h),this._cache.put(s,h),l&&u&&this.validateSchema(t,!0),h}function UP(t,e){if(t.compiling)return t.validate=n,n.schema=t.schema,n.errors=null,n.root=e||n,t.schema.$async===!0&&(n.$async=!0),n;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=am.call(this,t.schema,e,t.localRefs)}catch(s){throw delete t.validate,s}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=a,t.refs=a.refs,t.refVal=a.refVal,t.root=a.root,a;function n(){var s=t.validate,o=s.apply(this,arguments);return n.errors=s.errors,o}}function FP(t){switch(t.schemaId){case"auto":return VP;case"id":return qP;default:return ZP}}function qP(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function ZP(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function VP(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function BP(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,n="",s=0;s<t.length;s++){var o=t[s];o&&(n+=a+o.dataPath+" "+o.message+r)}return n.slice(0,-r.length)}function HP(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function JP(t){var e;if(t._opts.$data&&(e=EP,t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=rm;t._opts.$data&&(r=om(r,CP)),t.addMetaSchema(r,Vs,!0),t._refs["http://json-schema.org/schema"]=Vs}}function WP(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function GP(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function KP(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function dm(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function QP(t){for(var e=im.copy(t._opts),r=0;r<um.length;r++)delete e[um[r]];return e}function YP(t){var e=t._opts.logger;if(e===!1)t.logger={log:bl,warn:bl,error:bl};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function bl(){}const XP=sb(PP);class Hs extends FT{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._ajv=new XP}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qT(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const a=await this.request({method:"initialize",params:{protocolVersion:_s,capabilities:this._capabilities,clientInfo:this._clientInfo}},dh,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!jE.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,a,n,s,o;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},on,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Nh,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},on,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Sh,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},xh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},gh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},yh,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},_h,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},on,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},on,r)}async callTool(e,r=Ss,a){const n=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new Nr(ir.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!s(n.structuredContent))throw new Nr(ir.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(o){throw o instanceof Nr?o:new Nr(ir.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const r of e)if(r.outputSchema)try{const a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const a=await this.request({method:"tools/list",params:e},Th,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class pm extends Event{constructor(e,r){var a,n;super(e),this.code=(a=r==null?void 0:r.code)!=null?a:void 0,this.message=(n=r==null?void 0:r.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,a){return a(hm(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(hm(this),r)}}function eC(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function xl(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(xl).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${xl(t.cause)}`:t.message:`${t}`}function hm(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var fm=t=>{throw TypeError(t)},El=(t,e,r)=>e.has(t)||fm("Cannot "+r),Ee=(t,e,r)=>(El(t,e,"read from private field"),r?r.call(t):e.get(t)),ut=(t,e,r)=>e.has(t)?fm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),We=(t,e,r,a)=>(El(t,e,"write to private field"),e.set(t,r),r),Er=(t,e,r)=>(El(t,e,"access private method"),r),Tt,dn,Rn,Js,Ws,xa,On,Ea,Lr,$n,An,Nn,Sa,Qt,Sl,Il,Tl,mm,kl,Pl,Ia,Cl,Rl;class Gs extends EventTarget{constructor(e,r){var a,n;super(),ut(this,Qt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ut(this,Tt),ut(this,dn),ut(this,Rn),ut(this,Js),ut(this,Ws),ut(this,xa),ut(this,On),ut(this,Ea,null),ut(this,Lr),ut(this,$n),ut(this,An,null),ut(this,Nn,null),ut(this,Sa,null),ut(this,Il,async s=>{var o;Ee(this,$n).reset();const{body:i,redirected:l,status:u,headers:d}=s;if(u===204){Er(this,Qt,Ia).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?We(this,Rn,new URL(s.url)):We(this,Rn,void 0),u!==200){Er(this,Qt,Ia).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){Er(this,Qt,Ia).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Ee(this,Tt)===this.CLOSED)return;We(this,Tt,this.OPEN);const h=new Event("open");if((o=Ee(this,Sa))==null||o.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){Er(this,Qt,Ia).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const g=new TextDecoder,c=i.getReader();let p=!0;do{const{done:f,value:m}=await c.read();m&&Ee(this,$n).feed(g.decode(m,{stream:!f})),f&&(p=!1,Ee(this,$n).reset(),Er(this,Qt,Cl).call(this))}while(p)}),ut(this,Tl,s=>{We(this,Lr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Er(this,Qt,Cl).call(this,xl(s))}),ut(this,kl,s=>{typeof s.id=="string"&&We(this,Ea,s.id);const o=new MessageEvent(s.event||"message",{data:s.data,origin:Ee(this,Rn)?Ee(this,Rn).origin:Ee(this,dn).origin,lastEventId:s.id||""});Ee(this,Nn)&&(!s.event||s.event==="message")&&Ee(this,Nn).call(this,o),this.dispatchEvent(o)}),ut(this,Pl,s=>{We(this,xa,s)}),ut(this,Rl,()=>{We(this,On,void 0),Ee(this,Tt)===this.CONNECTING&&Er(this,Qt,Sl).call(this)});try{if(e instanceof URL)We(this,dn,e);else if(typeof e=="string")We(this,dn,new URL(e,tC()));else throw new Error("Invalid URL")}catch{throw eC("An invalid or illegal string was specified")}We(this,$n,Zh({onEvent:Ee(this,kl),onRetry:Ee(this,Pl)})),We(this,Tt,this.CONNECTING),We(this,xa,3e3),We(this,Ws,(a=r==null?void 0:r.fetch)!=null?a:globalThis.fetch),We(this,Js,(n=r==null?void 0:r.withCredentials)!=null?n:!1),Er(this,Qt,Sl).call(this)}get readyState(){return Ee(this,Tt)}get url(){return Ee(this,dn).href}get withCredentials(){return Ee(this,Js)}get onerror(){return Ee(this,An)}set onerror(e){We(this,An,e)}get onmessage(){return Ee(this,Nn)}set onmessage(e){We(this,Nn,e)}get onopen(){return Ee(this,Sa)}set onopen(e){We(this,Sa,e)}addEventListener(e,r,a){const n=r;super.addEventListener(e,n,a)}removeEventListener(e,r,a){const n=r;super.removeEventListener(e,n,a)}close(){Ee(this,On)&&clearTimeout(Ee(this,On)),Ee(this,Tt)!==this.CLOSED&&(Ee(this,Lr)&&Ee(this,Lr).abort(),We(this,Tt,this.CLOSED),We(this,Lr,void 0))}}Tt=new WeakMap,dn=new WeakMap,Rn=new WeakMap,Js=new WeakMap,Ws=new WeakMap,xa=new WeakMap,On=new WeakMap,Ea=new WeakMap,Lr=new WeakMap,$n=new WeakMap,An=new WeakMap,Nn=new WeakMap,Sa=new WeakMap,Qt=new WeakSet,Sl=function(){We(this,Tt,this.CONNECTING),We(this,Lr,new AbortController),Ee(this,Ws)(Ee(this,dn),Er(this,Qt,mm).call(this)).then(Ee(this,Il)).catch(Ee(this,Tl))},Il=new WeakMap,Tl=new WeakMap,mm=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ee(this,Ea)?{"Last-Event-ID":Ee(this,Ea)}:void 0},cache:"no-store",signal:(t=Ee(this,Lr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},kl=new WeakMap,Pl=new WeakMap,Ia=function(t,e){var r;Ee(this,Tt)!==this.CLOSED&&We(this,Tt,this.CLOSED);const a=new pm("error",{code:e,message:t});(r=Ee(this,An))==null||r.call(this,a),this.dispatchEvent(a)},Cl=function(t,e){var r;if(Ee(this,Tt)===this.CLOSED)return;We(this,Tt,this.CONNECTING);const a=new pm("error",{code:e,message:t});(r=Ee(this,An))==null||r.call(this,a),this.dispatchEvent(a),We(this,On,setTimeout(Ee(this,Rl),Ee(this,xa)))},Rl=new WeakMap,Gs.CONNECTING=0,Gs.OPEN=1,Gs.CLOSED=2;function tC(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}class rC extends Error{constructor(e,r,a){super(`SSE error: ${r}`),this.code=e,this.event=a}}class Ol{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r==null?void 0:r.eventSourceInit,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Gt("No auth provider");let r;try{r=await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Gt;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(r.Authorization=`Bearer ${a.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,a;const n=(a=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((s,o)=>{this._eventSource=new Gs(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const u=await this._commonHeaders();u.set("Accept","text/event-stream");const d=await n(i,{...l,headers:u});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=Ji(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,o);return}const u=new rC(i.code,i.message,i);o(u),(l=this.onerror)===null||l===void 0||l.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const u=i;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){o(d),(l=this.onerror)===null||l===void 0||l.call(this,d),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,u;const d=i;let h;try{h=sn.parse(JSON.parse(d.data))}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g);return}(u=this.onmessage)===null||u===void 0||u.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Gt("No auth provider");if(await Pn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt("Failed to authorize")}async close(){var e,r,a;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var r,a,n;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},i=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,o);if(!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ji(i),await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt;return this.send(e)}const l=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${l}`)}}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}const nC="mcp";class vm{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,nC),this._socket.onerror=a=>{var n;const s="error"in a?a.error:new Error(`WebSocket error: ${JSON.stringify(a)}`);r(s),(n=this.onerror)===null||n===void 0||n.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var a;(a=this.onclose)===null||a===void 0||a.call(this)},this._socket.onmessage=a=>{var n,s;let o;try{o=sn.parse(JSON.parse(a.data))}catch(i){(n=this.onerror)===null||n===void 0||n.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,o)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,a)=>{var n;if(!this._socket){a(new Error("Not connected"));return}(n=this._socket)===null||n===void 0||n.send(JSON.stringify(e)),r()})}}function Ks(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Ks=function(){return t},Ks()}(function(t,e){const r=gt,a=gt,n=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(a(429))/5)+parseInt(a(423))/6*(-parseInt(a(418))/7)+-parseInt(a(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ks,650197);const aC=()=>{const t=gt,e={EGhzU:function(r,a){return r!==a},kIrDB:"undefined",llYQe:function(r,a){return r!==a},PZfJg:function(r,a){return r(a)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},sC=(t,e,r)=>{const a=gt,n=gt,s={};s[a(410)]=n(398),s.dBkaX=function(i,l){return i===l},s[n(393)]="function";const o=s;typeof window!==o[n(410)]?t.postMessage(e,"*",r):n(428)in t&&o.dBkaX(typeof t.postMessage,o[a(393)])&&t.postMessage(e,r)};class gm{constructor(e){const r=gt;this[r(406)]=e}async start(){const e=gt,r=gt;this[e(406)]&&(this[e(406)][e(413)]=a=>{var n,s;const o=e,i=r;try{const l=sn[o(402)](a.data[o(400)]);(n=this[o(413)])==null||n.call(this,l,a[i(409)].extra)}catch(l){const u=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,u)}},this._port[e(396)]=a=>{var n;const s=r,o=r,i=new Error(s(394)+JSON[o(395)](a));(n=this.onerror)==null||n.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const a={lEyuq:function(n){return n()},YihNw:function(n,s){return n(s)}};return new Promise((n,s)=>{var o;const i=gt,l=gt;try{const u={};u[i(403)]=r==null?void 0:r[i(403)];const d={};d[l(400)]=e,d.extra=u,this[l(406)]&&this[i(406)].postMessage(d),a.lEyuq(n)}catch(u){const d=u instanceof Error?u:new Error(a.YihNw(String,u));(o=this[l(408)])==null||o.call(this,d),s(d)}})}async close(){var e,r;const a=gt,n=gt;(e=this._port)==null||e[a(431)](),this._port=void 0,(r=this[n(420)])==null||r.call(this)}}class oC extends gm{constructor(e,r=aC()){const a=gt,n=gt,s={EkZCC:function(i,l,u,d){return i(l,u,d)}};super(),this[a(391)]=e,this[n(401)]=r;const o=new MessageChannel;this[n(406)]=o.port1,s[n(426)](sC,this[a(401)],{endpoint:this[n(391)]},[o[n(414)]])}}function gt(t,e){const r=Ks();return gt=function(a,n){return a=a-(17*-491+-669+9407),r[a]},gt(t,e)}(function(t,e){const r=qe,a=qe,n=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(a(357))/5+-parseInt(a(389))/6*(-parseInt(r(396))/7)+parseInt(a(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Qs,-763475+-52067*10+1724410);const iC=async(t,e,r)=>{var a;const n=qe,s=qe,o={};o[n(345)]="tools/list",o.rqstG="tools/call",o.WqUnk="resources/list",o[n(329)]=s(358),o[n(365)]=n(335),o.ookoz="resources/unsubscribe",o[n(385)]=n(340),o.VTIWq="prompts/list",o.SkoRK=n(376),o.QUtUV=n(388),o.XtowM=s(332);const i=o,{id:l,method:u,params:d}=r;let h={};switch(u){case i[s(345)]:h=await e.listTools(d);break;case i.rqstG:h=await e.callTool(d);break;case i[n(334)]:h=await e[n(350)](d);break;case i[s(329)]:h=await e.listResourceTemplates(d);break;case n(372):h=await e[n(383)](d);break;case i.HgYgW:h=await e.subscribeResource(d);break;case i.ookoz:h=await e.unsubscribeResource(d);break;case i[n(385)]:h=await e.getPrompt(d);break;case i.VTIWq:h=await e.listPrompts(d);break;case i[n(344)]:h=await e[n(376)]();break;case i.QUtUV:h=await e.complete(d);break;case n(390):h=await e[n(336)](d==null?void 0:d.level);break}const g={};g[n(361)]=h,g[n(394)]=i[n(364)],g.id=l,await((a=t==null?void 0:t.transport)==null?void 0:a[n(392)](g))},lC=async(t,e,r)=>{var a;const n=qe,s=qe,o={};o.jQBBS="sampling/createMessage",o.EZqgC="elicitation/create",o[n(370)]=s(376),o.aVeaL=s(332);const i=o,{id:l,method:u,params:d}=r;let h={};switch(u){case n(368):const c={};c.method=u,c[s(367)]=d,h=await e.request(c,Dh);break;case i[s(391)]:const p={};p.method=u,p[s(367)]=d,h=await e[s(381)](p,Oh);break;case i.EZqgC:const f={};f.method=u,f.params=d,h=await e.request(f,Ah);break;case i[s(370)]:const m={};m.method=u,h=await e[s(381)](m,on);break}const g={};return g[s(361)]=h,g.jsonrpc=i[s(387)],g.id=l,await((a=t==null?void 0:t[n(371)])==null?void 0:a.send(g)),h},uC=(t,e)=>{const r=qe,a={gXsjT:function(s,o){return s===o},oegpC:r(351),lZOUC:function(s,o,i,l){return s(o,i,l)},ifIKG:"2.0"},n=t._onrequest;t._onrequest=async(s,o)=>{var i,l,u,d,h;const g=r,c=r,{id:p,method:f}=s;try{a[g(333)](f,a.oegpC)?await n[g(386)](t,s,o):await a.lZOUC(iC,t,e,s)}catch(m){const{code:v,message:w,data:y}=m;try{if(v){const _={};_.code=v,_.message=w,_.data=y;const E={};E.error=_,E[g(394)]=a[c(331)],E.id=p,await((i=t==null?void 0:t.transport)==null?void 0:i.send(E))}else(u=(l=t==null?void 0:t[c(371)])==null?void 0:l.onerror)==null||u.call(l,m)}catch(_){(h=(d=t==null?void 0:t[g(371)])==null?void 0:d.onerror)==null||h.call(d,_)}}}},cC=(t,e)=>{const r=qe,a=qe,n={};n[r(363)]=function(o,i){return o!==i},n[r(398)]=r(353),n.hzhyg="notifications/cancelled";const s=n;t._onnotification=async o=>{var i,l;const u=r,d=a,{method:h,params:g}=o;if(s[u(363)](h,s[d(398)])&&(s[u(363)](h,s.hzhyg)||g!=null&&g.forward))try{await e.notification(o)}catch(c){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,c)}}},dC=(t,e)=>async r=>{var a,n,s,o,i;const l=qe,u=qe,d={};d.SEmWX=l(332);const h=d;try{return await lC(t,e,r)}catch(g){const{code:c,message:p,data:f}=g;try{if(c){const m={};m[u(377)]=c,m.message=p,m.data=f;const v={};v[u(348)]=m,v.jsonrpc=h[l(338)],v.id=r.id,await((a=t==null?void 0:t.transport)==null?void 0:a[u(392)](v))}else(s=(n=t==null?void 0:t.transport)==null?void 0:n[u(339)])==null||s.call(n,g)}catch(m){(i=(o=t==null?void 0:t[l(371)])==null?void 0:o[u(339)])==null||i.call(o,m)}}},pC=(t,e)=>async r=>{var a,n,s;const o=qe,i=qe,l={};l.dtUgZ=function(g,c){return g!==c},l.jgCIb=o(353),l.uUjKY="2.0";const u=l,{method:d,params:h}=r;if(u.dtUgZ(d,u.jgCIb)&&(d!==o(400)||h!=null&&h.forward))try{const g={...r};g[o(394)]=u[i(352)],await((a=e==null?void 0:e[o(371)])==null?void 0:a[o(392)](g))}catch(g){(s=(n=t==null?void 0:t[o(371)])==null?void 0:n[i(339)])==null||s.call(n,g)}};function qe(t,e){const r=Qs();return qe=function(a,n){return a=a-(9*-113+-1439*-1+-97),r[a]},qe(t,e)}const hC=(t,e)=>async r=>{var a,n,s,o,i,l;const u=qe,d=qe,h={};h[u(401)]=d(332);const g=h;try{await((a=e==null?void 0:e.transport)==null?void 0:a.send(r))}catch(c){const{code:p,message:f,data:m}=c;try{if(p){const v={};v.code=p,v[u(399)]=f,v.data=m;const w={};w[u(348)]=v,w[u(394)]=g.OhJjz,w.id=r.id,await((n=t==null?void 0:t[u(371)])==null?void 0:n.send(w))}else(o=(s=t==null?void 0:t.transport)==null?void 0:s[d(339)])==null||o.call(s,c)}catch(v){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,v)}}},$l=()=>{const t=qe,e=qe,r={vnkqu:function(u,d){return u!==d},wxDWr:function(u,d){return u(d)},GdkkV:function(u,d){return u===d}},a=[],n=(u,d)=>{const h=qe,g=qe;if(d){const c=[];for(const p of a)try{c.push(p(u,d))}catch{}for(const p of c)if(r[h(379)](p,null))return p}else for(const c of a)try{r[g(343)](c,u)}catch{}},s=u=>{const d=qe;r[d(384)](typeof u,d(369))&&!a.includes(u)&&a.push(u)},o=u=>{const d=a.indexOf(u);d!==-1&&a.splice(d,1*-6854+8*-33+7119)},i=()=>{const u=qe;a[u(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=n,l[e(330)]=s,l.removeListener=o,l[t(359)]=i,l},fC=t=>{const e=qe,r=qe,a={xwPeb:function(n){return n()},Mfvzm:function(n){return n()}};{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(326)]($l);t._onresponse=n,t[e(395)]=s,t.removeResponseListener=o,t.clearResponseListener=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[r(326)]($l);t[r(328)]=n,t.addRequestListener=s,t[r(354)]=o,t[r(341)]=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(375)]($l);t[e(342)]=n,t[e(327)]=s,t.removeNotificationListener=o,t.clearNotificationListener=i}};function Qs(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return Qs=function(){return t},Qs()}const mC=(t,{beforeInit:e,afterInit:r}={})=>{const a=qe,n=qe,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:a(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},o=new Map(t._notificationHandlers);t[a(393)][a(402)](),t._notificationHandlers[a(402)](),s.tqDZP(typeof e,s[a(380)])&&e(),s[a(362)](t._onresponse.name,s[a(360)])&&(t[n(349)]=t._onresponse),s[a(347)](fC,t),t.addResponseListener(i=>{const l=n;t.originalOnResponse[l(386)](t,i)}),s.tqDZP(typeof r,s[n(380)])&&s[a(397)](r),t[n(327)](i=>{const{method:l}=i,u=o.get(l);s.tqDZP(typeof u,s.cjSoZ)&&u(i)})},vC=cr,gC=cr;(function(t,e){const r=cr,a=cr,n=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(a(398))/4+parseInt(r(390))/5*(parseInt(a(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(a(395))/9)+parseInt(a(399))/10*(parseInt(a(385))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ys,-1*-881393+2*180895+1*-644809);function cr(t,e){const r=Ys();return cr=function(a,n){return a=a-(-1861+-499*4+4241),r[a]},cr(t,e)}function Ys(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return Ys=function(){return t},Ys()}const yC=()=>{const t=cr,e=cr,r={};r.REzPF=function(n,s){return n&s},r.suJHI=function(n,s){return n===s},r[t(386)]=function(n,s){return n&s},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const a=r;return a.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():a.dHTfU.replace(/[xy]/g,n=>{const s=t,o=t,i=a[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(a.suJHI(n,"x")?i:a[o(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},_C=t=>{const e=cr,r=cr,a=new Uint8Array(t);return crypto.getRandomValues(a),Array[e(401)](a,n=>n[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},zr={};zr[vC(391)]=yC,zr[gC(396)]=_C;const $t=dr;(function(t,e){const r=dr,a=dr,n=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(a(499))/2)+parseInt(a(543))/3*(parseInt(a(514))/4)+parseInt(r(502))/5*(parseInt(a(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Xs,1472653*1+-2*-897917+-2275789);const wC=(t,e)=>{const r=dr,a=dr,n={FyYHt:function(l,u,d){return l(u,d)},Fxtoq:function(l,u,d){return l(u,d)}};uC(t,e),cC(t,e);const s=dC(e,t),o=n[r(510)](hC,e,t),i=n[a(549)](pC,e,t);e[a(537)](s),e[r(519)](o),e.addNotificationListener(i),t[a(556)]=()=>{const l=a;e.removeRequestListener(s),e[l(530)](o),e[l(529)](i)}},Al=(t,e,r)=>{const a=dr,n={pMiva:function(i,l){return i instanceof l},TeTEy:a(546),fyZbd:function(i,l,u){return i(l,u)}},s=()=>{var i;const l=a;n.pMiva(r,Ol)&&((i=r._eventSource)==null||i.addEventListener(n[l(547)],()=>{var u;const d=l;(u=r[d(509)])==null||u[d(546)]()})),wC(t,e)},o={};o.afterInit=s,n.fyZbd(mC,e,o)},ym=(t,e=zr.randomUUID())=>{const r=dr,a=dr,n={OfssH:function(d,h,g){return d(h,g)}},s={};s[r(528)]=e;const o=s,i={};i[r(528)]=e;const l={};l[a(558)]=i,l[r(534)]=r(524);const u={requestInit:l,eventSourceInit:{async fetch(d,h){const g=r,c=a,p=new Headers((h==null?void 0:h[g(558)])||{});Object.entries(o)[c(498)](([m,v])=>{p[c(527)](m,v)});const f={...h};return f[c(558)]=p,n.OfssH(fetch,d,f)},withCredentials:!0}};return t&&(u.requestInit[r(558)].Authorization=r(533)+t,o.Authorization="Bearer "+t),u},_m=(t,e=zr[$t(517)]())=>{const r=$t,a=$t,n={};n.nwQhY="include";const s=n,o={};o["stream-session-id"]=e;const i={};i.headers=o,i.credentials=s[r(520)];const l={};l[r(544)]=i;const u=l;return t&&(u.requestInit.headers[a(552)]=a(533)+t),u},Nl=async(t,e,r)=>{const a=$t,n=$t,s={CFfFC:function(i){return i()},egwVO:function(i,l,u,d){return i(l,u,d)}},o=s.CFfFC(r);try{return await t[a(538)](o),o}catch(i){if(i instanceof Gt){const l=await e();return await o[n(505)](l),await s[a(525)](Nl,t,e,r)}else throw i}};function dr(t,e){const r=Xs();return dr=function(a,n){return a=a-(74*-67+-8341+-73*-189),r[a]},dr(t,e)}const wm=(t,e)=>{const r=$t,a=$t,n={};n.RsKXs=function(o,i){return o in i},n.PBhps="waitForOAuthCode",n[r(535)]="function",n[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=n;if(s.RsKXs(s[a(551)],t))return t[a(523)];if(typeof e===s.yTKoP)return e;throw new Error(s.RZhOv)},bC=async t=>{const e=$t,r=$t,a={TFSRn:function($,z,L){return $(z,L)},HwvVa:"mcp-sse-proxy-client",ufTHS:function($){return $()},WIVYl:function($,z,L,F){return $(z,L,F)},jniGY:"sessionId"},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:u,eventSourceInit:d,waitForOAuthCode:h}=t,g={};g.authProvider=l,g.requestInit=u,g.eventSourceInit=d;const c=g,p=i||zr.randomUUID(),f=a[e(506)](ym,o,p);if(u){const $={...f.requestInit,...u};$.headers={...f[e(544)].headers,...u.headers},c.requestInit=$}else c[r(544)]=f.requestInit;if(d){const $={...f[e(559)],...d};c.eventSourceInit=$}else c.eventSourceInit=f.eventSourceInit;const m={};m.listChanged=!0;const v={};v.roots=m,v.sampling={},v[e(511)]={};const w=v,y={};y[r(536)]=a.HwvVa,y.version=e(526);const _={};_.capabilities=w;const E=new Hs(y,_),I=()=>new Ol(new URL(s),c);let S=a[r(504)](I);if(l){const $=a[e(506)](wm,l,h);S=await a[r(513)](Nl,E,$,I)}else await E[e(538)](S);a[r(513)](Al,E,n,S),S[r(557)]=S[r(542)].searchParams[r(532)](a.jniGY);const R={};return R.transport=S,R.sessionId=S[e(557)],R};function Xs(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return Xs=function(){return t},Xs()}const xC=async t=>{const e=$t,r=$t,a={Vajmx:e(500),biJOc:function($){return $()},zXcpO:function($,z,L){return $(z,L)},zDnjZ:function($,z,L,F){return $(z,L,F)},FQMAh:function($,z,L,F){return $(z,L,F)}},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:u,reconnectionOptions:d,waitForOAuthCode:h}=t,g={};g.authProvider=l,g.requestInit=u,g.reconnectionOptions=d;const c=g,p=i||zr.randomUUID(),f=_m(o,p);if(u){const $={...f.requestInit,...u};$.headers={...f.requestInit.headers,...u.headers},c[e(544)]=$}else c.requestInit=f.requestInit;const m={};m.listChanged=!0;const v={};v[r(550)]=m,v.sampling={},v.elicitation={};const w=v,y={};y[e(536)]=a[r(508)],y[e(555)]="1.0.0";const _={};_.capabilities=w;const E=new Hs(y,_),I=()=>new Ps(new URL(s),c);let S=a[e(503)](I);if(l){const $=a[e(501)](wm,l,h);S=await a.zDnjZ(Nl,E,$,I)}else await E.connect(S);a.FQMAh(Al,E,n,S);const R={};return R.transport=S,R[r(557)]=S.sessionId,R},EC=async t=>{const e=$t,r=$t,a={QgzDy:e(540),jkaVB:function(v,w,y,_){return v(w,y,_)}},{client:n,url:s,token:o,sessionId:i}=t,l={};l.listChanged=!0;const u={};u[e(550)]=l,u[e(515)]={},u[r(511)]={};const d=u,h={};h.name=a[r(548)],h[r(555)]=r(526);const g={};g.capabilities=d;const c=new Hs(h,g),p=i||zr[r(517)](),f=new vm(new URL(s+e(522)+p+r(554)+o));await c.connect(f),a.jkaVB(Al,c,n,f);const m={};return m[e(512)]=f,m[r(557)]=p,m},Ta=kt,eo=kt;function kt(t,e){const r=to();return kt=function(a,n){return a=a-(-16761+51*337),r[a]},kt(t,e)}(function(t,e){const r=kt,a=kt,n=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(a(449))/5)+-parseInt(a(455))/6+-parseInt(r(427))/7+-parseInt(a(438))/8*(parseInt(a(459))/9)+parseInt(r(430))/10*(parseInt(a(436))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(to,-220880+1*-333337+-2*-384996);function to(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return to=function(){return t},to()}const SC=()=>zr.randomBytes(3485*1+-261+-3184);class M2{constructor(e){const r=kt,a=kt;this._callBackPromise={};const{clientMetadata:n,state:s,redirectCallback:o,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=n,this[r(454)]=n[r(445)][0],this._state=s||SC(),this._redirectCallback=o||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[a(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,a,n,s,o,i;const l=kt,u=kt,d={qITTp:function(p,f,m){return p(f,m)},qcFPW:l(452)},h=await d.qITTp(fetch,e,{method:d[l(453)]});!h.ok&&((a=(r=this._callBackPromise).reject)==null||a.call(r,u(446)+h.statusText));const g=await this._getAuthCodeByState(this[u(454)],this[l(442)]);if(!g.ok){(s=(n=this[l(433)]).reject)==null||s.call(n,"Failed to fetch auth code: "+g.statusText);return}const c=await g[l(431)]();(i=(o=this[u(433)])[l(456)])==null||i.call(o,c[l(432)])}async getAuthCodeByStateFunction(e,r){const a=kt,n=kt,s={};s.tuSmb=a(429);const o=s,i={};i[a(460)]=o.tuSmb;const l={};return l[n(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=kt,r=this[e(433)];return()=>new Promise((a,n)=>{const s=e;r.resolve=a,r[s(434)]=n})}get redirectUrl(){return this[kt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Ta(447)](){return this[Ta(444)]}[eo(435)](e){const r=Ta;this[r(444)]=e}[eo(457)](){return this[eo(439)]}saveTokens(e){this._tokens=e}[eo(450)](e){this[Ta(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[Ta(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=no,a=no,n=t();;)try{var s=parseInt(r(361))/1*(parseInt(a(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(a(354))/6*(parseInt(r(360))/7)+parseInt(a(362))/8+parseInt(a(364))/9+-parseInt(a(356))/10*(parseInt(r(355))/11);if(s===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(ro,-73523*-3+1*-407717+530518);function ro(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return ro=function(){return t},ro()}function no(t,e){var r=ro();return no=function(a,n){a=a-(-1*-642+503*-5+2227);var s=r[a];return s},no(t,e)}class IC{constructor(e,r){const a={name:"web-mcp-client",version:"1.0.0"},n={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Hs(e||a,r||{capabilities:n}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:a,sessionId:n,type:s,agent:o,onError:i}=e;if(o===!0){const d={client:this.client,url:r,token:a,sessionId:n};let h;return await(async()=>{const{transport:c,sessionId:p}=s==="sse"?await bC(d):s==="socket"?await EC(d):await xC(d);c.onerror=async f=>{i==null||i(f)},h={transport:c,sessionId:p}})(),h}const l=new URL(r);let u;if(s==="channel"&&(u=new oC(r),await this.client.connect(u)),s==="sse"){const d=ym(a,n);u=new Ol(l,d),await this.client.connect(u)}if(s==="socket"&&(u=new vm(new URL(`${r}?sessionId=${n}&token=${a}`)),u.sessionId=n,await this.client.connect(u)),typeof u>"u"){const d=_m(a,n);u=new Ps(l,d),await this.client.connect(u)}return this.transport=u,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,Ss,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,a){return this.client.request(e,r,a)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler($h,e)}onCreateMessage(e){this.client.setRequestHandler(Rh,e)}onListRoots(e){this.client.setRequestHandler(Mh,e)}onToolListChanged(e){this.client.setNotificationHandler(kh,e)}onPromptListChanged(e){this.client.setNotificationHandler(Ih,e)}onResourceListChanged(e){this.client.setNotificationHandler(wh,e)}onResourceUpdated(e){this.client.setNotificationHandler(bh,e)}onLoggingMessage(e){this.client.setNotificationHandler(Ch,e)}async onPagehide(e){e.persisted||(TC(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const TC=t=>t instanceof Ps,Ml=async t=>{const e={};try{const r=await t.listTools();for(const{name:a,description:n,inputSchema:s}of r.tools){const o=async(i,l)=>t.callTool({name:a,arguments:i},{signal:l==null?void 0:l.abortSignal});e[a]=iw({description:n,inputSchema:ls({...s,properties:s.properties??{},additionalProperties:!1}),execute:o})}return e}catch(r){throw r}},kC={openai:gf,deepseek:Sf};class PC{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const a=e.providerType;let n;typeof a=="string"?n=kC[a]:n=a,this.llm=n({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided")}async _createOneClient(e){try{let r;"type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Ps(new URL(e.url)):"type"in e&&e.type==="extension"?r=new zT(e.sessionId):r=e;const a=new IC({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await a.connect(r),a.__transport__=r,a}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){var r,a,n;try{const s=e.__transport__;if(s&&s instanceof Cs||s&&s instanceof gm)return;await((r=s==null?void 0:s.terminateSession)==null?void 0:r.call(s)),await((a=s==null?void 0:s.close)==null?void 0:a.call(s)),await((n=e==null?void 0:e.close)==null?void 0:n.call(e))}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([a,n])=>{const s=await this._createOneClient(n);return{serverName:a,client:s}}));this.mcpClients={},r.forEach(({serverName:a,client:n})=>{this.mcpClients[a]=n})}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([a,n])=>{try{const s=n?await Ml(n):null;return{serverName:a,tools:s}}catch(s){return this.onError&&this.onError((s==null?void 0:s.message)||"Failed to query tools",s),console.error("Failed to query tools",s),{serverName:a,tools:null}}}));this.mcpTools={},r.forEach(({serverName:a,tools:n})=>{const s=n&&typeof n=="object"?n:{};this.mcpTools[a]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError((r==null?void 0:r.message)||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){var e;await this._createMpcClients(),await this._createMpcTools(),(e=this.onUpdatedTools)==null||e.call(this)}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){var s,o;if(this.mcpServers[e])return!1;const a=await this._createOneClient(r);if(!a)return(s=this.onError)==null||s.call(this,`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=a;const n=await Ml(a);return this.mcpTools[e]=n&&typeof n=="object"?n:{},this.mcpServers[e]=r,(o=this.onUpdatedTools)==null||o.call(this),a}async removeMcpServer(e){var n;if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const a=this.mcpTools[e];delete this.mcpTools[e],a&&Object.keys(a).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),(n=this.onUpdatedTools)==null||n.call(this)}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((a,n)=>({...a,...n}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(a=>{delete r[a]}),r}async _chat(e,{model:r,maxSteps:a=5,...n}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:_i(a),...n,tools:this._tempMergeTools(n.tools)};n.message&&!n.messages&&(this.messages.push({role:"user",content:n.message}),s.messages=[...this.messages]);const o=e(s);return(i=o==null?void 0:o.response)==null||i.then(l=>{this.messages.push(...l.messages)}),o}async chat(e){return this._chat(Yx,e)}async chatStream(e){return this._chat(gE,e)}}var Mn={},CC=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},bm={},At={};let Dl;const RC=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];At.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},At.getSymbolTotalCodewords=function(e){return RC[e]},At.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e},At.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Dl=e},At.isKanjiModeEnabled=function(){return typeof Dl<"u"},At.toSJIS=function(e){return Dl(e)};var ao={};(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,n){if(t.isValid(a))return a;try{return e(a)}catch{return n}}})(ao);function xm(){this.buffer=[],this.length=0}xm.prototype={get:function(t){const e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var OC=xm;function ka(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}ka.prototype.set=function(t,e,r,a){const n=t*this.size+e;this.data[n]=r,a&&(this.reservedBit[n]=!0)},ka.prototype.get=function(t,e){return this.data[t*this.size+e]},ka.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r},ka.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};var $C=ka,Em={};(function(t){const e=At.getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,s=e(a),o=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let l=1;l<n-1;l++)i[l]=i[l-1]-o;return i.push(6),i.reverse()},t.getPositions=function(a){const n=[],s=t.getRowColCoords(a),o=s.length;for(let i=0;i<o;i++)for(let l=0;l<o;l++)i===0&&l===0||i===0&&l===o-1||i===o-1&&l===0||n.push([s[i],s[l]]);return n}})(Em);var Sm={};const AC=At.getSymbolSize,Im=7;Sm.getPositions=function(e){const r=AC(e);return[[0,0],[r-Im,0],[0,r-Im]]};var Tm={};(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},t.from=function(n){return t.isValid(n)?parseInt(n,10):void 0},t.getPenaltyN1=function(n){const s=n.size;let o=0,i=0,l=0,u=null,d=null;for(let h=0;h<s;h++){i=l=0,u=d=null;for(let g=0;g<s;g++){let c=n.get(h,g);c===u?i++:(i>=5&&(o+=e.N1+(i-5)),u=c,i=1),c=n.get(g,h),c===d?l++:(l>=5&&(o+=e.N1+(l-5)),d=c,l=1)}i>=5&&(o+=e.N1+(i-5)),l>=5&&(o+=e.N1+(l-5))}return o},t.getPenaltyN2=function(n){const s=n.size;let o=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=n.get(i,l)+n.get(i,l+1)+n.get(i+1,l)+n.get(i+1,l+1);(u===4||u===0)&&o++}return o*e.N2},t.getPenaltyN3=function(n){const s=n.size;let o=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let d=0;d<s;d++)i=i<<1&2047|n.get(u,d),d>=10&&(i===1488||i===93)&&o++,l=l<<1&2047|n.get(d,u),d>=10&&(l===1488||l===93)&&o++}return o*e.N3},t.getPenaltyN4=function(n){let s=0;const o=n.data.length;for(let l=0;l<o;l++)s+=n.data[l];return Math.abs(Math.ceil(s*100/o/5)-10)*e.N4};function r(a,n,s){switch(a){case t.Patterns.PATTERN000:return(n+s)%2===0;case t.Patterns.PATTERN001:return n%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(n+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return n*s%2+n*s%3===0;case t.Patterns.PATTERN110:return(n*s%2+n*s%3)%2===0;case t.Patterns.PATTERN111:return(n*s%3+(n+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(n,s){const o=s.size;for(let i=0;i<o;i++)for(let l=0;l<o;l++)s.isReserved(l,i)||s.xor(l,i,r(n,l,i))},t.getBestMask=function(n,s){const o=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let u=0;u<o;u++){s(u),t.applyMask(u,n);const d=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(u,n),d<l&&(l=d,i=u)}return i}})(Tm);var so={};const Ur=ao,oo=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],io=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];so.getBlocksCount=function(e,r){switch(r){case Ur.L:return oo[(e-1)*4+0];case Ur.M:return oo[(e-1)*4+1];case Ur.Q:return oo[(e-1)*4+2];case Ur.H:return oo[(e-1)*4+3];default:return}},so.getTotalCodewordsCount=function(e,r){switch(r){case Ur.L:return io[(e-1)*4+0];case Ur.M:return io[(e-1)*4+1];case Ur.Q:return io[(e-1)*4+2];case Ur.H:return io[(e-1)*4+3];default:return}};var km={},lo={};const Pa=new Uint8Array(512),uo=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Pa[r]=e,uo[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Pa[r]=Pa[r-255]})(),lo.log=function(e){if(e<1)throw new Error("log("+e+")");return uo[e]},lo.exp=function(e){return Pa[e]},lo.mul=function(e,r){return e===0||r===0?0:Pa[uo[e]+uo[r]]},function(t){const e=lo;t.mul=function(a,n){const s=new Uint8Array(a.length+n.length-1);for(let o=0;o<a.length;o++)for(let i=0;i<n.length;i++)s[o+i]^=e.mul(a[o],n[i]);return s},t.mod=function(a,n){let s=new Uint8Array(a);for(;s.length-n.length>=0;){const o=s[0];for(let l=0;l<n.length;l++)s[l]^=e.mul(n[l],o);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},t.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let s=0;s<a;s++)n=t.mul(n,new Uint8Array([1,e.exp(s)]));return n}}(km);const Pm=km;function jl(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}jl.prototype.initialize=function(e){this.degree=e,this.genPoly=Pm.generateECPolynomial(this.degree)},jl.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");const r=new Uint8Array(e.length+this.degree);r.set(e);const a=Pm.mod(r,this.genPoly),n=this.degree-a.length;if(n>0){const s=new Uint8Array(this.degree);return s.set(a,n),s}return a};var NC=jl,Cm={},Fr={},Ll={};Ll.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var pr={};const Rm="[0-9]+",MC="[A-Z $%*+\\-./:]+";let Ca="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Ca=Ca.replace(/u/g,"\\u");const DC="(?:(?![A-Z0-9 $%*+\\-./:]|"+Ca+`)(?:.|[\r
72
- ]))+`;pr.KANJI=new RegExp(Ca,"g"),pr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),pr.BYTE=new RegExp(DC,"g"),pr.NUMERIC=new RegExp(Rm,"g"),pr.ALPHANUMERIC=new RegExp(MC,"g");const jC=new RegExp("^"+Ca+"$"),LC=new RegExp("^"+Rm+"$"),zC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");pr.testKanji=function(e){return jC.test(e)},pr.testNumeric=function(e){return LC.test(e)},pr.testAlphanumeric=function(e){return zC.test(e)},function(t){const e=Ll,r=pr;t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,o){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?s.ccBits[0]:o<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+n)}}t.from=function(s,o){if(t.isValid(s))return s;try{return a(s)}catch{return o}}}(Fr),function(t){const e=At,r=so,a=ao,n=Fr,s=Ll,o=7973,i=e.getBCHDigit(o);function l(g,c,p){for(let f=1;f<=40;f++)if(c<=t.getCapacity(f,p,g))return f}function u(g,c){return n.getCharCountIndicator(g,c)+4}function d(g,c){let p=0;return g.forEach(function(f){const m=u(f.mode,c);p+=m+f.getBitsLength()}),p}function h(g,c){for(let p=1;p<=40;p++)if(d(g,p)<=t.getCapacity(p,c,n.MIXED))return p}t.from=function(c,p){return s.isValid(c)?parseInt(c,10):p},t.getCapacity=function(c,p,f){if(!s.isValid(c))throw new Error("Invalid QR Code version");typeof f>"u"&&(f=n.BYTE);const m=e.getSymbolTotalCodewords(c),v=r.getTotalCodewordsCount(c,p),w=(m-v)*8;if(f===n.MIXED)return w;const y=w-u(f,c);switch(f){case n.NUMERIC:return Math.floor(y/10*3);case n.ALPHANUMERIC:return Math.floor(y/11*2);case n.KANJI:return Math.floor(y/13);case n.BYTE:default:return Math.floor(y/8)}},t.getBestVersionForData=function(c,p){let f;const m=a.from(p,a.M);if(Array.isArray(c)){if(c.length>1)return h(c,m);if(c.length===0)return 1;f=c[0]}else f=c;return l(f.mode,f.getLength(),m)},t.getEncodedBits=function(c){if(!s.isValid(c)||c<7)throw new Error("Invalid QR Code version");let p=c<<12;for(;e.getBCHDigit(p)-i>=0;)p^=o<<e.getBCHDigit(p)-i;return c<<12|p}}(Cm);var Om={};const zl=At,$m=1335,UC=21522,Am=zl.getBCHDigit($m);Om.getEncodedBits=function(e,r){const a=e.bit<<3|r;let n=a<<10;for(;zl.getBCHDigit(n)-Am>=0;)n^=$m<<zl.getBCHDigit(n)-Am;return(a<<10|n)^UC};var Nm={};const FC=Fr;function Dn(t){this.mode=FC.NUMERIC,this.data=t.toString()}Dn.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},Dn.prototype.getLength=function(){return this.data.length},Dn.prototype.getBitsLength=function(){return Dn.getBitsLength(this.data.length)},Dn.prototype.write=function(e){let r,a,n;for(r=0;r+3<=this.data.length;r+=3)a=this.data.substr(r,3),n=parseInt(a,10),e.put(n,10);const s=this.data.length-r;s>0&&(a=this.data.substr(r),n=parseInt(a,10),e.put(n,s*3+1))};var qC=Dn;const ZC=Fr,Ul=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function jn(t){this.mode=ZC.ALPHANUMERIC,this.data=t}jn.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},jn.prototype.getLength=function(){return this.data.length},jn.prototype.getBitsLength=function(){return jn.getBitsLength(this.data.length)},jn.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let a=Ul.indexOf(this.data[r])*45;a+=Ul.indexOf(this.data[r+1]),e.put(a,11)}this.data.length%2&&e.put(Ul.indexOf(this.data[r]),6)};var VC=jn;const BC=Fr;function Ln(t){this.mode=BC.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Ln.getBitsLength=function(e){return e*8},Ln.prototype.getLength=function(){return this.data.length},Ln.prototype.getBitsLength=function(){return Ln.getBitsLength(this.data.length)},Ln.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};var HC=Ln;const JC=Fr,WC=At;function zn(t){this.mode=JC.KANJI,this.data=t}zn.getBitsLength=function(e){return e*13},zn.prototype.getLength=function(){return this.data.length},zn.prototype.getBitsLength=function(){return zn.getBitsLength(this.data.length)},zn.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=WC.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
73
- Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};var GC=zn,Mm={exports:{}};(function(t){var e={single_source_shortest_paths:function(r,a,n){var s={},o={};o[a]=0;var i=e.PriorityQueue.make();i.push(a,0);for(var l,u,d,h,g,c,p,f,m;!i.empty();){l=i.pop(),u=l.value,h=l.cost,g=r[u]||{};for(d in g)g.hasOwnProperty(d)&&(c=g[d],p=h+c,f=o[d],m=typeof o[d]>"u",(m||f>p)&&(o[d]=p,i.push(d,p),s[d]=u))}if(typeof n<"u"&&typeof o[n]>"u"){var v=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(v)}return s},extract_shortest_path_from_predecessor_list:function(r,a){for(var n=[],s=a;s;)n.push(s),r[s],s=r[s];return n.reverse(),n},find_path:function(r,a,n){var s=e.single_source_shortest_paths(r,a,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(r){var a=e.PriorityQueue,n={},s;r=r||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=r.sorter||a.default_sorter,n},default_sorter:function(r,a){return r.cost-a.cost},push:function(r,a){var n={value:r,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Mm);var KC=Mm.exports;(function(t){const e=Fr,r=qC,a=VC,n=HC,s=GC,o=pr,i=At,l=KC;function u(v){return unescape(encodeURIComponent(v)).length}function d(v,w,y){const _=[];let E;for(;(E=v.exec(y))!==null;)_.push({data:E[0],index:E.index,mode:w,length:E[0].length});return _}function h(v){const w=d(o.NUMERIC,e.NUMERIC,v),y=d(o.ALPHANUMERIC,e.ALPHANUMERIC,v);let _,E;return i.isKanjiModeEnabled()?(_=d(o.BYTE,e.BYTE,v),E=d(o.KANJI,e.KANJI,v)):(_=d(o.BYTE_KANJI,e.BYTE,v),E=[]),w.concat(y,_,E).sort(function(S,R){return S.index-R.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.length}})}function g(v,w){switch(w){case e.NUMERIC:return r.getBitsLength(v);case e.ALPHANUMERIC:return a.getBitsLength(v);case e.KANJI:return s.getBitsLength(v);case e.BYTE:return n.getBitsLength(v)}}function c(v){return v.reduce(function(w,y){const _=w.length-1>=0?w[w.length-1]:null;return _&&_.mode===y.mode?(w[w.length-1].data+=y.data,w):(w.push(y),w)},[])}function p(v){const w=[];for(let y=0;y<v.length;y++){const _=v[y];switch(_.mode){case e.NUMERIC:w.push([_,{data:_.data,mode:e.ALPHANUMERIC,length:_.length},{data:_.data,mode:e.BYTE,length:_.length}]);break;case e.ALPHANUMERIC:w.push([_,{data:_.data,mode:e.BYTE,length:_.length}]);break;case e.KANJI:w.push([_,{data:_.data,mode:e.BYTE,length:u(_.data)}]);break;case e.BYTE:w.push([{data:_.data,mode:e.BYTE,length:u(_.data)}])}}return w}function f(v,w){const y={},_={start:{}};let E=["start"];for(let I=0;I<v.length;I++){const S=v[I],R=[];for(let $=0;$<S.length;$++){const z=S[$],L=""+I+$;R.push(L),y[L]={node:z,lastCount:0},_[L]={};for(let F=0;F<E.length;F++){const M=E[F];y[M]&&y[M].node.mode===z.mode?(_[M][L]=g(y[M].lastCount+z.length,z.mode)-g(y[M].lastCount,z.mode),y[M].lastCount+=z.length):(y[M]&&(y[M].lastCount=z.length),_[M][L]=g(z.length,z.mode)+4+e.getCharCountIndicator(z.mode,w))}}E=R}for(let I=0;I<E.length;I++)_[E[I]].end=0;return{map:_,table:y}}function m(v,w){let y;const _=e.getBestModeForData(v);if(y=e.from(w,_),y!==e.BYTE&&y.bit<_.bit)throw new Error('"'+v+'" cannot be encoded with mode '+e.toString(y)+`.
74
- Suggested mode is: `+e.toString(_));switch(y===e.KANJI&&!i.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new r(v);case e.ALPHANUMERIC:return new a(v);case e.KANJI:return new s(v);case e.BYTE:return new n(v)}}t.fromArray=function(w){return w.reduce(function(y,_){return typeof _=="string"?y.push(m(_,null)):_.data&&y.push(m(_.data,_.mode)),y},[])},t.fromString=function(w,y){const _=h(w,i.isKanjiModeEnabled()),E=p(_),I=f(E,y),S=l.find_path(I.map,"start","end"),R=[];for(let $=1;$<S.length-1;$++)R.push(I.table[S[$]].node);return t.fromArray(c(R))},t.rawSplit=function(w){return t.fromArray(h(w,i.isKanjiModeEnabled()))}})(Nm);const co=At,Fl=ao,QC=OC,YC=$C,XC=Em,e2=Sm,ql=Tm,Zl=so,t2=NC,po=Cm,r2=Om,n2=Fr,Vl=Nm;function a2(t,e){const r=t.size,a=e2.getPositions(e);for(let n=0;n<a.length;n++){const s=a[n][0],o=a[n][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||r<=s+i))for(let l=-1;l<=7;l++)o+l<=-1||r<=o+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?t.set(s+i,o+l,!0,!0):t.set(s+i,o+l,!1,!0))}}function s2(t){const e=t.size;for(let r=8;r<e-8;r++){const a=r%2===0;t.set(r,6,a,!0),t.set(6,r,a,!0)}}function o2(t,e){const r=XC.getPositions(e);for(let a=0;a<r.length;a++){const n=r[a][0],s=r[a][1];for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)o===-2||o===2||i===-2||i===2||o===0&&i===0?t.set(n+o,s+i,!0,!0):t.set(n+o,s+i,!1,!0)}}function i2(t,e){const r=t.size,a=po.getEncodedBits(e);let n,s,o;for(let i=0;i<18;i++)n=Math.floor(i/3),s=i%3+r-8-3,o=(a>>i&1)===1,t.set(n,s,o,!0),t.set(s,n,o,!0)}function Bl(t,e,r){const a=t.size,n=r2.getEncodedBits(e,r);let s,o;for(s=0;s<15;s++)o=(n>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(a-15+s,8,o,!0),s<8?t.set(8,a-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(a-8,8,1,!0)}function l2(t,e){const r=t.size;let a=-1,n=r-1,s=7,o=0;for(let i=r-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!t.isReserved(n,i-l)){let u=!1;o<e.length&&(u=(e[o]>>>s&1)===1),t.set(n,i-l,u),s--,s===-1&&(o++,s=7)}if(n+=a,n<0||r<=n){n-=a,a=-a;break}}}function u2(t,e,r){const a=new QC;r.forEach(function(l){a.put(l.mode.bit,4),a.put(l.getLength(),n2.getCharCountIndicator(l.mode,t)),l.write(a)});const n=co.getSymbolTotalCodewords(t),s=Zl.getTotalCodewordsCount(t,e),o=(n-s)*8;for(a.getLengthInBits()+4<=o&&a.put(0,4);a.getLengthInBits()%8!==0;)a.putBit(0);const i=(o-a.getLengthInBits())/8;for(let l=0;l<i;l++)a.put(l%2?17:236,8);return c2(a,t,e)}function c2(t,e,r){const a=co.getSymbolTotalCodewords(e),n=Zl.getTotalCodewordsCount(e,r),s=a-n,o=Zl.getBlocksCount(e,r),i=a%o,l=o-i,u=Math.floor(a/o),d=Math.floor(s/o),h=d+1,g=u-d,c=new t2(g);let p=0;const f=new Array(o),m=new Array(o);let v=0;const w=new Uint8Array(t.buffer);for(let S=0;S<o;S++){const R=S<l?d:h;f[S]=w.slice(p,p+R),m[S]=c.encode(f[S]),p+=R,v=Math.max(v,R)}const y=new Uint8Array(a);let _=0,E,I;for(E=0;E<v;E++)for(I=0;I<o;I++)E<f[I].length&&(y[_++]=f[I][E]);for(E=0;E<g;E++)for(I=0;I<o;I++)y[_++]=m[I][E];return y}function d2(t,e,r,a){let n;if(Array.isArray(t))n=Vl.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){const d=Vl.rawSplit(t);u=po.getBestVersionForData(d,r)}n=Vl.fromString(t,u||40)}else throw new Error("Invalid data");const s=po.getBestVersionForData(n,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
69
+ `;break}case"tool":throw new Ct({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
70
+ `,{prompt:n,stopSequences:[`
71
+ ${t}:`]}}function Mf({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Nf(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 q8=rt(()=>Ce(T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({text:v(),finish_reason:v(),logprobs:T({tokens:A(v()),token_logprobs:A(q()),top_logprobs:A(ve(v(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}))),L8=rt(()=>Ce(ne([T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({text:v(),finish_reason:v().nullish(),index:q(),logprobs:T({tokens:A(v()),token_logprobs:A(q()),top_logprobs:A(ve(v(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}),Xi]))),Af=rt(()=>Ce(T({echo:ce().optional(),logitBias:ve(v(),q()).optional(),suffix:v().optional(),user:v().optional(),logprobs:ne([ce(),q()]).optional()}))),j8=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:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:g,providerOptions:h}){const d=[],p={...await pr({provider:"openai",providerOptions:h,schema:Af}),...await pr({provider:this.providerOptionsName,providerOptions:h,schema:Af})};o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),c?.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:w,stopSequences:m}=A8({prompt:e}),y=[...m??[],...i??[]];return{args:{model:this.modelId,echo:p.echo,logit_bias:p.logitBias,logprobs:p?.logprobs===!0?0:p?.logprobs===!1?void 0:p?.logprobs,suffix:p.suffix,user:p.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:g,prompt:w,stop:y.length>0?y:void 0},warnings:d}}async doGenerate(e){var t,r,n;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:o,failedResponseHandler:Zt,successfulResponseHandler:sn(q8),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(n=i.usage)==null?void 0:n.total_tokens},finishReason:Nf(c.finish_reason),request:{body:o},response:{...Mf(i),headers:a,body:l},providerMetadata:u,warnings:s}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:n,failedResponseHandler:Zt,successfulResponseHandler:Wi(L8),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,g){if(e.includeRawChunks&&g.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",g.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){a="error",g.enqueue({type:"error",error:h.error});return}c&&(c=!1,g.enqueue({type:"response-metadata",...Mf(h)}),g.enqueue({type:"text-start",id:"0"})),h.usage!=null&&(l.inputTokens=h.usage.prompt_tokens,l.outputTokens=h.usage.completion_tokens,l.totalTokens=h.usage.total_tokens);const d=h.choices[0];d?.finish_reason!=null&&(a=Nf(d.finish_reason)),d?.logprobs!=null&&(i.openai.logprobs=d.logprobs),d?.text!=null&&d.text.length>0&&g.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:n},response:{headers:o}}}},U8=rt(()=>Ce(T({dimensions:q().optional(),user:v().optional()}))),z8=rt(()=>Ce(T({data:A(T({embedding:A(q())})),usage:T({prompt_tokens:q()}).nullish()}))),D8=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:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new z2({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await pr({provider:"openai",providerOptions:n,schema:U8}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Dt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Zt,successfulResponseHandler:sn(z8),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},Z8=rt(()=>Ce(T({created:q().nullish(),data:A(T({b64_json:v(),revised_prompt:v().nullish()})),background:v().nullish(),output_format:v().nullish(),size:v().nullish(),quality:v().nullish(),usage:T({input_tokens:q().nullish(),output_tokens:q().nullish(),total_tokens:q().nullish(),input_tokens_details:T({image_tokens:q().nullish(),text_tokens:q().nullish()}).nullish()}).nullish()}))),F8={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},V8=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),H8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=F8[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,c,u,g;const h=[];n!=null&&h.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&h.push({type:"unsupported-setting",setting:"seed"});const d=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:p,responseHeaders:w}=await Kt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Dt(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:r,...(g=s.openai)!=null?g:{},...V8.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Zt,successfulResponseHandler:sn(Z8),abortSignal:i,fetch:this.config.fetch});return{images:p.data.map(m=>m.b64_json),warnings:h,response:{timestamp:d,modelId:this.modelId,headers:w},providerMetadata:{openai:{images:p.data.map(m=>({...m.revised_prompt?{revisedPrompt:m.revised_prompt}:{},...p.created!=null?{created:p.created}:{},...p.size!=null?{size:p.size}:{},...p.quality!=null?{quality:p.quality}:{},...p.background!=null?{background:p.background}:{},...p.output_format!=null?{outputFormat:p.output_format}:{}}))}}}}},B8=Qe(()=>Ce(T({code:v().nullish(),containerId:v()}))),J8=Qe(()=>Ce(T({outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullish()}))),G8=Qe(()=>Ce(T({container:ne([v(),T({fileIds:A(v()).optional()})]).optional()}))),W8=on({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:B8,outputSchema:J8}),K8=(e={})=>W8(e),qf=T({key:v(),type:_e(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ne([v(),q(),ce(),A(v())])}),Lf=T({type:_e(["and","or"]),filters:A(ne([qf,Fu(()=>Lf)]))}),Y8=Qe(()=>Ce(T({vectorStoreIds:A(v()),maxNumResults:q().optional(),ranking:T({ranker:v().optional(),scoreThreshold:q().optional()}).optional(),filters:ne([qf,Lf]).optional()}))),Q8=Qe(()=>Ce(T({queries:A(v()),results:A(T({attributes:ve(v(),$e()),fileId:v(),filename:v(),score:q(),text:v()})).nullable()}))),X8=on({id:"openai.file_search",name:"file_search",inputSchema:T({}),outputSchema:Q8}),e7=Qe(()=>Ce(T({background:_e(["auto","opaque","transparent"]).optional(),inputFidelity:_e(["low","high"]).optional(),inputImageMask:T({fileId:v().optional(),imageUrl:v().optional()}).optional(),model:v().optional(),moderation:_e(["auto"]).optional(),outputCompression:q().int().min(0).max(100).optional(),outputFormat:_e(["png","jpeg","webp"]).optional(),partialImages:q().int().min(0).max(3).optional(),quality:_e(["auto","low","medium","high"]).optional(),size:_e(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),t7=Qe(()=>Ce(T({}))),r7=Qe(()=>Ce(T({result:v()}))),n7=on({id:"openai.image_generation",name:"image_generation",inputSchema:t7,outputSchema:r7}),o7=(e={})=>n7(e),jf=Qe(()=>Ce(T({action:T({type:L("exec"),command:A(v()),timeoutMs:q().optional(),user:v().optional(),workingDirectory:v().optional(),env:ve(v(),v()).optional()})}))),Uf=Qe(()=>Ce(T({output:v()}))),s7=on({id:"openai.local_shell",name:"local_shell",inputSchema:jf,outputSchema:Uf}),a7=Qe(()=>Ce(T({externalWebAccess:ce().optional(),filters:T({allowedDomains:A(v()).optional()}).optional(),searchContextSize:_e(["low","medium","high"]).optional(),userLocation:T({type:L("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),i7=Qe(()=>Ce(T({}))),l7=Qe(()=>Ce(T({action:Ze("type",[T({type:L("search"),query:v().optional()}),T({type:L("openPage"),url:v().nullish()}),T({type:L("findInPage"),url:v().nullish(),pattern:v().nullish()})]),sources:A(Ze("type",[T({type:L("url"),url:v()}),T({type:L("api"),name:v()})])).optional()}))),c7=on({id:"openai.web_search",name:"web_search",inputSchema:i7,outputSchema:l7}),u7=(e={})=>c7(e),d7=Qe(()=>Ce(T({searchContextSize:_e(["low","medium","high"]).optional(),userLocation:T({type:L("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),p7=Qe(()=>Ce(T({}))),f7=Qe(()=>Ce(T({action:Ze("type",[T({type:L("search"),query:v().optional()}),T({type:L("openPage"),url:v().nullish()}),T({type:L("findInPage"),url:v().nullish(),pattern:v().nullish()})])}))),h7=on({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:p7,outputSchema:f7}),m7={codeInterpreter:K8,fileSearch:X8,imageGeneration:o7,localShell:s7,webSearchPreview:h7,webSearch:u7};function zf(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function g7({prompt:e,systemMessageMode:t,fileIdPrefixes:r,store:n,hasLocalShellTool:o=!1}){var s,a,i,l;const c=[],u=[];for(const{role:g,content:h}of e)switch(g){case"system":{switch(t){case"system":{c.push({role:"system",content:h});break}case"developer":{c.push({role:"developer",content:h});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=t;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{c.push({role:"user",content:h.map((d,p)=>{var w,m,y;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const _=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&zf(d.data,r)?{file_id:d.data}:{image_url:`data:${_};base64,${an(d.data)}`},detail:(m=(w=d.providerOptions)==null?void 0:w.openai)==null?void 0:m.imageDetail}}else{if(d.mediaType==="application/pdf")return d.data instanceof URL?{type:"input_file",file_url:d.data.toString()}:{type:"input_file",...typeof d.data=="string"&&zf(d.data,r)?{file_id:d.data}:{filename:(y=d.filename)!=null?y:`part-${p}.pdf`,file_data:`data:application/pdf;base64,${an(d.data)}`}};throw new Ct({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},p={};for(const w of h)switch(w.type){case"text":{const m=(a=(s=w.providerOptions)==null?void 0:s.openai)==null?void 0:a.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:w.text}],id:m});break}case"tool-call":{if(p[w.toolCallId]=w,w.providerExecuted)break;const m=(l=(i=w.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}if(o&&w.toolName==="local_shell"){const y=await dr({value:w.input,schema:jf});c.push({type:"local_shell_call",call_id:w.toolCallId,id:m,action:{type:"exec",command:y.action.command,timeout_ms:y.action.timeoutMs,user:y.action.user,working_directory:y.action.workingDirectory,env:y.action.env}});break}c.push({type:"function_call",call_id:w.toolCallId,name:w.toolName,arguments:JSON.stringify(w.input),id:m});break}case"tool-result":{n?c.push({type:"item_reference",id:w.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${w.toolName} are not sent to the API when store is false`});break}case"reasoning":{const m=await pr({provider:"openai",providerOptions:w.providerOptions,schema:v7}),y=m?.itemId;if(y!=null){const _=d[y];if(n)_===void 0&&(c.push({type:"item_reference",id:y}),d[y]={type:"reasoning",id:y,summary:[]});else{const f=[];w.text.length>0?f.push({type:"summary_text",text:w.text}):_!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(w)}.`}),_===void 0?(d[y]={type:"reasoning",id:y,encrypted_content:m?.reasoningEncryptedContent,summary:f},c.push(d[y])):(_.summary.push(...f),m?.reasoningEncryptedContent!=null&&(_.encrypted_content=m.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(w)}.`});break}}break}case"tool":{for(const d of h){const p=d.output;if(o&&d.toolName==="local_shell"&&p.type==="json"){const m=await dr({value:p.value,schema:Uf});c.push({type:"local_shell_call_output",call_id:d.toolCallId,output:m.output});break}let w;switch(p.type){case"text":case"error-text":w=p.value;break;case"json":case"error-json":w=JSON.stringify(p.value);break;case"content":w=p.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}c.push({type:"function_call_output",call_id:d.toolCallId,output:w})}break}default:{const d=g;throw new Error(`Unsupported role: ${d}`)}}return{input:c,warnings:u}}var v7=T({itemId:v().nullish(),reasoningEncryptedContent:v().nullish()});function Df({finishReason:e,hasFunctionCall: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 _7=rt(()=>Ce(ne([T({type:L("response.output_text.delta"),item_id:v(),delta:v(),logprobs:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish()}),T({type:_e(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:v()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish()}).nullish()}),service_tier:v().nullish()})}),T({type:L("response.created"),response:T({id:v(),created_at:q(),model:v(),service_tier:v().nullish()})}),T({type:L("response.output_item.added"),output_index:q(),item:Ze("type",[T({type:L("message"),id:v()}),T({type:L("reasoning"),id:v(),encrypted_content:v().nullish()}),T({type:L("function_call"),id:v(),call_id:v(),name:v(),arguments:v()}),T({type:L("web_search_call"),id:v(),status:v()}),T({type:L("computer_call"),id:v(),status:v()}),T({type:L("file_search_call"),id:v()}),T({type:L("image_generation_call"),id:v()}),T({type:L("code_interpreter_call"),id:v(),container_id:v(),code:v().nullable(),outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullable(),status:v()})])}),T({type:L("response.output_item.done"),output_index:q(),item:Ze("type",[T({type:L("message"),id:v()}),T({type:L("reasoning"),id:v(),encrypted_content:v().nullish()}),T({type:L("function_call"),id:v(),call_id:v(),name:v(),arguments:v(),status:L("completed")}),T({type:L("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullable()}),T({type:L("image_generation_call"),id:v(),result:v()}),T({type:L("web_search_call"),id:v(),status:v(),action:Ze("type",[T({type:L("search"),query:v().nullish(),sources:A(Ze("type",[T({type:L("url"),url:v()}),T({type:L("api"),name:v()})])).nullish()}),T({type:L("open_page"),url:v().nullish()}),T({type:L("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),T({type:L("file_search_call"),id:v(),queries:A(v()),results:A(T({attributes:ve(v(),$e()),file_id:v(),filename:v(),score:q(),text:v()})).nullish()}),T({type:L("local_shell_call"),id:v(),call_id:v(),action:T({type:L("exec"),command:A(v()),timeout_ms:q().optional(),user:v().optional(),working_directory:v().optional(),env:ve(v(),v()).optional()})}),T({type:L("computer_call"),id:v(),status:L("completed")})])}),T({type:L("response.function_call_arguments.delta"),item_id:v(),output_index:q(),delta:v()}),T({type:L("response.image_generation_call.partial_image"),item_id:v(),output_index:q(),partial_image_b64:v()}),T({type:L("response.code_interpreter_call_code.delta"),item_id:v(),output_index:q(),delta:v()}),T({type:L("response.code_interpreter_call_code.done"),item_id:v(),output_index:q(),code:v()}),T({type:L("response.output_text.annotation.added"),annotation:Ze("type",[T({type:L("url_citation"),start_index:q(),end_index:q(),url:v(),title:v()}),T({type:L("file_citation"),file_id:v(),filename:v().nullish(),index:q().nullish(),start_index:q().nullish(),end_index:q().nullish(),quote:v().nullish()})])}),T({type:L("response.reasoning_summary_part.added"),item_id:v(),summary_index:q()}),T({type:L("response.reasoning_summary_text.delta"),item_id:v(),summary_index:q(),delta:v()}),T({type:L("response.reasoning_summary_part.done"),item_id:v(),summary_index:q()}),T({type:L("error"),sequence_number:q(),error:T({type:v(),code:v(),message:v(),param:v().nullish()})}),T({type:v()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),y7=rt(()=>Ce(T({id:v().optional(),created_at:q().optional(),error:T({message:v(),type:v(),param:v().nullish(),code:v()}).nullish(),model:v().optional(),output:A(Ze("type",[T({type:L("message"),role:L("assistant"),id:v(),content:A(T({type:L("output_text"),text:v(),logprobs:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish(),annotations:A(Ze("type",[T({type:L("url_citation"),start_index:q(),end_index:q(),url:v(),title:v()}),T({type:L("file_citation"),file_id:v(),filename:v().nullish(),index:q().nullish(),start_index:q().nullish(),end_index:q().nullish(),quote:v().nullish()}),T({type:L("container_file_citation"),container_id:v(),file_id:v(),filename:v().nullish(),start_index:q().nullish(),end_index:q().nullish(),index:q().nullish()}),T({type:L("file_path"),file_id:v(),index:q().nullish()})]))}))}),T({type:L("web_search_call"),id:v(),status:v(),action:Ze("type",[T({type:L("search"),query:v().nullish(),sources:A(Ze("type",[T({type:L("url"),url:v()}),T({type:L("api"),name:v()})])).nullish()}),T({type:L("open_page"),url:v().nullish()}),T({type:L("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),T({type:L("file_search_call"),id:v(),queries:A(v()),results:A(T({attributes:ve(v(),ne([v(),q(),ce()])),file_id:v(),filename:v(),score:q(),text:v()})).nullish()}),T({type:L("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullable()}),T({type:L("image_generation_call"),id:v(),result:v()}),T({type:L("local_shell_call"),id:v(),call_id:v(),action:T({type:L("exec"),command:A(v()),timeout_ms:q().optional(),user:v().optional(),working_directory:v().optional(),env:ve(v(),v()).optional()})}),T({type:L("function_call"),call_id:v(),name:v(),arguments:v(),id:v()}),T({type:L("computer_call"),id:v(),status:v().optional()}),T({type:L("reasoning"),id:v(),encrypted_content:v().nullish(),summary:A(T({type:L("summary_text"),text:v()}))})])).optional(),service_tier:v().nullish(),incomplete_details:T({reason:v()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish()}).nullish()}).optional()}))),Zf=20,w7=rt(()=>Ce(T({conversation:v().nullish(),include:A(_e(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:v().nullish(),logprobs:ne([ce(),q().min(1).max(Zf)]).optional(),maxToolCalls:q().nullish(),metadata:et().nullish(),parallelToolCalls:ce().nullish(),previousResponseId:v().nullish(),promptCacheKey:v().nullish(),promptCacheRetention:_e(["in_memory","24h"]).nullish(),reasoningEffort:v().nullish(),reasoningSummary:v().nullish(),safetyIdentifier:v().nullish(),serviceTier:_e(["auto","flex","priority","default"]).nullish(),store:ce().nullish(),strictJsonSchema:ce().nullish(),textVerbosity:_e(["low","medium","high"]).nullish(),truncation:_e(["auto","disabled"]).nullish(),user:v().nullish()})));async function b7({tools:e,toolChoice:t,strictJsonSchema:r}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await dr({value:a.args,schema:Y8});o.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await dr({value:a.args,schema:d7});o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await dr({value:a.args,schema:a7});o.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,external_web_access:i.externalWebAccess,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await dr({value:a.args,schema:G8});o.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await dr({value:a.args,schema:e7});o.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:n};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:n};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const a=s;throw new Ct({functionality:`tool choice type: ${a}`})}}}var k7=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:g,responseFormat:h}){var d,p,w,m;const y=[],_=Pf(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),s!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const f=await pr({provider:"openai",providerOptions:c,schema:w7});f?.conversation&&f?.previousResponseId&&y.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:k}=await g7({prompt:l,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=f?.store)!=null?d:!0,hasLocalShellTool:x("openai.local_shell")});y.push(...k);const S=(p=f?.strictJsonSchema)!=null?p:!1;let C=f?.include;function I(se){C==null?C=[se]:C.includes(se)||(C=[...C,se])}function x(se){return u?.find(ee=>ee.type==="provider-defined"&&ee.id===se)!=null}const M=typeof f?.logprobs=="number"?f?.logprobs:f?.logprobs===!0?Zf:void 0;M&&I("message.output_text.logprobs");const P=(w=u?.find(se=>se.type==="provider-defined"&&(se.id==="openai.web_search"||se.id==="openai.web_search_preview")))==null?void 0:w.name;P&&I("web_search_call.action.sources"),x("openai.code_interpreter")&&I("code_interpreter_call.outputs");const U=f?.store;U===!1&&_.isReasoningModel&&I("reasoning.encrypted_content");const z={model:this.modelId,input:b,temperature:t,top_p:n,max_output_tokens:e,...(h?.type==="json"||f?.textVerbosity)&&{text:{...h?.type==="json"&&{format:h.schema!=null?{type:"json_schema",strict:S,name:(m=h.name)!=null?m:"response",description:h.description,schema:h.schema}:{type:"json_object"}},...f?.textVerbosity&&{verbosity:f.textVerbosity}}},conversation:f?.conversation,max_tool_calls:f?.maxToolCalls,metadata:f?.metadata,parallel_tool_calls:f?.parallelToolCalls,previous_response_id:f?.previousResponseId,store:U,user:f?.user,instructions:f?.instructions,service_tier:f?.serviceTier,include:C,prompt_cache_key:f?.promptCacheKey,prompt_cache_retention:f?.promptCacheRetention,safety_identifier:f?.safetyIdentifier,top_logprobs:M,truncation:f?.truncation,..._.isReasoningModel&&(f?.reasoningEffort!=null||f?.reasoningSummary!=null)&&{reasoning:{...f?.reasoningEffort!=null&&{effort:f.reasoningEffort},...f?.reasoningSummary!=null&&{summary:f.reasoningSummary}}}};_.isReasoningModel?f?.reasoningEffort==="none"&&_.supportsNonReasoningParameters||(z.temperature!=null&&(z.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(f?.reasoningEffort!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),f?.reasoningSummary!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),f?.serviceTier==="flex"&&!_.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete z.service_tier),f?.serviceTier==="priority"&&!_.supportsPriorityProcessing&&(y.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 z.service_tier);const{tools:F,toolChoice:te,toolWarnings:ie}=await b7({tools:u,toolChoice:g,strictJsonSchema:S});return{webSearchToolName:P,args:{...z,tools:F,tool_choice:te},warnings:[...y,...ie],store:U}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,h,d,p,w,m,y,_,f,b,k,S,C,I,x,M,P,U;const{args:z,warnings:F,webSearchToolName:te}=await this.getArgs(e),ie=this.config.url({path:"/responses",modelId:this.modelId}),se=this.config.provider.replace(".responses",""),{responseHeaders:ee,value:pe,rawValue:V}=await Kt({url:ie,headers:Dt(this.config.headers(),e.headers),body:z,failedResponseHandler:Zt,successfulResponseHandler:sn(y7),abortSignal:e.abortSignal,fetch:this.config.fetch});if(pe.error)throw new Pe({message:pe.error.message,url:ie,requestBodyValues:z,statusCode:400,responseHeaders:ee,responseBody:V,isRetryable:!1});const O=[],Z=[];let j=!1;for(const $ of pe.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const H of $.summary)O.push({type:"reasoning",text:H.text,providerMetadata:{[se]:{itemId:$.id,reasoningEncryptedContent:(t=$.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{O.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[se]:{itemId:$.id}}});break}case"message":{for(const H of $.content){(n=(r=e.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&H.logprobs&&Z.push(H.logprobs),O.push({type:"text",text:H.text,providerMetadata:{[se]:{itemId:$.id}}});for(const G of H.annotations)G.type==="url_citation"?O.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:It(),url:G.url,title:G.title}):G.type==="file_citation"?O.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:It(),mediaType:"text/plain",title:(g=(u=G.quote)!=null?u:G.filename)!=null?g:"Document",filename:(h=G.filename)!=null?h:G.file_id,...G.file_id?{providerMetadata:{[se]:{fileId:G.file_id}}}:{}}):G.type==="container_file_citation"?O.push({type:"source",sourceType:"document",id:(w=(p=(d=this.config).generateId)==null?void 0:p.call(d))!=null?w:It(),mediaType:"text/plain",title:(y=(m=G.filename)!=null?m:G.file_id)!=null?y:"Document",filename:(_=G.filename)!=null?_:G.file_id,providerMetadata:{[se]:{fileId:G.file_id,containerId:G.container_id,...G.index!=null?{index:G.index}:{}}}}):G.type==="file_path"&&O.push({type:"source",sourceType:"document",id:(k=(b=(f=this.config).generateId)==null?void 0:b.call(f))!=null?k:It(),mediaType:"application/octet-stream",title:G.file_id,filename:G.file_id,providerMetadata:{[se]:{fileId:G.file_id,...G.index!=null?{index:G.index}:{}}}})}break}case"function_call":{j=!0,O.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[se]:{itemId:$.id}}});break}case"web_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:te??"web_search",input:JSON.stringify({}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:te??"web_search",result:Vf($.action),providerExecuted:!0});break}case"computer_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(C=(S=$.results)==null?void 0:S.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?C:null},providerExecuted:!0});break}case"code_interpreter_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const E={[se]:{...pe.id!=null?{responseId:pe.id}:{}}};Z.length>0&&(E[se].logprobs=Z),typeof pe.service_tier=="string"&&(E[se].serviceTier=pe.service_tier);const R=pe.usage;return{content:O,finishReason:Df({finishReason:(I=pe.incomplete_details)==null?void 0:I.reason,hasFunctionCall:j}),usage:{inputTokens:R.input_tokens,outputTokens:R.output_tokens,totalTokens:R.input_tokens+R.output_tokens,reasoningTokens:(M=(x=R.output_tokens_details)==null?void 0:x.reasoning_tokens)!=null?M:void 0,cachedInputTokens:(U=(P=R.input_tokens_details)==null?void 0:P.cached_tokens)!=null?U:void 0},request:{body:z},response:{id:pe.id,timestamp:new Date(pe.created_at*1e3),modelId:pe.model,headers:ee,body:V},providerMetadata:E,warnings:F}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,store:o}=await this.getArgs(e),{responseHeaders:s,value:a}=await Kt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Zt,successfulResponseHandler:Wi(_7),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=this,l=this.config.provider.replace(".responses","");let c="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},g=[];let h=null;const d={},p=[];let w=!1;const m={};let y;return{stream:a.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,f){var b,k,S,C,I,x,M,P,U,z,F,te,ie,se,ee,pe,V,O,Z,j,E,R;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){c="error",f.enqueue({type:"error",error:_.error});return}const $=_.value;if(Ff($))$.item.type==="function_call"?(d[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},f.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(d[$.output_index]={toolName:n??"web_search",toolCallId:$.item.id},f.enqueue({type:"tool-input-start",id:$.item.id,toolName:n??"web_search",providerExecuted:!0}),f.enqueue({type:"tool-input-end",id:$.item.id}),f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(d[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},f.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(d[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},f.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),f.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(p.splice(0,p.length),f.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id}}})):Ff($)&&$.item.type==="reasoning"&&(m[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},f.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(C7($)){if($.item.type==="message")f.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id,...p.length>0&&{annotations:p}}}});else if($.item.type==="function_call")d[$.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:$.item.call_id}),f.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")d[$.output_index]=void 0,f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:n??"web_search",result:Vf($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")d[$.output_index]=void 0,f.enqueue({type:"tool-input-end",id:$.item.id}),f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")d[$.output_index]=void 0,f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(S=(k=$.item.results)==null?void 0:k.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?S:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")d[$.output_index]=void 0,f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")d[$.output_index]=void 0,f.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const H=m[$.item.id],G=Object.entries(H.summaryParts).filter(([fe,ae])=>ae==="active"||ae==="can-conclude").map(([fe])=>fe);for(const fe of G)f.enqueue({type:"reasoning-end",id:`${$.item.id}:${fe}`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(C=$.item.encrypted_content)!=null?C:null}}});delete m[$.item.id]}}else if(E7($)){const H=d[$.output_index];H!=null&&f.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:$.delta})}else if(I7($)){const H=d[$.output_index];H!=null&&f.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(x7($)){const H=d[$.output_index];H!=null&&(f.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:'"}'}),f.enqueue({type:"tool-input-end",id:H.toolCallId}),f.enqueue({type:"tool-call",toolCallId:H.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:H.codeInterpreter.containerId}),providerExecuted:!0}))}else if($7($))h=$.response.id,f.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(S7($))f.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(x=(I=e.providerOptions)==null?void 0:I.openai)!=null&&x.logprobs&&$.logprobs&&g.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const H=m[$.item_id];H.summaryParts[$.summary_index]="active";for(const G of Object.keys(H.summaryParts))H.summaryParts[G]==="can-conclude"&&(f.enqueue({type:"reasoning-end",id:`${$.item_id}:${G}`,providerMetadata:{[l]:{itemId:$.item_id}}}),H.summaryParts[G]="concluded");f.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id,reasoningEncryptedContent:(P=(M=m[$.item_id])==null?void 0:M.encryptedContent)!=null?P:null}}})}}else $.type==="response.reasoning_summary_text.delta"?f.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[l]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?o?(f.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id}}}),m[$.item_id].summaryParts[$.summary_index]="concluded"):m[$.item_id].summaryParts[$.summary_index]="can-conclude":T7($)?(c=Df({finishReason:(U=$.response.incomplete_details)==null?void 0:U.reason,hasFunctionCall:w}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(F=(z=$.response.usage.output_tokens_details)==null?void 0:z.reasoning_tokens)!=null?F:void 0,u.cachedInputTokens=(ie=(te=$.response.usage.input_tokens_details)==null?void 0:te.cached_tokens)!=null?ie:void 0,typeof $.response.service_tier=="string"&&(y=$.response.service_tier)):R7($)?(p.push($.annotation),$.annotation.type==="url_citation"?f.enqueue({type:"source",sourceType:"url",id:(pe=(ee=(se=i.config).generateId)==null?void 0:ee.call(se))!=null?pe:It(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&f.enqueue({type:"source",sourceType:"document",id:(Z=(O=(V=i.config).generateId)==null?void 0:O.call(V))!=null?Z:It(),mediaType:"text/plain",title:(E=(j=$.annotation.quote)!=null?j:$.annotation.filename)!=null?E:"Document",filename:(R=$.annotation.filename)!=null?R:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[l]:{fileId:$.annotation.file_id}}}:{}})):P7($)&&f.enqueue({type:"error",error:$})},flush(_){const f={[l]:{responseId:h}};g.length>0&&(f[l].logprobs=g),y!==void 0&&(f[l].serviceTier=y),_.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:f})}})),request:{body:t},response:{headers:s}}}};function S7(e){return e.type==="response.output_text.delta"}function C7(e){return e.type==="response.output_item.done"}function T7(e){return e.type==="response.completed"||e.type==="response.incomplete"}function $7(e){return e.type==="response.created"}function E7(e){return e.type==="response.function_call_arguments.delta"}function I7(e){return e.type==="response.code_interpreter_call_code.delta"}function x7(e){return e.type==="response.code_interpreter_call_code.done"}function Ff(e){return e.type==="response.output_item.added"}function R7(e){return e.type==="response.output_text.annotation.added"}function P7(e){return e.type==="error"}function Vf(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}var O7=rt(()=>Ce(T({instructions:v().nullish(),speed:q().min(.25).max(4).default(1).nullish()}))),M7=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:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await pr({provider:"openai",providerOptions:a,schema:O7}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const g in u){const h=u[g];h!==void 0&&(c[g]=h)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await Kt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:s,failedResponseHandler:Zt,successfulResponseHandler:O5(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},N7=rt(()=>Ce(T({text:v(),language:v().nullish(),duration:q().nullish(),words:A(T({word:v(),start:q(),end:q()})).nullish(),segments:A(T({id:q(),seek:q(),start:q(),end:q(),text:v(),tokens:A(q()),temperature:q(),avg_logprob:q(),compression_ratio:q(),no_speech_prob:q()})).nullish()}))),A7=rt(()=>Ce(T({include:A(v()).optional(),language:v().optional(),prompt:v().optional(),temperature:q().min(0).max(1).default(0).optional(),timestampGranularities:A(_e(["word","segment"])).default(["segment"]).optional()}))),Hf={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"},q7=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:r}){const n=[],o=await pr({provider:"openai",providerOptions:r,schema:A7}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([$8(e)]);s.append("model",this.modelId);const i=y5(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const g of u)s.append(`${c}[]`,String(g));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,a,i,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:g}=await this.getArgs(e),{value:h,responseHeaders:d,rawValue:p}=await R5({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Zt,successfulResponseHandler:sn(N7),abortSignal:e.abortSignal,fetch:this.config.fetch}),w=h.language!=null&&h.language in Hf?Hf[h.language]:void 0;return{text:h.text,segments:(i=(a=(o=h.segments)==null?void 0:o.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?a:(s=h.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:w,durationInSeconds:(l=h.duration)!=null?l:void 0,warnings:g,response:{timestamp:c,modelId:this.modelId,headers:d,body:p}}}},L7="2.0.88";function Bf(e={}){var t,r;const n=(t=I8(_5({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>yf({Authorization:`Bearer ${v5({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${L7}`),a=w=>new N8(w,{provider:`${o}.chat`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),i=w=>new j8(w,{provider:`${o}.completion`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),l=w=>new D8(w,{provider:`${o}.embedding`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),c=w=>new H8(w,{provider:`${o}.image`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),u=w=>new q7(w,{provider:`${o}.transcription`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),g=w=>new M7(w,{provider:`${o}.speech`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),h=w=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(w)},d=w=>new k7(w,{provider:`${o}.responses`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(w){return h(w)};return p.languageModel=h,p.chat=a,p.completion=i,p.responses=d,p.embedding=l,p.textEmbedding=l,p.textEmbeddingModel=l,p.image=c,p.imageModel=c,p.transcription=u,p.transcriptionModel=u,p.speech=g,p.speechModel=g,p.tools=m7,p}Bf();function Wn(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function j7(e){const t=[];for(const{role:r,content:n,...o}of e){const s=Wn({...o});switch(r){case"system":{t.push({role:"system",content:n,...s});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...Wn(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=Wn(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${Gy(a.data)}`},...i}}else throw new Ct({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=Wn(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of n){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=Wn(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return t}function Jf({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Gf(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 tl=T({user:v().optional(),reasoningEffort:v().optional(),textVerbosity:v().optional()}),U7=T({error:T({message:v(),type:v().nullish(),param:et().nullish(),code:ne([v(),q()]).nullish()})}),z7={errorSchema:U7,errorToMessage:e=>e.error.message};function D7({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new Ct({functionality:`tool choice type: ${s}`})}}}var Z7=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:z7;this.chunkSchema=V7(o.errorSchema),this.failedResponseHandler=$r(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:g,tools:h}){var d,p,w,m;const y=[],_=Object.assign((d=await ed({provider:"openai-compatible",providerOptions:i,schema:tl}))!=null?d:{},(p=await ed({provider:this.providerOptionsName,providerOptions:i,schema:tl}))!=null?p:{});o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:f,toolChoice:b,toolWarnings:k}=D7({tools:h,toolChoice:g});return{args:{model:this.modelId,user:_.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(w=c.name)!=null?w:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((m=i?.[this.providerOptionsName])!=null?m:{}).filter(([S])=>!Object.keys(tl.shape).includes(S))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:j7(e),tools:f,tool_choice:b},warnings:[...y,...k]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,h,d,p,w,m,y;const{args:_,warnings:f}=await this.getArgs({...e}),b=JSON.stringify(_),{responseHeaders:k,value:S,rawValue:C}=await Jr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Hr(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Gr(F7),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=S.choices[0],x=[],M=I.message.content;M!=null&&M.length>0&&x.push({type:"text",text:M});const P=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(P!=null&&P.length>0&&x.push({type:"reasoning",text:P}),I.message.tool_calls!=null)for(const F of I.message.tool_calls)x.push({type:"tool-call",toolCallId:(r=F.id)!=null?r:In(),toolName:F.function.name,input:F.function.arguments});const U={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:C}))},z=(s=S.usage)==null?void 0:s.completion_tokens_details;return z?.accepted_prediction_tokens!=null&&(U[this.providerOptionsName].acceptedPredictionTokens=z?.accepted_prediction_tokens),z?.rejected_prediction_tokens!=null&&(U[this.providerOptionsName].rejectedPredictionTokens=z?.rejected_prediction_tokens),{content:x,finishReason:Gf(I.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=S.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(g=(u=S.usage)==null?void 0:u.total_tokens)!=null?g:void 0,reasoningTokens:(p=(d=(h=S.usage)==null?void 0:h.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(y=(m=(w=S.usage)==null?void 0:w.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?y:void 0},providerMetadata:U,request:{body:b},response:{...Jf(S),headers:k,body:C},warnings:f}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await Jr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Hr(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:rd(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let g=!0;const h=this.providerOptionsName;let d=!1,p=!1;return{stream:i.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,m){var y,_,f,b,k,S,C,I,x,M,P,U,z;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",m.enqueue({type:"error",error:w.error});return}const F=w.value;if(s?.processChunk(w.rawValue),"error"in F){c="error",m.enqueue({type:"error",error:F.error.message});return}if(g&&(g=!1,m.enqueue({type:"response-metadata",...Jf(F)})),F.usage!=null){const{prompt_tokens:ee,completion_tokens:pe,total_tokens:V,prompt_tokens_details:O,completion_tokens_details:Z}=F.usage;u.promptTokens=ee??void 0,u.completionTokens=pe??void 0,u.totalTokens=V??void 0,Z?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=Z?.reasoning_tokens),Z?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=Z?.accepted_prediction_tokens),Z?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=Z?.rejected_prediction_tokens),O?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=O?.cached_tokens)}const te=F.choices[0];if(te?.finish_reason!=null&&(c=Gf(te.finish_reason)),te?.delta==null)return;const ie=te.delta,se=(y=ie.reasoning_content)!=null?y:ie.reasoning;if(se&&(d||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:se})),ie.content&&(p||(m.enqueue({type:"text-start",id:"txt-0"}),p=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:ie.content})),ie.tool_calls!=null)for(const ee of ie.tool_calls){const pe=ee.index;if(l[pe]==null){if(ee.id==null)throw new _n({data:ee,message:"Expected 'id' to be a string."});if(((_=ee.function)==null?void 0:_.name)==null)throw new _n({data:ee,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:ee.id,toolName:ee.function.name}),l[pe]={id:ee.id,type:"function",function:{name:ee.function.name,arguments:(f=ee.function.arguments)!=null?f:""},hasFinished:!1};const O=l[pe];((b=O.function)==null?void 0:b.name)!=null&&((k=O.function)==null?void 0:k.arguments)!=null&&(O.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:O.id,delta:O.function.arguments}),Xu(O.function.arguments)&&(m.enqueue({type:"tool-input-end",id:O.id}),m.enqueue({type:"tool-call",toolCallId:(S=O.id)!=null?S:In(),toolName:O.function.name,input:O.function.arguments}),O.hasFinished=!0));continue}const V=l[pe];V.hasFinished||(((C=ee.function)==null?void 0:C.arguments)!=null&&(V.function.arguments+=(x=(I=ee.function)==null?void 0:I.arguments)!=null?x:""),m.enqueue({type:"tool-input-delta",id:V.id,delta:(M=ee.function.arguments)!=null?M:""}),((P=V.function)==null?void 0:P.name)!=null&&((U=V.function)==null?void 0:U.arguments)!=null&&Xu(V.function.arguments)&&(m.enqueue({type:"tool-input-end",id:V.id}),m.enqueue({type:"tool-call",toolCallId:(z=V.id)!=null?z:In(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(w){var m,y,_,f,b,k;d&&w.enqueue({type:"reasoning-end",id:"reasoning-0"}),p&&w.enqueue({type:"text-end",id:"txt-0"});for(const C of l.filter(I=>!I.hasFinished))w.enqueue({type:"tool-input-end",id:C.id}),w.enqueue({type:"tool-call",toolCallId:(m=C.id)!=null?m:In(),toolName:C.function.name,input:C.function.arguments});const S={[h]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(S[h].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(S[h].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),w.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(y=u.promptTokens)!=null?y:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(f=u.totalTokens)!=null?f:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:S})}})),request:{body:o},response:{headers:a}}}},Wf=T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish(),F7=T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({message:T({role:L("assistant").nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:A(T({id:v().nullish(),function:T({name:v(),arguments:v()})})).nullish()}),finish_reason:v().nullish()})),usage:Wf}),V7=e=>ne([T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({delta:T({role:_e(["assistant"]).nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:A(T({index:q(),id:v().nullish(),function:T({name:v().nullish(),arguments:v().nullish()})})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:Wf}),e]);T({echo:ce().optional(),logitBias:ve(v(),q()).optional(),suffix:v().optional(),user:v().optional()});var H7=T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()});T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({text:v(),finish_reason:v()})),usage:H7.nullish()}),T({dimensions:q().optional(),user:v().optional()}),T({data:A(T({embedding:A(q())})),usage:T({prompt_tokens:q()}).nullish(),providerMetadata:ve(v(),ve(v(),et())).optional()}),T({data:A(T({b64_json:v()}))});var Kf=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},B7={extractMetadata:async({parsedBody:e})=>{const t=await Tt({value:e,schema:J7});return!t.success||t.value.usage==null?void 0:Kf(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Tt({value:t,schema:G7});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>Kf(e)}}},Yf=T({prompt_cache_hit_tokens:q().nullish(),prompt_cache_miss_tokens:q().nullish()}),J7=T({usage:Yf.nullish()}),G7=T({choices:A(T({finish_reason:v().nullish()})).nullish(),usage:Yf.nullish()}),W7="1.0.30";function Qf(e={}){var t;const r=cd((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>cr({Authorization:`Bearer ${F_({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${W7}`);class o extends Z7{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const h=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:h}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:B7}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new Oc({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Oc({modelId:i,modelType:"imageModel"})},a}Qf();const K7=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},Y7=(e,t,r,n)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===r){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class Xf{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Y7("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Or.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const n=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!n,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const o=n.tabIds[n.tabIds.length-1];K7("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:o,mcpMessage:t},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}function es(e){return!!e._zod}function fr(e,t){return es(e)?Qc(e,t):e.safeParse(t)}function eh(e){var t,r;if(!e)return;let n;if(es(e)?n=(r=(t=e._zod)===null||t===void 0?void 0:t.def)===null||r===void 0?void 0:r.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function Q7(e){var t;if(es(e)){const a=(t=e._zod)===null||t===void 0?void 0:t.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const o=e.value;if(o!==void 0)return o}function Ar(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function th(e){const t=eh(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Q7(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function rh(e,t){const r=fr(e,t);if(!r.success)throw r.error;return r.data}const X7=6e4;class ek{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(di,r=>{this._oncancel(r)}),this.setNotificationHandler(fi,r=>{this._onprogress(r)}),this.setRequestHandler(pi,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(hi,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new de(ge.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(gi,async(r,n)=>{const o=async()=>{var s;const a=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(l.type==="response"||l.type==="error"){const c=l.message,u=c.id,g=this._requestResolvers.get(u);if(g)if(this._requestResolvers.delete(u),l.type==="response")g(c);else{const h=c,d=new de(h.error.code,h.error.message,h.error.data);g(d)}else{const h=l.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${u}`))}continue}await((s=this._transport)===null||s===void 0?void 0:s.send(l.message,{relatedRequestId:n.requestId}))}}const i=await this._taskStore.getTask(a,n.sessionId);if(!i)throw new de(ge.InvalidParams,`Task not found: ${a}`);if(!Ar(i.status))return await this._waitForTaskUpdate(a,n.signal),await o();if(Ar(i.status)){const l=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...l,_meta:{...l._meta,[Wt]:{taskId:a}}}}return await o()};return await o()}),this.setRequestHandler(vi,async(r,n)=>{var o;try{const{tasks:s,nextCursor:a}=await this._taskStore.listTasks((o=r.params)===null||o===void 0?void 0:o.cursor,n.sessionId);return{tasks:s,nextCursor:a,_meta:{}}}catch(s){throw new de(ge.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(E4,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new de(ge.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ar(o.status))throw new de(ge.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new de(ge.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof de?o:new de(ge.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){const r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),de.fromError(ge.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var r,n,o;this._transport=t;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};const a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=l=>{a?.(l),this._onerror(l)};const i=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(l,c)=>{i?.(l,c),Dn(l)||d4(l)?this._onresponse(l):ui(l)?this._onrequest(l,c):u4(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var t;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const n=de.fromError(ge.ConnectionClosed,"Connection closed");this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);for(const o of r.values())o(n)}_onerror(t){var r;(r=this.onerror)===null||r===void 0||r.call(this,t)}_onnotification(t){var r;const n=(r=this._notificationHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){var n,o,s,a,i,l;const c=(n=this._requestHandlers.get(t.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,u=this._transport,g=(a=(s=(o=t.params)===null||o===void 0?void 0:o._meta)===null||s===void 0?void 0:s[Wt])===null||a===void 0?void 0:a.taskId;if(c===void 0){const m={jsonrpc:"2.0",id:t.id,error:{code:ge.MethodNotFound,message:"Method not found"}};g&&this._taskMessageQueue?this._enqueueTaskMessage(g,{type:"error",message:m,timestamp:Date.now()},u?.sessionId).catch(y=>this._onerror(new Error(`Failed to enqueue error response: ${y}`))):u?.send(m).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)));return}const h=new AbortController;this._requestHandlerAbortControllers.set(t.id,h);const d=(i=t.params)===null||i===void 0?void 0:i.task,p=this._taskStore?this.requestTaskStore(t,u?.sessionId):void 0,w={signal:h.signal,sessionId:u?.sessionId,_meta:(l=t.params)===null||l===void 0?void 0:l._meta,sendNotification:async m=>{const y={relatedRequestId:t.id};g&&(y.relatedTask={taskId:g}),await this.notification(m,y)},sendRequest:async(m,y,_)=>{var f,b;const k={..._,relatedRequestId:t.id};g&&!k.relatedTask&&(k.relatedTask={taskId:g});const S=(b=(f=k.relatedTask)===null||f===void 0?void 0:f.taskId)!==null&&b!==void 0?b:g;return S&&p&&await p.updateTaskStatus(S,"input_required"),await this.request(m,y,k)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:g,taskStore:p,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{d&&this.assertTaskHandlerCapability(t.method)}).then(()=>c(t,w)).then(async m=>{if(h.signal.aborted)return;const y={result:m,jsonrpc:"2.0",id:t.id};g&&this._taskMessageQueue?await this._enqueueTaskMessage(g,{type:"response",message:y,timestamp:Date.now()},u?.sessionId):await u?.send(y)},async m=>{var y;if(h.signal.aborted)return;const _={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(m.code)?m.code:ge.InternalError,message:(y=m.message)!==null&&y!==void 0?y:"Internal error",...m.data!==void 0&&{data:m.data}}};g&&this._taskMessageQueue?await this._enqueueTaskMessage(g,{type:"error",message:_,timestamp:Date.now()},u?.sessionId):await u?.send(_)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Dn(t))n(t);else{const a=new de(t.error.code,t.error.message,t.error.data);n(a)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Dn(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,r))}}if(s||this._progressHandlers.delete(r),Dn(t))o(t);else{const a=de.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}async*requestStream(t,r,n){var o,s,a,i;const{task:l}=n??{};if(!l){try{yield{type:"result",result:await this.request(t,r,n)}}catch(u){yield{type:"error",error:u instanceof de?u:new de(ge.InternalError,String(u))}}return}let c;try{const u=await this.request(t,Bn,n);if(u.task)c=u.task.taskId,yield{type:"taskCreated",task:u.task};else throw new de(ge.InternalError,"Task creation did not return a task");for(;;){const g=await this.getTask({taskId:c},n);if(yield{type:"taskStatus",task:g},Ar(g.status)){g.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)}:g.status==="failed"?yield{type:"error",error:new de(ge.InternalError,`Task ${c} failed`)}:g.status==="cancelled"&&(yield{type:"error",error:new de(ge.InternalError,`Task ${c} was cancelled`)});return}if(g.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)};return}const h=(a=(o=g.pollInterval)!==null&&o!==void 0?o:(s=this._options)===null||s===void 0?void 0:s.defaultTaskPollInterval)!==null&&a!==void 0?a:1e3;await new Promise(d=>setTimeout(d,h)),(i=n?.signal)===null||i===void 0||i.throwIfAborted()}}catch(u){yield{type:"error",error:u instanceof de?u:new de(ge.InternalError,String(u))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{var g,h,d,p,w,m,y;const _=x=>{u(x)};if(!this._transport){_(new Error("Not connected"));return}if(((g=this._options)===null||g===void 0?void 0:g.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(x){_(x);return}(h=n?.signal)===null||h===void 0||h.throwIfAborted();const f=this._requestMessageId++,b={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),b.params={...t.params,_meta:{...((d=t.params)===null||d===void 0?void 0:d._meta)||{},progressToken:f}}),i&&(b.params={...b.params,task:i}),l&&(b.params={...b.params,_meta:{...((p=b.params)===null||p===void 0?void 0:p._meta)||{},[Wt]:l}});const k=x=>{var M;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(M=this._transport)===null||M===void 0||M.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(U=>this._onerror(new Error(`Failed to send cancellation: ${U}`)));const P=x instanceof de?x:new de(ge.RequestTimeout,String(x));u(P)};this._responseHandlers.set(f,x=>{var M;if(!(!((M=n?.signal)===null||M===void 0)&&M.aborted)){if(x instanceof Error)return u(x);try{const P=fr(r,x.result);P.success?c(P.data):u(P.error)}catch(P){u(P)}}}),(w=n?.signal)===null||w===void 0||w.addEventListener("abort",()=>{var x;k((x=n?.signal)===null||x===void 0?void 0:x.reason)});const S=(m=n?.timeout)!==null&&m!==void 0?m:X7,C=()=>k(de.fromError(ge.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(f,S,n?.maxTotalTimeout,C,(y=n?.resetTimeoutOnProgress)!==null&&y!==void 0?y:!1);const I=l?.taskId;if(I){const x=M=>{const P=this._responseHandlers.get(f);P?P(M):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,x),this._enqueueTaskMessage(I,{type:"request",message:b,timestamp:Date.now()}).catch(M=>{this._cleanupTimeout(f),u(M)})}else this._transport.send(b,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(f),u(x)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},mi,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},_i,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},I4,r)}async notification(t,r){var n,o,s,a,i;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const l=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(l){const h={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...((o=t.params)===null||o===void 0?void 0:o._meta)||{},[Wt]:r.relatedTask}}};await this._enqueueTaskMessage(l,{type:"notification",message:h,timestamp:Date.now()});return}if(((a=(s=this._options)===null||s===void 0?void 0:s.debouncedNotificationMethods)!==null&&a!==void 0?a:[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var h,d;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let p={...t,jsonrpc:"2.0"};r?.relatedTask&&(p={...p,params:{...p.params,_meta:{...((h=p.params)===null||h===void 0?void 0:h._meta)||{},[Wt]:r.relatedTask}}}),(d=this._transport)===null||d===void 0||d.send(p,r).catch(w=>this._onerror(w))});return}let g={...t,jsonrpc:"2.0"};r?.relatedTask&&(g={...g,params:{...g.params,_meta:{...((i=g.params)===null||i===void 0?void 0:i._meta)||{},[Wt]:r.relatedTask}}}),await this._transport.send(g,r)}setRequestHandler(t,r){const n=th(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=rh(t,o);return Promise.resolve(r(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const n=th(t);this._notificationHandlers.set(n,o=>{const s=rh(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){var o;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=(o=this._options)===null||o===void 0?void 0:o.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,s)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&ui(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new de(ge.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){var n,o,s;let a=(o=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&o!==void 0?o:1e3;try{const i=await((s=this._taskStore)===null||s===void 0?void 0:s.getTask(t));i?.pollInterval&&(a=i.pollInterval)}catch{}return new Promise((i,l)=>{if(r.aborted){l(new de(ge.InvalidRequest,"Request cancelled"));return}const c=setTimeout(i,a);r.addEventListener("abort",()=>{clearTimeout(c),l(new de(ge.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new de(ge.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=Fo.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Ar(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,a)=>{const i=await n.getTask(o,r);if(!i)throw new de(ge.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Ar(i.status))throw new de(ge.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=Fo.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Ar(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function nh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tk(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const a=r[o];nh(a)&&nh(s)?r[o]={...a,...s}:r[o]=s}return r}var ts={exports:{}},rl={},Yt={},qr={},nl={},ol={},sl={},oh;function rs(){return oh||(oh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((f,b)=>`${f}${b}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((f,b)=>(b instanceof r&&(f[b.str]=(f[b.str]||0)+1),f),{})}}e._Code=n,e.nil=new n("");function o(y,..._){const f=[y[0]];let b=0;for(;b<_.length;)i(f,_[b]),f.push(y[++b]);return new n(f)}e._=o;const s=new n("+");function a(y,..._){const f=[d(y[0])];let b=0;for(;b<_.length;)f.push(s),i(f,_[b]),f.push(s,d(y[++b]));return l(f),new n(f)}e.str=a;function i(y,_){_ instanceof n?y.push(..._._items):_ instanceof r?y.push(_):y.push(g(_))}e.addCodeArg=i;function l(y){let _=1;for(;_<y.length-1;){if(y[_]===s){const f=c(y[_-1],y[_+1]);if(f!==void 0){y.splice(_-1,3,f);continue}y[_++]="+"}_++}}function c(y,_){if(_==='""')return y;if(y==='""')return _;if(typeof y=="string")return _ instanceof r||y[y.length-1]!=='"'?void 0:typeof _!="string"?`${y.slice(0,-1)}${_}"`:_[0]==='"'?y.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(y instanceof r))return`"${y}${_.slice(1)}`}function u(y,_){return _.emptyStr()?y:y.emptyStr()?_:a`${y}${_}`}e.strConcat=u;function g(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:d(Array.isArray(y)?y.join(","):y)}function h(y){return new n(d(y))}e.stringify=h;function d(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=d;function p(y){return typeof y=="string"&&e.IDENTIFIER.test(y)?new n(`.${y}`):o`[${y}]`}e.getProperty=p;function w(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new n(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=w;function m(y){return new n(y.toString())}e.regexpCode=m})(sl)),sl}var al={},sh;function ah(){return sh||(sh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=rs();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,g;if(!((g=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||g===void 0)&&g.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:g}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${g}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var g;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const h=this.toName(c),{prefix:d}=h,p=(g=u.key)!==null&&g!==void 0?g:u.ref;let w=this._values[d];if(w){const _=w.get(p);if(_)return _}else w=this._values[d]=new Map;w.set(p,h);const m=this._scope[d]||(this._scope[d]=[]),y=m.length;return m[y]=u.ref,h.setValue(u,{property:d,itemIndex:y}),h}getValue(c,u){const g=this._values[c];if(g)return g.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,g=>{if(g.scopePath===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return(0,t._)`${c}${g.scopePath}`})}scopeCode(c=this._values,u,g){return this._reduceValues(c,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},u,g)}_reduceValues(c,u,g={},h){let d=t.nil;for(const p in c){const w=c[p];if(!w)continue;const m=g[p]=g[p]||new Map;w.forEach(y=>{if(m.has(y))return;m.set(y,n.Started);let _=u(y);if(_){const f=this.opts.es5?e.varKinds.var:e.varKinds.const;d=(0,t._)`${d}${f} ${y} = ${_};${this.opts._n}`}else if(_=h?.(y))d=(0,t._)`${d}${_}${this.opts._n}`;else throw new r(y);m.set(y,n.Completed)})}return d}}e.ValueScope=i})(al)),al}var ih;function ye(){return ih||(ih=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=rs(),r=ah();var n=rs();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=ah();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(E,R){return this}}class a extends s{constructor(E,R,$){super(),this.varKind=E,this.name=R,this.rhs=$}render({es5:E,_n:R}){const $=E?r.varKinds.var:this.varKind,H=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${H};`+R}optimizeNames(E,R){if(E[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,E,R)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(E,R,$){super(),this.lhs=E,this.rhs=R,this.sideEffects=$}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,R){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,E,R),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return z(E,this.rhs)}}class l extends i{constructor(E,R,$,H){super(E,$,H),this.op=R}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class g extends s{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class h extends s{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,R){return this.code=F(this.code,E,R),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class d extends s{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((R,$)=>R+$.render(E),"")}optimizeNodes(){const{nodes:E}=this;let R=E.length;for(;R--;){const $=E[R].optimizeNodes();Array.isArray($)?E.splice(R,1,...$):$?E[R]=$:E.splice(R,1)}return E.length>0?this:void 0}optimizeNames(E,R){const{nodes:$}=this;let H=$.length;for(;H--;){const G=$[H];G.optimizeNames(E,R)||(te(E,G.names),$.splice(H,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((E,R)=>U(E,R.names),{})}}class p extends d{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class w extends d{}class m extends p{}m.kind="else";class y extends p{constructor(E,R){super(R),this.condition=E}render(E){let R=`if(${this.condition})`+super.render(E);return this.else&&(R+="else "+this.else.render(E)),R}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let R=this.else;if(R){const $=R.optimizeNodes();R=this.else=Array.isArray($)?new m($):$}if(R)return E===!1?R instanceof y?R:R.nodes:this.nodes.length?this:new y(ie(E),R instanceof y?[R]:R.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,R){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(E,R),!!(super.optimizeNames(E,R)||this.else))return this.condition=F(this.condition,E,R),this}get names(){const E=super.names;return z(E,this.condition),this.else&&U(E,this.else.names),E}}y.kind="if";class _ extends p{}_.kind="for";class f extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iteration=F(this.iteration,E,R),this}get names(){return U(super.names,this.iteration.names)}}class b extends _{constructor(E,R,$,H){super(),this.varKind=E,this.name=R,this.from=$,this.to=H}render(E){const R=E.es5?r.varKinds.var:this.varKind,{name:$,from:H,to:G}=this;return`for(${R} ${$}=${H}; ${$}<${G}; ${$}++)`+super.render(E)}get names(){const E=z(super.names,this.from);return z(E,this.to)}}class k extends _{constructor(E,R,$,H){super(),this.loop=E,this.varKind=R,this.name=$,this.iterable=H}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iterable=F(this.iterable,E,R),this}get names(){return U(super.names,this.iterable.names)}}class S extends p{constructor(E,R,$){super(),this.name=E,this.args=R,this.async=$}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}S.kind="func";class C extends d{render(E){return"return "+super.render(E)}}C.kind="return";class I extends p{render(E){let R="try"+super.render(E);return this.catch&&(R+=this.catch.render(E)),this.finally&&(R+=this.finally.render(E)),R}optimizeNodes(){var E,R;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(E,R){var $,H;return super.optimizeNames(E,R),($=this.catch)===null||$===void 0||$.optimizeNames(E,R),(H=this.finally)===null||H===void 0||H.optimizeNames(E,R),this}get names(){const E=super.names;return this.catch&&U(E,this.catch.names),this.finally&&U(E,this.finally.names),E}}class x extends p{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}x.kind="catch";class M extends p{render(E){return"finally"+super.render(E)}}M.kind="finally";class P{constructor(E,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
72
+ `:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,R){const $=this._extScope.value(E,R);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(E,R){return this._extScope.getValue(E,R)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,R,$,H){const G=this._scope.toName(R);return $!==void 0&&H&&(this._constants[G.str]=$),this._leafNode(new a(E,G,$)),G}const(E,R,$){return this._def(r.varKinds.const,E,R,$)}let(E,R,$){return this._def(r.varKinds.let,E,R,$)}var(E,R,$){return this._def(r.varKinds.var,E,R,$)}assign(E,R,$){return this._leafNode(new i(E,R,$))}add(E,R){return this._leafNode(new l(E,e.operators.ADD,R))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new h(E)),this}object(...E){const R=["{"];for(const[$,H]of E)R.length>1&&R.push(","),R.push($),($!==H||this.opts.es5)&&(R.push(":"),(0,t.addCodeArg)(R,H));return R.push("}"),new t._Code(R)}if(E,R,$){if(this._blockNode(new y(E)),R&&$)this.code(R).else().code($).endIf();else if(R)this.code(R).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new y(E))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(y,m)}_for(E,R){return this._blockNode(E),R&&this.code(R).endFor(),this}for(E,R){return this._for(new f(E),R)}forRange(E,R,$,H,G=this.opts.es5?r.varKinds.var:r.varKinds.let){const fe=this._scope.toName(E);return this._for(new b(G,fe,R,$),()=>H(fe))}forOf(E,R,$,H=r.varKinds.const){const G=this._scope.toName(E);if(this.opts.es5){const fe=R instanceof t.Name?R:this.var("_arr",R);return this.forRange("_i",0,(0,t._)`${fe}.length`,ae=>{this.var(G,(0,t._)`${fe}[${ae}]`),$(G)})}return this._for(new k("of",H,G,R),()=>$(G))}forIn(E,R,$,H=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${R})`,$);const G=this._scope.toName(E);return this._for(new k("in",H,G,R),()=>$(G))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const R=new C;if(this._blockNode(R),this.code(E),R.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(E,R,$){if(!R&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const H=new I;if(this._blockNode(H),this.code(E),R){const G=this.name("e");this._currNode=H.catch=new x(G),R(G)}return $&&(this._currNode=H.finally=new M,this.code($)),this._endBlockNode(x,M)}throw(E){return this._leafNode(new g(E))}block(E,R){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(R),this}endBlock(E){const R=this._blockStarts.pop();if(R===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-R;if($<0||E!==void 0&&$!==E)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${E} expected`);return this._nodes.length=R,this}func(E,R=t.nil,$,H){return this._blockNode(new S(E,R,$)),H&&this.code(H).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,R){const $=this._currNode;if($ instanceof E||R&&$ instanceof R)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${R?`${E.kind}/${R.kind}`:E.kind}"`)}_elseNode(E){const R=this._currNode;if(!(R instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=R.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const R=this._nodes;R[R.length-1]=E}}e.CodeGen=P;function U(j,E){for(const R in E)j[R]=(j[R]||0)+(E[R]||0);return j}function z(j,E){return E instanceof t._CodeOrName?U(j,E.names):j}function F(j,E,R){if(j instanceof t.Name)return $(j);if(!H(j))return j;return new t._Code(j._items.reduce((G,fe)=>(fe instanceof t.Name&&(fe=$(fe)),fe instanceof t._Code?G.push(...fe._items):G.push(fe),G),[]));function $(G){const fe=R[G.str];return fe===void 0||E[G.str]!==1?G:(delete E[G.str],fe)}function H(G){return G instanceof t._Code&&G._items.some(fe=>fe instanceof t.Name&&E[fe.str]===1&&R[fe.str]!==void 0)}}function te(j,E){for(const R in E)j[R]=(j[R]||0)-(E[R]||0)}function ie(j){return typeof j=="boolean"||typeof j=="number"||j===null?!j:(0,t._)`!${Z(j)}`}e.not=ie;const se=O(e.operators.AND);function ee(...j){return j.reduce(se)}e.and=ee;const pe=O(e.operators.OR);function V(...j){return j.reduce(pe)}e.or=V;function O(j){return(E,R)=>E===t.nil?R:R===t.nil?E:(0,t._)`${Z(E)} ${j} ${Z(R)}`}function Z(j){return j instanceof t.Name?j:(0,t._)`(${j})`}})(ol)),ol}var we={},lh;function Se(){if(lh)return we;lh=1,Object.defineProperty(we,"__esModule",{value:!0}),we.checkStrictMode=we.getErrorPath=we.Type=we.useFunc=we.setEvaluated=we.evaluatedPropsToName=we.mergeEvaluated=we.eachItem=we.unescapeJsonPointer=we.escapeJsonPointer=we.escapeFragment=we.unescapeFragment=we.schemaRefOrVal=we.schemaHasRulesButRef=we.schemaHasRules=we.checkUnknownRules=we.alwaysValidSchema=we.toHash=void 0;const e=ye(),t=rs();function r(k){const S={};for(const C of k)S[C]=!0;return S}we.toHash=r;function n(k,S){return typeof S=="boolean"?S:Object.keys(S).length===0?!0:(o(k,S),!s(S,k.self.RULES.all))}we.alwaysValidSchema=n;function o(k,S=k.schema){const{opts:C,self:I}=k;if(!C.strictSchema||typeof S=="boolean")return;const x=I.RULES.keywords;for(const M in S)x[M]||b(k,`unknown keyword: "${M}"`)}we.checkUnknownRules=o;function s(k,S){if(typeof k=="boolean")return!k;for(const C in k)if(S[C])return!0;return!1}we.schemaHasRules=s;function a(k,S){if(typeof k=="boolean")return!k;for(const C in k)if(C!=="$ref"&&S.all[C])return!0;return!1}we.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:S},C,I,x){if(!x){if(typeof C=="number"||typeof C=="boolean")return C;if(typeof C=="string")return(0,e._)`${C}`}return(0,e._)`${k}${S}${(0,e.getProperty)(I)}`}we.schemaRefOrVal=i;function l(k){return g(decodeURIComponent(k))}we.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}we.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}we.escapeJsonPointer=u;function g(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}we.unescapeJsonPointer=g;function h(k,S){if(Array.isArray(k))for(const C of k)S(C);else S(k)}we.eachItem=h;function d({mergeNames:k,mergeToName:S,mergeValues:C,resultToName:I}){return(x,M,P,U)=>{const z=P===void 0?M:P instanceof e.Name?(M instanceof e.Name?k(x,M,P):S(x,M,P),P):M instanceof e.Name?(S(x,P,M),M):C(M,P);return U===e.Name&&!(z instanceof e.Name)?I(x,z):z}}we.mergeEvaluated={props:d({mergeNames:(k,S,C)=>k.if((0,e._)`${C} !== true && ${S} !== undefined`,()=>{k.if((0,e._)`${S} === true`,()=>k.assign(C,!0),()=>k.assign(C,(0,e._)`${C} || {}`).code((0,e._)`Object.assign(${C}, ${S})`))}),mergeToName:(k,S,C)=>k.if((0,e._)`${C} !== true`,()=>{S===!0?k.assign(C,!0):(k.assign(C,(0,e._)`${C} || {}`),w(k,C,S))}),mergeValues:(k,S)=>k===!0?!0:{...k,...S},resultToName:p}),items:d({mergeNames:(k,S,C)=>k.if((0,e._)`${C} !== true && ${S} !== undefined`,()=>k.assign(C,(0,e._)`${S} === true ? true : ${C} > ${S} ? ${C} : ${S}`)),mergeToName:(k,S,C)=>k.if((0,e._)`${C} !== true`,()=>k.assign(C,S===!0?!0:(0,e._)`${C} > ${S} ? ${C} : ${S}`)),mergeValues:(k,S)=>k===!0?!0:Math.max(k,S),resultToName:(k,S)=>k.var("items",S)})};function p(k,S){if(S===!0)return k.var("props",!0);const C=k.var("props",(0,e._)`{}`);return S!==void 0&&w(k,C,S),C}we.evaluatedPropsToName=p;function w(k,S,C){Object.keys(C).forEach(I=>k.assign((0,e._)`${S}${(0,e.getProperty)(I)}`,!0))}we.setEvaluated=w;const m={};function y(k,S){return k.scopeValue("func",{ref:S,code:m[S.code]||(m[S.code]=new t._Code(S.code))})}we.useFunc=y;var _;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(_||(we.Type=_={}));function f(k,S,C){if(k instanceof e.Name){const I=S===_.Num;return C?I?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:I?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return C?(0,e.getProperty)(k).toString():"/"+u(k)}we.getErrorPath=f;function b(k,S,C=k.opts.strictSchema){if(C){if(S=`strict mode: ${S}`,C===!0)throw new Error(S);k.self.logger.warn(S)}}return we.checkStrictMode=b,we}var ns={},ch;function hr(){if(ch)return ns;ch=1,Object.defineProperty(ns,"__esModule",{value:!0});const e=ye(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return ns.default=t,ns}var uh;function os(){return uh||(uh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=ye(),r=Se(),n=hr();e.keywordError={message:({keyword:m})=>(0,t.str)`must pass "${m}" keyword validation`},e.keyword$DataError={message:({keyword:m,schemaType:y})=>y?(0,t.str)`"${m}" keyword must be ${y} ($data)`:(0,t.str)`"${m}" keyword is invalid ($data)`};function o(m,y=e.keywordError,_,f){const{it:b}=m,{gen:k,compositeRule:S,allErrors:C}=b,I=g(m,y,_);f??(S||C)?l(k,I):c(b,(0,t._)`[${I}]`)}e.reportError=o;function s(m,y=e.keywordError,_){const{it:f}=m,{gen:b,compositeRule:k,allErrors:S}=f,C=g(m,y,_);l(b,C),k||S||c(f,n.default.vErrors)}e.reportExtraError=s;function a(m,y){m.assign(n.default.errors,y),m.if((0,t._)`${n.default.vErrors} !== null`,()=>m.if(y,()=>m.assign((0,t._)`${n.default.vErrors}.length`,y),()=>m.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:m,keyword:y,schemaValue:_,data:f,errsCount:b,it:k}){if(b===void 0)throw new Error("ajv implementation error");const S=m.name("err");m.forRange("i",b,n.default.errors,C=>{m.const(S,(0,t._)`${n.default.vErrors}[${C}]`),m.if((0,t._)`${S}.instancePath === undefined`,()=>m.assign((0,t._)`${S}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),m.assign((0,t._)`${S}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${y}`),k.opts.verbose&&(m.assign((0,t._)`${S}.schema`,_),m.assign((0,t._)`${S}.data`,f))})}e.extendErrors=i;function l(m,y){const _=m.const("err",y);m.if((0,t._)`${n.default.vErrors} === null`,()=>m.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),m.code((0,t._)`${n.default.errors}++`)}function c(m,y){const{gen:_,validateName:f,schemaEnv:b}=m;b.$async?_.throw((0,t._)`new ${m.ValidationError}(${y})`):(_.assign((0,t._)`${f}.errors`,y),_.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function g(m,y,_){const{createErrors:f}=m.it;return f===!1?(0,t._)`{}`:h(m,y,_)}function h(m,y,_={}){const{gen:f,it:b}=m,k=[d(b,_),p(m,_)];return w(m,y,k),f.object(...k)}function d({errorPath:m},{instancePath:y}){const _=y?(0,t.str)`${m}${(0,r.getErrorPath)(y,r.Type.Str)}`:m;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function p({keyword:m,it:{errSchemaPath:y}},{schemaPath:_,parentSchema:f}){let b=f?y:(0,t.str)`${y}/${m}`;return _&&(b=(0,t.str)`${b}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,b]}function w(m,{params:y,message:_},f){const{keyword:b,data:k,schemaValue:S,it:C}=m,{opts:I,propertyName:x,topSchemaRef:M,schemaPath:P}=C;f.push([u.keyword,b],[u.params,typeof y=="function"?y(m):y||(0,t._)`{}`]),I.messages&&f.push([u.message,typeof _=="function"?_(m):_]),I.verbose&&f.push([u.schema,S],[u.parentSchema,(0,t._)`${M}${P}`],[n.default.data,k]),x&&f.push([u.propertyName,x])}})(nl)),nl}var dh;function rk(){if(dh)return qr;dh=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.boolOrEmptySchema=qr.topBoolOrEmptySchema=void 0;const e=os(),t=ye(),r=hr(),n={message:"boolean schema is false"};function o(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}qr.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}qr.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,g={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(g,n,void 0,l)}return qr}var Ge={},Lr={},ph;function fh(){if(ph)return Lr;ph=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.getRules=Lr.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}Lr.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return Lr.getRules=n,Lr}var Qt={},hh;function mh(){if(hh)return Qt;hh=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.shouldUseRule=Qt.shouldUseGroup=Qt.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}Qt.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Qt.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(a=>n[a]!==void 0))}return Qt.shouldUseRule=r,Qt}var gh;function ss(){if(gh)return Ge;gh=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.reportTypeError=Ge.checkDataTypes=Ge.checkDataType=Ge.coerceAndCheckDataType=Ge.getJSONTypes=Ge.getSchemaTypes=Ge.DataType=void 0;const e=fh(),t=mh(),r=os(),n=ye(),o=Se();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||(Ge.DataType=s={}));function a(_){const f=i(_.type);if(f.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!f.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&f.push("null")}return f}Ge.getSchemaTypes=a;function i(_){const f=Array.isArray(_)?_:_?[_]:[];if(f.every(e.isJSONType))return f;throw new Error("type must be JSONType or JSONType[]: "+f.join(","))}Ge.getJSONTypes=i;function l(_,f){const{gen:b,data:k,opts:S}=_,C=u(f,S.coerceTypes),I=f.length>0&&!(C.length===0&&f.length===1&&(0,t.schemaHasRulesForType)(_,f[0]));if(I){const x=p(f,k,S.strictNumbers,s.Wrong);b.if(x,()=>{C.length?g(_,f,C):m(_)})}return I}Ge.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,f){return f?_.filter(b=>c.has(b)||f==="array"&&b==="array"):[]}function g(_,f,b){const{gen:k,data:S,opts:C}=_,I=k.let("dataType",(0,n._)`typeof ${S}`),x=k.let("coerced",(0,n._)`undefined`);C.coerceTypes==="array"&&k.if((0,n._)`${I} == 'object' && Array.isArray(${S}) && ${S}.length == 1`,()=>k.assign(S,(0,n._)`${S}[0]`).assign(I,(0,n._)`typeof ${S}`).if(p(f,S,C.strictNumbers),()=>k.assign(x,S))),k.if((0,n._)`${x} !== undefined`);for(const P of b)(c.has(P)||P==="array"&&C.coerceTypes==="array")&&M(P);k.else(),m(_),k.endIf(),k.if((0,n._)`${x} !== undefined`,()=>{k.assign(S,x),h(_,x)});function M(P){switch(P){case"string":k.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(x,(0,n._)`"" + ${S}`).elseIf((0,n._)`${S} === null`).assign(x,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${I} == "boolean" || ${S} === null
73
+ || (${I} == "string" && ${S} && ${S} == +${S})`).assign(x,(0,n._)`+${S}`);return;case"integer":k.elseIf((0,n._)`${I} === "boolean" || ${S} === null
74
+ || (${I} === "string" && ${S} && ${S} == +${S} && !(${S} % 1))`).assign(x,(0,n._)`+${S}`);return;case"boolean":k.elseIf((0,n._)`${S} === "false" || ${S} === 0 || ${S} === null`).assign(x,!1).elseIf((0,n._)`${S} === "true" || ${S} === 1`).assign(x,!0);return;case"null":k.elseIf((0,n._)`${S} === "" || ${S} === 0 || ${S} === false`),k.assign(x,null);return;case"array":k.elseIf((0,n._)`${I} === "string" || ${I} === "number"
75
+ || ${I} === "boolean" || ${S} === null`).assign(x,(0,n._)`[${S}]`)}}}function h({gen:_,parentData:f,parentDataProperty:b},k){_.if((0,n._)`${f} !== undefined`,()=>_.assign((0,n._)`${f}[${b}]`,k))}function d(_,f,b,k=s.Correct){const S=k===s.Correct?n.operators.EQ:n.operators.NEQ;let C;switch(_){case"null":return(0,n._)`${f} ${S} null`;case"array":C=(0,n._)`Array.isArray(${f})`;break;case"object":C=(0,n._)`${f} && typeof ${f} == "object" && !Array.isArray(${f})`;break;case"integer":C=I((0,n._)`!(${f} % 1) && !isNaN(${f})`);break;case"number":C=I();break;default:return(0,n._)`typeof ${f} ${S} ${_}`}return k===s.Correct?C:(0,n.not)(C);function I(x=n.nil){return(0,n.and)((0,n._)`typeof ${f} == "number"`,x,b?(0,n._)`isFinite(${f})`:n.nil)}}Ge.checkDataType=d;function p(_,f,b,k){if(_.length===1)return d(_[0],f,b,k);let S;const C=(0,o.toHash)(_);if(C.array&&C.object){const I=(0,n._)`typeof ${f} != "object"`;S=C.null?I:(0,n._)`!${f} || ${I}`,delete C.null,delete C.array,delete C.object}else S=n.nil;C.number&&delete C.integer;for(const I in C)S=(0,n.and)(S,d(I,f,b,k));return S}Ge.checkDataTypes=p;const w={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:f})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${f}}`};function m(_){const f=y(_);(0,r.reportError)(f,w)}Ge.reportTypeError=m;function y(_){const{gen:f,data:b,schema:k}=_,S=(0,o.schemaRefOrVal)(_,k,"type");return{gen:f,keyword:"type",data:b,schema:k.type,schemaCode:S,schemaValue:S,parentSchema:k,params:{},it:_}}return Ge}var Kn={},vh;function nk(){if(vh)return Kn;vh=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.assignDefaults=void 0;const e=ye(),t=Se();function r(o,s){const{properties:a,items:i}=o.schema;if(s==="object"&&a)for(const l in a)n(o,l,a[l].default);else s==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}Kn.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const g=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${g}`);return}let h=(0,e._)`${g} === undefined`;u.useDefaults==="empty"&&(h=(0,e._)`${h} || ${g} === null || ${g} === ""`),i.if(h,(0,e._)`${g} = ${(0,e.stringify)(a)}`)}return Kn}var Pt={},Re={},_h;function Ot(){if(_h)return Re;_h=1,Object.defineProperty(Re,"__esModule",{value:!0}),Re.validateUnion=Re.validateArray=Re.usePattern=Re.callValidateCode=Re.schemaProperties=Re.allSchemaProperties=Re.noPropertyInData=Re.propertyInData=Re.isOwnProperty=Re.hasPropFunc=Re.reportMissingProp=Re.checkMissingProp=Re.checkReportMissingProp=void 0;const e=ye(),t=Se(),r=hr(),n=Se();function o(_,f){const{gen:b,data:k,it:S}=_;b.if(u(b,k,f,S.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${f}`},!0),_.error()})}Re.checkReportMissingProp=o;function s({gen:_,data:f,it:{opts:b}},k,S){return(0,e.or)(...k.map(C=>(0,e.and)(u(_,f,C,b.ownProperties),(0,e._)`${S} = ${C}`)))}Re.checkMissingProp=s;function a(_,f){_.setParams({missingProperty:f},!0),_.error()}Re.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Re.hasPropFunc=i;function l(_,f,b){return(0,e._)`${i(_)}.call(${f}, ${b})`}Re.isOwnProperty=l;function c(_,f,b,k){const S=(0,e._)`${f}${(0,e.getProperty)(b)} !== undefined`;return k?(0,e._)`${S} && ${l(_,f,b)}`:S}Re.propertyInData=c;function u(_,f,b,k){const S=(0,e._)`${f}${(0,e.getProperty)(b)} === undefined`;return k?(0,e.or)(S,(0,e.not)(l(_,f,b))):S}Re.noPropertyInData=u;function g(_){return _?Object.keys(_).filter(f=>f!=="__proto__"):[]}Re.allSchemaProperties=g;function h(_,f){return g(f).filter(b=>!(0,t.alwaysValidSchema)(_,f[b]))}Re.schemaProperties=h;function d({schemaCode:_,data:f,it:{gen:b,topSchemaRef:k,schemaPath:S,errorPath:C},it:I},x,M,P){const U=P?(0,e._)`${_}, ${f}, ${k}${S}`:f,z=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,C)],[r.default.parentData,I.parentData],[r.default.parentDataProperty,I.parentDataProperty],[r.default.rootData,r.default.rootData]];I.opts.dynamicRef&&z.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const F=(0,e._)`${U}, ${b.object(...z)}`;return M!==e.nil?(0,e._)`${x}.call(${M}, ${F})`:(0,e._)`${x}(${F})`}Re.callValidateCode=d;const p=(0,e._)`new RegExp`;function w({gen:_,it:{opts:f}},b){const k=f.unicodeRegExp?"u":"",{regExp:S}=f.code,C=S(b,k);return _.scopeValue("pattern",{key:C.toString(),ref:C,code:(0,e._)`${S.code==="new RegExp"?p:(0,n.useFunc)(_,S)}(${b}, ${k})`})}Re.usePattern=w;function m(_){const{gen:f,data:b,keyword:k,it:S}=_,C=f.name("valid");if(S.allErrors){const x=f.let("valid",!0);return I(()=>f.assign(x,!1)),x}return f.var(C,!0),I(()=>f.break()),C;function I(x){const M=f.const("len",(0,e._)`${b}.length`);f.forRange("i",0,M,P=>{_.subschema({keyword:k,dataProp:P,dataPropType:t.Type.Num},C),f.if((0,e.not)(C),x)})}}Re.validateArray=m;function y(_){const{gen:f,schema:b,keyword:k,it:S}=_;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(M=>(0,t.alwaysValidSchema)(S,M))&&!S.opts.unevaluated)return;const I=f.let("valid",!1),x=f.name("_valid");f.block(()=>b.forEach((M,P)=>{const U=_.subschema({keyword:k,schemaProp:P,compositeRule:!0},x);f.assign(I,(0,e._)`${I} || ${x}`),_.mergeValidEvaluated(U,x)||f.if((0,e.not)(I))})),_.result(I,()=>_.reset(),()=>_.error(!0))}return Re.validateUnion=y,Re}var yh;function ok(){if(yh)return Pt;yh=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;const e=ye(),t=hr(),r=Ot(),n=os();function o(h,d){const{gen:p,keyword:w,schema:m,parentSchema:y,it:_}=h,f=d.macro.call(_.self,m,y,_),b=c(p,w,f);_.opts.validateSchema!==!1&&_.self.validateSchema(f,!0);const k=p.name("valid");h.subschema({schema:f,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${w}`,topSchemaRef:b,compositeRule:!0},k),h.pass(k,()=>h.error(!0))}Pt.macroKeywordCode=o;function s(h,d){var p;const{gen:w,keyword:m,schema:y,parentSchema:_,$data:f,it:b}=h;l(b,d);const k=!f&&d.compile?d.compile.call(b.self,y,_,b):d.validate,S=c(w,m,k),C=w.let("valid");h.block$data(C,I),h.ok((p=d.valid)!==null&&p!==void 0?p:C);function I(){if(d.errors===!1)P(),d.modifying&&a(h),U(()=>h.error());else{const z=d.async?x():M();d.modifying&&a(h),U(()=>i(h,z))}}function x(){const z=w.let("ruleErrs",null);return w.try(()=>P((0,e._)`await `),F=>w.assign(C,!1).if((0,e._)`${F} instanceof ${b.ValidationError}`,()=>w.assign(z,(0,e._)`${F}.errors`),()=>w.throw(F))),z}function M(){const z=(0,e._)`${S}.errors`;return w.assign(z,null),P(e.nil),z}function P(z=d.async?(0,e._)`await `:e.nil){const F=b.opts.passContext?t.default.this:t.default.self,te=!("compile"in d&&!f||d.schema===!1);w.assign(C,(0,e._)`${z}${(0,r.callValidateCode)(h,S,F,te)}`,d.modifying)}function U(z){var F;w.if((0,e.not)((F=d.valid)!==null&&F!==void 0?F:C),z)}}Pt.funcKeywordCode=s;function a(h){const{gen:d,data:p,it:w}=h;d.if(w.parentData,()=>d.assign(p,(0,e._)`${w.parentData}[${w.parentDataProperty}]`))}function i(h,d){const{gen:p}=h;p.if((0,e._)`Array.isArray(${d})`,()=>{p.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${d} : ${t.default.vErrors}.concat(${d})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(h)},()=>h.error())}function l({schemaEnv:h},d){if(d.async&&!h.$async)throw new Error("async keyword in sync schema")}function c(h,d,p){if(p===void 0)throw new Error(`keyword "${d}" failed to compile`);return h.scopeValue("keyword",typeof p=="function"?{ref:p}:{ref:p,code:(0,e.stringify)(p)})}function u(h,d,p=!1){return!d.length||d.some(w=>w==="array"?Array.isArray(h):w==="object"?h&&typeof h=="object"&&!Array.isArray(h):typeof h==w||p&&typeof h>"u")}Pt.validSchemaType=u;function g({schema:h,opts:d,self:p,errSchemaPath:w},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");const _=m.dependencies;if(_?.some(f=>!Object.prototype.hasOwnProperty.call(h,f)))throw new Error(`parent schema must have dependencies of ${y}: ${_.join(",")}`);if(m.validateSchema&&!m.validateSchema(h[y])){const b=`keyword "${y}" value is invalid at path "${w}": `+p.errorsText(m.validateSchema.errors);if(d.validateSchema==="log")p.logger.error(b);else throw new Error(b)}}return Pt.validateKeywordUsage=g,Pt}var Xt={},wh;function sk(){if(wh)return Xt;wh=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.extendSubschemaMode=Xt.extendSubschemaData=Xt.getSubschema=void 0;const e=ye(),t=Se();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:g}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const h=s.schema[a];return i===void 0?{schema:h,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:h[i],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||g===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:g,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Xt.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:g}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=a;if(i!==void 0){const{errorPath:p,dataPathArr:w,opts:m}=a,y=h.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);d(y),s.errorPath=(0,e.str)`${p}${(0,t.getErrorPath)(i,l,m.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[...w,s.parentDataProperty]}if(c!==void 0){const p=c instanceof e.Name?c:h.let("data",c,!0);d(p),g!==void 0&&(s.propertyName=g)}u&&(s.dataTypes=u);function d(p){s.data=p,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,p]}}Xt.extendSubschemaData=n;function o(s,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=a,s.jtdMetadata=i}return Xt.extendSubschemaMode=o,Xt}var ot={},il,bh;function kh(){return bh||(bh=1,il=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var a=s[o];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}),il}var ll={exports:{}},Sh;function ak(){if(Sh)return ll.exports;Sh=1;var e=ll.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var a=typeof s=="function"?s:s.pre||function(){},i=s.post||function(){};t(o,a,i,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,a,i,l,c,u,g,h){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,g,h);for(var d in a){var p=a[d];if(Array.isArray(p)){if(d in e.arrayKeywords)for(var w=0;w<p.length;w++)t(n,o,s,p[w],i+"/"+d+"/"+w,l,i,d,a,w)}else if(d in e.propsKeywords){if(p&&typeof p=="object")for(var m in p)t(n,o,s,p[m],i+"/"+d+"/"+r(m),l,i,d,a,m)}else(d in e.keywords||n.allKeys&&!(d in e.skipKeywords))&&t(n,o,s,p,i+"/"+d,l,i,d,a)}s(a,i,l,c,u,g,h)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return ll.exports}var Ch;function as(){if(Ch)return ot;Ch=1,Object.defineProperty(ot,"__esModule",{value:!0}),ot.getSchemaRefs=ot.resolveUrl=ot.normalizeId=ot._getFullPath=ot.getFullPath=ot.inlineRef=void 0;const e=Se(),t=kh(),r=ak(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(w,m=!0){return typeof w=="boolean"?!0:m===!0?!a(w):m?i(w)<=m:!1}ot.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(w){for(const m in w){if(s.has(m))return!0;const y=w[m];if(Array.isArray(y)&&y.some(a)||typeof y=="object"&&a(y))return!0}return!1}function i(w){let m=0;for(const y in w){if(y==="$ref")return 1/0;if(m++,!n.has(y)&&(typeof w[y]=="object"&&(0,e.eachItem)(w[y],_=>m+=i(_)),m===1/0))return 1/0}return m}function l(w,m="",y){y!==!1&&(m=g(m));const _=w.parse(m);return c(w,_)}ot.getFullPath=l;function c(w,m){return w.serialize(m).split("#")[0]+"#"}ot._getFullPath=c;const u=/#\/?$/;function g(w){return w?w.replace(u,""):""}ot.normalizeId=g;function h(w,m,y){return y=g(y),w.resolve(m,y)}ot.resolveUrl=h;const d=/^[a-z_][-a-z0-9._]*$/i;function p(w,m){if(typeof w=="boolean")return{};const{schemaId:y,uriResolver:_}=this.opts,f=g(w[y]||m),b={"":f},k=l(_,f,!1),S={},C=new Set;return r(w,{allKeys:!0},(M,P,U,z)=>{if(z===void 0)return;const F=k+P;let te=b[z];typeof M[y]=="string"&&(te=ie.call(this,M[y])),se.call(this,M.$anchor),se.call(this,M.$dynamicAnchor),b[P]=te;function ie(ee){const pe=this.opts.uriResolver.resolve;if(ee=g(te?pe(te,ee):ee),C.has(ee))throw x(ee);C.add(ee);let V=this.refs[ee];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?I(M,V.schema,ee):ee!==g(F)&&(ee[0]==="#"?(I(M,S[ee],ee),S[ee]=M):this.refs[ee]=F),ee}function se(ee){if(typeof ee=="string"){if(!d.test(ee))throw new Error(`invalid anchor "${ee}"`);ie.call(this,`#${ee}`)}}}),S;function I(M,P,U){if(P!==void 0&&!t(M,P))throw x(U)}function x(M){return new Error(`reference "${M}" resolves to more than one schema`)}}return ot.getSchemaRefs=p,ot}var Th;function is(){if(Th)return Yt;Th=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.getData=Yt.KeywordCxt=Yt.validateFunctionCode=void 0;const e=rk(),t=ss(),r=mh(),n=ss(),o=nk(),s=ok(),a=sk(),i=ye(),l=hr(),c=as(),u=Se(),g=os();function h(N){if(k(N)&&(C(N),b(N))){m(N);return}d(N,()=>(0,e.topBoolOrEmptySchema)(N))}Yt.validateFunctionCode=h;function d({gen:N,validateName:D,schema:B,schemaEnv:W,opts:Y},oe){Y.code.es5?N.func(D,(0,i._)`${l.default.data}, ${l.default.valCxt}`,W.$async,()=>{N.code((0,i._)`"use strict"; ${_(B,Y)}`),w(N,Y),N.code(oe)}):N.func(D,(0,i._)`${l.default.data}, ${p(Y)}`,W.$async,()=>N.code(_(B,Y)).code(oe))}function p(N){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${N.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function w(N,D){N.if(l.default.valCxt,()=>{N.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),N.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),N.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),N.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),D.dynamicRef&&N.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{N.var(l.default.instancePath,(0,i._)`""`),N.var(l.default.parentData,(0,i._)`undefined`),N.var(l.default.parentDataProperty,(0,i._)`undefined`),N.var(l.default.rootData,l.default.data),D.dynamicRef&&N.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function m(N){const{schema:D,opts:B,gen:W}=N;d(N,()=>{B.$comment&&D.$comment&&z(N),M(N),W.let(l.default.vErrors,null),W.let(l.default.errors,0),B.unevaluated&&y(N),I(N),F(N)})}function y(N){const{gen:D,validateName:B}=N;N.evaluated=D.const("evaluated",(0,i._)`${B}.evaluated`),D.if((0,i._)`${N.evaluated}.dynamicProps`,()=>D.assign((0,i._)`${N.evaluated}.props`,(0,i._)`undefined`)),D.if((0,i._)`${N.evaluated}.dynamicItems`,()=>D.assign((0,i._)`${N.evaluated}.items`,(0,i._)`undefined`))}function _(N,D){const B=typeof N=="object"&&N[D.schemaId];return B&&(D.code.source||D.code.process)?(0,i._)`/*# sourceURL=${B} */`:i.nil}function f(N,D){if(k(N)&&(C(N),b(N))){S(N,D);return}(0,e.boolOrEmptySchema)(N,D)}function b({schema:N,self:D}){if(typeof N=="boolean")return!N;for(const B in N)if(D.RULES.all[B])return!0;return!1}function k(N){return typeof N.schema!="boolean"}function S(N,D){const{schema:B,gen:W,opts:Y}=N;Y.$comment&&B.$comment&&z(N),P(N),U(N);const oe=W.const("_errs",l.default.errors);I(N,oe),W.var(D,(0,i._)`${oe} === ${l.default.errors}`)}function C(N){(0,u.checkUnknownRules)(N),x(N)}function I(N,D){if(N.opts.jtd)return ie(N,[],!1,D);const B=(0,t.getSchemaTypes)(N.schema),W=(0,t.coerceAndCheckDataType)(N,B);ie(N,B,!W,D)}function x(N){const{schema:D,errSchemaPath:B,opts:W,self:Y}=N;D.$ref&&W.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(D,Y.RULES)&&Y.logger.warn(`$ref: keywords ignored in schema at path "${B}"`)}function M(N){const{schema:D,opts:B}=N;D.default!==void 0&&B.useDefaults&&B.strictSchema&&(0,u.checkStrictMode)(N,"default is ignored in the schema root")}function P(N){const D=N.schema[N.opts.schemaId];D&&(N.baseId=(0,c.resolveUrl)(N.opts.uriResolver,N.baseId,D))}function U(N){if(N.schema.$async&&!N.schemaEnv.$async)throw new Error("async schema in sync schema")}function z({gen:N,schemaEnv:D,schema:B,errSchemaPath:W,opts:Y}){const oe=B.$comment;if(Y.$comment===!0)N.code((0,i._)`${l.default.self}.logger.log(${oe})`);else if(typeof Y.$comment=="function"){const le=(0,i.str)`${W}/$comment`,Ne=N.scopeValue("root",{ref:D.root});N.code((0,i._)`${l.default.self}.opts.$comment(${oe}, ${le}, ${Ne}.schema)`)}}function F(N){const{gen:D,schemaEnv:B,validateName:W,ValidationError:Y,opts:oe}=N;B.$async?D.if((0,i._)`${l.default.errors} === 0`,()=>D.return(l.default.data),()=>D.throw((0,i._)`new ${Y}(${l.default.vErrors})`)):(D.assign((0,i._)`${W}.errors`,l.default.vErrors),oe.unevaluated&&te(N),D.return((0,i._)`${l.default.errors} === 0`))}function te({gen:N,evaluated:D,props:B,items:W}){B instanceof i.Name&&N.assign((0,i._)`${D}.props`,B),W instanceof i.Name&&N.assign((0,i._)`${D}.items`,W)}function ie(N,D,B,W){const{gen:Y,schema:oe,data:le,allErrors:Ne,opts:qe,self:X}=N,{RULES:me}=X;if(oe.$ref&&(qe.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(oe,me))){Y.block(()=>H(N,"$ref",me.all.$ref.definition));return}qe.jtd||ee(N,D),Y.block(()=>{for(const be of me.rules)st(be);st(me.post)});function st(be){(0,r.shouldUseGroup)(oe,be)&&(be.type?(Y.if((0,n.checkDataType)(be.type,le,qe.strictNumbers)),se(N,be),D.length===1&&D[0]===be.type&&B&&(Y.else(),(0,n.reportTypeError)(N)),Y.endIf()):se(N,be),Ne||Y.if((0,i._)`${l.default.errors} === ${W||0}`))}}function se(N,D){const{gen:B,schema:W,opts:{useDefaults:Y}}=N;Y&&(0,o.assignDefaults)(N,D.type),B.block(()=>{for(const oe of D.rules)(0,r.shouldUseRule)(W,oe)&&H(N,oe.keyword,oe.definition,D.type)})}function ee(N,D){N.schemaEnv.meta||!N.opts.strictTypes||(pe(N,D),N.opts.allowUnionTypes||V(N,D),O(N,N.dataTypes))}function pe(N,D){if(D.length){if(!N.dataTypes.length){N.dataTypes=D;return}D.forEach(B=>{j(N.dataTypes,B)||R(N,`type "${B}" not allowed by context "${N.dataTypes.join(",")}"`)}),E(N,D)}}function V(N,D){D.length>1&&!(D.length===2&&D.includes("null"))&&R(N,"use allowUnionTypes to allow union type keyword")}function O(N,D){const B=N.self.RULES.all;for(const W in B){const Y=B[W];if(typeof Y=="object"&&(0,r.shouldUseRule)(N.schema,Y)){const{type:oe}=Y.definition;oe.length&&!oe.some(le=>Z(D,le))&&R(N,`missing type "${oe.join(",")}" for keyword "${W}"`)}}}function Z(N,D){return N.includes(D)||D==="number"&&N.includes("integer")}function j(N,D){return N.includes(D)||D==="integer"&&N.includes("number")}function E(N,D){const B=[];for(const W of N.dataTypes)j(D,W)?B.push(W):D.includes("integer")&&W==="number"&&B.push("integer");N.dataTypes=B}function R(N,D){const B=N.schemaEnv.baseId+N.errSchemaPath;D+=` at "${B}" (strictTypes)`,(0,u.checkStrictMode)(N,D,N.opts.strictTypes)}class ${constructor(D,B,W){if((0,s.validateKeywordUsage)(D,B,W),this.gen=D.gen,this.allErrors=D.allErrors,this.keyword=W,this.data=D.data,this.schema=D.schema[W],this.$data=B.$data&&D.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(D,this.schema,W,this.$data),this.schemaType=B.schemaType,this.parentSchema=D.schema,this.params={},this.it=D,this.def=B,this.$data)this.schemaCode=D.gen.const("vSchema",ae(this.$data,D));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,B.schemaType,B.allowUndefined))throw new Error(`${W} value must be ${JSON.stringify(B.schemaType)}`);("code"in B?B.trackErrors:B.errors!==!1)&&(this.errsCount=D.gen.const("_errs",l.default.errors))}result(D,B,W){this.failResult((0,i.not)(D),B,W)}failResult(D,B,W){this.gen.if(D),W?W():this.error(),B?(this.gen.else(),B(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(D,B){this.failResult((0,i.not)(D),void 0,B)}fail(D){if(D===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(D),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(D){if(!this.$data)return this.fail(D);const{schemaCode:B}=this;this.fail((0,i._)`${B} !== undefined && (${(0,i.or)(this.invalid$data(),D)})`)}error(D,B,W){if(B){this.setParams(B),this._error(D,W),this.setParams({});return}this._error(D,W)}_error(D,B){(D?g.reportExtraError:g.reportError)(this,this.def.error,B)}$dataError(){(0,g.reportError)(this,this.def.$dataError||g.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,g.resetErrorsCount)(this.gen,this.errsCount)}ok(D){this.allErrors||this.gen.if(D)}setParams(D,B){B?Object.assign(this.params,D):this.params=D}block$data(D,B,W=i.nil){this.gen.block(()=>{this.check$data(D,W),B()})}check$data(D=i.nil,B=i.nil){if(!this.$data)return;const{gen:W,schemaCode:Y,schemaType:oe,def:le}=this;W.if((0,i.or)((0,i._)`${Y} === undefined`,B)),D!==i.nil&&W.assign(D,!0),(oe.length||le.validateSchema)&&(W.elseIf(this.invalid$data()),this.$dataError(),D!==i.nil&&W.assign(D,!1)),W.else()}invalid$data(){const{gen:D,schemaCode:B,schemaType:W,def:Y,it:oe}=this;return(0,i.or)(le(),Ne());function le(){if(W.length){if(!(B instanceof i.Name))throw new Error("ajv implementation error");const qe=Array.isArray(W)?W:[W];return(0,i._)`${(0,n.checkDataTypes)(qe,B,oe.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function Ne(){if(Y.validateSchema){const qe=D.scopeValue("validate$data",{ref:Y.validateSchema});return(0,i._)`!${qe}(${B})`}return i.nil}}subschema(D,B){const W=(0,a.getSubschema)(this.it,D);(0,a.extendSubschemaData)(W,this.it,D),(0,a.extendSubschemaMode)(W,D);const Y={...this.it,...W,items:void 0,props:void 0};return f(Y,B),Y}mergeEvaluated(D,B){const{it:W,gen:Y}=this;W.opts.unevaluated&&(W.props!==!0&&D.props!==void 0&&(W.props=u.mergeEvaluated.props(Y,D.props,W.props,B)),W.items!==!0&&D.items!==void 0&&(W.items=u.mergeEvaluated.items(Y,D.items,W.items,B)))}mergeValidEvaluated(D,B){const{it:W,gen:Y}=this;if(W.opts.unevaluated&&(W.props!==!0||W.items!==!0))return Y.if(B,()=>this.mergeEvaluated(D,i.Name)),!0}}Yt.KeywordCxt=$;function H(N,D,B,W){const Y=new $(N,B,D);"code"in B?B.code(Y,W):Y.$data&&B.validate?(0,s.funcKeywordCode)(Y,B):"macro"in B?(0,s.macroKeywordCode)(Y,B):(B.compile||B.validate)&&(0,s.funcKeywordCode)(Y,B)}const G=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ae(N,{dataLevel:D,dataNames:B,dataPathArr:W}){let Y,oe;if(N==="")return l.default.rootData;if(N[0]==="/"){if(!G.test(N))throw new Error(`Invalid JSON-pointer: ${N}`);Y=N,oe=l.default.rootData}else{const X=fe.exec(N);if(!X)throw new Error(`Invalid JSON-pointer: ${N}`);const me=+X[1];if(Y=X[2],Y==="#"){if(me>=D)throw new Error(qe("property/index",me));return W[D-me]}if(me>D)throw new Error(qe("data",me));if(oe=B[D-me],!Y)return oe}let le=oe;const Ne=Y.split("/");for(const X of Ne)X&&(oe=(0,i._)`${oe}${(0,i.getProperty)((0,u.unescapeJsonPointer)(X))}`,le=(0,i._)`${le} && ${oe}`);return le;function qe(X,me){return`Cannot access ${X} ${me} levels up, current level is ${D}`}}return Yt.getData=ae,Yt}var ls={},$h;function cl(){if($h)return ls;$h=1,Object.defineProperty(ls,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return ls.default=e,ls}var cs={},Eh;function us(){if(Eh)return cs;Eh=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=as();class t extends Error{constructor(n,o,s,a){super(a||`can't resolve reference ${s} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return cs.default=t,cs}var _t={},Ih;function ul(){if(Ih)return _t;Ih=1,Object.defineProperty(_t,"__esModule",{value:!0}),_t.resolveSchema=_t.getCompilingSchema=_t.resolveRef=_t.compileSchema=_t.SchemaEnv=void 0;const e=ye(),t=cl(),r=hr(),n=as(),o=Se(),s=is();class a{constructor(y){var _;this.refs={},this.dynamicAnchors={};let f;typeof y.schema=="object"&&(f=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(_=y.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(f?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=f?.$async,this.refs={}}}_t.SchemaEnv=a;function i(m){const y=u.call(this,m);if(y)return y;const _=(0,n.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:f,lines:b}=this.opts.code,{ownProperties:k}=this.opts,S=new e.CodeGen(this.scope,{es5:f,lines:b,ownProperties:k});let C;m.$async&&(C=S.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=S.scopeName("validate");m.validateName=I;const x={gen:S,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:S.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,e.stringify)(m.schema)}:{ref:m.schema}),validateName:I,ValidationError:C,schema:m.schema,schemaEnv:m,rootId:_,baseId:m.baseId||_,schemaPath:e.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let M;try{this._compilations.add(m),(0,s.validateFunctionCode)(x),S.optimize(this.opts.code.optimize);const P=S.toString();M=`${S.scopeRefs(r.default.scope)}return ${P}`,this.opts.code.process&&(M=this.opts.code.process(M,m));const z=new Function(`${r.default.self}`,`${r.default.scope}`,M)(this,this.scope.get());if(this.scope.value(I,{ref:z}),z.errors=null,z.schema=m.schema,z.schemaEnv=m,m.$async&&(z.$async=!0),this.opts.code.source===!0&&(z.source={validateName:I,validateCode:P,scopeValues:S._values}),this.opts.unevaluated){const{props:F,items:te}=x;z.evaluated={props:F instanceof e.Name?void 0:F,items:te instanceof e.Name?void 0:te,dynamicProps:F instanceof e.Name,dynamicItems:te instanceof e.Name},z.source&&(z.source.evaluated=(0,e.stringify)(z.evaluated))}return m.validate=z,m}catch(P){throw delete m.validate,delete m.validateName,M&&this.logger.error("Error compiling schema, function code:",M),P}finally{this._compilations.delete(m)}}_t.compileSchema=i;function l(m,y,_){var f;_=(0,n.resolveUrl)(this.opts.uriResolver,y,_);const b=m.refs[_];if(b)return b;let k=h.call(this,m,_);if(k===void 0){const S=(f=m.localRefs)===null||f===void 0?void 0:f[_],{schemaId:C}=this.opts;S&&(k=new a({schema:S,schemaId:C,root:m,baseId:y}))}if(k!==void 0)return m.refs[_]=c.call(this,k)}_t.resolveRef=l;function c(m){return(0,n.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:i.call(this,m)}function u(m){for(const y of this._compilations)if(g(y,m))return y}_t.getCompilingSchema=u;function g(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function h(m,y){let _;for(;typeof(_=this.refs[y])=="string";)y=_;return _||this.schemas[y]||d.call(this,m,y)}function d(m,y){const _=this.opts.uriResolver.parse(y),f=(0,n._getFullPath)(this.opts.uriResolver,_);let b=(0,n.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&f===b)return w.call(this,_,m);const k=(0,n.normalizeId)(f),S=this.refs[k]||this.schemas[k];if(typeof S=="string"){const C=d.call(this,m,S);return typeof C?.schema!="object"?void 0:w.call(this,_,C)}if(typeof S?.schema=="object"){if(S.validate||i.call(this,S),k===(0,n.normalizeId)(y)){const{schema:C}=S,{schemaId:I}=this.opts,x=C[I];return x&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,x)),new a({schema:C,schemaId:I,root:m,baseId:b})}return w.call(this,_,S)}}_t.resolveSchema=d;const p=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(m,{baseId:y,schema:_,root:f}){var b;if(((b=m.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const C of m.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const I=_[(0,o.unescapeFragment)(C)];if(I===void 0)return;_=I;const x=typeof _=="object"&&_[this.opts.schemaId];!p.has(C)&&x&&(y=(0,n.resolveUrl)(this.opts.uriResolver,y,x))}let k;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const C=(0,n.resolveUrl)(this.opts.uriResolver,y,_.$ref);k=d.call(this,f,C)}const{schemaId:S}=this.opts;if(k=k||new a({schema:_,schemaId:S,root:f,baseId:y}),k.schema!==k.root.schema)return k}return _t}const ik={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var ds={},Yn={exports:{}},dl,xh;function Rh(){if(xh)return dl;xh=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(h){let d="",p=0,w=0;for(w=0;w<h.length;w++)if(p=h[w].charCodeAt(0),p!==48){if(!(p>=48&&p<=57||p>=65&&p<=70||p>=97&&p<=102))return"";d+=h[w];break}for(w+=1;w<h.length;w++){if(p=h[w].charCodeAt(0),!(p>=48&&p<=57||p>=65&&p<=70||p>=97&&p<=102))return"";d+=h[w]}return d}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(h){return h.length=0,!0}function s(h,d,p){if(h.length){const w=r(h);if(w!=="")d.push(w);else return p.error=!0,!1;h.length=0}return!0}function a(h){let d=0;const p={error:!1,address:"",zone:""},w=[],m=[];let y=!1,_=!1,f=s;for(let b=0;b<h.length;b++){const k=h[b];if(!(k==="["||k==="]"))if(k===":"){if(y===!0&&(_=!0),!f(m,w,p))break;if(++d>7){p.error=!0;break}b>0&&h[b-1]===":"&&(y=!0),w.push(":");continue}else if(k==="%"){if(!f(m,w,p))break;f=o}else{m.push(k);continue}}return m.length&&(f===o?p.zone=m.join(""):_?w.push(m.join("")):w.push(r(m))),p.address=w.join(""),p}function i(h){if(l(h,":")<2)return{host:h,isIPV6:!1};const d=a(h);if(d.error)return{host:h,isIPV6:!1};{let p=d.address,w=d.address;return d.zone&&(p+="%"+d.zone,w+="%25"+d.zone),{host:p,isIPV6:!0,escapedHost:w}}}function l(h,d){let p=0;for(let w=0;w<h.length;w++)h[w]===d&&p++;return p}function c(h){let d=h;const p=[];let w=-1,m=0;for(;m=d.length;){if(m===1){if(d===".")break;if(d==="/"){p.push("/");break}else{p.push(d);break}}else if(m===2){if(d[0]==="."){if(d[1]===".")break;if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&(d[1]==="."||d[1]==="/")){p.push("/");break}}else if(m===3&&d==="/.."){p.length!==0&&p.pop(),p.push("/");break}if(d[0]==="."){if(d[1]==="."){if(d[2]==="/"){d=d.slice(3);continue}}else if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&d[1]==="."){if(d[2]==="/"){d=d.slice(2);continue}else if(d[2]==="."&&d[3]==="/"){d=d.slice(3),p.length!==0&&p.pop();continue}}if((w=d.indexOf("/",1))===-1){p.push(d);break}else p.push(d.slice(0,w)),d=d.slice(w)}return p.join("")}function u(h,d){const p=d!==!0?escape:unescape;return h.scheme!==void 0&&(h.scheme=p(h.scheme)),h.userinfo!==void 0&&(h.userinfo=p(h.userinfo)),h.host!==void 0&&(h.host=p(h.host)),h.path!==void 0&&(h.path=p(h.path)),h.query!==void 0&&(h.query=p(h.query)),h.fragment!==void 0&&(h.fragment=p(h.fragment)),h}function g(h){const d=[];if(h.userinfo!==void 0&&(d.push(h.userinfo),d.push("@")),h.host!==void 0){let p=unescape(h.host);if(!t(p)){const w=i(p);w.isIPV6===!0?p=`[${w.escapedHost}]`:p=h.host}d.push(p)}return(typeof h.port=="number"||typeof h.port=="string")&&(d.push(":"),d.push(String(h.port))),d.length?d.join(""):void 0}return dl={nonSimpleDomain:n,recomposeAuthority:g,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},dl}var pl,Ph;function lk(){if(Ph)return pl;Ph=1;const{isUUID:e}=Rh(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function o(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function s(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const S=String(k.scheme).toLowerCase()==="https";return(k.port===(S?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=o(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function l(k){if((k.port===(o(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[S,C]=k.resourceName.split("?");k.path=S&&S!=="/"?S:void 0,k.query=C,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,S){if(!k.path)return k.error="URN can not be parsed",k;const C=k.path.match(t);if(C){const I=S.scheme||k.scheme||"urn";k.nid=C[1].toLowerCase(),k.nss=C[2];const x=`${I}:${S.nid||k.nid}`,M=b(x);k.path=void 0,M&&(k=M.parse(k,S))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,S){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const C=S.scheme||k.scheme||"urn",I=k.nid.toLowerCase(),x=`${C}:${S.nid||I}`,M=b(x);M&&(k=M.serialize(k,S));const P=k,U=k.nss;return P.path=`${I||S.nid}:${U}`,S.skipEscape=!0,P}function g(k,S){const C=k;return C.uuid=C.nss,C.nss=void 0,!S.tolerant&&(!C.uuid||!e(C.uuid))&&(C.error=C.error||"UUID is not valid."),C}function h(k){const S=k;return S.nss=(k.uuid||"").toLowerCase(),S}const d={scheme:"http",domainHost:!0,parse:s,serialize:a},p={scheme:"https",domainHost:d.domainHost,parse:s,serialize:a},w={scheme:"ws",domainHost:!0,parse:i,serialize:l},m={scheme:"wss",domainHost:w.domainHost,parse:w.parse,serialize:w.serialize},f={http:d,https:p,ws:w,wss:m,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:g,serialize:h,skipNormalize:!0}};Object.setPrototypeOf(f,null);function b(k){return k&&(f[k]||f[k.toLowerCase()])||void 0}return pl={wsIsSecure:o,SCHEMES:f,isValidSchemeName:n,getSchemeHandler:b},pl}var Oh;function ck(){if(Oh)return Yn.exports;Oh=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Rh(),{SCHEMES:a,getSchemeHandler:i}=lk();function l(m,y){return typeof m=="string"?m=h(p(m,y),y):typeof m=="object"&&(m=p(h(m,y),y)),m}function c(m,y,_){const f=_?Object.assign({scheme:"null"},_):{scheme:"null"},b=u(p(m,f),p(y,f),f,!0);return f.skipEscape=!0,h(b,f)}function u(m,y,_,f){const b={};return f||(m=p(h(m,_),_),y=p(h(y,_),_)),_=_||{},!_.tolerant&&y.scheme?(b.scheme=y.scheme,b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=t(y.path||""),b.query=y.query):(y.userinfo!==void 0||y.host!==void 0||y.port!==void 0?(b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=t(y.path||""),b.query=y.query):(y.path?(y.path[0]==="/"?b.path=t(y.path):((m.userinfo!==void 0||m.host!==void 0||m.port!==void 0)&&!m.path?b.path="/"+y.path:m.path?b.path=m.path.slice(0,m.path.lastIndexOf("/")+1)+y.path:b.path=y.path,b.path=t(b.path)),b.query=y.query):(b.path=m.path,y.query!==void 0?b.query=y.query:b.query=m.query),b.userinfo=m.userinfo,b.host=m.host,b.port=m.port),b.scheme=m.scheme),b.fragment=y.fragment,b}function g(m,y,_){return typeof m=="string"?(m=unescape(m),m=h(n(p(m,_),!0),{..._,skipEscape:!0})):typeof m=="object"&&(m=h(n(m,!0),{..._,skipEscape:!0})),typeof y=="string"?(y=unescape(y),y=h(n(p(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=h(n(y,!0),{..._,skipEscape:!0})),m.toLowerCase()===y.toLowerCase()}function h(m,y){const _={host:m.host,scheme:m.scheme,userinfo:m.userinfo,port:m.port,path:m.path,query:m.query,nid:m.nid,nss:m.nss,uuid:m.uuid,fragment:m.fragment,reference:m.reference,resourceName:m.resourceName,secure:m.secure,error:""},f=Object.assign({},y),b=[],k=i(f.scheme||_.scheme);k&&k.serialize&&k.serialize(_,f),_.path!==void 0&&(f.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),f.reference!=="suffix"&&_.scheme&&b.push(_.scheme,":");const S=r(_);if(S!==void 0&&(f.reference!=="suffix"&&b.push("//"),b.push(S),_.path&&_.path[0]!=="/"&&b.push("/")),_.path!==void 0){let C=_.path;!f.absolutePath&&(!k||!k.absolutePath)&&(C=t(C)),S===void 0&&C[0]==="/"&&C[1]==="/"&&(C="/%2F"+C.slice(2)),b.push(C)}return _.query!==void 0&&b.push("?",_.query),_.fragment!==void 0&&b.push("#",_.fragment),b.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function p(m,y){const _=Object.assign({},y),f={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;_.reference==="suffix"&&(_.scheme?m=_.scheme+":"+m:m="//"+m);const k=m.match(d);if(k){if(f.scheme=k[1],f.userinfo=k[3],f.host=k[4],f.port=parseInt(k[5],10),f.path=k[6]||"",f.query=k[7],f.fragment=k[8],isNaN(f.port)&&(f.port=k[5]),f.host)if(o(f.host)===!1){const I=e(f.host);f.host=I.host.toLowerCase(),b=I.isIPV6}else b=!0;f.scheme===void 0&&f.userinfo===void 0&&f.host===void 0&&f.port===void 0&&f.query===void 0&&!f.path?f.reference="same-document":f.scheme===void 0?f.reference="relative":f.fragment===void 0?f.reference="absolute":f.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==f.reference&&(f.error=f.error||"URI is not a "+_.reference+" reference.");const S=i(_.scheme||f.scheme);if(!_.unicodeSupport&&(!S||!S.unicodeSupport)&&f.host&&(_.domainHost||S&&S.domainHost)&&b===!1&&s(f.host))try{f.host=URL.domainToASCII(f.host.toLowerCase())}catch(C){f.error=f.error||"Host's domain name can not be converted to ASCII: "+C}(!S||S&&!S.skipNormalize)&&(m.indexOf("%")!==-1&&(f.scheme!==void 0&&(f.scheme=unescape(f.scheme)),f.host!==void 0&&(f.host=unescape(f.host))),f.path&&(f.path=escape(unescape(f.path))),f.fragment&&(f.fragment=encodeURI(decodeURIComponent(f.fragment)))),S&&S.parse&&S.parse(f,_)}else f.error=f.error||"URI can not be parsed.";return f}const w={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:g,serialize:h,parse:p};return Yn.exports=w,Yn.exports.default=w,Yn.exports.fastUri=w,Yn.exports}var Mh;function uk(){if(Mh)return ds;Mh=1,Object.defineProperty(ds,"__esModule",{value:!0});const e=ck();return e.code='require("ajv/dist/runtime/uri").default',ds.default=e,ds}var Nh;function dk(){return Nh||(Nh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=is();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=ye();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=cl(),o=us(),s=fh(),a=ul(),i=ye(),l=as(),c=ss(),u=Se(),g=ik,h=uk(),d=(V,O)=>new RegExp(V,O);d.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],w=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function f(V){var O,Z,j,E,R,$,H,G,fe,ae,N,D,B,W,Y,oe,le,Ne,qe,X,me,st,be,pt,tr;const ft=V.strict,We=(O=V.code)===null||O===void 0?void 0:O.optimize,St=We===!0||We===void 0?1:We||0,yr=(j=(Z=V.code)===null||Z===void 0?void 0:Z.regExp)!==null&&j!==void 0?j:d,wr=(E=V.uriResolver)!==null&&E!==void 0?E:h.default;return{strictSchema:($=(R=V.strictSchema)!==null&&R!==void 0?R:ft)!==null&&$!==void 0?$:!0,strictNumbers:(G=(H=V.strictNumbers)!==null&&H!==void 0?H:ft)!==null&&G!==void 0?G:!0,strictTypes:(ae=(fe=V.strictTypes)!==null&&fe!==void 0?fe:ft)!==null&&ae!==void 0?ae:"log",strictTuples:(D=(N=V.strictTuples)!==null&&N!==void 0?N:ft)!==null&&D!==void 0?D:"log",strictRequired:(W=(B=V.strictRequired)!==null&&B!==void 0?B:ft)!==null&&W!==void 0?W:!1,code:V.code?{...V.code,optimize:St,regExp:yr}:{optimize:St,regExp:yr},loopRequired:(Y=V.loopRequired)!==null&&Y!==void 0?Y:_,loopEnum:(oe=V.loopEnum)!==null&&oe!==void 0?oe:_,meta:(le=V.meta)!==null&&le!==void 0?le:!0,messages:(Ne=V.messages)!==null&&Ne!==void 0?Ne:!0,inlineRefs:(qe=V.inlineRefs)!==null&&qe!==void 0?qe:!0,schemaId:(X=V.schemaId)!==null&&X!==void 0?X:"$id",addUsedSchema:(me=V.addUsedSchema)!==null&&me!==void 0?me:!0,validateSchema:(st=V.validateSchema)!==null&&st!==void 0?st:!0,validateFormats:(be=V.validateFormats)!==null&&be!==void 0?be:!0,unicodeRegExp:(pt=V.unicodeRegExp)!==null&&pt!==void 0?pt:!0,int32range:(tr=V.int32range)!==null&&tr!==void 0?tr:!0,uriResolver:wr}}class b{constructor(O={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,O=this.opts={...O,...f(O)};const{es5:Z,lines:j}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:w,es5:Z,lines:j}),this.logger=U(O.logger);const E=O.validateFormats;O.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,m,O,"NOT SUPPORTED"),k.call(this,y,O,"DEPRECATED","warn"),this._metaOpts=M.call(this),O.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),O.keywords&&x.call(this,O.keywords),typeof O.meta=="object"&&this.addMetaSchema(O.meta),C.call(this),O.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:O,meta:Z,schemaId:j}=this.opts;let E=g;j==="id"&&(E={...g},E.id=E.$id,delete E.$id),Z&&O&&this.addMetaSchema(E,E[j],!1)}defaultMeta(){const{meta:O,schemaId:Z}=this.opts;return this.opts.defaultMeta=typeof O=="object"?O[Z]||O:void 0}validate(O,Z){let j;if(typeof O=="string"){if(j=this.getSchema(O),!j)throw new Error(`no schema with key or ref "${O}"`)}else j=this.compile(O);const E=j(Z);return"$async"in j||(this.errors=j.errors),E}compile(O,Z){const j=this._addSchema(O,Z);return j.validate||this._compileSchemaEnv(j)}compileAsync(O,Z){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:j}=this.opts;return E.call(this,O,Z);async function E(ae,N){await R.call(this,ae.$schema);const D=this._addSchema(ae,N);return D.validate||$.call(this,D)}async function R(ae){ae&&!this.getSchema(ae)&&await E.call(this,{$ref:ae},!0)}async function $(ae){try{return this._compileSchemaEnv(ae)}catch(N){if(!(N instanceof o.default))throw N;return H.call(this,N),await G.call(this,N.missingSchema),$.call(this,ae)}}function H({missingSchema:ae,missingRef:N}){if(this.refs[ae])throw new Error(`AnySchema ${ae} is loaded but ${N} cannot be resolved`)}async function G(ae){const N=await fe.call(this,ae);this.refs[ae]||await R.call(this,N.$schema),this.refs[ae]||this.addSchema(N,ae,Z)}async function fe(ae){const N=this._loading[ae];if(N)return N;try{return await(this._loading[ae]=j(ae))}finally{delete this._loading[ae]}}}addSchema(O,Z,j,E=this.opts.validateSchema){if(Array.isArray(O)){for(const $ of O)this.addSchema($,void 0,j,E);return this}let R;if(typeof O=="object"){const{schemaId:$}=this.opts;if(R=O[$],R!==void 0&&typeof R!="string")throw new Error(`schema ${$} must be string`)}return Z=(0,l.normalizeId)(Z||R),this._checkUnique(Z),this.schemas[Z]=this._addSchema(O,j,Z,E,!0),this}addMetaSchema(O,Z,j=this.opts.validateSchema){return this.addSchema(O,Z,!0,j),this}validateSchema(O,Z){if(typeof O=="boolean")return!0;let j;if(j=O.$schema,j!==void 0&&typeof j!="string")throw new Error("$schema must be a string");if(j=j||this.opts.defaultMeta||this.defaultMeta(),!j)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(j,O);if(!E&&Z){const R="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(R);else throw new Error(R)}return E}getSchema(O){let Z;for(;typeof(Z=S.call(this,O))=="string";)O=Z;if(Z===void 0){const{schemaId:j}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:j});if(Z=a.resolveSchema.call(this,E,O),!Z)return;this.refs[O]=Z}return Z.validate||this._compileSchemaEnv(Z)}removeSchema(O){if(O instanceof RegExp)return this._removeAllSchemas(this.schemas,O),this._removeAllSchemas(this.refs,O),this;switch(typeof O){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const Z=S.call(this,O);return typeof Z=="object"&&this._cache.delete(Z.schema),delete this.schemas[O],delete this.refs[O],this}case"object":{const Z=O;this._cache.delete(Z);let j=O[this.opts.schemaId];return j&&(j=(0,l.normalizeId)(j),delete this.schemas[j],delete this.refs[j]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(O){for(const Z of O)this.addKeyword(Z);return this}addKeyword(O,Z){let j;if(typeof O=="string")j=O,typeof Z=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Z.keyword=j);else if(typeof O=="object"&&Z===void 0){if(Z=O,j=Z.keyword,Array.isArray(j)&&!j.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(F.call(this,j,Z),!Z)return(0,u.eachItem)(j,R=>te.call(this,R)),this;se.call(this,Z);const E={...Z,type:(0,c.getJSONTypes)(Z.type),schemaType:(0,c.getJSONTypes)(Z.schemaType)};return(0,u.eachItem)(j,E.type.length===0?R=>te.call(this,R,E):R=>E.type.forEach($=>te.call(this,R,E,$))),this}getKeyword(O){const Z=this.RULES.all[O];return typeof Z=="object"?Z.definition:!!Z}removeKeyword(O){const{RULES:Z}=this;delete Z.keywords[O],delete Z.all[O];for(const j of Z.rules){const E=j.rules.findIndex(R=>R.keyword===O);E>=0&&j.rules.splice(E,1)}return this}addFormat(O,Z){return typeof Z=="string"&&(Z=new RegExp(Z)),this.formats[O]=Z,this}errorsText(O=this.errors,{separator:Z=", ",dataVar:j="data"}={}){return!O||O.length===0?"No errors":O.map(E=>`${j}${E.instancePath} ${E.message}`).reduce((E,R)=>E+Z+R)}$dataMetaSchema(O,Z){const j=this.RULES.all;O=JSON.parse(JSON.stringify(O));for(const E of Z){const R=E.split("/").slice(1);let $=O;for(const H of R)$=$[H];for(const H in j){const G=j[H];if(typeof G!="object")continue;const{$data:fe}=G.definition,ae=$[H];fe&&ae&&($[H]=pe(ae))}}return O}_removeAllSchemas(O,Z){for(const j in O){const E=O[j];(!Z||Z.test(j))&&(typeof E=="string"?delete O[j]:E&&!E.meta&&(this._cache.delete(E.schema),delete O[j]))}}_addSchema(O,Z,j,E=this.opts.validateSchema,R=this.opts.addUsedSchema){let $;const{schemaId:H}=this.opts;if(typeof O=="object")$=O[H];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof O!="boolean")throw new Error("schema must be object or boolean")}let G=this._cache.get(O);if(G!==void 0)return G;j=(0,l.normalizeId)($||j);const fe=l.getSchemaRefs.call(this,O,j);return G=new a.SchemaEnv({schema:O,schemaId:H,meta:Z,baseId:j,localRefs:fe}),this._cache.set(G.schema,G),R&&!j.startsWith("#")&&(j&&this._checkUnique(j),this.refs[j]=G),E&&this.validateSchema(O,!0),G}_checkUnique(O){if(this.schemas[O]||this.refs[O])throw new Error(`schema with key or id "${O}" already exists`)}_compileSchemaEnv(O){if(O.meta?this._compileMetaSchema(O):a.compileSchema.call(this,O),!O.validate)throw new Error("ajv implementation error");return O.validate}_compileMetaSchema(O){const Z=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,O)}finally{this.opts=Z}}}b.ValidationError=n.default,b.MissingRefError=o.default,e.default=b;function k(V,O,Z,j="error"){for(const E in V){const R=E;R in O&&this.logger[j](`${Z}: option ${E}. ${V[R]}`)}}function S(V){return V=(0,l.normalizeId)(V),this.schemas[V]||this.refs[V]}function C(){const V=this.opts.schemas;if(V)if(Array.isArray(V))this.addSchema(V);else for(const O in V)this.addSchema(V[O],O)}function I(){for(const V in this.opts.formats){const O=this.opts.formats[V];O&&this.addFormat(V,O)}}function x(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const O in V){const Z=V[O];Z.keyword||(Z.keyword=O),this.addKeyword(Z)}}function M(){const V={...this.opts};for(const O of p)delete V[O];return V}const P={log(){},warn(){},error(){}};function U(V){if(V===!1)return P;if(V===void 0)return console;if(V.log&&V.warn&&V.error)return V;throw new Error("logger must implement log, warn and error methods")}const z=/^[a-z_$][a-z0-9_$:-]*$/i;function F(V,O){const{RULES:Z}=this;if((0,u.eachItem)(V,j=>{if(Z.keywords[j])throw new Error(`Keyword ${j} is already defined`);if(!z.test(j))throw new Error(`Keyword ${j} has invalid name`)}),!!O&&O.$data&&!("code"in O||"validate"in O))throw new Error('$data keyword must have "code" or "validate" function')}function te(V,O,Z){var j;const E=O?.post;if(Z&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:R}=this;let $=E?R.post:R.rules.find(({type:G})=>G===Z);if($||($={type:Z,rules:[]},R.rules.push($)),R.keywords[V]=!0,!O)return;const H={keyword:V,definition:{...O,type:(0,c.getJSONTypes)(O.type),schemaType:(0,c.getJSONTypes)(O.schemaType)}};O.before?ie.call(this,$,H,O.before):$.rules.push(H),R.all[V]=H,(j=O.implements)===null||j===void 0||j.forEach(G=>this.addKeyword(G))}function ie(V,O,Z){const j=V.rules.findIndex(E=>E.keyword===Z);j>=0?V.rules.splice(j,0,O):(V.rules.push(O),this.logger.warn(`rule ${Z} is not defined`))}function se(V){let{metaSchema:O}=V;O!==void 0&&(V.$data&&this.opts.$data&&(O=pe(O)),V.validateSchema=this.compile(O,!0))}const ee={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pe(V){return{anyOf:[V,ee]}}})(rl)),rl}var ps={},fs={},hs={},Ah;function pk(){if(Ah)return hs;Ah=1,Object.defineProperty(hs,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return hs.default=e,hs}var mr={},qh;function fk(){if(qh)return mr;qh=1,Object.defineProperty(mr,"__esModule",{value:!0}),mr.callRef=mr.getValidate=void 0;const e=us(),t=Ot(),r=ye(),n=hr(),o=ul(),s=Se(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:g,it:h}=c,{baseId:d,schemaEnv:p,validateName:w,opts:m,self:y}=h,{root:_}=p;if((g==="#"||g==="#/")&&d===_.baseId)return b();const f=o.resolveRef.call(y,_,d,g);if(f===void 0)throw new e.default(h.opts.uriResolver,d,g);if(f instanceof o.SchemaEnv)return k(f);return S(f);function b(){if(p===_)return l(c,w,p,p.$async);const C=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${C}.validate`,_,_.$async)}function k(C){const I=i(c,C);l(c,I,C,C.$async)}function S(C){const I=u.scopeValue("schema",m.code.source===!0?{ref:C,code:(0,r.stringify)(C)}:{ref:C}),x=u.name("valid"),M=c.subschema({schema:C,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:g},x);c.mergeEvaluated(M),c.ok(x)}}};function i(c,u){const{gen:g}=c;return u.validate?g.scopeValue("validate",{ref:u.validate}):(0,r._)`${g.scopeValue("wrapper",{ref:u})}.validate`}mr.getValidate=i;function l(c,u,g,h){const{gen:d,it:p}=c,{allErrors:w,schemaEnv:m,opts:y}=p,_=y.passContext?n.default.this:r.nil;h?f():b();function f(){if(!m.$async)throw new Error("async schema referenced by sync schema");const C=d.let("valid");d.try(()=>{d.code((0,r._)`await ${(0,t.callValidateCode)(c,u,_)}`),S(u),w||d.assign(C,!0)},I=>{d.if((0,r._)`!(${I} instanceof ${p.ValidationError})`,()=>d.throw(I)),k(I),w||d.assign(C,!1)}),c.ok(C)}function b(){c.result((0,t.callValidateCode)(c,u,_),()=>S(u),()=>k(u))}function k(C){const I=(0,r._)`${C}.errors`;d.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${I} : ${n.default.vErrors}.concat(${I})`),d.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function S(C){var I;if(!p.opts.unevaluated)return;const x=(I=g?.validate)===null||I===void 0?void 0:I.evaluated;if(p.props!==!0)if(x&&!x.dynamicProps)x.props!==void 0&&(p.props=s.mergeEvaluated.props(d,x.props,p.props));else{const M=d.var("props",(0,r._)`${C}.evaluated.props`);p.props=s.mergeEvaluated.props(d,M,p.props,r.Name)}if(p.items!==!0)if(x&&!x.dynamicItems)x.items!==void 0&&(p.items=s.mergeEvaluated.items(d,x.items,p.items));else{const M=d.var("items",(0,r._)`${C}.evaluated.items`);p.items=s.mergeEvaluated.items(d,M,p.items,r.Name)}}}return mr.callRef=l,mr.default=a,mr}var Lh;function hk(){if(Lh)return fs;Lh=1,Object.defineProperty(fs,"__esModule",{value:!0});const e=pk(),t=fk(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return fs.default=r,fs}var ms={},gs={},jh;function mk(){if(jh)return gs;jh=1,Object.defineProperty(gs,"__esModule",{value:!0});const e=ye(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:a})=>(0,e.str)`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${a}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:a,data:i,schemaCode:l}=s;s.fail$data((0,e._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return gs.default=o,gs}var vs={},Uh;function gk(){if(Uh)return vs;Uh=1,Object.defineProperty(vs,"__esModule",{value:!0});const e=ye(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${a} === 0 || (${c} = ${s}/${a}, ${u}))`)}};return vs.default=r,vs}var _s={},ys={},zh;function vk(){if(zh)return ys;zh=1,Object.defineProperty(ys,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,s;for(;o<r;)n++,s=t.charCodeAt(o++),s>=55296&&s<=56319&&o<r&&(s=t.charCodeAt(o),(s&64512)===56320&&o++);return n}return ys.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ys}var Dh;function _k(){if(Dh)return _s;Dh=1,Object.defineProperty(_s,"__esModule",{value:!0});const e=ye(),t=Se(),r=vk(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:a}){const i=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:a,data:i,schemaCode:l,it:c}=s,u=a==="maxLength"?e.operators.GT:e.operators.LT,g=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${g} ${u} ${l}`)}};return _s.default=o,_s}var ws={},Zh;function yk(){if(Zh)return ws;Zh=1,Object.defineProperty(ws,"__esModule",{value:!0});const e=Ot(),t=ye(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:o})=>(0,t.str)`must match pattern "${o}"`,params:({schemaCode:o})=>(0,t._)`{pattern: ${o}}`},code(o){const{data:s,$data:a,schema:i,schemaCode:l,it:c}=o,u=c.opts.unicodeRegExp?"u":"",g=a?(0,t._)`(new RegExp(${l}, ${u}))`:(0,e.usePattern)(o,i);o.fail$data((0,t._)`!${g}.test(${s})`)}};return ws.default=n,ws}var bs={},Fh;function wk(){if(Fh)return bs;Fh=1,Object.defineProperty(bs,"__esModule",{value:!0});const e=ye(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${i} ${a}`)}};return bs.default=r,bs}var ks={},Vh;function bk(){if(Vh)return ks;Vh=1,Object.defineProperty(ks,"__esModule",{value:!0});const e=Ot(),t=ye(),r=Se(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:g}=s,{opts:h}=g;if(!u&&i.length===0)return;const d=i.length>=h.loopRequired;if(g.allErrors?p():w(),h.strictRequired){const _=s.parentSchema.properties,{definedProperties:f}=s.it;for(const b of i)if(_?.[b]===void 0&&!f.has(b)){const k=g.schemaEnv.baseId+g.errSchemaPath,S=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(g,S,g.opts.strictRequired)}}function p(){if(d||u)s.block$data(t.nil,m);else for(const _ of i)(0,e.checkReportMissingProp)(s,_)}function w(){const _=a.let("missing");if(d||u){const f=a.let("valid",!0);s.block$data(f,()=>y(_,f)),s.ok(f)}else a.if((0,e.checkMissingProp)(s,i,_)),(0,e.reportMissingProp)(s,_),a.else()}function m(){a.forOf("prop",l,_=>{s.setParams({missingProperty:_}),a.if((0,e.noPropertyInData)(a,c,_,h.ownProperties),()=>s.error())})}function y(_,f){s.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(f,(0,e.propertyInData)(a,c,_,h.ownProperties)),a.if((0,t.not)(f),()=>{s.error(),a.break()})},t.nil)}}};return ks.default=o,ks}var Ss={},Hh;function kk(){if(Hh)return Ss;Hh=1,Object.defineProperty(Ss,"__esModule",{value:!0});const e=ye(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${i} ${a}`)}};return Ss.default=r,Ss}var Cs={},Ts={},Bh;function fl(){if(Bh)return Ts;Bh=1,Object.defineProperty(Ts,"__esModule",{value:!0});const e=kh();return e.code='require("ajv/dist/runtime/equal").default',Ts.default=e,Ts}var Jh;function Sk(){if(Jh)return Cs;Jh=1,Object.defineProperty(Cs,"__esModule",{value:!0});const e=ss(),t=ye(),r=Se(),n=fl(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,t._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:g,schemaCode:h,it:d}=a;if(!c&&!u)return;const p=i.let("valid"),w=g.items?(0,e.getSchemaTypes)(g.items):[];a.block$data(p,m,(0,t._)`${h} === false`),a.ok(p);function m(){const b=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:b,j:k}),i.assign(p,!0),i.if((0,t._)`${b} > 1`,()=>(y()?_:f)(b,k))}function y(){return w.length>0&&!w.some(b=>b==="object"||b==="array")}function _(b,k){const S=i.name("item"),C=(0,e.checkDataTypes)(w,S,d.opts.strictNumbers,e.DataType.Wrong),I=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${b}--;`,()=>{i.let(S,(0,t._)`${l}[${b}]`),i.if(C,(0,t._)`continue`),w.length>1&&i.if((0,t._)`typeof ${S} == "string"`,(0,t._)`${S} += "_"`),i.if((0,t._)`typeof ${I}[${S}] == "number"`,()=>{i.assign(k,(0,t._)`${I}[${S}]`),a.error(),i.assign(p,!1).break()}).code((0,t._)`${I}[${S}] = ${b}`)})}function f(b,k){const S=(0,r.useFunc)(i,n.default),C=i.name("outer");i.label(C).for((0,t._)`;${b}--;`,()=>i.for((0,t._)`${k} = ${b}; ${k}--;`,()=>i.if((0,t._)`${S}(${l}[${b}], ${l}[${k}])`,()=>{a.error(),i.assign(p,!1).break(C)})))}}};return Cs.default=s,Cs}var $s={},Gh;function Ck(){if(Gh)return $s;Gh=1,Object.defineProperty($s,"__esModule",{value:!0});const e=ye(),t=Se(),r=fl(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${i}, ${c})`):s.fail((0,e._)`${u} !== ${i}`)}};return $s.default=o,$s}var Es={},Wh;function Tk(){if(Wh)return Es;Wh=1,Object.defineProperty(Es,"__esModule",{value:!0});const e=ye(),t=Se(),r=fl(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:g}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const h=c.length>=g.opts.loopEnum;let d;const p=()=>d??(d=(0,t.useFunc)(a,r.default));let w;if(h||l)w=a.let("valid"),s.block$data(w,m);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);w=(0,e.or)(...c.map((f,b)=>y(_,b)))}s.pass(w);function m(){a.assign(w,!1),a.forOf("v",u,_=>a.if((0,e._)`${p()}(${i}, ${_})`,()=>a.assign(w,!0).break()))}function y(_,f){const b=c[f];return typeof b=="object"&&b!==null?(0,e._)`${p()}(${i}, ${_}[${f}])`:(0,e._)`${i} === ${b}`}}};return Es.default=o,Es}var Kh;function $k(){if(Kh)return ms;Kh=1,Object.defineProperty(ms,"__esModule",{value:!0});const e=mk(),t=gk(),r=_k(),n=yk(),o=wk(),s=bk(),a=kk(),i=Sk(),l=Ck(),c=Tk(),u=[e.default,t.default,r.default,n.default,o.default,s.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return ms.default=u,ms}var Is={},ln={},Yh;function Qh(){if(Yh)return ln;Yh=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.validateAdditionalItems=void 0;const e=ye(),t=Se(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:a,it:i}=s,{items:l}=a;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,a){const{gen:i,schema:l,data:c,keyword:u,it:g}=s;g.items=!0;const h=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${h} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(g,l)){const p=i.var("valid",(0,e._)`${h} <= ${a.length}`);i.if((0,e.not)(p),()=>d(p)),s.ok(p)}function d(p){i.forRange("i",a.length,h,w=>{s.subschema({keyword:u,dataProp:w,dataPropType:t.Type.Num},p),g.allErrors||i.if((0,e.not)(p),()=>i.break())})}}return ln.validateAdditionalItems=o,ln.default=n,ln}var xs={},cn={},Xh;function em(){if(Xh)return cn;Xh=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.validateTuple=void 0;const e=ye(),t=Se(),r=Ot(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:a,it:i}=s;if(Array.isArray(a))return o(s,"additionalItems",a);i.items=!0,!(0,t.alwaysValidSchema)(i,a)&&s.ok((0,r.validateArray)(s))}};function o(s,a,i=s.schema){const{gen:l,parentSchema:c,data:u,keyword:g,it:h}=s;w(c),h.opts.unevaluated&&i.length&&h.items!==!0&&(h.items=t.mergeEvaluated.items(l,i.length,h.items));const d=l.name("valid"),p=l.const("len",(0,e._)`${u}.length`);i.forEach((m,y)=>{(0,t.alwaysValidSchema)(h,m)||(l.if((0,e._)`${p} > ${y}`,()=>s.subschema({keyword:g,schemaProp:y,dataProp:y},d)),s.ok(d))});function w(m){const{opts:y,errSchemaPath:_}=h,f=i.length,b=f===m.minItems&&(f===m.maxItems||m[a]===!1);if(y.strictTuples&&!b){const k=`"${g}" is ${f}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(h,k,y.strictTuples)}}}return cn.validateTuple=o,cn.default=n,cn}var tm;function Ek(){if(tm)return xs;tm=1,Object.defineProperty(xs,"__esModule",{value:!0});const e=em(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return xs.default=t,xs}var Rs={},rm;function Ik(){if(rm)return Rs;rm=1,Object.defineProperty(Rs,"__esModule",{value:!0});const e=ye(),t=Se(),r=Ot(),n=Qh(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return Rs.default=s,Rs}var Ps={},nm;function xk(){if(nm)return Ps;nm=1,Object.defineProperty(Ps,"__esModule",{value:!0});const e=ye(),t=Se(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:a,parentSchema:i,data:l,it:c}=o;let u,g;const{minContains:h,maxContains:d}=i;c.opts.next?(u=h===void 0?1:h,g=d):u=1;const p=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:g}),g===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(g!==void 0&&u>g){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let f=(0,e._)`${p} >= ${u}`;g!==void 0&&(f=(0,e._)`${f} && ${p} <= ${g}`),o.pass(f);return}c.items=!0;const w=s.name("valid");g===void 0&&u===1?y(w,()=>s.if(w,()=>s.break())):u===0?(s.let(w,!0),g!==void 0&&s.if((0,e._)`${l}.length > 0`,m)):(s.let(w,!1),m()),o.result(w,()=>o.reset());function m(){const f=s.name("_valid"),b=s.let("count",0);y(f,()=>s.if(f,()=>_(b)))}function y(f,b){s.forRange("i",0,p,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},f),b()})}function _(f){s.code((0,e._)`${f}++`),g===void 0?s.if((0,e._)`${f} >= ${u}`,()=>s.assign(w,!0).break()):(s.if((0,e._)`${f} > ${g}`,()=>s.assign(w,!1).break()),u===1?s.assign(w,!0):s.if((0,e._)`${f} >= ${u}`,()=>s.assign(w,!0)))}}};return Ps.default=n,Ps}var hl={},om;function Rk(){return om||(om=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=ye(),r=Se(),n=Ot();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const g=c===1?"property":"properties";return(0,t.str)`must have ${g} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:g}})=>(0,t._)`{property: ${l},
76
+ missingProperty: ${g},
77
+ depsCount: ${c},
78
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const g in l){if(g==="__proto__")continue;const h=Array.isArray(l[g])?c:u;h[g]=l[g]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:g,it:h}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const p in c){const w=c[p];if(w.length===0)continue;const m=(0,n.propertyInData)(u,g,p,h.opts.ownProperties);l.setParams({property:p,depsCount:w.length,deps:w.join(", ")}),h.allErrors?u.if(m,()=>{for(const y of w)(0,n.checkReportMissingProp)(l,y)}):(u.if((0,t._)`${m} && (${(0,n.checkMissingProp)(l,w,d)})`),(0,n.reportMissingProp)(l,d),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:g,keyword:h,it:d}=l,p=u.name("valid");for(const w in c)(0,r.alwaysValidSchema)(d,c[w])||(u.if((0,n.propertyInData)(u,g,w,d.opts.ownProperties),()=>{const m=l.subschema({keyword:h,schemaProp:w},p);l.mergeValidEvaluated(m,p)},()=>u.var(p,!0)),l.ok(p))}e.validateSchemaDeps=i,e.default=o})(hl)),hl}var Os={},sm;function Pk(){if(sm)return Os;sm=1,Object.defineProperty(Os,"__esModule",{value:!0});const e=ye(),t=Se(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:a,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,a))return;const c=s.name("valid");s.forIn("key",i,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return Os.default=n,Os}var Ms={},am;function im(){if(am)return Ms;am=1,Object.defineProperty(Ms,"__esModule",{value:!0});const e=Ot(),t=ye(),r=hr(),n=Se(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,t._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:g,it:h}=a;if(!g)throw new Error("ajv implementation error");const{allErrors:d,opts:p}=h;if(h.props=!0,p.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(h,l))return;const w=(0,e.allSchemaProperties)(c.properties),m=(0,e.allSchemaProperties)(c.patternProperties);y(),a.ok((0,t._)`${g} === ${r.default.errors}`);function y(){i.forIn("key",u,S=>{!w.length&&!m.length?b(S):i.if(_(S),()=>b(S))})}function _(S){let C;if(w.length>8){const I=(0,n.schemaRefOrVal)(h,c.properties,"properties");C=(0,e.isOwnProperty)(i,I,S)}else w.length?C=(0,t.or)(...w.map(I=>(0,t._)`${S} === ${I}`)):C=t.nil;return m.length&&(C=(0,t.or)(C,...m.map(I=>(0,t._)`${(0,e.usePattern)(a,I)}.test(${S})`))),(0,t.not)(C)}function f(S){i.code((0,t._)`delete ${u}[${S}]`)}function b(S){if(p.removeAdditional==="all"||p.removeAdditional&&l===!1){f(S);return}if(l===!1){a.setParams({additionalProperty:S}),a.error(),d||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(h,l)){const C=i.name("valid");p.removeAdditional==="failing"?(k(S,C,!1),i.if((0,t.not)(C),()=>{a.reset(),f(S)})):(k(S,C),d||i.if((0,t.not)(C),()=>i.break()))}}function k(S,C,I){const x={keyword:"additionalProperties",dataProp:S,dataPropType:n.Type.Str};I===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(x,C)}}};return Ms.default=s,Ms}var Ns={},lm;function Ok(){if(lm)return Ns;lm=1,Object.defineProperty(Ns,"__esModule",{value:!0});const e=is(),t=Ot(),r=Se(),n=im(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const g=(0,t.allSchemaProperties)(i);for(const m of g)u.definedProperties.add(m);u.opts.unevaluated&&g.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(g),u.props));const h=g.filter(m=>!(0,r.alwaysValidSchema)(u,i[m]));if(h.length===0)return;const d=a.name("valid");for(const m of h)p(m)?w(m):(a.if((0,t.propertyInData)(a,c,m,u.opts.ownProperties)),w(m),u.allErrors||a.else().var(d,!0),a.endIf()),s.it.definedProperties.add(m),s.ok(d);function p(m){return u.opts.useDefaults&&!u.compositeRule&&i[m].default!==void 0}function w(m){s.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}}};return Ns.default=o,Ns}var As={},cm;function Mk(){if(cm)return As;cm=1,Object.defineProperty(As,"__esModule",{value:!0});const e=Ot(),t=ye(),r=Se(),n=Se(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:g}=u,h=(0,e.allSchemaProperties)(i),d=h.filter(b=>(0,r.alwaysValidSchema)(u,i[b]));if(h.length===0||d.length===h.length&&(!u.opts.unevaluated||u.props===!0))return;const p=g.strictSchema&&!g.allowMatchingProperties&&c.properties,w=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:m}=u;y();function y(){for(const b of h)p&&_(b),u.allErrors?f(b):(a.var(w,!0),f(b),a.if(w))}function _(b){for(const k in p)new RegExp(b).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function f(b){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,b)}.test(${k})`,()=>{const S=d.includes(b);S||s.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:n.Type.Str},w),u.opts.unevaluated&&m!==!0?a.assign((0,t._)`${m}[${k}]`,!0):!S&&!u.allErrors&&a.if((0,t.not)(w),()=>a.break())})})}}};return As.default=o,As}var qs={},um;function Nk(){if(um)return qs;um=1,Object.defineProperty(qs,"__esModule",{value:!0});const e=Se(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return qs.default=t,qs}var Ls={},dm;function Ak(){if(dm)return Ls;dm=1,Object.defineProperty(Ls,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ot().validateUnion,error:{message:"must match a schema in anyOf"}};return Ls.default=t,Ls}var js={},pm;function qk(){if(pm)return js;pm=1,Object.defineProperty(js,"__esModule",{value:!0});const e=ye(),t=Se(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:a,parentSchema:i,it:l}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=s.let("valid",!1),g=s.let("passing",null),h=s.name("_valid");o.setParams({passing:g}),s.block(d),o.result(u,()=>o.reset(),()=>o.error(!0));function d(){c.forEach((p,w)=>{let m;(0,t.alwaysValidSchema)(l,p)?s.var(h,!0):m=o.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},h),w>0&&s.if((0,e._)`${h} && ${u}`).assign(u,!1).assign(g,(0,e._)`[${g}, ${w}]`).else(),s.if(h,()=>{s.assign(u,!0),s.assign(g,w),m&&o.mergeEvaluated(m,e.Name)})})}}};return js.default=n,js}var Us={},fm;function Lk(){if(fm)return Us;fm=1,Object.defineProperty(Us,"__esModule",{value:!0});const e=Se(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const a=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(s,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return Us.default=t,Us}var zs={},hm;function jk(){if(hm)return zs;hm=1,Object.defineProperty(zs,"__esModule",{value:!0});const e=ye(),t=Se(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:a,parentSchema:i,it:l}=s;i.then===void 0&&i.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const g=a.let("valid",!0),h=a.name("_valid");if(d(),s.reset(),c&&u){const w=a.let("ifClause");s.setParams({ifClause:w}),a.if(h,p("then",w),p("else",w))}else c?a.if(h,p("then")):a.if((0,e.not)(h),p("else"));s.pass(g,()=>s.error(!0));function d(){const w=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},h);s.mergeEvaluated(w)}function p(w,m){return()=>{const y=s.subschema({keyword:w},h);a.assign(g,h),s.mergeValidEvaluated(y,g),m?a.assign(m,(0,e._)`${w}`):s.setParams({ifClause:w})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return zs.default=n,zs}var Ds={},mm;function Uk(){if(mm)return Ds;mm=1,Object.defineProperty(Ds,"__esModule",{value:!0});const e=Se(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return Ds.default=t,Ds}var gm;function zk(){if(gm)return Is;gm=1,Object.defineProperty(Is,"__esModule",{value:!0});const e=Qh(),t=Ek(),r=em(),n=Ik(),o=xk(),s=Rk(),a=Pk(),i=im(),l=Ok(),c=Mk(),u=Nk(),g=Ak(),h=qk(),d=Lk(),p=jk(),w=Uk();function m(y=!1){const _=[u.default,g.default,h.default,d.default,p.default,w.default,a.default,i.default,s.default,l.default,c.default];return y?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return Is.default=m,Is}var Zs={},Fs={},vm;function Dk(){if(vm)return Fs;vm=1,Object.defineProperty(Fs,"__esModule",{value:!0});const e=ye(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:g,errSchemaPath:h,schemaEnv:d,self:p}=u;if(!g.validateFormats)return;i?w():m();function w(){const y=s.scopeValue("formats",{ref:p.formats,code:g.code.formats}),_=s.const("fDef",(0,e._)`${y}[${c}]`),f=s.let("fType"),b=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(f,(0,e._)`${_}.type || "string"`).assign(b,(0,e._)`${_}.validate`),()=>s.assign(f,(0,e._)`"string"`).assign(b,_)),n.fail$data((0,e.or)(k(),S()));function k(){return g.strictSchema===!1?e.nil:(0,e._)`${c} && !${b}`}function S(){const C=d.$async?(0,e._)`(${_}.async ? await ${b}(${a}) : ${b}(${a}))`:(0,e._)`${b}(${a})`,I=(0,e._)`(typeof ${b} == "function" ? ${C} : ${b}.test(${a}))`;return(0,e._)`${b} && ${b} !== true && ${f} === ${o} && !${I}`}}function m(){const y=p.formats[l];if(!y){k();return}if(y===!0)return;const[_,f,b]=S(y);_===o&&n.pass(C());function k(){if(g.strictSchema===!1){p.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${h}"`}}function S(I){const x=I instanceof RegExp?(0,e.regexpCode)(I):g.code.formats?(0,e._)`${g.code.formats}${(0,e.getProperty)(l)}`:void 0,M=s.scopeValue("formats",{key:l,ref:I,code:x});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${M}.validate`]:["string",I,M]}function C(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,e._)`await ${b}(${a})`}return typeof f=="function"?(0,e._)`${b}(${a})`:(0,e._)`${b}.test(${a})`}}}};return Fs.default=r,Fs}var _m;function Zk(){if(_m)return Zs;_m=1,Object.defineProperty(Zs,"__esModule",{value:!0});const t=[Dk().default];return Zs.default=t,Zs}var jr={},ym;function Fk(){return ym||(ym=1,Object.defineProperty(jr,"__esModule",{value:!0}),jr.contentVocabulary=jr.metadataVocabulary=void 0,jr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],jr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),jr}var wm;function Vk(){if(wm)return ps;wm=1,Object.defineProperty(ps,"__esModule",{value:!0});const e=hk(),t=$k(),r=zk(),n=Zk(),o=Fk(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ps.default=s,ps}var Vs={},Qn={},bm;function Hk(){if(bm)return Qn;bm=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(Qn.DiscrError=e={})),Qn}var km;function Bk(){if(km)return Vs;km=1,Object.defineProperty(Vs,"__esModule",{value:!0});const e=ye(),t=Hk(),r=ul(),n=us(),o=Se(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:g,it:h}=i,{oneOf:d}=g;if(!h.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=u.propertyName;if(typeof p!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const w=l.let("valid",!1),m=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(p)}`);l.if((0,e._)`typeof ${m} == "string"`,()=>y(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:p})),i.ok(w);function y(){const b=f();l.if(!1);for(const k in b)l.elseIf((0,e._)`${m} === ${k}`),l.assign(w,_(b[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:p}),l.endIf()}function _(b){const k=l.name("valid"),S=i.subschema({keyword:"oneOf",schemaProp:b},k);return i.mergeEvaluated(S,e.Name),k}function f(){var b;const k={},S=I(g);let C=!0;for(let P=0;P<d.length;P++){let U=d[P];if(U?.$ref&&!(0,o.schemaHasRulesButRef)(U,h.self.RULES)){const F=U.$ref;if(U=r.resolveRef.call(h.self,h.schemaEnv.root,h.baseId,F),U instanceof r.SchemaEnv&&(U=U.schema),U===void 0)throw new n.default(h.opts.uriResolver,h.baseId,F)}const z=(b=U?.properties)===null||b===void 0?void 0:b[p];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);C=C&&(S||I(U)),x(z,P)}if(!C)throw new Error(`discriminator: "${p}" must be required`);return k;function I({required:P}){return Array.isArray(P)&&P.includes(p)}function x(P,U){if(P.const)M(P.const,U);else if(P.enum)for(const z of P.enum)M(z,U);else throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`)}function M(P,U){if(typeof P!="string"||P in k)throw new Error(`discriminator: "${p}" values must be unique strings`);k[P]=U}}}};return Vs.default=a,Vs}const Jk={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var Sm;function Cm(){return Sm||(Sm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=dk(),n=Vk(),o=Bk(),s=Jk,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(p=>this.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(p,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=is();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=ye();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var g=cl();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return g.default}});var h=us();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})(ts,ts.exports)),ts.exports}var Gk=Cm(),Hs={exports:{}},ml={},Tm;function Wk(){return Tm||(Tm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(P,U){return{validate:P,compare:U}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(h(!0),d),"iso-time":t(l(),u),"iso-date-time":t(h(),p),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:M,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:f,int32:{type:"number",validate:S},int64:{type:"number",validate:C},float:{type:"number",validate:I},double:{type:"number",validate:I},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,p),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(P){return P%4===0&&(P%100!==0||P%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(P){const U=n.exec(P);if(!U)return!1;const z=+U[1],F=+U[2],te=+U[3];return F>=1&&F<=12&&te>=1&&te<=(F===2&&r(z)?29:o[F])}function a(P,U){if(P&&U)return P>U?1:P<U?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(P){return function(z){const F=i.exec(z);if(!F)return!1;const te=+F[1],ie=+F[2],se=+F[3],ee=F[4],pe=F[5]==="-"?-1:1,V=+(F[6]||0),O=+(F[7]||0);if(V>23||O>59||P&&!ee)return!1;if(te<=23&&ie<=59&&se<60)return!0;const Z=ie-O*pe,j=te-V*pe-(Z<0?1:0);return(j===23||j===-1)&&(Z===59||Z===-1)&&se<61}}function c(P,U){if(!(P&&U))return;const z=new Date("2020-01-01T"+P).valueOf(),F=new Date("2020-01-01T"+U).valueOf();if(z&&F)return z-F}function u(P,U){if(!(P&&U))return;const z=i.exec(P),F=i.exec(U);if(z&&F)return P=z[1]+z[2]+z[3],U=F[1]+F[2]+F[3],P>U?1:P<U?-1:0}const g=/t|\s/i;function h(P){const U=l(P);return function(F){const te=F.split(g);return te.length===2&&s(te[0])&&U(te[1])}}function d(P,U){if(!(P&&U))return;const z=new Date(P).valueOf(),F=new Date(U).valueOf();if(z&&F)return z-F}function p(P,U){if(!(P&&U))return;const[z,F]=P.split(g),[te,ie]=U.split(g),se=a(z,te);if(se!==void 0)return se||c(F,ie)}const w=/\/|:/,m=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function y(P){return w.test(P)&&m.test(P)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function f(P){return _.lastIndex=0,_.test(P)}const b=-2147483648,k=2**31-1;function S(P){return Number.isInteger(P)&&P<=k&&P>=b}function C(P){return Number.isInteger(P)}function I(){return!0}const x=/[^\\]\\Z/;function M(P){if(x.test(P))return!1;try{return new RegExp(P),!0}catch{return!1}}})(ml)),ml}var gl={},$m;function Kk(){return $m||($m=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Cm(),r=ye(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:g,it:h}=i,{opts:d,self:p}=h;if(!d.validateFormats)return;const w=new t.KeywordCxt(h,p.RULES.all.format.definition,"format");w.$data?m():y();function m(){const f=l.scopeValue("formats",{ref:p.formats,code:d.code.formats}),b=l.const("fmt",(0,r._)`${f}[${w.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,_(b)))}function y(){const f=w.schema,b=p.formats[f];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${g}": format "${f}" does not define "compare" function`);const k=l.scopeValue("formats",{key:f,ref:b,code:d.code.formats?(0,r._)`${d.code.formats}${(0,r.getProperty)(f)}`:void 0});i.fail$data(_(k))}function _(f){return(0,r._)`${f}.compare(${c}, ${u}) ${o[g].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(gl)),gl}var Em;function Yk(){return Em||(Em=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Wk(),n=Kk(),o=ye(),s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[g,h]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],d=u.formats||r.formatNames;return l(c,d,g,h),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const h=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!h)throw new Error(`Unknown format "${c}"`);return h};function l(c,u,g,h){var d,p;(d=(p=c.opts.code).formats)!==null&&d!==void 0||(p.formats=(0,o._)`require("ajv-formats/dist/formats").${h}`);for(const w of u)c.addFormat(w,g[w])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(Hs,Hs.exports)),Hs.exports}var Qk=Yk();const Xk=dd(Qk);function eS(){const e=new Gk.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Xk(e),e}class tS{constructor(t){this._ajv=t??eS()}getValidator(t){var r;const n="$id"in t&&typeof t.$id=="string"?(r=this._ajv.getSchema(t.$id))!==null&&r!==void 0?r:this._ajv.compile(t):this._ajv.compile(t);return o=>n(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}class rS{constructor(t){this._client=t}async*callToolStream(t,r=Jn,n){var o;const s=this._client,a={...n,task:(o=n?.task)!==null&&o!==void 0?o:s.isToolTask(t.name)?{}:void 0},i=s.requestStream({method:"tools/call",params:t},r,a),l=s.getToolOutputValidator(t.name);for await(const c of i){if(c.type==="result"&&l){const u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new de(ge.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{const g=l(u.structuredContent);if(!g.valid){yield{type:"error",error:new de(ge.InvalidParams,`Structured content does not match the tool's output schema: ${g.errorMessage}`)};return}}catch(g){if(g instanceof de){yield{type:"error",error:g};return}yield{type:"error",error:new de(ge.InvalidParams,`Failed to validate structured content: ${g instanceof Error?g.message:String(g)}`)};return}}yield c}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function nS(e,t,r){var n;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!(!((n=e.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function oS(e,t,r){var n,o;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!(!((n=e.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!(!((o=e.elicitation)===null||o===void 0)&&o.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function Bs(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Bs(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)Bs(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)Bs(r,t)}}function sS(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class Js extends ek{constructor(t,r){var n,o;super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(o=r?.jsonSchemaValidator)!==null&&o!==void 0?o:new tS}get experimental(){return this._experimental||(this._experimental={tasks:new rS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=tk(this._capabilities,t)}setRequestHandler(t,r){var n,o,s;const a=eh(t),i=a?.method;if(!i)throw new Error("Schema is missing a method literal");let l;if(es(i)){const u=i,g=(n=u._zod)===null||n===void 0?void 0:n.def;l=(o=g?.value)!==null&&o!==void 0?o:u.value}else{const u=i,g=u._def;l=(s=g?.value)!==null&&s!==void 0?s:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");const c=l;if(c==="elicitation/create"){const u=async(g,h)=>{var d,p,w;const m=fr(Ei,g);if(!m.success){const x=m.error instanceof Error?m.error.message:String(m.error);throw new de(ge.InvalidParams,`Invalid elicitation request: ${x}`)}const{params:y}=m.data,_=(d=y.mode)!==null&&d!==void 0?d:"form",{supportsFormMode:f,supportsUrlMode:b}=sS(this._capabilities.elicitation);if(_==="form"&&!f)throw new de(ge.InvalidParams,"Client does not support form-mode elicitation requests");if(_==="url"&&!b)throw new de(ge.InvalidParams,"Client does not support URL-mode elicitation requests");const k=await Promise.resolve(r(g,h));if(y.task){const x=fr(Bn,k);if(!x.success){const M=x.error instanceof Error?x.error.message:String(x.error);throw new de(ge.InvalidParams,`Invalid task creation result: ${M}`)}return x.data}const S=fr(Ii,k);if(!S.success){const x=S.error instanceof Error?S.error.message:String(S.error);throw new de(ge.InvalidParams,`Invalid elicitation result: ${x}`)}const C=S.data,I=_==="form"?y.requestedSchema:void 0;if(_==="form"&&C.action==="accept"&&C.content&&I&&!((w=(p=this._capabilities.elicitation)===null||p===void 0?void 0:p.form)===null||w===void 0)&&w.applyDefaults)try{Bs(I,C.content)}catch{}return C};return super.setRequestHandler(t,u)}if(c==="sampling/createMessage"){const u=async(g,h)=>{const d=fr(Ti,g);if(!d.success){const y=d.error instanceof Error?d.error.message:String(d.error);throw new de(ge.InvalidParams,`Invalid sampling request: ${y}`)}const{params:p}=d.data,w=await Promise.resolve(r(g,h));if(p.task){const y=fr(Bn,w);if(!y.success){const _=y.error instanceof Error?y.error.message:String(y.error);throw new de(ge.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}const m=fr($i,w);if(!m.success){const y=m.error instanceof Error?m.error.message:String(m.error);throw new de(ge.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(t,u)}return super.setRequestHandler(t,r)}assertCapability(t,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[t]))throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:zo,capabilities:this._capabilities,clientInfo:this._clientInfo}},H0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!i4.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var r,n,o,s,a;switch(t){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.resources))throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){var r;switch(t){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){var r,n;nS((n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,t,"Server")}assertTaskHandlerCapability(t){var r;this._capabilities&&oS((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Mr,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},df,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Mr,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},nf,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},rf,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Y0,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Q0,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},X0,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Mr,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Mr,r)}async callTool(t,r=Jn,n){if(this.isToolTaskRequired(t.name))throw new de(ge.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new de(ge.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new de(ge.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof de?a:new de(ge.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){var r,n,o,s;return!((s=(o=(n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests)===null||o===void 0?void 0:o.tools)===null||s===void 0)&&s.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){var r;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const n of t){if(n.outputSchema){const s=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,s)}const o=(r=n.execution)===null||r===void 0?void 0:r.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(n.name),o==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},af,r);return this.cacheToolMetadata(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Im extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(xm(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(xm(this),r)}}function aS(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function vl(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(vl).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${vl(e.cause)}`:e.message:`${e}`}function xm(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Rm=e=>{throw TypeError(e)},_l=(e,t,r)=>t.has(e)||Rm("Cannot "+r),ke=(e,t,r)=>(_l(e,t,"read from private field"),r?r.call(e):t.get(e)),Fe=(e,t,r)=>t.has(e)?Rm("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),je=(e,t,r,n)=>(_l(e,t,"write to private field"),t.set(e,r),r),er=(e,t,r)=>(_l(e,t,"access private method"),r),ut,Ur,un,Gs,Ws,Xn,dn,eo,gr,pn,fn,hn,to,Mt,yl,wl,bl,Pm,kl,Sl,ro,Cl,Tl;class Ks extends EventTarget{constructor(t,r){var n,o;super(),Fe(this,Mt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Fe(this,ut),Fe(this,Ur),Fe(this,un),Fe(this,Gs),Fe(this,Ws),Fe(this,Xn),Fe(this,dn),Fe(this,eo,null),Fe(this,gr),Fe(this,pn),Fe(this,fn,null),Fe(this,hn,null),Fe(this,to,null),Fe(this,wl,async s=>{var a;ke(this,pn).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){er(this,Mt,ro).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?je(this,un,new URL(s.url)):je(this,un,void 0),c!==200){er(this,Mt,ro).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){er(this,Mt,ro).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(ke(this,ut)===this.CLOSED)return;je(this,ut,this.OPEN);const g=new Event("open");if((a=ke(this,to))==null||a.call(this,g),this.dispatchEvent(g),typeof i!="object"||!i||!("getReader"in i)){er(this,Mt,ro).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const h=new TextDecoder,d=i.getReader();let p=!0;do{const{done:w,value:m}=await d.read();m&&ke(this,pn).feed(h.decode(m,{stream:!w})),w&&(p=!1,ke(this,pn).reset(),er(this,Mt,Cl).call(this))}while(p)}),Fe(this,bl,s=>{je(this,gr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&er(this,Mt,Cl).call(this,vl(s))}),Fe(this,kl,s=>{typeof s.id=="string"&&je(this,eo,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:ke(this,un)?ke(this,un).origin:ke(this,Ur).origin,lastEventId:s.id||""});ke(this,hn)&&(!s.event||s.event==="message")&&ke(this,hn).call(this,a),this.dispatchEvent(a)}),Fe(this,Sl,s=>{je(this,Xn,s)}),Fe(this,Tl,()=>{je(this,dn,void 0),ke(this,ut)===this.CONNECTING&&er(this,Mt,yl).call(this)});try{if(t instanceof URL)je(this,Ur,t);else if(typeof t=="string")je(this,Ur,new URL(t,iS()));else throw new Error("Invalid URL")}catch{throw aS("An invalid or illegal string was specified")}je(this,pn,Fc({onEvent:ke(this,kl),onRetry:ke(this,Sl)})),je(this,ut,this.CONNECTING),je(this,Xn,3e3),je(this,Ws,(n=r?.fetch)!=null?n:globalThis.fetch),je(this,Gs,(o=r?.withCredentials)!=null?o:!1),er(this,Mt,yl).call(this)}get readyState(){return ke(this,ut)}get url(){return ke(this,Ur).href}get withCredentials(){return ke(this,Gs)}get onerror(){return ke(this,fn)}set onerror(t){je(this,fn,t)}get onmessage(){return ke(this,hn)}set onmessage(t){je(this,hn,t)}get onopen(){return ke(this,to)}set onopen(t){je(this,to,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){ke(this,dn)&&clearTimeout(ke(this,dn)),ke(this,ut)!==this.CLOSED&&(ke(this,gr)&&ke(this,gr).abort(),je(this,ut,this.CLOSED),je(this,gr,void 0))}}ut=new WeakMap,Ur=new WeakMap,un=new WeakMap,Gs=new WeakMap,Ws=new WeakMap,Xn=new WeakMap,dn=new WeakMap,eo=new WeakMap,gr=new WeakMap,pn=new WeakMap,fn=new WeakMap,hn=new WeakMap,to=new WeakMap,Mt=new WeakSet,yl=function(){je(this,ut,this.CONNECTING),je(this,gr,new AbortController),ke(this,Ws)(ke(this,Ur),er(this,Mt,Pm).call(this)).then(ke(this,wl)).catch(ke(this,bl))},wl=new WeakMap,bl=new WeakMap,Pm=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...ke(this,eo)?{"Last-Event-ID":ke(this,eo)}:void 0},cache:"no-store",signal:(e=ke(this,gr))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},kl=new WeakMap,Sl=new WeakMap,ro=function(e,t){var r;ke(this,ut)!==this.CLOSED&&je(this,ut,this.CLOSED);const n=new Im("error",{code:t,message:e});(r=ke(this,fn))==null||r.call(this,n),this.dispatchEvent(n)},Cl=function(e,t){var r;if(ke(this,ut)===this.CLOSED)return;je(this,ut,this.CONNECTING);const n=new Im("error",{code:t,message:e});(r=ke(this,fn))==null||r.call(this,n),this.dispatchEvent(n),je(this,dn,setTimeout(ke(this,Tl),ke(this,Xn)))},Tl=new WeakMap,Ks.CONNECTING=0,Ks.OPEN=1,Ks.CLOSED=2;function iS(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class lS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class $l{constructor(t,r){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=L0(r?.fetch,r?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new kt("No auth provider");let r;try{r=await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(t=this.onerror)===null||t===void 0||t.call(this,n),n}if(r!=="AUTHORIZED")throw new kt;return await this._startOrAuth()}async _commonHeaders(){var t;const r={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(r.Authorization=`Bearer ${o.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Uo((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...r,...n})}_startOrAuth(){var t,r,n;const o=(n=(r=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((s,a)=>{this._eventSource=new Ks(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await o(i,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:g,scope:h}=Wo(u);this._resourceMetadataUrl=g,this._scope=h}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,a);return}const c=new lS(i.code,i.message,i);a(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){a(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let g;try{g=Or.parse(JSON.parse(u.data))}catch(h){(l=this.onerror)===null||l===void 0||l.call(this,h);return}(c=this.onmessage)===null||c===void 0||c.call(this,g)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new kt("No auth provider");if(await Nr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt("Failed to authorize")}async close(){var t,r,n;(t=this._abortController)===null||t===void 0||t.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t){var r,n,o,s;if(!this._endpoint)throw new Error("Not connected");try{const a=await this._commonHeaders();a.set("content-type","application/json");const i={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,i);if(!l.ok){const c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){const{resourceMetadataUrl:u,scope:g}=Wo(l);if(this._resourceMetadataUrl=u,this._scope=g,await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((o=l.body)===null||o===void 0?void 0:o.cancel())}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}setProtocolVersion(t){this._protocolVersion=t}}const cS="mcp";class Om{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._socket=new WebSocket(this._url,cS),this._socket.onerror=n=>{var o;const s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(s),(o=this.onerror)===null||o===void 0||o.call(this,s)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var o,s;let a;try{a=Or.parse(JSON.parse(n.data))}catch(i){(o=this.onerror)===null||o===void 0||o.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,a)}})}async close(){var t;(t=this._socket)===null||t===void 0||t.close()}send(t){return new Promise((r,n)=>{var o;if(!this._socket){n(new Error("Not connected"));return}(o=this._socket)===null||o===void 0||o.send(JSON.stringify(t)),r()})}}function Ys(){const e=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Ys=function(){return e},Ys()}(function(e,t){const r=Xe,n=Xe,o=e();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(n(429))/5)+parseInt(n(423))/6*(-parseInt(n(418))/7)+-parseInt(n(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ys,650197);const uS=()=>{const e=Xe,t={EGhzU:function(r,n){return r!==n},kIrDB:"undefined",llYQe:function(r,n){return r!==n},PZfJg:function(r,n){return r(n)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:t[e(407)](typeof window,t.kIrDB)?window:t.llYQe(typeof global,t.kIrDB)?global:typeof self!==e(398)?self:t.PZfJg(Function,t[e(399)])()},dS=(e,t,r)=>{const n=Xe,o=Xe,s={};s[n(410)]=o(398),s.dBkaX=function(i,l){return i===l},s[o(393)]="function";const a=s;typeof window!==a[o(410)]?e.postMessage(t,"*",r):o(428)in e&&a.dBkaX(typeof e.postMessage,a[n(393)])&&e.postMessage(t,r)};class Mm{constructor(t){const r=Xe;this[r(406)]=t}async start(){const t=Xe,r=Xe;this[t(406)]&&(this[t(406)][t(413)]=n=>{var o,s;const a=t,i=r;try{const l=Or[a(402)](n.data[a(400)]);(o=this[a(413)])==null||o.call(this,l,n[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,c)}},this._port[t(396)]=n=>{var o;const s=r,a=r,i=new Error(s(394)+JSON[a(395)](n));(o=this.onerror)==null||o.call(this,i)},this[t(406)][t(434)]())}async send(t,r){const n={lEyuq:function(o){return o()},YihNw:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=Xe,l=Xe;try{const c={};c[i(403)]=r?.[i(403)];const u={};u[l(400)]=t,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),n.lEyuq(o)}catch(c){const u=c instanceof Error?c:new Error(n.YihNw(String,c));(a=this[l(408)])==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=Xe,o=Xe;(t=this._port)==null||t[n(431)](),this._port=void 0,(r=this[o(420)])==null||r.call(this)}}class pS extends Mm{constructor(t,r=uS()){const n=Xe,o=Xe,s={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[n(391)]=t,this[o(401)]=r;const a=new MessageChannel;this[o(406)]=a.port1,s[o(426)](dS,this[n(401)],{endpoint:this[o(391)]},[a[o(414)]])}}function Xe(e,t){const r=Ys();return Xe=function(n,o){return n=n-(17*-491+-669+9407),r[n]},Xe(e,t)}(function(e,t){const r=Me,n=Me,o=e();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(n(357))/5+-parseInt(n(389))/6*(-parseInt(r(396))/7)+parseInt(n(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Qs,-763475+-52067*10+1724410);const fS=async(e,t,r)=>{var n;const o=Me,s=Me,a={};a[o(345)]="tools/list",a.rqstG="tools/call",a.WqUnk="resources/list",a[o(329)]=s(358),a[o(365)]=o(335),a.ookoz="resources/unsubscribe",a[o(385)]=o(340),a.VTIWq="prompts/list",a.SkoRK=o(376),a.QUtUV=o(388),a.XtowM=s(332);const i=a,{id:l,method:c,params:u}=r;let g={};switch(c){case i[s(345)]:g=await t.listTools(u);break;case i.rqstG:g=await t.callTool(u);break;case i[o(334)]:g=await t[o(350)](u);break;case i[s(329)]:g=await t.listResourceTemplates(u);break;case o(372):g=await t[o(383)](u);break;case i.HgYgW:g=await t.subscribeResource(u);break;case i.ookoz:g=await t.unsubscribeResource(u);break;case i[o(385)]:g=await t.getPrompt(u);break;case i.VTIWq:g=await t.listPrompts(u);break;case i[o(344)]:g=await t[o(376)]();break;case i.QUtUV:g=await t.complete(u);break;case o(390):g=await t[o(336)](u?.level);break}const h={};h[o(361)]=g,h[o(394)]=i[o(364)],h.id=l,await((n=e?.transport)==null?void 0:n[o(392)](h))},hS=async(e,t,r)=>{var n;const o=Me,s=Me,a={};a.jQBBS="sampling/createMessage",a.EZqgC="elicitation/create",a[o(370)]=s(376),a.aVeaL=s(332);const i=a,{id:l,method:c,params:u}=r;let g={};switch(c){case o(368):const d={};d.method=c,d[s(367)]=u,g=await t.request(d,ff);break;case i[s(391)]:const p={};p.method=c,p[s(367)]=u,g=await t[s(381)](p,$i);break;case i.EZqgC:const w={};w.method=c,w.params=u,g=await t.request(w,Ii);break;case i[s(370)]:const m={};m.method=c,g=await t[s(381)](m,Mr);break}const h={};return h[s(361)]=g,h.jsonrpc=i[s(387)],h.id=l,await((n=e?.[o(371)])==null?void 0:n.send(h)),g},mS=(e,t)=>{const r=Me,n={gXsjT:function(s,a){return s===a},oegpC:r(351),lZOUC:function(s,a,i,l){return s(a,i,l)},ifIKG:"2.0"},o=e._onrequest;e._onrequest=async(s,a)=>{var i,l,c,u,g;const h=r,d=r,{id:p,method:w}=s;try{n[h(333)](w,n.oegpC)?await o[h(386)](e,s,a):await n.lZOUC(fS,e,t,s)}catch(m){const{code:y,message:_,data:f}=m;try{if(y){const b={};b.code=y,b.message=_,b.data=f;const k={};k.error=b,k[h(394)]=n[d(331)],k.id=p,await((i=e?.transport)==null?void 0:i.send(k))}else(c=(l=e?.[d(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(b){(g=(u=e?.[h(371)])==null?void 0:u.onerror)==null||g.call(u,b)}}}},gS=(e,t)=>{const r=Me,n=Me,o={};o[r(363)]=function(a,i){return a!==i},o[r(398)]=r(353),o.hzhyg="notifications/cancelled";const s=o;e._onnotification=async a=>{var i,l;const c=r,u=n,{method:g,params:h}=a;if(s[c(363)](g,s[u(398)])&&(s[c(363)](g,s.hzhyg)||h?.forward))try{await t.notification(a)}catch(d){(l=(i=e?.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},vS=(e,t)=>async r=>{var n,o,s,a,i;const l=Me,c=Me,u={};u.SEmWX=l(332);const g=u;try{return await hS(e,t,r)}catch(h){const{code:d,message:p,data:w}=h;try{if(d){const m={};m[c(377)]=d,m.message=p,m.data=w;const y={};y[c(348)]=m,y.jsonrpc=g[l(338)],y.id=r.id,await((n=e?.transport)==null?void 0:n[c(392)](y))}else(s=(o=e?.transport)==null?void 0:o[c(339)])==null||s.call(o,h)}catch(m){(i=(a=e?.[l(371)])==null?void 0:a[c(339)])==null||i.call(a,m)}}},_S=(e,t)=>async r=>{var n,o,s;const a=Me,i=Me,l={};l.dtUgZ=function(h,d){return h!==d},l.jgCIb=a(353),l.uUjKY="2.0";const c=l,{method:u,params:g}=r;if(c.dtUgZ(u,c.jgCIb)&&(u!==a(400)||g?.forward))try{const h={...r};h[a(394)]=c[i(352)],await((n=t?.[a(371)])==null?void 0:n[a(392)](h))}catch(h){(s=(o=e?.[a(371)])==null?void 0:o[i(339)])==null||s.call(o,h)}};function Me(e,t){const r=Qs();return Me=function(n,o){return n=n-(-1017+-1439*-1+-97),r[n]},Me(e,t)}const yS=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Me,u=Me,g={};g[c(401)]=u(332);const h=g;try{await((n=t?.transport)==null?void 0:n.send(r))}catch(d){const{code:p,message:w,data:m}=d;try{if(p){const y={};y.code=p,y[c(399)]=w,y.data=m;const _={};_[c(348)]=y,_[c(394)]=h.OhJjz,_.id=r.id,await((o=e?.[c(371)])==null?void 0:o.send(_))}else(a=(s=e?.transport)==null?void 0:s[u(339)])==null||a.call(s,d)}catch(y){(l=(i=e?.transport)==null?void 0:i.onerror)==null||l.call(i,y)}}},El=()=>{const e=Me,t=Me,r={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},n=[],o=(c,u)=>{const g=Me,h=Me;if(u){const d=[];for(const p of n)try{d.push(p(c,u))}catch{}for(const p of d)if(r[g(379)](p,null))return p}else for(const d of n)try{r[h(343)](d,c)}catch{}},s=c=>{const u=Me;r[u(384)](typeof c,u(369))&&!n.includes(c)&&n.push(c)},a=c=>{const u=n.indexOf(c);u!==-1&&n.splice(u,1*-6854+-264+7119)},i=()=>{const c=Me;n[c(374)]=7102*1+5522+-526*24},l={};return l[e(346)]=o,l[t(330)]=s,l.removeListener=a,l[e(359)]=i,l},wS=e=>{const t=Me,r=Me,n={xwPeb:function(o){return o()},Mfvzm:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(326)](El);e._onresponse=o,e[t(395)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[r(326)](El);e[r(328)]=o,e.addRequestListener=s,e[r(354)]=a,e[r(341)]=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(375)](El);e[t(342)]=o,e[t(327)]=s,e.removeNotificationListener=a,e.clearNotificationListener=i}};function Qs(){const e=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return Qs=function(){return e},Qs()}const bS=(e,{beforeInit:t,afterInit:r}={})=>{const n=Me,o=Me,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:n(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(393)][n(402)](),e._notificationHandlers[n(402)](),s.tqDZP(typeof t,s[n(380)])&&t(),s[n(362)](e._onresponse.name,s[n(360)])&&(e[o(349)]=e._onresponse),s[n(347)](wS,e),e.addResponseListener(i=>{const l=o;e.originalOnResponse[l(386)](e,i)}),s.tqDZP(typeof r,s[o(380)])&&s[n(397)](r),e[o(327)](i=>{const{method:l}=i,c=a.get(l);s.tqDZP(typeof c,s.cjSoZ)&&c(i)})},kS=Ft,SS=Ft;(function(e,t){const r=Ft,n=Ft,o=e();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(n(398))/4+parseInt(r(390))/5*(parseInt(n(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(n(395))/9)+parseInt(n(399))/10*(parseInt(n(385))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Xs,-1*-881393+2*180895+1*-644809);function Ft(e,t){const r=Xs();return Ft=function(n,o){return n=n-(-1861+-499*4+4241),r[n]},Ft(e,t)}function Xs(){const e=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return Xs=function(){return e},Xs()}const CS=()=>{const e=Ft,t=Ft,r={};r.REzPF=function(o,s){return o&s},r.suJHI=function(o,s){return o===s},r[e(386)]=function(o,s){return o&s},r[t(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[t(391)]():n.dHTfU.replace(/[xy]/g,o=>{const s=e,a=e,i=n[s(392)](crypto[s(384)](new Uint8Array(8663+2*-4331))[741*2+-1385*-2+4252*-1],15);return(n.suJHI(o,"x")?i:n[a(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},TS=e=>{const t=Ft,r=Ft,n=new Uint8Array(e);return crypto.getRandomValues(n),Array[t(401)](n,o=>o[r(403)](-3*1739+-6509+2*5871)[t(387)](2,"0")).join("")},vr={};vr[kS(391)]=CS,vr[SS(396)]=TS;const yt=Vt;(function(e,t){const r=Vt,n=Vt,o=e();for(;;)try{if(parseInt(r(521))/1*(parseInt(n(499))/2)+parseInt(n(543))/3*(parseInt(n(514))/4)+parseInt(r(502))/5*(parseInt(n(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ea,1472653*1+-2*-897917+-2275789);const $S=(e,t)=>{const r=Vt,n=Vt,o={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};mS(e,t),gS(e,t);const s=vS(t,e),a=o[r(510)](yS,t,e),i=o[n(549)](_S,t,e);t[n(537)](s),t[r(519)](a),t.addNotificationListener(i),e[n(556)]=()=>{const l=n;t.removeRequestListener(s),t[l(530)](a),t[l(529)](i)}},Il=(e,t,r)=>{const n=Vt,o={pMiva:function(i,l){return i instanceof l},TeTEy:n(546),fyZbd:function(i,l,c){return i(l,c)}},s=()=>{var i;const l=n;o.pMiva(r,$l)&&((i=r._eventSource)==null||i.addEventListener(o[l(547)],()=>{var c;const u=l;(c=r[u(509)])==null||c[u(546)]()})),$S(e,t)},a={};a.afterInit=s,o.fyZbd(bS,t,a)},Nm=(e,t=vr.randomUUID())=>{const r=Vt,n=Vt,o={OfssH:function(u,g,h){return u(g,h)}},s={};s[r(528)]=t;const a=s,i={};i[r(528)]=t;const l={};l[n(558)]=i,l[r(534)]=r(524);const c={requestInit:l,eventSourceInit:{async fetch(u,g){const h=r,d=n,p=new Headers(g?.[h(558)]||{});Object.entries(a)[d(498)](([m,y])=>{p[d(527)](m,y)});const w={...g};return w[d(558)]=p,o.OfssH(fetch,u,w)},withCredentials:!0}};return e&&(c.requestInit[r(558)].Authorization=r(533)+e,a.Authorization="Bearer "+e),c},Am=(e,t=vr[yt(517)]())=>{const r=yt,n=yt,o={};o.nwQhY="include";const s=o,a={};a["stream-session-id"]=t;const i={};i.headers=a,i.credentials=s[r(520)];const l={};l[r(544)]=i;const c=l;return e&&(c.requestInit.headers[n(552)]=n(533)+e),c},xl=async(e,t,r)=>{const n=yt,o=yt,s={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},a=s.CFfFC(r);try{return await e[n(538)](a),a}catch(i){if(i instanceof kt){const l=await t();return await a[o(505)](l),await s[n(525)](xl,e,t,r)}else throw i}};function Vt(e,t){const r=ea();return Vt=function(n,o){return n=n-498,r[n]},Vt(e,t)}const qm=(e,t)=>{const r=yt,n=yt,o={};o.RsKXs=function(a,i){return a in i},o.PBhps="waitForOAuthCode",o[r(535)]="function",o[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=o;if(s.RsKXs(s[n(551)],e))return e[n(523)];if(typeof t===s.yTKoP)return t;throw new Error(s.RZhOv)},ES=async e=>{const t=yt,r=yt,n={TFSRn:function(x,M,P){return x(M,P)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(x){return x()},WIVYl:function(x,M,P,U){return x(M,P,U)},jniGY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:g}=e,h={};h.authProvider=l,h.requestInit=c,h.eventSourceInit=u;const d=h,p=i||vr.randomUUID(),w=n[t(506)](Nm,a,p);if(c){const x={...w.requestInit,...c};x.headers={...w[t(544)].headers,...c.headers},d.requestInit=x}else d[r(544)]=w.requestInit;if(u){const x={...w[t(559)],...u};d.eventSourceInit=x}else d.eventSourceInit=w.eventSourceInit;const m={};m.listChanged=!0;const y={};y.roots=m,y.sampling={},y[t(511)]={};const _=y,f={};f[r(536)]=n.HwvVa,f.version=t(526);const b={};b.capabilities=_;const k=new Js(f,b),S=()=>new $l(new URL(s),d);let C=n[r(504)](S);if(l){const x=n[t(506)](qm,l,g);C=await n[r(513)](xl,k,x,S)}else await k[t(538)](C);n[r(513)](Il,k,o,C),C[r(557)]=C[r(542)].searchParams[r(532)](n.jniGY);const I={};return I.transport=C,I.sessionId=C[t(557)],I};function ea(){const e=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return ea=function(){return e},ea()}const IS=async e=>{const t=yt,r=yt,n={Vajmx:t(500),biJOc:function(x){return x()},zXcpO:function(x,M,P){return x(M,P)},zDnjZ:function(x,M,P,U){return x(M,P,U)},FQMAh:function(x,M,P,U){return x(M,P,U)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:g}=e,h={};h.authProvider=l,h.requestInit=c,h.reconnectionOptions=u;const d=h,p=i||vr.randomUUID(),w=Am(a,p);if(c){const x={...w.requestInit,...c};x.headers={...w.requestInit.headers,...c.headers},d[t(544)]=x}else d.requestInit=w.requestInit;const m={};m.listChanged=!0;const y={};y[r(550)]=m,y.sampling={},y.elicitation={};const _=y,f={};f[t(536)]=n[r(508)],f[t(555)]="1.0.0";const b={};b.capabilities=_;const k=new Js(f,b),S=()=>new Ko(new URL(s),d);let C=n[t(503)](S);if(l){const x=n[t(501)](qm,l,g);C=await n.zDnjZ(xl,k,x,S)}else await k.connect(C);n.FQMAh(Il,k,o,C);const I={};return I.transport=C,I[r(557)]=C.sessionId,I},xS=async e=>{const t=yt,r=yt,n={QgzDy:t(540),jkaVB:function(y,_,f,b){return y(_,f,b)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l.listChanged=!0;const c={};c[t(550)]=l,c[t(515)]={},c[r(511)]={};const u=c,g={};g.name=n[r(548)],g[r(555)]=r(526);const h={};h.capabilities=u;const d=new Js(g,h),p=i||vr[r(517)](),w=new Om(new URL(s+t(522)+p+r(554)+a));await d.connect(w),n.jkaVB(Il,d,o,w);const m={};return m[t(512)]=w,m[r(557)]=p,m},no=dt,ta=dt;function dt(e,t){const r=ra();return dt=function(n,o){return n=n-(-16761+51*337),r[n]},dt(e,t)}(function(e,t){const r=dt,n=dt,o=e();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(n(449))/5)+-parseInt(n(455))/6+-parseInt(r(427))/7+-parseInt(n(438))/8*(parseInt(n(459))/9)+parseInt(r(430))/10*(parseInt(n(436))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ra,-220880+1*-333337+-2*-384996);function ra(){const e=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return ra=function(){return e},ra()}const RS=()=>vr.randomBytes(3485*1+-261+-3184);class PC{constructor(t){const r=dt,n=dt;this._callBackPromise={};const{clientMetadata:o,state:s,redirectCallback:a,getAuthCodeByState:i,waitForOAuthCode:l}=t;this[r(428)]=o,this[r(454)]=o[r(445)][0],this._state=s||RS(),this._redirectCallback=a||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[n(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=dt,c=dt,u={qITTp:function(p,w,m){return p(w,m)},qcFPW:l(452)},g=await u.qITTp(fetch,t,{method:u[l(453)]});!g.ok&&((n=(r=this._callBackPromise).reject)==null||n.call(r,c(446)+g.statusText));const h=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!h.ok){(s=(o=this[l(433)]).reject)==null||s.call(o,"Failed to fetch auth code: "+h.statusText);return}const d=await h[l(431)]();(i=(a=this[c(433)])[l(456)])==null||i.call(a,d[l(432)])}async getAuthCodeByStateFunction(t,r){const n=dt,o=dt,s={};s.tuSmb=n(429);const a=s,i={};i[n(460)]=a.tuSmb;const l={};return l[o(441)]=r,fetch(t,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const t=dt,r=this[t(433)];return()=>new Promise((n,o)=>{const s=t;r.resolve=n,r[s(434)]=o})}get redirectUrl(){return this[dt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[no(447)](){return this[no(444)]}[ta(435)](t){const r=no;this[r(444)]=t}[ta(457)](){return this[ta(439)]}saveTokens(t){this._tokens=t}[ta(450)](t){this[no(443)](t)}saveCodeVerifier(t){this._codeVerifier=t}codeVerifier(){if(!this[no(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(e,t){for(var r=oa,n=oa,o=e();;)try{var s=parseInt(r(361))/1*(parseInt(n(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(n(354))/6*(parseInt(r(360))/7)+parseInt(n(362))/8+parseInt(n(364))/9+-parseInt(n(356))/10*(parseInt(r(355))/11);if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(na,-73523*-3+1*-407717+530518);function na(){var e=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return na=function(){return e},na()}function oa(e,t){var r=na();return oa=function(n,o){n=n-(-1*-642+503*-5+2227);var s=r[n];return s},oa(e,t)}class PS{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Js(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:a,onError:i}=t;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:o};let g;return await(async()=>{const{transport:d,sessionId:p}=s==="sse"?await ES(u):s==="socket"?await xS(u):await IS(u);d.onerror=async w=>{i?.(w)},g={transport:d,sessionId:p}})(),g}const l=new URL(r);let c;if(s==="channel"&&(c=new pS(r),await this.client.connect(c)),s==="sse"){const u=Nm(n,o);c=new $l(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Om(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=Am(n,o);c=new Ko(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,Jn,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(Ei,t)}onCreateMessage(t){this.client.setRequestHandler(Ti,t)}onListRoots(t){this.client.setRequestHandler(pf,t)}onToolListChanged(t){this.client.setNotificationHandler(lf,t)}onPromptListChanged(t){this.client.setNotificationHandler(of,t)}onResourceListChanged(t){this.client.setNotificationHandler(ef,t)}onResourceUpdated(t){this.client.setNotificationHandler(tf,t)}onLoggingMessage(t){this.client.setNotificationHandler(uf,t)}async onPagehide(t){t.persisted||(OS(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const OS=e=>e instanceof Ko,Lm=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const a=async(i,l)=>e.callTool({name:n,arguments:i},{signal:l?.abortSignal});t[n]=td({description:o,inputSchema:Rn({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function MS(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
79
+
80
+ # 工具调用
81
+
82
+ `;return r+=`你可以根据需要调用以下工具:
83
+
84
+ `,r+=`<tools>
85
+ `,t.forEach(([n,o])=>{const s=o,a=s.description||"无描述",i=s.parameters||s.inputSchema||{};r+=`${JSON.stringify({name:n,description:a,parameters:i},null,2)}
86
+ `}),r+=`</tools>
87
+
88
+ `,r+=`## 工具调用格式
89
+
90
+ `,r+=`要调用工具,请使用以下 XML 格式:
91
+ `,r+=`Thought: [你的思考过程]
92
+ `,r+=`<tool_call>{"name": "toolName", "arguments": {"arg1": "value1"}}</tool_call>
93
+
94
+ `,r+=`工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
95
+
96
+ `,r+=`## 使用示例
97
+
98
+ `,r+=`如果用户要求"获取今天的日期",你可以这样调用工具:
99
+ `,r+=`Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
100
+ `,r+=`<tool_call>{"name": "get-today", "arguments": {}}</tool_call>
101
+
102
+ `,r+=`然后等待工具返回结果(Observation),再根据结果给出最终答案。
103
+
104
+ `,r+=`## 任务完成
105
+
106
+ `,r+=`当任务完成或无法继续时,直接给出最终答案即可。
107
+
108
+ `,r+=`**重要提示**:
109
+ `,r+=`- 必须严格按照 XML 格式调用工具
110
+ `,r+=`- arguments 必须是有效的 JSON 格式
111
+ `,r+=`- 如果不需要调用工具,直接给出最终答案即可
112
+ `,r}function jm(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,a=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:a}}catch{}return null}const NS={openai:Bf,deepseek:Qf};class AS{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=NS[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?r=new Ko(new URL(t.url)):"type"in t&&t.type==="extension"?r=new Xf(t.sessionId):r=t,t.useAISdkClient??!1){const o=await s4({transport:r});return o.__transport__=r,o}else{const o=new PS({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof Yo||r&&r instanceof Mm||r&&r instanceof Xf)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await Lm(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={}){const r=Object.values(this.mcpTools).reduce((n,o)=>({...n,...o}),{});return Object.assign(r,t),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(t,r,n){const o=MS(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
113
+ ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,a=s.execute||s.call;return typeof a!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.messages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},g=i[0]?.role==="system"?i:[u,...i];return t===ni?this._chatReActStream(g,s,l,n,o):this._chatReActNonStream(g,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(s<n)a.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return o.push(...a),o}async _chatReActNonStream(t,r,n,o,s){let a=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const h=this._buildMessagesForModel(i,l,u),{tools:d,...p}=s,m=(await a0({model:this.llm(n),messages:h,...p})).text,y={role:"assistant",content:m};l.push(y),a.push(y);const _=jm(m,r);if(!_)return this.messages=a,{text:m,response:{messages:a}};const f=await this._executeReActToolCall(_.toolName,_.arguments,r),S={role:"user",content:`<tool_response>
114
+ ${f.success?JSON.stringify(f.result):`工具执行失败 - ${f.error}`}
115
+ </tool_response>`};l.push(S),a.push(S)}return this.messages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(t,r,n,o,s){const a=this,i=this.llm(n);let l,c;const u=new Promise((h,d)=>{l=h,c=d});return{fullStream:new ReadableStream({async start(h){let d=[...t];const p=t[0]?.role==="system"?t[0]:null,w=p?t.slice(1):[...t];let m=0,y="";const _=s.maxImages??3;try{for(;m<o;){m++;const f=a._buildMessagesForModel(p,w,_),{tools:b,...k}=s;delete k.system;const S=await ni({...k,model:i,messages:f});let C="";for await(const ee of S.fullStream)ee.type==="text-delta"?(C+=ee.text||"",h.enqueue({type:"text-delta",text:ee.text})):ee.type==="text-start"?h.enqueue({type:"text-start"}):ee.type==="text-end"||h.enqueue(ee);y+=C;const I={role:"assistant",content:y};w.push(I),d.push(I);const x=jm(y,r);if(!x){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}if(x.toolName==="computer"&&x.arguments?.action==="terminate"){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}const M=`react-${Date.now()}`;h.enqueue({type:"tool-input-start",id:M,toolName:x.toolName});const P=JSON.stringify(x.arguments,null,2);h.enqueue({type:"tool-input-delta",id:M,delta:P});const U=await a._executeReActToolCall(x.toolName,x.arguments,r);let z,F=U.result;if(U.success&&U.result&&typeof U.result=="object"&&U.result.screenshot){z=U.result.screenshot;const{screenshot:ee,...pe}=U.result;F=pe}let te="";U.success?F&&Array.isArray(F.content)&&F.content.length>0&&F.content[0].text?te=F.content[0].text:te=JSON.stringify(F):te=`工具执行失败 - ${U.error}`;let ie=`<tool_response>
116
+ ${te}
117
+ </tool_response>`;z&&(ie+=`
118
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),h.enqueue({type:"tool-result",toolCallId:M,result:ie});const se=z?{role:"user",content:[{type:"text",text:ie},{type:"image",image:z}]}:{role:"user",content:ie};w.push(se),d.push(se),y=""}h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d})}catch(f){h.error(f),c(f)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:Xa(n),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const a=t(s);return a?.response?.then(i=>{this.messages.push(...i.messages)}),a}async chat(t){return this._chat(a0,t)}async chatStream(t){return this._chat(ni,t)}}var mn={},Rl,Um;function qS(){return Um||(Um=1,Rl=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Rl}var Pl={},_r={},zm;function zr(){if(zm)return _r;zm=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return _r.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},_r.getSymbolTotalCodewords=function(n){return t[n]},_r.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},_r.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},_r.isKanjiModeEnabled=function(){return typeof e<"u"},_r.toSJIS=function(n){return e(n)},_r}var Ol={},Dm;function Ml(){return Dm||(Dm=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(Ol)),Ol}var Nl,Zm;function LS(){if(Zm)return Nl;Zm=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Nl=e,Nl}var Al,Fm;function jS(){if(Fm)return Al;Fm=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},Al=e,Al}var ql={},Vm;function US(){return Vm||(Vm=1,(function(e){const t=zr().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(n){const o=[],s=e.getRowColCoords(n),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(ql)),ql}var Ll={},Hm;function zS(){if(Hm)return Ll;Hm=1;const e=zr().getSymbolSize,t=7;return Ll.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Ll}var jl={},Bm;function DS(){return Bm||(Bm=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,c=null,u=null;for(let g=0;g<s;g++){i=l=0,c=u=null;for(let h=0;h<s;h++){let d=o.get(g,h);d===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=d,i=1),d=o.get(h,g),d===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=d,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function r(n,o,s){switch(n){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,r(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})(jl)),jl}var sa={},Jm;function Gm(){if(Jm)return sa;Jm=1;const e=Ml(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return sa.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},sa.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},sa}var Ul={},oo={},Wm;function ZS(){if(Wm)return oo;Wm=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),oo.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},oo.exp=function(n){return e[n]},oo.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},oo}var Km;function FS(){return Km||(Km=1,(function(e){const t=ZS();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(n[a],o[i]);return s},e.mod=function(n,o){let s=new Uint8Array(n);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(Ul)),Ul}var zl,Ym;function VS(){if(Ym)return zl;Ym=1;const e=FS();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=e.mod(o,this.genPoly),a=this.degree-s.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(s,a),i}return s},zl=t,zl}var Dl={},Zl={},Fl={},Qm;function Xm(){return Qm||(Qm=1,Fl.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Fl}var Ht={},e2;function t2(){if(e2)return Ht;e2=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
119
+ ]))+`;Ht.KANJI=new RegExp(r,"g"),Ht.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Ht.BYTE=new RegExp(n,"g"),Ht.NUMERIC=new RegExp(e,"g"),Ht.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Ht.testKanji=function(l){return o.test(l)},Ht.testNumeric=function(l){return s.test(l)},Ht.testAlphanumeric=function(l){return a.test(l)},Ht}var r2;function Dr(){return r2||(r2=1,(function(e){const t=Xm(),r=t2();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return n(s)}catch{return a}}})(Zl)),Zl}var n2;function HS(){return n2||(n2=1,(function(e){const t=zr(),r=Gm(),n=Ml(),o=Dr(),s=Xm(),a=7973,i=t.getBCHDigit(a);function l(h,d,p){for(let w=1;w<=40;w++)if(d<=e.getCapacity(w,p,h))return w}function c(h,d){return o.getCharCountIndicator(h,d)+4}function u(h,d){let p=0;return h.forEach(function(w){const m=c(w.mode,d);p+=m+w.getBitsLength()}),p}function g(h,d){for(let p=1;p<=40;p++)if(u(h,p)<=e.getCapacity(p,d,o.MIXED))return p}e.from=function(d,p){return s.isValid(d)?parseInt(d,10):p},e.getCapacity=function(d,p,w){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof w>"u"&&(w=o.BYTE);const m=t.getSymbolTotalCodewords(d),y=r.getTotalCodewordsCount(d,p),_=(m-y)*8;if(w===o.MIXED)return _;const f=_-c(w,d);switch(w){case o.NUMERIC:return Math.floor(f/10*3);case o.ALPHANUMERIC:return Math.floor(f/11*2);case o.KANJI:return Math.floor(f/13);case o.BYTE:default:return Math.floor(f/8)}},e.getBestVersionForData=function(d,p){let w;const m=n.from(p,n.M);if(Array.isArray(d)){if(d.length>1)return g(d,m);if(d.length===0)return 1;w=d[0]}else w=d;return l(w.mode,w.getLength(),m)},e.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let p=d<<12;for(;t.getBCHDigit(p)-i>=0;)p^=a<<t.getBCHDigit(p)-i;return d<<12|p}})(Dl)),Dl}var Vl={},o2;function BS(){if(o2)return Vl;o2=1;const e=zr(),t=1335,r=21522,n=e.getBCHDigit(t);return Vl.getEncodedBits=function(s,a){const i=s.bit<<3|a;let l=i<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(i<<10|l)^r},Vl}var Hl={},Bl,s2;function JS(){if(s2)return Bl;s2=1;const e=Dr();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,a;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),a=parseInt(s,10),n.put(a,10);const i=this.data.length-o;i>0&&(s=this.data.substr(o),a=parseInt(s,10),n.put(a,i*3+1))},Bl=t,Bl}var Jl,a2;function GS(){if(a2)return Jl;a2=1;const e=Dr(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let a=t.indexOf(this.data[s])*45;a+=t.indexOf(this.data[s+1]),o.put(a,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},Jl=r,Jl}var Gl,i2;function WS(){if(i2)return Gl;i2=1;const e=Dr();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},Gl=t,Gl}var Wl,l2;function KS(){if(l2)return Wl;l2=1;const e=Dr(),t=zr();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
120
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},Wl=r,Wl}var Kl={exports:{}},c2;function YS(){return c2||(c2=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},a={};a[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,g,h,d,p,w,m;!i.empty();){l=i.pop(),c=l.value,g=l.cost,h=r[c]||{};for(u in h)h.hasOwnProperty(u)&&(d=h[u],p=g+d,w=a[u],m=typeof a[u]>"u",(m||w>p)&&(a[u]=p,i.push(u,p),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var y=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(y)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Kl)),Kl.exports}var u2;function QS(){return u2||(u2=1,(function(e){const t=Dr(),r=JS(),n=GS(),o=WS(),s=KS(),a=t2(),i=zr(),l=YS();function c(y){return unescape(encodeURIComponent(y)).length}function u(y,_,f){const b=[];let k;for(;(k=y.exec(f))!==null;)b.push({data:k[0],index:k.index,mode:_,length:k[0].length});return b}function g(y){const _=u(a.NUMERIC,t.NUMERIC,y),f=u(a.ALPHANUMERIC,t.ALPHANUMERIC,y);let b,k;return i.isKanjiModeEnabled()?(b=u(a.BYTE,t.BYTE,y),k=u(a.KANJI,t.KANJI,y)):(b=u(a.BYTE_KANJI,t.BYTE,y),k=[]),_.concat(f,b,k).sort(function(C,I){return C.index-I.index}).map(function(C){return{data:C.data,mode:C.mode,length:C.length}})}function h(y,_){switch(_){case t.NUMERIC:return r.getBitsLength(y);case t.ALPHANUMERIC:return n.getBitsLength(y);case t.KANJI:return s.getBitsLength(y);case t.BYTE:return o.getBitsLength(y)}}function d(y){return y.reduce(function(_,f){const b=_.length-1>=0?_[_.length-1]:null;return b&&b.mode===f.mode?(_[_.length-1].data+=f.data,_):(_.push(f),_)},[])}function p(y){const _=[];for(let f=0;f<y.length;f++){const b=y[f];switch(b.mode){case t.NUMERIC:_.push([b,{data:b.data,mode:t.ALPHANUMERIC,length:b.length},{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.ALPHANUMERIC:_.push([b,{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.KANJI:_.push([b,{data:b.data,mode:t.BYTE,length:c(b.data)}]);break;case t.BYTE:_.push([{data:b.data,mode:t.BYTE,length:c(b.data)}])}}return _}function w(y,_){const f={},b={start:{}};let k=["start"];for(let S=0;S<y.length;S++){const C=y[S],I=[];for(let x=0;x<C.length;x++){const M=C[x],P=""+S+x;I.push(P),f[P]={node:M,lastCount:0},b[P]={};for(let U=0;U<k.length;U++){const z=k[U];f[z]&&f[z].node.mode===M.mode?(b[z][P]=h(f[z].lastCount+M.length,M.mode)-h(f[z].lastCount,M.mode),f[z].lastCount+=M.length):(f[z]&&(f[z].lastCount=M.length),b[z][P]=h(M.length,M.mode)+4+t.getCharCountIndicator(M.mode,_))}}k=I}for(let S=0;S<k.length;S++)b[k[S]].end=0;return{map:b,table:f}}function m(y,_){let f;const b=t.getBestModeForData(y);if(f=t.from(_,b),f!==t.BYTE&&f.bit<b.bit)throw new Error('"'+y+'" cannot be encoded with mode '+t.toString(f)+`.
121
+ Suggested mode is: `+t.toString(b));switch(f===t.KANJI&&!i.isKanjiModeEnabled()&&(f=t.BYTE),f){case t.NUMERIC:return new r(y);case t.ALPHANUMERIC:return new n(y);case t.KANJI:return new s(y);case t.BYTE:return new o(y)}}e.fromArray=function(_){return _.reduce(function(f,b){return typeof b=="string"?f.push(m(b,null)):b.data&&f.push(m(b.data,b.mode)),f},[])},e.fromString=function(_,f){const b=g(_,i.isKanjiModeEnabled()),k=p(b),S=w(k,f),C=l.find_path(S.map,"start","end"),I=[];for(let x=1;x<C.length-1;x++)I.push(S.table[C[x]].node);return e.fromArray(d(I))},e.rawSplit=function(_){return e.fromArray(g(_,i.isKanjiModeEnabled()))}})(Hl)),Hl}var d2;function XS(){if(d2)return Pl;d2=1;const e=zr(),t=Ml(),r=LS(),n=jS(),o=US(),s=zS(),a=DS(),i=Gm(),l=VS(),c=HS(),u=BS(),g=Dr(),h=QS();function d(S,C){const I=S.size,x=s.getPositions(C);for(let M=0;M<x.length;M++){const P=x[M][0],U=x[M][1];for(let z=-1;z<=7;z++)if(!(P+z<=-1||I<=P+z))for(let F=-1;F<=7;F++)U+F<=-1||I<=U+F||(z>=0&&z<=6&&(F===0||F===6)||F>=0&&F<=6&&(z===0||z===6)||z>=2&&z<=4&&F>=2&&F<=4?S.set(P+z,U+F,!0,!0):S.set(P+z,U+F,!1,!0))}}function p(S){const C=S.size;for(let I=8;I<C-8;I++){const x=I%2===0;S.set(I,6,x,!0),S.set(6,I,x,!0)}}function w(S,C){const I=o.getPositions(C);for(let x=0;x<I.length;x++){const M=I[x][0],P=I[x][1];for(let U=-2;U<=2;U++)for(let z=-2;z<=2;z++)U===-2||U===2||z===-2||z===2||U===0&&z===0?S.set(M+U,P+z,!0,!0):S.set(M+U,P+z,!1,!0)}}function m(S,C){const I=S.size,x=c.getEncodedBits(C);let M,P,U;for(let z=0;z<18;z++)M=Math.floor(z/3),P=z%3+I-8-3,U=(x>>z&1)===1,S.set(M,P,U,!0),S.set(P,M,U,!0)}function y(S,C,I){const x=S.size,M=u.getEncodedBits(C,I);let P,U;for(P=0;P<15;P++)U=(M>>P&1)===1,P<6?S.set(P,8,U,!0):P<8?S.set(P+1,8,U,!0):S.set(x-15+P,8,U,!0),P<8?S.set(8,x-P-1,U,!0):P<9?S.set(8,15-P-1+1,U,!0):S.set(8,15-P-1,U,!0);S.set(x-8,8,1,!0)}function _(S,C){const I=S.size;let x=-1,M=I-1,P=7,U=0;for(let z=I-1;z>0;z-=2)for(z===6&&z--;;){for(let F=0;F<2;F++)if(!S.isReserved(M,z-F)){let te=!1;U<C.length&&(te=(C[U]>>>P&1)===1),S.set(M,z-F,te),P--,P===-1&&(U++,P=7)}if(M+=x,M<0||I<=M){M-=x,x=-x;break}}}function f(S,C,I){const x=new r;I.forEach(function(F){x.put(F.mode.bit,4),x.put(F.getLength(),g.getCharCountIndicator(F.mode,S)),F.write(x)});const M=e.getSymbolTotalCodewords(S),P=i.getTotalCodewordsCount(S,C),U=(M-P)*8;for(x.getLengthInBits()+4<=U&&x.put(0,4);x.getLengthInBits()%8!==0;)x.putBit(0);const z=(U-x.getLengthInBits())/8;for(let F=0;F<z;F++)x.put(F%2?17:236,8);return b(x,S,C)}function b(S,C,I){const x=e.getSymbolTotalCodewords(C),M=i.getTotalCodewordsCount(C,I),P=x-M,U=i.getBlocksCount(C,I),z=x%U,F=U-z,te=Math.floor(x/U),ie=Math.floor(P/U),se=ie+1,ee=te-ie,pe=new l(ee);let V=0;const O=new Array(U),Z=new Array(U);let j=0;const E=new Uint8Array(S.buffer);for(let fe=0;fe<U;fe++){const ae=fe<F?ie:se;O[fe]=E.slice(V,V+ae),Z[fe]=pe.encode(O[fe]),V+=ae,j=Math.max(j,ae)}const R=new Uint8Array(x);let $=0,H,G;for(H=0;H<j;H++)for(G=0;G<U;G++)H<O[G].length&&(R[$++]=O[G][H]);for(H=0;H<ee;H++)for(G=0;G<U;G++)R[$++]=Z[G][H];return R}function k(S,C,I,x){let M;if(Array.isArray(S))M=h.fromArray(S);else if(typeof S=="string"){let te=C;if(!te){const ie=h.rawSplit(S);te=c.getBestVersionForData(ie,I)}M=h.fromString(S,te||40)}else throw new Error("Invalid data");const P=c.getBestVersionForData(M,I);if(!P)throw new Error("The amount of data is too big to be stored in a QR Code");if(!C)C=P;else if(C<P)throw new Error(`
75
122
  The chosen QR Code version cannot contain this amount of data.
76
- Minimum version required to store current data is: `+s+`.
77
- `);const o=u2(e,r,n),i=co.getSymbolSize(e),l=new YC(i);return a2(l,e),s2(l),o2(l,e),Bl(l,r,0),e>=7&&i2(l,e),l2(l,o),isNaN(a)&&(a=ql.getBestMask(l,Bl.bind(null,l,r))),ql.applyMask(a,l),Bl(l,r,a),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:a,segments:n}}bm.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let a=Fl.M,n,s;return typeof r<"u"&&(a=Fl.from(r.errorCorrectionLevel,Fl.M),n=po.from(r.version),s=ql.from(r.maskPattern),r.toSJISFunc&&co.setToSJISFunction(r.toSJISFunc)),d2(e,n,a,s)};var Dm={},Hl={};(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let a=r.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+r);(a.length===3||a.length===4)&&(a=Array.prototype.concat.apply([],a.map(function(s){return[s,s]}))),a.length===6&&a.push("F","F");const n=parseInt(a.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const n=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,o=a.scale||4;return{width:s,scale:s?4:o,margin:n,color:{dark:e(a.color.dark||"#000000ff"),light:e(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,n){return n.width&&n.width>=a+n.margin*2?n.width/(a+n.margin*2):n.scale},t.getImageWidth=function(a,n){const s=t.getScale(a,n);return Math.floor((a+n.margin*2)*s)},t.qrToImageData=function(a,n,s){const o=n.modules.size,i=n.modules.data,l=t.getScale(o,s),u=Math.floor((o+s.margin*2)*l),d=s.margin*l,h=[s.color.light,s.color.dark];for(let g=0;g<u;g++)for(let c=0;c<u;c++){let p=(g*u+c)*4,f=s.color.light;if(g>=d&&c>=d&&g<u-d&&c<u-d){const m=Math.floor((g-d)/l),v=Math.floor((c-d)/l);f=h[i[m*o+v]?1:0]}a[p++]=f.r,a[p++]=f.g,a[p++]=f.b,a[p]=f.a}}})(Hl),function(t){const e=Hl;function r(n,s,o){n.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,o,i){let l=i,u=o;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),o||(u=a()),l=e.getOptions(l);const d=e.getImageWidth(s.modules.size,l),h=u.getContext("2d"),g=h.createImageData(d,d);return e.qrToImageData(g.data,s,l),r(h,u,d),h.putImageData(g,0,0),u},t.renderToDataURL=function(s,o,i){let l=i;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),l||(l={});const u=t.render(s,o,l),d=l.type||"image/png",h=l.rendererOpts||{};return u.toDataURL(d,h.quality)}}(Dm);var jm={};const p2=Hl;function Lm(t,e){const r=t.a/255,a=e+'="'+t.hex+'"';return r<1?a+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':a}function Jl(t,e,r){let a=t+e;return typeof r<"u"&&(a+=" "+r),a}function h2(t,e,r){let a="",n=0,s=!1,o=0;for(let i=0;i<t.length;i++){const l=Math.floor(i%e),u=Math.floor(i/e);!l&&!s&&(s=!0),t[i]?(o++,i>0&&l>0&&t[i-1]||(a+=s?Jl("M",l+r,.5+u+r):Jl("m",n,0),n=0,s=!1),l+1<e&&t[i+1]||(a+=Jl("h",o),o=0)):n++}return a}jm.render=function(e,r,a){const n=p2.getOptions(r),s=e.modules.size,o=e.modules.data,i=s+n.margin*2,l=n.color.light.a?"<path "+Lm(n.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",u="<path "+Lm(n.color.dark,"stroke")+' d="'+h2(o,s,n.margin)+'"/>',d='viewBox="0 0 '+i+" "+i+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(n.width?'width="'+n.width+'" height="'+n.width+'" ':"")+d+' shape-rendering="crispEdges">'+l+u+`</svg>
78
- `;return typeof a=="function"&&a(null,g),g};const f2=CC,Wl=bm,zm=Dm,m2=jm;function Gl(t,e,r,a,n){const s=[].slice.call(arguments,1),o=s.length,i=typeof s[o-1]=="function";if(!i&&!f2())throw new Error("Callback required as last argument");if(i){if(o<2)throw new Error("Too few arguments provided");o===2?(n=r,r=e,e=a=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=a,a=void 0):(n=a,a=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=a=void 0):o===2&&!e.getContext&&(a=r,r=e,e=void 0),new Promise(function(l,u){try{const d=Wl.create(r,a);l(t(d,e,a))}catch(d){u(d)}})}try{const l=Wl.create(r,a);n(null,t(l,e,a))}catch(l){n(l)}}Mn.create=Wl.create,Mn.toCanvas=Gl.bind(null,zm.render),Mn.toDataURL=Gl.bind(null,zm.renderToDataURL),Mn.toString=Gl.bind(null,function(t,e,r){return m2.render(t,r)});class Um{constructor(e,{size:r=200,margin:a=4,color:n="#000",bgColor:s="#fff"}){this.value=e,this.size=r,this.margin=a,this.color=n,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return Mn.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return Mn.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const v2="https://agent.opentiny.design/tiny-robot",Fm="https://ai.opentiny.design/next-remoter",qm=t=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
79
- <rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
80
- <rect x="15" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
81
- <rect x="3" y="15" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
82
- <line x1="9" y1="6" x2="9" y2="18" stroke="currentColor" stroke-width="1.5"/>
83
- <line x1="15" y1="6" x2="15" y2="18" stroke="currentColor" stroke-width="1.5"/>
84
- <line x1="6" y1="9" x2="18" y2="9" stroke="currentColor" stroke-width="1.5"/>
85
- <line x1="6" y1="15" x2="18" y2="15" stroke="currentColor" stroke-width="1.5"/>
86
- <circle cx="12" cy="12" r="1" fill="currentColor"/>
87
- </svg>`},{action:"ai-chat",show:!0,text:"弹出 AI 对话框",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
88
- <path d="M20 2H4C2.9 2 2 2.9 2 4V22L6 18H20C21.1 18 22 17.1 22 16V4C22 2.9 21.1 2 20 2ZM20 16H6L4 18V4H20V16Z" fill="currentColor"/>
89
- <path d="M7 9H17V11H7V9Z" fill="currentColor"/>
90
- <path d="M7 12H14V14H7V12Z" fill="currentColor"/>
91
- </svg>`},{action:"remote-control",show:!0,text:`识别码:${t.sessionId.slice(-6)}`,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
92
- <rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" stroke-width="2" fill="none"/>
93
- <rect x="6" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
94
- <rect x="10" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
95
- <rect x="14" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
96
- <rect x="6" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
97
- <rect x="10" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
98
- <rect x="14" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
99
- <rect x="6" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
100
- <rect x="10" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
101
- <rect x="14" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
102
- </svg>`},{action:"remote-url",show:!0,text:`${t.remoteUrl}`,tip:t.remoteUrl,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
103
- <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
104
- <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
105
- </svg>`}];class g2{constructor(e){if(this.isExpanded=!1,!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||Fm,remoteUrl:e.remoteUrl||v2},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){var e;return(e=this.options.qrCodeUrl)!=null&&e.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?qm(this.options).map(r=>{const a=e.find(n=>n.action===r.action);return a?{...r,...a,show:a.show!==void 0?a.show:r.show}:r}):qm(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
123
+ Minimum version required to store current data is: `+P+`.
124
+ `);const U=f(C,I,M),z=e.getSymbolSize(C),F=new n(z);return d(F,C),p(F),w(F,C),y(F,I,0),C>=7&&m(F,C),_(F,U),isNaN(x)&&(x=a.getBestMask(F,y.bind(null,F,I))),a.applyMask(x,F),y(F,I,x),{modules:F,version:C,errorCorrectionLevel:I,maskPattern:x,segments:M}}return Pl.create=function(C,I){if(typeof C>"u"||C==="")throw new Error("No input text");let x=t.M,M,P;return typeof I<"u"&&(x=t.from(I.errorCorrectionLevel,t.M),M=c.from(I.version),P=a.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),k(C,M,x,P)},Pl}var Yl={},Ql={},p2;function f2(){return p2||(p2=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,g=[s.color.light,s.color.dark];for(let h=0;h<c;h++)for(let d=0;d<c;d++){let p=(h*c+d)*4,w=s.color.light;if(h>=u&&d>=u&&h<c-u&&d<c-u){const m=Math.floor((h-u)/l),y=Math.floor((d-u)/l);w=g[i[m*a+y]?1:0]}n[p++]=w.r,n[p++]=w.g,n[p++]=w.b,n[p]=w.a}}})(Ql)),Ql}var h2;function eC(){return h2||(h2=1,(function(e){const t=f2();function r(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),g=c.getContext("2d"),h=g.createImageData(u,u);return t.qrToImageData(h.data,s,l),r(g,c,u),g.putImageData(h,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",g=l.rendererOpts||{};return c.toDataURL(u,g.quality)}})(Yl)),Yl}var Xl={},m2;function tC(){if(m2)return Xl;m2=1;const e=f2();function t(o,s){const a=o.a/255,i=s+'="'+o.hex+'"';return a<1?i+" "+s+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(o,s,a){let i=o+s;return typeof a<"u"&&(i+=" "+a),i}function n(o,s,a){let i="",l=0,c=!1,u=0;for(let g=0;g<o.length;g++){const h=Math.floor(g%s),d=Math.floor(g/s);!h&&!c&&(c=!0),o[g]?(u++,g>0&&h>0&&o[g-1]||(i+=c?r("M",h+a,.5+d+a):r("m",l,0),l=0,c=!1),h+1<s&&o[g+1]||(i+=r("h",u),u=0)):l++}return i}return Xl.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,g=c+l.margin*2,h=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+g+"v"+g+'H0z"/>':"",d="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',p='viewBox="0 0 '+g+" "+g+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+p+' shape-rendering="crispEdges">'+h+d+`</svg>
125
+ `;return typeof i=="function"&&i(null,m),m},Xl}var g2;function rC(){if(g2)return mn;g2=1;const e=qS(),t=XS(),r=eC(),n=tC();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),g=u.length,h=typeof u[g-1]=="function";if(!h&&!e())throw new Error("Callback required as last argument");if(h){if(g<2)throw new Error("Too few arguments provided");g===2?(c=i,i=a,a=l=void 0):g===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(g<1)throw new Error("Too few arguments provided");return g===1?(i=a,a=l=void 0):g===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(d,p){try{const w=t.create(i,l);d(s(w,a,l))}catch(w){p(w)}})}try{const d=t.create(i,l);c(null,s(d,a,l))}catch(d){c(d)}}return mn.create=t.create,mn.toCanvas=o.bind(null,r.render),mn.toDataURL=o.bind(null,r.renderToDataURL),mn.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),mn}var nC=rC();const v2=dd(nC);class _2{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return v2.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return v2.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const oC={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class sC{constructor(t,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...oC,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
126
+ <div class="${this.opts.className}__arrow"></div>
127
+ <div class="${this.opts.className}__inner">${t}</div>
128
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-a:i==="bottom"?c=r.bottom+o+a:i==="left"?u=r.left+s-n.width-a:i==="right"&&(u=r.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+a.width<=o-5&&t+a.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const y2="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(y2))return;const e=document.createElement("style");e.id=y2,e.textContent=`
129
+ .tiny-remoter-native-tooltip {
130
+ position: absolute;
131
+ z-index: 9999;
132
+ max-width: 200px;
133
+ padding: 6px 10px;
134
+ font-size: 12px;
135
+ line-height: 1.4;
136
+ color: #fff;
137
+ background: #191919;
138
+ border-radius: 4px;
139
+ pointer-events: none;
140
+ box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.2);
141
+ }
142
+ .tiny-remoter-native-tooltip__arrow {
143
+ position: absolute;
144
+ width: 0; height: 0;
145
+ border: 6px solid transparent;
146
+ }
147
+ .tiny-remoter-native-tooltip--top
148
+ .tiny-remoter-native-tooltip__arrow {
149
+ bottom: -12px;
150
+ left: 50%; transform:
151
+ translateX(-50%);
152
+ border-top-color: rgba(0,0,0,.75);
153
+ }
154
+ .tiny-remoter-native-tooltip--bottom
155
+ .tiny-remoter-native-tooltip__arrow {
156
+ top: -12px;
157
+ left: 50%; transform:
158
+ translateX(-50%);
159
+ border-bottom-color: rgba(0,0,0,.75);
160
+ }
161
+ .tiny-remoter-native-tooltip--left
162
+ .tiny-remoter-native-tooltip__arrow {
163
+ right: -12px;
164
+ top: 50%;
165
+ transform: translateY(-50%);
166
+ border-left-color: rgba(0,0,0,.75);
167
+ }
168
+ .tiny-remoter-native-tooltip--right
169
+ .tiny-remoter-native-tooltip__arrow {
170
+ left: -12px;
171
+ top: 50%;
172
+ transform: translateY(-50%);
173
+ border-right-color: rgba(0,0,0,.75);
174
+ }
175
+ `,document.head.appendChild(e)})();const aC="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",iC="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",lC="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",cC="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",uC="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",dC="https://agent.opentiny.design/tiny-robot",w2="https://ai.opentiny.design/next-remoter",b2=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:cC},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:aC},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:lC},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:iC}];class pC{constructor(t){if(this.isExpanded=!1,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new sC(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||w2,remoteUrl:t.remoteUrl||dC},this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?b2(this.options).map(r=>{const n=t.find(o=>o.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):b2(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
106
176
  <div class="tiny-remoter-floating-block__icon">
107
- <img style="display: block; width: 56px;" src="${Fm}/svgs/logo-next-no-bg-left.svg" alt="icon" />
177
+ <img style="display: block; width: 56px;" src="${w2}/svgs/logo-next-no-bg-left.svg" alt="icon" />
108
178
  </div>
109
- `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const e=this.menuItems.filter(r=>r.show!==!1).map(r=>`
179
+ `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(r=>r.show!==!1).map(r=>`
110
180
  <div class="tiny-remoter-dropdown-item" data-action="${r.action}">
111
- <div class="tiny-remoter-dropdown-item__icon">
112
- ${r.icon}
181
+ <div id="tiny-remoter-icon-item-${r.action}" class="tiny-remoter-dropdown-item__icon">
113
182
  </div>
114
- <span title="${r.tip}">${r.text}</span>
115
- ${r.showCopyIcon?`
116
- <div class="tiny-remoter-copy-icon" data-action="${r.action}">
117
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
118
- <path d="M16 1H4C2.9 1 2 1.9 2 3V17H4V3H16V1ZM19 5H8C6.9 5 6 5.9 6 7V21C6 22.1 6.9 23 8 23H19C20.1 23 21 22.1 21 21V7C21 5.9 20.1 5 19 5ZM19 21H8V7H19V21Z" fill="currentColor"/>
119
- </svg>
183
+ <div class="tiny-remoter-dropdown-item__content">
184
+ <div title="${r.tip}">${r.text}</div>
185
+ <div class="tiny-remoter-dropdown-item__desc-wrapper">
186
+ <div class="tiny-remoter-dropdown-item__desc ${r.active?"tiny-remoter-dropdown-item__desc--active":""} ${r.know?"tiny-remoter-dropdown-item__desc--know":""}">${r.desc}</div>
187
+ <div>
188
+ ${r.showCopyIcon?`
189
+ <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
190
+ <img src="${uC}"/>
191
+ </div>
192
+ `:""}
193
+ </div>
120
194
  </div>
121
- `:""}
195
+ </div>
122
196
  </div>
123
- `).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,a=r.closest(".tiny-remoter-copy-icon");if(a){e.stopPropagation();const o=a.dataset.action;o&&this.handleAction(o);return}const n=r.closest(".tiny-remoter-dropdown-item"),s=n==null?void 0:n.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const a=document.execCommand("copy");document.body.removeChild(r),a?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",a=document.createElement("div");a.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,a.textContent=r,document.body.appendChild(a),setTimeout(()=>a.classList.add("show"),10),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},300)},1500)}async showQRCode(){const r=await new Um((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),a=this.createModal("扫码前往智能遥控器",`
197
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new _2((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
124
198
  <div style="text-align: center; padding: 32px;">
125
199
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
126
200
  <div style="
@@ -201,18 +275,18 @@ Minimum version required to store current data is: `+s+`.
201
275
  <span>支持微信、浏览器等多种方式</span>
202
276
  </div>
203
277
  </div>
204
- `);this.showModal(a)}showAIChat(){var e,r;(r=(e=this.options).onShowAIChat)==null||r.call(e)}createModal(e,r){const a=document.createElement("div");a.className="tiny-remoter-floating-modal",a.innerHTML=`
278
+ `);this.showModal(n)}showAIChat(){this.options.onShowAIChat?.()}createModal(t,r){const n=document.createElement("div");n.className="tiny-remoter-floating-modal",n.innerHTML=`
205
279
  <div class="tiny-remoter-modal-overlay"></div>
206
280
  <div class="tiny-remoter-modal-content">
207
281
  <div class="tiny-remoter-modal-header">
208
- <h3>${e}</h3>
282
+ <h3>${t}</h3>
209
283
  <button class="tiny-remoter-modal-close">&times;</button>
210
284
  </div>
211
285
  <div class="tiny-remoter-modal-body">
212
286
  ${r}
213
287
  </div>
214
288
  </div>
215
- `;const n=a.querySelector(".tiny-remoter-modal-close"),s=a.querySelector(".tiny-remoter-modal-overlay");return n.addEventListener("click",()=>this.hideModal(a)),s.addEventListener("click",()=>this.hideModal(a)),a}showModal(e){document.body.appendChild(e),setTimeout(()=>e.classList.add("show"),10)}hideModal(e){e.classList.remove("show"),setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},100)}addStyles(){const e=document.createElement("style");e.textContent=`
289
+ `;const o=n.querySelector(".tiny-remoter-modal-close"),s=n.querySelector(".tiny-remoter-modal-overlay");return o.addEventListener("click",()=>this.hideModal(n)),s.addEventListener("click",()=>this.hideModal(n)),n}showModal(t){document.body.appendChild(t),setTimeout(()=>t.classList.add("show"),10)}hideModal(t){t.classList.remove("show"),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},100)}addStyles(){const t=document.createElement("style");t.textContent=`
216
290
  /* 浮动块样式 */
217
291
  .tiny-remoter-floating-block {
218
292
  position: fixed;
@@ -250,15 +324,17 @@ Minimum version required to store current data is: `+s+`.
250
324
  bottom: 100px;
251
325
  right: 30px;
252
326
  background: white;
253
- border-radius: 16px;
327
+ border-radius: 18px;
254
328
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
255
- padding: 8px;
329
+ padding: 24px 24px 0px 24px;
256
330
  opacity: 0;
257
331
  visibility: hidden;
258
332
  transform: translateY(20px) scale(0.95);
259
333
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
260
334
  z-index: 999;
261
335
  min-width: 200px;
336
+ width: 223px;
337
+ height: auto;
262
338
  }
263
339
 
264
340
  .tiny-remoter-floating-dropdown.show {
@@ -270,12 +346,16 @@ Minimum version required to store current data is: `+s+`.
270
346
  .tiny-remoter-dropdown-item {
271
347
  display: flex;
272
348
  align-items: center;
273
- gap: 12px;
274
- padding: 12px 16px;
275
349
  border-radius: 12px;
276
350
  cursor: pointer;
277
351
  transition: all 0.2s ease;
278
352
  color: #333;
353
+ margin-bottom: 24px;
354
+ height: 40px;
355
+ }
356
+
357
+ .tiny-remoter-dropdown-item:last-child {
358
+ margin-bottom: 32px;
279
359
  }
280
360
 
281
361
  .tiny-remoter-dropdown-item > span {
@@ -286,22 +366,48 @@ Minimum version required to store current data is: `+s+`.
286
366
  white-space: nowrap;
287
367
  }
288
368
 
289
- .tiny-remoter-dropdown-item:hover {
290
- background: #f8f9fa;
291
- transform: translateX(4px);
292
- }
293
-
294
369
  .tiny-remoter-dropdown-item__icon {
295
370
  display: flex;
296
371
  align-items: center;
297
372
  justify-content: center;
298
- width: 32px;
299
- height: 32px;
373
+ width: 40px;
374
+ height: 40px;
300
375
  background: #f8f9fa;
301
376
  border-radius: 8px;
302
377
  color: #667eea;
303
378
  }
304
379
 
380
+ .tiny-remoter-dropdown-item__content {
381
+ flex: 1;
382
+ display: flex;
383
+ flex-direction: column;
384
+ gap: 4px;
385
+ overflow: hidden;
386
+ font-size: 12px;
387
+ margin-left: 16px;
388
+ }
389
+
390
+ .tiny-remoter-dropdown-item__desc-wrapper {
391
+ display: flex;
392
+ align-items: center;
393
+ gap: 4px;
394
+ }
395
+
396
+ .tiny-remoter-dropdown-item__desc {
397
+ color: #808080;
398
+ overflow: hidden;
399
+ white-space: nowrap;
400
+ text-overflow: ellipsis;
401
+ }
402
+
403
+ .tiny-remoter-dropdown-item__desc--active {
404
+ color: #1476ff;
405
+ }
406
+
407
+ .tiny-remoter-dropdown-item__desc--know {
408
+ color: #191919;
409
+ }
410
+
305
411
  /* 复制图标样式 */
306
412
  .tiny-remoter-copy-icon {
307
413
  display: flex;
@@ -490,13 +596,6 @@ Minimum version required to store current data is: `+s+`.
490
596
  color: white;
491
597
  }
492
598
 
493
- .tiny-remoter-dropdown-item:hover {
494
- background: #2a2a2a;
495
- }
496
-
497
- .tiny-remoter-dropdown-item__icon {
498
- background: #2a2a2a;
499
- }
500
599
 
501
600
  .tiny-remoter-copy-icon {
502
601
  background: #2a2a2a;
@@ -521,4 +620,4 @@ Minimum version required to store current data is: `+s+`.
521
620
  color: white;
522
621
  }
523
622
  }
524
- `,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const y2=(t={})=>new g2(t);gr.AgentModelProvider=PC,gr.QrCode=Um,gr.createRemoter=y2,gr.getAISDKTools=Ml,Object.defineProperty(gr,Symbol.toStringTag,{value:"Module"})});
623
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const fC=(e={})=>new pC(e);Jt.AgentModelProvider=AS,Jt.QrCode=_2,Jt.createRemoter=fC,Jt.getAISDKTools=Lm,Object.defineProperty(Jt,Symbol.toStringTag,{value:"Module"})}));