@cline/core 0.0.95 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/ClineCore.d.ts +6 -1
  2. package/dist/account/rpc.d.ts +3 -1
  3. package/dist/cline-core/runtime-services.d.ts +4 -2
  4. package/dist/cloud/controller.d.ts +5 -2
  5. package/dist/cloud/hub-client.d.ts +51 -0
  6. package/dist/cloud/hub-protocol.d.ts +18 -0
  7. package/dist/cloud/index.d.ts +2 -0
  8. package/dist/cloud/index.js +16 -16
  9. package/dist/cloud/types.d.ts +4 -1
  10. package/dist/extensions/context/compaction-shared.d.ts +1 -0
  11. package/dist/extensions/context/compaction.d.ts +7 -0
  12. package/dist/extensions/context/summarize-conversation.d.ts +7 -0
  13. package/dist/extensions/context/summary-generation.d.ts +14 -0
  14. package/dist/extensions/mcp/apps.d.ts +16 -0
  15. package/dist/extensions/mcp/client.d.ts +1 -0
  16. package/dist/extensions/mcp/index.d.ts +5 -1
  17. package/dist/extensions/mcp/manager.d.ts +2 -1
  18. package/dist/extensions/mcp/session-apps.d.ts +28 -0
  19. package/dist/extensions/mcp/types.d.ts +22 -0
  20. package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
  21. package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
  22. package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
  23. package/dist/hub/client/index.d.ts +6 -0
  24. package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
  25. package/dist/hub/client/plugin-commands.d.ts +4 -0
  26. package/dist/hub/client/session-client.d.ts +2 -0
  27. package/dist/hub/daemon/entry.js +241 -228
  28. package/dist/hub/index.d.ts +1 -0
  29. package/dist/hub/index.js +231 -218
  30. package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
  31. package/dist/hub/server/cloud-session-service.d.ts +50 -0
  32. package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
  33. package/dist/hub/server/handlers/context.d.ts +13 -2
  34. package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
  35. package/dist/hub/server/hub-server-options.d.ts +3 -0
  36. package/dist/hub/server/hub-server-transport.d.ts +2 -0
  37. package/dist/index.d.ts +8 -4
  38. package/dist/index.js +278 -258
  39. package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
  40. package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
  41. package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-b1d8eb67.js +1 -0
  42. package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-33qvrctr.js +1 -0
  43. package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-paabhz8w.js +1 -0
  44. package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-yhsfqcy1.js +1 -0
  45. package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +21 -0
  46. package/dist/plugin-runtime/node_modules/@cline/core/dist/community-gqgs7446.js +1 -0
  47. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-822304b0.js +1 -0
  48. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-hky2m2yx.js +1 -0
  49. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-sqf1kd37.js +1 -0
  50. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-tx1kp6xn.js +1 -0
  51. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-6cpgjxme.js +2 -0
  52. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-fxchqbze.js +2 -0
  53. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-m3bzwmzc.js +1 -0
  54. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-pr9sb5fr.js +1 -0
  55. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-nckraycx.js +1 -0
  56. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-w91yq3tm.js +1 -0
  57. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-xdyxc2tf.js +1 -0
  58. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-yxsvs11a.js +1 -0
  59. package/dist/plugin-runtime/node_modules/@cline/core/dist/google-pgdk2dm9.js +1 -0
  60. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1160 -0
  61. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1147 -0
  62. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-02jpyn9y.js +85 -0
  63. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0cb4390m.js +137 -0
  64. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0f8xrhgt.js +209 -0
  65. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1f8vb421.js +2 -0
  66. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-28c7m0fv.js +16 -0
  67. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-2em3jg4q.js +1 -0
  68. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4n1zpzbe.js +2 -0
  69. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-54eea0ex.js +2 -0
  70. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5j92dtg5.js +16 -0
  71. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6akf3a5d.js +2 -0
  72. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6k6ep10s.js +136 -0
  73. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-71ym4q6s.js +2 -0
  74. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-91p1ghfk.js +14 -0
  75. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9qkpjy7x.js +2 -0
  76. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9swk4nej.js +3 -0
  77. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-aa2s5myc.js +1 -0
  78. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ae0ajw38.js +13 -0
  79. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bxvyzjhc.js +1 -0
  80. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bzy863k0.js +6 -0
  81. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d96n0s70.js +20 -0
  82. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-dsd6vt8c.js +1 -0
  83. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-e2q4azd9.js +119 -0
  84. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-egd18jj2.js +4 -0
  85. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-eh83hr16.js +2 -0
  86. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ev9r2dy3.js +1204 -0
  87. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f2mvvryf.js +190 -0
  88. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7gn5v3f.js +2 -0
  89. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7s1a560.js +12 -0
  90. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkhq3jtz.js +21 -0
  91. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-j8r18nfg.js +15 -0
  92. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-jhny555h.js +6 -0
  93. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m1gpa2eg.js +146 -0
  94. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m2ad6tgj.js +1 -0
  95. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m7mks2jq.js +4 -0
  96. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-mcnngj50.js +62 -0
  97. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-n2srkkh0.js +39 -0
  98. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nbs1tsny.js +142 -0
  99. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nqjnz7m4.js +9 -0
  100. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rmhzyxr8.js +3 -0
  101. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rtzf3vvk.js +6 -0
  102. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sw74pcm3.js +2 -0
  103. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t3eanyjj.js +3 -0
  104. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-tseksj1v.js +1 -0
  105. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v0ctpcdr.js +12 -0
  106. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-dx8bd4wq.js +1 -0
  107. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v695918t.js +14 -0
  108. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v96yy1pw.js +1 -0
  109. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vfm7r9wk.js +65 -0
  110. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xecthgrg.js +9 -0
  111. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xn1xhp06.js +9 -0
  112. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yfdscfdx.js +1 -0
  113. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yrnwqsdt.js +2 -0
  114. package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
  115. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-3mgy2y9y.js +473 -0
  116. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-w1xrs0vd.js +1 -0
  117. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-9tppg77c.js +1 -0
  118. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-y658kpzy.js +1 -0
  119. package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-cmhqd91b.js +1 -0
  120. package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-qkjjf8mm.js +2 -0
  121. package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-8z6y9d1h.js +1 -0
  122. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-cfmja1ez.js +1 -0
  123. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-1t7n5sxj.js +1 -0
  124. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-k6yqgnyd.js +1 -0
  125. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-6rdyebbq.js +1 -0
  126. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
  127. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
  128. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-1h068py9.js +1 -0
  129. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-7jchft51.js +1 -0
  130. package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-qfxfsrn4.js +1 -0
  131. package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
  132. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
  133. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
  134. package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
  135. package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
  136. package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
  137. package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
  138. package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
  139. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
  140. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
  141. package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
  142. package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
  143. package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
  144. package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
  145. package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
  146. package/dist/plugin-runtime/package.json +1 -0
  147. package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
  148. package/dist/remote/remote-environments.d.ts +1 -0
  149. package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
  150. package/dist/runtime/host/local-runtime-host.d.ts +10 -0
  151. package/dist/runtime/host/runtime-host.d.ts +6 -0
  152. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
  153. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
  154. package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
  155. package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
  156. package/dist/services/llms/cline-recommended-models.d.ts +2 -0
  157. package/dist/services/local-runtime-bootstrap.d.ts +1 -0
  158. package/dist/services/plugin-command-api.d.ts +47 -0
  159. package/dist/services/plugin-commands.d.ts +25 -27
  160. package/dist/services/skills-cli.d.ts +2 -0
  161. package/dist/services/telemetry/core-events.d.ts +26 -0
  162. package/dist/services/telemetry/index.js +1 -1
  163. package/dist/services/telemetry/run-health.d.ts +40 -0
  164. package/dist/services/telemetry/stall-signals.d.ts +12 -0
  165. package/dist/types/config.d.ts +1 -0
  166. package/dist/types/session.d.ts +7 -0
  167. package/package.json +6 -5
@@ -0,0 +1,20 @@
1
+ import{Dr}from"./index-6k6ep10s.js";var qt="vercel.ai.error",Hr=Symbol.for(qt),gt,yt,x=class e extends(yt=Error,gt=Hr,yt){constructor({name:t,message:r,cause:n}){super(r);this[gt]=!0,this.name=t,this.cause=n}static isInstance(t){return e.hasMarker(t,qt)}static hasMarker(t,r){let n=Symbol.for(r);return t!=null&&typeof t==="object"&&n in t&&typeof t[n]==="boolean"&&t[n]===!0}},Wt="AI_APICallError",Ht=`vercel.ai.error.${Wt}`,Jr=Symbol.for(Ht),vt,_t,P=class extends(_t=x,vt=Jr,_t){constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:a,cause:i,isRetryable:o=n!=null&&(n===408||n===409||n===429||n>=500),data:u}){super({name:Wt,message:e,cause:i});this[vt]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=a,this.isRetryable=o,this.data=u}static isInstance(e){return x.hasMarker(e,Ht)}},Jt="AI_EmptyResponseBodyError",Gt=`vercel.ai.error.${Jt}`,Gr=Symbol.for(Gt),bt,wt,Kt=class extends(wt=x,bt=Gr,wt){constructor({message:e="Empty response body"}={}){super({name:Jt,message:e});this[bt]=!0}static isInstance(e){return x.hasMarker(e,Gt)}};function Yt(e){if(e==null)return"unknown error";if(typeof e==="string")return e;if(e instanceof Error)return e.message;return JSON.stringify(e)}var Xt="AI_InvalidArgumentError",Qt=`vercel.ai.error.${Xt}`,Kr=Symbol.for(Qt),xt,kt,Zt=class extends(kt=x,xt=Kr,kt){constructor({message:e,cause:t,argument:r}){super({name:Xt,message:e,cause:t});this[xt]=!0,this.argument=r}static isInstance(e){return x.hasMarker(e,Qt)}},er="AI_InvalidPromptError",tr=`vercel.ai.error.${er}`,Yr=Symbol.for(tr),St,Tt,$s=class extends(Tt=x,St=Yr,Tt){constructor({prompt:e,message:t,cause:r}){super({name:er,message:`Invalid prompt: ${t}`,cause:r});this[St]=!0,this.prompt=e}static isInstance(e){return x.hasMarker(e,tr)}},rr="AI_InvalidResponseDataError",nr=`vercel.ai.error.${rr}`,Xr=Symbol.for(nr),Et,At,Ns=class extends(At=x,Et=Xr,At){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:rr,message:t});this[Et]=!0,this.data=e}static isInstance(e){return x.hasMarker(e,nr)}},sr="AI_JSONParseError",ar=`vercel.ai.error.${sr}`,Qr=Symbol.for(ar),It,Ct,me=class extends(Ct=x,It=Qr,Ct){constructor({text:e,cause:t}){super({name:sr,message:`JSON parsing failed: Text: ${e}.
2
+ Error message: ${Yt(t)}`,cause:t});this[It]=!0,this.text=e}static isInstance(e){return x.hasMarker(e,ar)}},ir="AI_LoadAPIKeyError",or=`vercel.ai.error.${ir}`,Zr=Symbol.for(or),Pt,Rt,ge=class extends(Rt=x,Pt=Zr,Rt){constructor({message:e}){super({name:ir,message:e});this[Pt]=!0}static isInstance(e){return x.hasMarker(e,or)}},ur="AI_LoadSettingError",cr=`vercel.ai.error.${ur}`,en=Symbol.for(cr),Ot,$t,Ms=class extends($t=x,Ot=en,$t){constructor({message:e}){super({name:ur,message:e});this[Ot]=!0}static isInstance(e){return x.hasMarker(e,cr)}},lr="AI_NoContentGeneratedError",dr=`vercel.ai.error.${lr}`,tn=Symbol.for(dr),Nt,Mt,js=class extends(Mt=x,Nt=tn,Mt){constructor({message:e="No content generated."}={}){super({name:lr,message:e});this[Nt]=!0}static isInstance(e){return x.hasMarker(e,dr)}},fr="AI_NoSuchModelError",hr=`vercel.ai.error.${fr}`,rn=Symbol.for(hr),jt,Dt,Ds=class extends(Dt=x,jt=rn,Dt){constructor({errorName:e=fr,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n});this[jt]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return x.hasMarker(e,hr)}},pr="AI_TooManyEmbeddingValuesForCallError",mr=`vercel.ai.error.${pr}`,nn=Symbol.for(mr),Lt,Ft,Ls=class extends(Ft=x,Lt=nn,Ft){constructor(e){super({name:pr,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[Lt]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return x.hasMarker(e,mr)}},gr="AI_TypeValidationError",yr=`vercel.ai.error.${gr}`,sn=Symbol.for(yr),Bt,Vt,ee=class e extends(Vt=x,Bt=sn,Vt){constructor({value:t,cause:r}){super({name:gr,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
+ Error message: ${Yt(r)}`,cause:r});this[Bt]=!0,this.value=t}static isInstance(t){return x.hasMarker(t,yr)}static wrap({value:t,cause:r}){return e.isInstance(r)&&r.value===t?r:new e({value:t,cause:r})}},vr="AI_UnsupportedFunctionalityError",_r=`vercel.ai.error.${vr}`,an=Symbol.for(_r),Ut,zt,Fs=class extends(zt=x,Ut=an,zt){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:vr,message:t});this[Ut]=!0,this.functionality=e}static isInstance(e){return x.hasMarker(e,_r)}};var b;(function(e){e.assertEqual=(s)=>{};function t(s){}e.assertIs=t;function r(s){throw Error()}e.assertNever=r,e.arrayToEnum=(s)=>{let a={};for(let i of s)a[i]=i;return a},e.getValidEnumValues=(s)=>{let a=e.objectKeys(s).filter((o)=>typeof s[s[o]]!=="number"),i={};for(let o of a)i[o]=s[o];return e.objectValues(i)},e.objectValues=(s)=>e.objectKeys(s).map(function(a){return s[a]}),e.objectKeys=typeof Object.keys==="function"?(s)=>Object.keys(s):(s)=>{let a=[];for(let i in s)if(Object.prototype.hasOwnProperty.call(s,i))a.push(i);return a},e.find=(s,a)=>{for(let i of s)if(a(i))return i;return},e.isInteger=typeof Number.isInteger==="function"?(s)=>Number.isInteger(s):(s)=>typeof s==="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map((i)=>typeof i==="string"?`'${i}'`:i).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(s,a)=>{if(typeof a==="bigint")return a.toString();return a}})(b||(b={}));var br;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(br||(br={}));var f=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=(e)=>{switch(typeof e){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(e)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":if(Array.isArray(e))return f.array;if(e===null)return f.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return f.promise;if(typeof Map<"u"&&e instanceof Map)return f.map;if(typeof Set<"u"&&e instanceof Set)return f.set;if(typeof Date<"u"&&e instanceof Date)return f.date;return f.object;default:return f.unknown}};var c=b.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 F extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(s){return s.message},r={_errors:[]},n=(s)=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let i=r,o=0;while(o<a.path.length){let u=a.path[o];if(o!==a.path.length-1)i[u]=i[u]||{_errors:[]};else i[u]=i[u]||{_errors:[]},i[u]._errors.push(t(a));i=i[u],o++}}};return n(this),r}static assert(e){if(!(e instanceof F))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},r=[];for(let n of this.issues)if(n.path.length>0){let s=n.path[0];t[s]=t[s]||[],t[s].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}F.create=(e)=>new F(e);var on=(e,t)=>{let r;switch(e.code){case c.invalid_type:if(e.received===f.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case c.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,b.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:r=`Unrecognized key(s) in object: ${b.joinValues(e.keys,", ")}`;break;case c.invalid_union:r="Invalid input";break;case c.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${b.joinValues(e.options)}`;break;case c.invalid_enum_value:r=`Invalid enum value. Expected ${b.joinValues(e.options)}, received '${e.received}'`;break;case c.invalid_arguments:r="Invalid function arguments";break;case c.invalid_return_type:r="Invalid function return type";break;case c.invalid_date:r="Invalid date";break;case c.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else b.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case c.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case c.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case c.custom:r="Invalid input";break;case c.invalid_intersection_types:r="Intersection results could not be merged";break;case c.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case c.not_finite:r="Number must be finite";break;default:r=t.defaultError,b.assertNever(e)}return{message:r}},te=on;var un=te;function ye(){return un}var Ne=(e)=>{let{data:t,path:r,errorMaps:n,issueData:s}=e,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",u=n.filter((l)=>!!l).slice().reverse();for(let l of u)o=l(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}};function d(e,t){let r=ye(),n=Ne({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===te?void 0:te].filter((s)=>!!s)});e.common.issues.push(n)}class N{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return g;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let s=await n.key,a=await n.value;r.push({key:s,value:a})}return N.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:s,value:a}=n;if(s.status==="aborted")return g;if(a.status==="aborted")return g;if(s.status==="dirty")e.dirty();if(a.status==="dirty")e.dirty();if(s.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet))r[s.value]=a.value}return{status:e.value,value:r}}}var g=Object.freeze({status:"aborted"}),ce=(e)=>({status:"dirty",value:e}),j=(e)=>({status:"valid",value:e}),Ke=(e)=>e.status==="aborted",Ye=(e)=>e.status==="dirty",se=(e)=>e.status==="valid",ve=(e)=>typeof Promise<"u"&&e instanceof Promise;var p;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(p||(p={}));class V{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var wr=(e,t)=>{if(se(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new F(e.common.issues);return this._error=r,this._error}}}};function v(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:s};return{errorMap:(i,o)=>{let{message:u}=e;if(i.code==="invalid_enum_value")return{message:u??o.defaultError};if(typeof o.data>"u")return{message:u??n??o.defaultError};if(i.code!=="invalid_type")return{message:o.defaultError};return{message:u??r??o.defaultError}},description:s}}class _{get description(){return this._def.description}_getType(e){return J(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ve(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},n=this._parseSync({data:e,path:r.path,parent:r});return wr(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return se(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>se(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(ve(n)?n:Promise.resolve(n));return wr(r,s)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,s)=>{let a=e(n),i=()=>s.addIssue({code:c.custom,...r(n)});if(typeof Promise<"u"&&a instanceof Promise)return a.then((o)=>{if(!o)return i(),!1;else return!0});if(!a)return i(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new H({schema:this,typeName:y.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:(t)=>this["~validate"](t)}}optional(){return W.create(this,this._def)}nullable(){return re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return q.create(this)}promise(){return pe.create(this,this._def)}or(e){return ke.create([this,e],this._def)}and(e){return Se.create(this,e,this._def)}transform(e){return new H({...v(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new Ie({...v(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new et({typeName:y.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new Ce({...v(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Ue.create(this,e)}readonly(){return Pe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var cn=/^c[^\s-]{8,}$/i,ln=/^[0-9a-z]+$/,dn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fn=/^[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,hn=/^[a-z0-9_-]{21}$/i,pn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mn=/^[-+]?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)?)??$/,gn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,yn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Xe,vn=/^(?:(?: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])$/,_n=/^(?:(?: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])$/,bn=/^(([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]))$/,wn=/^(([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])$/,xn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,xr="((\\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])))",Sn=new RegExp(`^${xr}$`);function kr(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Tn(e){return new RegExp(`^${kr(e)}$`)}function En(e){let t=`${xr}T${kr(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function An(e,t){if((t==="v4"||!t)&&vn.test(e))return!0;if((t==="v6"||!t)&&bn.test(e))return!0;return!1}function In(e,t){if(!pn.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));if(typeof s!=="object"||s===null)return!1;if("typ"in s&&s?.typ!=="JWT")return!1;if(!s.alg)return!1;if(t&&s.alg!==t)return!1;return!0}catch{return!1}}function Cn(e,t){if((t==="v4"||!t)&&_n.test(e))return!0;if((t==="v6"||!t)&&wn.test(e))return!0;return!1}class K extends _{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==f.string){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:f.string,received:s.parsedType}),g}let r=new N,n=void 0;for(let s of this._def.checks)if(s.kind==="min"){if(e.data.length<s.value)n=this._getOrReturnCtx(e,n),d(n,{code:c.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="max"){if(e.data.length>s.value)n=this._getOrReturnCtx(e,n),d(n,{code:c.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="length"){let a=e.data.length>s.value,i=e.data.length<s.value;if(a||i){if(n=this._getOrReturnCtx(e,n),a)d(n,{code:c.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});else if(i)d(n,{code:c.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});r.dirty()}}else if(s.kind==="email"){if(!gn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"email",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="emoji"){if(!Xe)Xe=new RegExp(yn,"u");if(!Xe.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"emoji",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="uuid"){if(!fn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"uuid",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="nanoid"){if(!hn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"nanoid",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="cuid"){if(!cn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"cuid",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="cuid2"){if(!ln.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"cuid2",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="ulid"){if(!dn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"ulid",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),d(n,{validation:"url",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="regex"){if(s.regex.lastIndex=0,!s.regex.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"regex",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="trim")e.data=e.data.trim();else if(s.kind==="includes"){if(!e.data.includes(s.value,s.position))n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()}else if(s.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(s.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(s.kind==="startsWith"){if(!e.data.startsWith(s.value))n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()}else if(s.kind==="endsWith"){if(!e.data.endsWith(s.value))n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()}else if(s.kind==="datetime"){if(!En(s).test(e.data))n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:"datetime",message:s.message}),r.dirty()}else if(s.kind==="date"){if(!Sn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:"date",message:s.message}),r.dirty()}else if(s.kind==="time"){if(!Tn(s).test(e.data))n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:"time",message:s.message}),r.dirty()}else if(s.kind==="duration"){if(!mn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"duration",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="ip"){if(!An(e.data,s.version))n=this._getOrReturnCtx(e,n),d(n,{validation:"ip",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="jwt"){if(!In(e.data,s.alg))n=this._getOrReturnCtx(e,n),d(n,{validation:"jwt",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="cidr"){if(!Cn(e.data,s.version))n=this._getOrReturnCtx(e,n),d(n,{validation:"cidr",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="base64"){if(!xn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"base64",code:c.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="base64url"){if(!kn.test(e.data))n=this._getOrReturnCtx(e,n),d(n,{validation:"base64url",code:c.invalid_string,message:s.message}),r.dirty()}else b.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:c.invalid_string,...p.errToObj(r)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...p.errToObj(e)})}url(e){return this._addCheck({kind:"url",...p.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...p.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...p.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...p.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...p.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...p.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...p.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...p.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...p.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...p.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...p.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...p.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...p.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...p.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...p.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...p.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...p.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...p.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...p.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...p.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...p.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...p.errToObj(t)})}nonempty(e){return this.min(1,p.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...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(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}K.create=(e)=>new K({checks:[],typeName:y.ZodString,coerce:e?.coerce??!1,...v(e)});function Pn(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}class de extends _{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);if(this._getType(e)!==f.number){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:f.number,received:s.parsedType}),g}let r=void 0,n=new N;for(let s of this._def.checks)if(s.kind==="int"){if(!b.isInteger(e.data))r=this._getOrReturnCtx(e,r),d(r,{code:c.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()}else if(s.kind==="min"){if(s.inclusive?e.data<s.value:e.data<=s.value)r=this._getOrReturnCtx(e,r),d(r,{code:c.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()}else if(s.kind==="max"){if(s.inclusive?e.data>s.value:e.data>=s.value)r=this._getOrReturnCtx(e,r),d(r,{code:c.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()}else if(s.kind==="multipleOf"){if(Pn(e.data,s.value)!==0)r=this._getOrReturnCtx(e,r),d(r,{code:c.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()}else if(s.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),d(r,{code:c.not_finite,message:s.message}),n.dirty()}else b.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,p.toString(t))}gt(e,t){return this.setLimit("min",e,!1,p.toString(t))}lte(e,t){return this.setLimit("max",e,!0,p.toString(t))}lt(e,t){return this.setLimit("max",e,!1,p.toString(t))}setLimit(e,t,r,n){return new de({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:p.toString(n)}]})}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:p.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:p.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:p.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:p.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:p.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:p.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:p.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:p.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:p.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}de.create=(e)=>new de({checks:[],typeName:y.ZodNumber,coerce:e?.coerce||!1,...v(e)});class fe extends _{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)!==f.bigint)return this._getInvalidInput(e);let r=void 0,n=new N;for(let s of this._def.checks)if(s.kind==="min"){if(s.inclusive?e.data<s.value:e.data<=s.value)r=this._getOrReturnCtx(e,r),d(r,{code:c.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()}else if(s.kind==="max"){if(s.inclusive?e.data>s.value:e.data>=s.value)r=this._getOrReturnCtx(e,r),d(r,{code:c.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()}else if(s.kind==="multipleOf"){if(e.data%s.value!==BigInt(0))r=this._getOrReturnCtx(e,r),d(r,{code:c.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()}else b.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,p.toString(t))}gt(e,t){return this.setLimit("min",e,!1,p.toString(t))}lte(e,t){return this.setLimit("max",e,!0,p.toString(t))}lt(e,t){return this.setLimit("max",e,!1,p.toString(t))}setLimit(e,t,r,n){return new fe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:p.toString(n)}]})}_addCheck(e){return new fe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:p.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:p.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:p.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:p.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:p.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}fe.create=(e)=>new fe({checks:[],typeName:y.ZodBigInt,coerce:e?.coerce??!1,...v(e)});class Me extends _{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==f.boolean){let r=this._getOrReturnCtx(e);return d(r,{code:c.invalid_type,expected:f.boolean,received:r.parsedType}),g}return j(e.data)}}Me.create=(e)=>new Me({typeName:y.ZodBoolean,coerce:e?.coerce||!1,...v(e)});class be extends _{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==f.date){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:f.date,received:s.parsedType}),g}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_date}),g}let r=new N,n=void 0;for(let s of this._def.checks)if(s.kind==="min"){if(e.data.getTime()<s.value)n=this._getOrReturnCtx(e,n),d(n,{code:c.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()}else if(s.kind==="max"){if(e.data.getTime()>s.value)n=this._getOrReturnCtx(e,n),d(n,{code:c.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()}else b.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new be({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:p.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:p.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}be.create=(e)=>new be({checks:[],coerce:e?.coerce||!1,typeName:y.ZodDate,...v(e)});class je extends _{_parse(e){if(this._getType(e)!==f.symbol){let r=this._getOrReturnCtx(e);return d(r,{code:c.invalid_type,expected:f.symbol,received:r.parsedType}),g}return j(e.data)}}je.create=(e)=>new je({typeName:y.ZodSymbol,...v(e)});class we extends _{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return d(r,{code:c.invalid_type,expected:f.undefined,received:r.parsedType}),g}return j(e.data)}}we.create=(e)=>new we({typeName:y.ZodUndefined,...v(e)});class xe extends _{_parse(e){if(this._getType(e)!==f.null){let r=this._getOrReturnCtx(e);return d(r,{code:c.invalid_type,expected:f.null,received:r.parsedType}),g}return j(e.data)}}xe.create=(e)=>new xe({typeName:y.ZodNull,...v(e)});class De extends _{constructor(){super(...arguments);this._any=!0}_parse(e){return j(e.data)}}De.create=(e)=>new De({typeName:y.ZodAny,...v(e)});class ae extends _{constructor(){super(...arguments);this._unknown=!0}_parse(e){return j(e.data)}}ae.create=(e)=>new ae({typeName:y.ZodUnknown,...v(e)});class Y extends _{_parse(e){let t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:f.never,received:t.parsedType}),g}}Y.create=(e)=>new Y({typeName:y.ZodNever,...v(e)});class Le extends _{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return d(r,{code:c.invalid_type,expected:f.void,received:r.parsedType}),g}return j(e.data)}}Le.create=(e)=>new Le({typeName:y.ZodVoid,...v(e)});class q extends _{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return d(t,{code:c.invalid_type,expected:f.array,received:t.parsedType}),g;if(n.exactLength!==null){let a=t.data.length>n.exactLength.value,i=t.data.length<n.exactLength.value;if(a||i)d(t,{code:a?c.too_big:c.too_small,minimum:i?n.exactLength.value:void 0,maximum:a?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)d(t,{code:c.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)d(t,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((a,i)=>n.type._parseAsync(new V(t,a,t.path,i)))).then((a)=>N.mergeArray(r,a));let s=[...t.data].map((a,i)=>n.type._parseSync(new V(t,a,t.path,i)));return N.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new q({...this._def,minLength:{value:e,message:p.toString(t)}})}max(e,t){return new q({...this._def,maxLength:{value:e,message:p.toString(t)}})}length(e,t){return new q({...this._def,exactLength:{value:e,message:p.toString(t)}})}nonempty(e){return this.min(1,e)}}q.create=(e,t)=>new q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...v(t)});function le(e){if(e instanceof I){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=W.create(le(n))}return new I({...e._def,shape:()=>t})}else if(e instanceof q)return new q({...e._def,type:le(e.element)});else if(e instanceof W)return W.create(le(e.unwrap()));else if(e instanceof re)return re.create(le(e.unwrap()));else if(e instanceof X)return X.create(e.items.map((t)=>le(t)));else return e}class I extends _{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return d(u,{code:c.invalid_type,expected:f.object,received:u.parsedType}),g}let{status:r,ctx:n}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Y&&this._def.unknownKeys==="strip")){for(let u in n.data)if(!a.includes(u))i.push(u)}let o=[];for(let u of a){let l=s[u],h=n.data[u];o.push({key:{status:"valid",value:u},value:l._parse(new V(n,h,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof Y){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of i)o.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(u==="strict"){if(i.length>0)d(n,{code:c.unrecognized_keys,keys:i}),r.dirty()}else if(u==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of i){let h=n.data[l];o.push({key:{status:"valid",value:l},value:u._parse(new V(n,h,n.path,l)),alwaysSet:l in n.data})}}if(n.common.async)return Promise.resolve().then(async()=>{let u=[];for(let l of o){let h=await l.key,w=await l.value;u.push({key:h,value:w,alwaysSet:l.alwaysSet})}return u}).then((u)=>N.mergeObjectSync(r,u));else return N.mergeObjectSync(r,o)}get shape(){return this._def.shape()}strict(e){return p.errToObj,new I({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:p.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new I({...this._def,unknownKeys:"strip"})}passthrough(){return new I({...this._def,unknownKeys:"passthrough"})}extend(e){return new I({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new I({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new I({...this._def,catchall:e})}pick(e){let t={};for(let r of b.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new I({...this._def,shape:()=>t})}omit(e){let t={};for(let r of b.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new I({...this._def,shape:()=>t})}deepPartial(){return le(this)}partial(e){let t={};for(let r of b.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new I({...this._def,shape:()=>t})}required(e){let t={};for(let r of b.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let s=this.shape[r];while(s instanceof W)s=s._def.innerType;t[r]=s}return new I({...this._def,shape:()=>t})}keyof(){return Sr(b.objectKeys(this.shape))}}I.create=(e,t)=>new I({shape:()=>e,unknownKeys:"strip",catchall:Y.create(),typeName:y.ZodObject,...v(t)});I.strictCreate=(e,t)=>new I({shape:()=>e,unknownKeys:"strict",catchall:Y.create(),typeName:y.ZodObject,...v(t)});I.lazycreate=(e,t)=>new I({shape:e,unknownKeys:"strip",catchall:Y.create(),typeName:y.ZodObject,...v(t)});class ke extends _{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map((i)=>new F(i.ctx.common.issues));return d(t,{code:c.invalid_union,unionErrors:a}),g}if(t.common.async)return Promise.all(r.map(async(s)=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(n);else{let s=void 0,a=[];for(let o of r){let u={...t,common:{...t.common,issues:[]},parent:null},l=o._parseSync({data:t.data,path:t.path,parent:u});if(l.status==="valid")return l;else if(l.status==="dirty"&&!s)s={result:l,ctx:u};if(u.common.issues.length)a.push(u.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map((o)=>new F(o));return d(t,{code:c.invalid_union,unionErrors:i}),g}}get options(){return this._def.options}}ke.create=(e,t)=>new ke({options:e,typeName:y.ZodUnion,...v(t)});var G=(e)=>{if(e instanceof Te)return G(e.schema);else if(e instanceof H)return G(e.innerType());else if(e instanceof Ee)return[e.value];else if(e instanceof ie)return e.options;else if(e instanceof Ae)return b.objectValues(e.enum);else if(e instanceof Ie)return G(e._def.innerType);else if(e instanceof we)return[void 0];else if(e instanceof xe)return[null];else if(e instanceof W)return[void 0,...G(e.unwrap())];else if(e instanceof re)return[null,...G(e.unwrap())];else if(e instanceof et)return G(e.unwrap());else if(e instanceof Pe)return G(e.unwrap());else if(e instanceof Ce)return G(e._def.innerType);else return[]};class Ze extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return d(t,{code:c.invalid_type,expected:f.object,received:t.parsedType}),g;let r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);if(!s)return d(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g;if(t.common.async)return s._parseAsync({data:t.data,path:t.path,parent:t});else return s._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let s of t){let a=G(s.shape[e]);if(!a.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of a){if(n.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new Ze({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...v(r)})}}function Qe(e,t){let r=J(e),n=J(t);if(e===t)return{valid:!0,data:e};else if(r===f.object&&n===f.object){let s=b.objectKeys(t),a=b.objectKeys(e).filter((o)=>s.indexOf(o)!==-1),i={...e,...t};for(let o of a){let u=Qe(e[o],t[o]);if(!u.valid)return{valid:!1};i[o]=u.data}return{valid:!0,data:i}}else if(r===f.array&&n===f.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let a=0;a<e.length;a++){let i=e[a],o=t[a],u=Qe(i,o);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else if(r===f.date&&n===f.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class Se extends _{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(s,a)=>{if(Ke(s)||Ke(a))return g;let i=Qe(s.value,a.value);if(!i.valid)return d(r,{code:c.invalid_intersection_types}),g;if(Ye(s)||Ye(a))t.dirty();return{status:t.value,value:i.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>n(s,a));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Se.create=(e,t,r)=>new Se({left:e,right:t,typeName:y.ZodIntersection,...v(r)});class X extends _{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.array)return d(r,{code:c.invalid_type,expected:f.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return d(r,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;if(!this._def.rest&&r.data.length>this._def.items.length)d(r,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let s=[...r.data].map((a,i)=>{let o=this._def.items[i]||this._def.rest;if(!o)return null;return o._parse(new V(r,a,r.path,i))}).filter((a)=>!!a);if(r.common.async)return Promise.all(s).then((a)=>N.mergeArray(t,a));else return N.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new X({...this._def,rest:e})}}X.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new X({items:e,typeName:y.ZodTuple,rest:null,...v(t)})};class Fe extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return d(r,{code:c.invalid_type,expected:f.object,received:r.parsedType}),g;let n=[],s=this._def.keyType,a=this._def.valueType;for(let i in r.data)n.push({key:s._parse(new V(r,i,r.path,i)),value:a._parse(new V(r,r.data[i],r.path,i)),alwaysSet:i in r.data});if(r.common.async)return N.mergeObjectAsync(t,n);else return N.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof _)return new Fe({keyType:e,valueType:t,typeName:y.ZodRecord,...v(r)});return new Fe({keyType:K.create(),valueType:e,typeName:y.ZodRecord,...v(t)})}}class Be extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.map)return d(r,{code:c.invalid_type,expected:f.map,received:r.parsedType}),g;let n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([i,o],u)=>({key:n._parse(new V(r,i,r.path,[u,"key"])),value:s._parse(new V(r,o,r.path,[u,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let o of a){let u=await o.key,l=await o.value;if(u.status==="aborted"||l.status==="aborted")return g;if(u.status==="dirty"||l.status==="dirty")t.dirty();i.set(u.value,l.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let o of a){let{key:u,value:l}=o;if(u.status==="aborted"||l.status==="aborted")return g;if(u.status==="dirty"||l.status==="dirty")t.dirty();i.set(u.value,l.value)}return{status:t.value,value:i}}}}Be.create=(e,t,r)=>new Be({valueType:t,keyType:e,typeName:y.ZodMap,...v(r)});class he extends _{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.set)return d(r,{code:c.invalid_type,expected:f.set,received:r.parsedType}),g;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)d(r,{code:c.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)d(r,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let s=this._def.valueType;function a(o){let u=new Set;for(let l of o){if(l.status==="aborted")return g;if(l.status==="dirty")t.dirty();u.add(l.value)}return{status:t.value,value:u}}let i=[...r.data.values()].map((o,u)=>s._parse(new V(r,o,r.path,u)));if(r.common.async)return Promise.all(i).then((o)=>a(o));else return a(i)}min(e,t){return new he({...this._def,minSize:{value:e,message:p.toString(t)}})}max(e,t){return new he({...this._def,maxSize:{value:e,message:p.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}he.create=(e,t)=>new he({valueType:e,minSize:null,maxSize:null,typeName:y.ZodSet,...v(t)});class _e extends _{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return d(t,{code:c.invalid_type,expected:f.function,received:t.parsedType}),g;function r(i,o){return Ne({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ye(),te].filter((u)=>!!u),issueData:{code:c.invalid_arguments,argumentsError:o}})}function n(i,o){return Ne({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ye(),te].filter((u)=>!!u),issueData:{code:c.invalid_return_type,returnTypeError:o}})}let s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof pe){let i=this;return j(async function(...o){let u=new F([]),l=await i._def.args.parseAsync(o,s).catch((k)=>{throw u.addIssue(r(o,k)),u}),h=await Reflect.apply(a,this,l);return await i._def.returns._def.type.parseAsync(h,s).catch((k)=>{throw u.addIssue(n(h,k)),u})})}else{let i=this;return j(function(...o){let u=i._def.args.safeParse(o,s);if(!u.success)throw new F([r(o,u.error)]);let l=Reflect.apply(a,this,u.data),h=i._def.returns.safeParse(l,s);if(!h.success)throw new F([n(l,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new _e({...this._def,args:X.create(e).rest(ae.create())})}returns(e){return new _e({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new _e({args:e?e:X.create([]).rest(ae.create()),returns:t||ae.create(),typeName:y.ZodFunction,...v(r)})}}class Te extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Te.create=(e,t)=>new Te({getter:e,typeName:y.ZodLazy,...v(t)});class Ee extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ee.create=(e,t)=>new Ee({value:e,typeName:y.ZodLiteral,...v(t)});function Sr(e,t){return new ie({values:e,typeName:y.ZodEnum,...v(t)})}class ie extends _{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return d(t,{expected:b.joinValues(r),received:t.parsedType,code:c.invalid_type}),g}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return d(t,{received:t.data,code:c.invalid_enum_value,options:r}),g}return j(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ie.create(e,{...this._def,...t})}exclude(e,t=this._def){return ie.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}ie.create=Sr;class Ae extends _{_parse(e){let t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==f.string&&r.parsedType!==f.number){let n=b.objectValues(t);return d(r,{expected:b.joinValues(n),received:r.parsedType,code:c.invalid_type}),g}if(!this._cache)this._cache=new Set(b.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=b.objectValues(t);return d(r,{received:r.data,code:c.invalid_enum_value,options:n}),g}return j(e.data)}get enum(){return this._def.values}}Ae.create=(e,t)=>new Ae({values:e,typeName:y.ZodNativeEnum,...v(t)});class pe extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return d(t,{code:c.invalid_type,expected:f.promise,received:t.parsedType}),g;let r=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return j(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}pe.create=(e,t)=>new pe({type:e,typeName:y.ZodPromise,...v(t)});class H extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:(a)=>{if(d(r,a),a.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){let a=n.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async(i)=>{if(t.value==="aborted")return g;let o=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});if(o.status==="aborted")return g;if(o.status==="dirty")return ce(o.value);if(t.value==="dirty")return ce(o.value);return o});else{if(t.value==="aborted")return g;let i=this._def.schema._parseSync({data:a,path:r.path,parent:r});if(i.status==="aborted")return g;if(i.status==="dirty")return ce(i.value);if(t.value==="dirty")return ce(i.value);return i}}if(n.type==="refinement"){let a=(i)=>{let o=n.refinement(i,s);if(r.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(i.status==="aborted")return g;if(i.status==="dirty")t.dirty();return a(i.value),{status:t.value,value:i.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(i.status==="aborted")return g;if(i.status==="dirty")t.dirty();return a(i.value).then(()=>({status:t.value,value:i.value}))})}if(n.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!se(a))return g;let i=n.transform(a.value,s);if(i instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((a)=>{if(!se(a))return g;return Promise.resolve(n.transform(a.value,s)).then((i)=>({status:t.value,value:i}))});b.assertNever(n)}}H.create=(e,t,r)=>new H({schema:e,typeName:y.ZodEffects,effect:t,...v(r)});H.createWithPreprocess=(e,t,r)=>new H({schema:t,effect:{type:"preprocess",transform:e},typeName:y.ZodEffects,...v(r)});class W extends _{_parse(e){if(this._getType(e)===f.undefined)return j(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}W.create=(e,t)=>new W({innerType:e,typeName:y.ZodOptional,...v(t)});class re extends _{_parse(e){if(this._getType(e)===f.null)return j(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}re.create=(e,t)=>new re({innerType:e,typeName:y.ZodNullable,...v(t)});class Ie extends _{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===f.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:y.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...v(t)});class Ce extends _{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(ve(n))return n.then((s)=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new F(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new F(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:y.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...v(t)});class Ve extends _{_parse(e){if(this._getType(e)!==f.nan){let r=this._getOrReturnCtx(e);return d(r,{code:c.invalid_type,expected:f.nan,received:r.parsedType}),g}return{status:"valid",value:e.data}}}Ve.create=(e)=>new Ve({typeName:y.ZodNaN,...v(e)});var ga=Symbol("zod_brand");class et extends _{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ue extends _{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(s.status==="aborted")return g;if(s.status==="dirty")return t.dirty(),ce(s.value);else return this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return g;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Ue({in:e,out:t,typeName:y.ZodPipeline})}}class Pe extends _{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(se(n))n.value=Object.freeze(n.value);return n};return ve(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}}Pe.create=(e,t)=>new Pe({innerType:e,typeName:y.ZodReadonly,...v(t)});var ya={object:I.lazycreate},y;(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"})(y||(y={}));var m=K.create,M=de.create,va=Ve.create,_a=fe.create,ba=Me.create,wa=be.create,xa=je.create,ka=we.create,Sa=xe.create,Ta=De.create,ze=ae.create,Ea=Y.create,Aa=Le.create,qe=q.create,{create:U,strictCreate:Ia}=I,Ca=ke.create,Rn=Ze.create,Pa=Se.create,Ra=X.create,Tr=Fe.create,Oa=Be.create,$a=he.create,Na=_e.create,Ma=Te.create,L=Ee.create,ja=ie.create,Da=Ae.create,La=pe.create,Fa=H.create,Ba=W.create,On=re.create,Va=H.createWithPreprocess,Ua=Ue.create;function rt(...e){return e.reduce((t,r)=>({...t,...r}),{})}function He(e){return Object.fromEntries([...e.headers])}var Pr="AI_DownloadError",Rr=`vercel.ai.error.${Pr}`,$n=Symbol.for(Rr),Er,Ar,Ir=class extends(Ar=x,Er=$n,Ar){constructor({url:e,statusCode:t,statusText:r,cause:n,message:s=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:Pr,message:s,cause:n});this[Er]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return x.hasMarker(e,Rr)}};async function Nn(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch(r){}}var Mn=2147483648;async function jn({response:e,url:t,maxBytes:r=Mn}){let n=e.headers.get("content-length");if(n!=null){let h=parseInt(n,10);if(!isNaN(h)&&h>r)throw await Nn(e),new Ir({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${h}).`})}let s=e.body;if(s==null)return new Uint8Array(0);let a=s.getReader(),i=[],o=0;try{while(!0){let{done:h,value:w}=await a.read();if(h)break;if(o+=w.length,o>r)throw new Ir({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});i.push(w)}}finally{try{await a.cancel()}catch(h){}finally{a.releaseLock()}}let u=new Uint8Array(o),l=0;for(let h of i)u.set(h,l),l+=h.length;return u}var Dn=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let s=()=>{let a=r.length,i=Array(t);for(let o=0;o<t;o++)i[o]=r[Math.random()*a|0];return i.join("")};if(e==null)return s;if(r.includes(n))throw new Zt({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${s()}`},Or=Dn();function We(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Ln=["fetch failed","failed to fetch"],Fn=new Set(["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"]);function Bn(e){let t=new Set,r=e;while(r instanceof Error&&!t.has(r)){t.add(r);let n=r;if(typeof n.code==="string"&&Fn.has(n.code))return n;r=r.cause}return}function $r({error:e,url:t,requestBodyValues:r}){if(We(e))return e;if(e instanceof TypeError&&Ln.includes(e.message.toLowerCase())){let s=e.cause;if(s!=null)return new P({message:`Cannot connect to API: ${s.message}`,cause:s,url:t,requestBodyValues:r,isRetryable:!0})}let n=Bn(e);if(n!=null){if(P.isInstance(e))return new P({message:e.message,cause:e.cause,url:e.url,requestBodyValues:e.requestBodyValues,statusCode:e.statusCode,responseHeaders:e.responseHeaders,responseBody:e.responseBody,data:e.data,isRetryable:!0});return new P({message:`Cannot connect to API: ${e instanceof Error?e.message:n.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0})}return e}function Vn(e=globalThis){var t,r,n;if(e.window)return"runtime/browser";if((t=e.navigator)==null?void 0:t.userAgent)return`runtime/${e.navigator.userAgent.toLowerCase()}`;if((n=(r=e.process)==null?void 0:r.versions)==null?void 0:n.node)return`runtime/node.js/${e.process.version.substring(0)}`;if(e.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function Un(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{if(!Array.isArray(e))e=Object.entries(e);for(let[r,n]of e)if(n!=null)t[r.toLowerCase()]=n}return t}function zn(e,...t){let r=new Headers(Un(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var qn="3.0.42";function Nr({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e==="string")return e;if(e!=null)throw new ge({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ge({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 ge({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!=="string")throw new ge({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Wn=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,Hn=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Cr(e){let t=JSON.parse(e);if(t===null||typeof t!=="object")return t;if(Wn.test(e)===!1&&Hn.test(e)===!1)return t;return Jn(t)}function Jn(e){let t=[e];while(t.length){let r=t;t=[];for(let n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&n.constructor!==null&&typeof n.constructor==="object"&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let s in n){let a=n[s];if(a&&typeof a==="object")t.push(a)}}}return e}function Mr(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch(r){return Cr(e)}try{return Cr(e)}finally{Error.stackTraceLimit=t}}var tt=Symbol.for("vercel.ai.validator");function Gn(e){return{[tt]:!0,validate:e}}function Kn(e){return typeof e==="object"&&e!==null&&tt in e&&e[tt]===!0&&"validate"in e}function Yn(e){return Kn(e)?e:("~standard"in e)?Xn(e):e()}function Xn(e){return Gn(async(t)=>{let r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new ee({value:t,cause:r.issues})}})}async function Qn({value:e,schema:t}){let r=await jr({value:e,schema:t});if(!r.success)throw ee.wrap({value:e,cause:r.error});return r.value}async function jr({value:e,schema:t}){let r=Yn(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);if(n.success)return{success:!0,value:n.value,rawValue:e};return{success:!1,error:ee.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:ee.wrap({value:e,cause:n}),rawValue:e}}}async function Zn({text:e,schema:t}){try{let r=Mr(e);if(t==null)return r;return Qn({value:r,schema:t})}catch(r){if(me.isInstance(r)||ee.isInstance(r))throw r;throw new me({text:e,cause:r})}}async function Lr({text:e,schema:t}){try{let r=Mr(e);if(t==null)return{success:!0,value:r,rawValue:r};return await jr({value:r,schema:t})}catch(r){return{success:!1,error:me.isInstance(r)?r:new me({text:e,cause:r}),rawValue:void 0}}}function es({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Dr).pipeThrough(new TransformStream({async transform({data:r},n){if(r==="[DONE]")return;n.enqueue(await Lr({text:r,schema:t}))}}))}var ts=()=>globalThis.fetch,nt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i})=>rs({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i});var rs=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:a,fetch:i=ts()})=>{try{let o=await i(e,{method:"POST",headers:zn(t,`ai-sdk/provider-utils/${qn}`,Vn()),body:r.content,signal:a}),u=He(o);if(!o.ok){let l;try{l=await s({response:o,url:e,requestBodyValues:r.values})}catch(h){if(We(h)||P.isInstance(h))throw h;throw new P({message:"Failed to process error response",cause:h,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:r.values})}throw l.value}try{return await n({response:o,url:e,requestBodyValues:r.values})}catch(l){if(l instanceof Error){if(We(l)||P.isInstance(l))throw l}throw new P({message:"Failed to process successful response",cause:l,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:r.values})}}catch(o){throw $r({error:o,url:e,requestBodyValues:r.values})}};var ns=new TextDecoder;function ss({stream:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:s}){let a=e.getReader(),i=!1,o=()=>{if(!i)a.releaseLock(),i=!0};return new ReadableStream({async pull(u){try{let{done:l,value:h}=await a.read();if(l)o(),u.close();else u.enqueue(h)}catch(l){if(o(),We(l)){u.error(l);return}u.error($r({error:new P({message:"Failed to process successful response",cause:l,statusCode:n,url:t,responseHeaders:s,requestBodyValues:r}),url:t,requestBodyValues:r}))}},async cancel(u){try{await a.cancel(u)}finally{o()}}})}async function Fr({response:e,url:t}){return ns.decode(await jn({response:e,url:t}))}var Br=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:s,requestBodyValues:a})=>{let i=await Fr({response:n,url:s}),o=He(n);if(i.trim()==="")return{responseHeaders:o,value:new P({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})};try{let u=await Zn({text:i,schema:e});return{responseHeaders:o,value:new P({message:t(u),url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,data:u,isRetryable:r==null?void 0:r(n,u)})}}catch(u){return{responseHeaders:o,value:new P({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})}}},Vr=(e)=>async({response:t,url:r,requestBodyValues:n})=>{let s=He(t);if(t.body==null)throw new Kt({});return{responseHeaders:s,value:es({stream:ss({stream:t.body,url:r,requestBodyValues:n,statusCode:t.status,responseHeaders:s}),schema:e})}};var Ur=(e)=>async({response:t,url:r,requestBodyValues:n})=>{let s=await Fr({response:t,url:r}),a=await Lr({text:s,schema:e}),i=He(t);if(!a.success)throw new P({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:i,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}};var ei=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:ti,atob:ri}=globalThis;var is={debug:(e,t)=>console.debug(`[dify-ai-provider] ${e}`,t!=null?t:""),info:(e,t)=>console.log(`[dify-ai-provider] ${e}`,t!=null?t:""),warn:(e,t)=>console.warn(`[dify-ai-provider] ${e}`,t!=null?t:""),error:(e,t)=>console.error(`[dify-ai-provider] ${e}`,t!=null?t:"")},os=U({id:m(),answer:m(),task_id:m(),conversation_id:m(),message_id:m(),metadata:U({usage:U({completion_tokens:M(),prompt_tokens:M(),total_tokens:M()})})}),us=U({code:m(),message:m(),status:M()}),D=U({event:m(),conversation_id:m().optional(),message_id:m().optional(),task_id:m().optional(),created_at:M().optional()}).passthrough(),cs=D.extend({event:L("workflow_started"),workflow_run_id:m(),data:U({id:m(),workflow_id:m(),created_at:M()}).passthrough()}),ls=D.extend({event:L("workflow_finished"),workflow_run_id:m(),task_id:m().optional(),data:U({id:m(),workflow_id:m(),outputs:Tr(ze()).optional(),status:m().optional(),elapsed_time:M().optional(),total_tokens:M().optional(),total_steps:m().optional(),created_at:M().optional(),finished_at:M().optional()}).passthrough()}),ds=D.extend({event:L("node_started"),workflow_run_id:m(),data:U({id:m(),node_id:m(),node_type:m()}).passthrough()}),fs=D.extend({event:L("node_finished"),workflow_run_id:m(),data:U({id:m(),node_id:m(),node_type:m()}).passthrough()}),hs=D.extend({event:L("message"),id:m().optional(),answer:m(),from_variable_selector:qe(m()).optional()}),ps=D.extend({event:L("message_end"),id:m().optional(),metadata:U({usage:U({prompt_tokens:M().optional(),completion_tokens:M().optional(),total_tokens:M().optional(),prompt_unit_price:m().optional(),prompt_price_unit:m().optional(),prompt_price:m().optional(),completion_unit_price:m().optional(),completion_price_unit:m().optional(),completion_price:m().optional(),total_price:m().optional(),currency:m().optional(),latency:M().optional()}).passthrough(),retriever_resources:qe(ze()).optional()}).passthrough(),files:On(qe(ze())).optional()}),ms=D.extend({event:L("tts_message"),audio:m()}),gs=D.extend({event:L("tts_message_end"),audio:m()}),ys=D.extend({event:L("agent_message"),answer:m()}),vs=D.extend({event:L("agent_thought"),id:m(),position:M(),thought:m(),observation:m(),tool:m(),tool_labels:Tr(m(),m()).optional(),tool_input:m(),message_files:qe(ze())}),_s=D.extend({event:L("message_replace"),answer:m()}),bs=D.extend({event:L("message_file"),id:m(),type:m(),belongs_to:m(),url:m()}),ws=D.extend({event:L("ping")}),xs=D.extend({event:L("error"),status:M().optional(),code:m().optional(),message:m().optional()}),ks=Rn("event",[cs,ls,ds,fs,hs,ps,ms,gs,vs,ys,_s,bs,ws,xs]).or(D),Ss=class{constructor(){this.state="text",this.buffer="",this.accumulated="",this.hasStarted=!1,this.closed=!1,this.textAccumulated="",this.inString=!1,this.escape=!1}feed(e){let t=[];this.accumulated+=e;for(let n=0;n<e.length;n++){let s=e[n];if(!this.hasStarted){if(s.trim()==="")continue;this.hasStarted=!0}if(this.inString){if(this.escape)this.escape=!1,t.push({type:"text",content:s});else if(s==="\\")this.escape=!0,t.push({type:"text",content:s});else if(s==='"')this.inString=!1,t.push({type:"text",content:s});else t.push({type:"text",content:s});continue}if(s==='"'){this.inString=!0,t.push({type:"text",content:s});continue}switch(this.state){case"text":if(s==="<"&&!this.closed)this.state="maybe-open",this.buffer="<";else t.push({type:"text",content:s});break;case"maybe-open":if(this.buffer+=s,"<think>".startsWith(this.buffer)){if(this.buffer==="<think>")this.state="reasoning",this.buffer=""}else t.push({type:"text",content:this.buffer}),this.buffer="",this.state="text";break;case"reasoning":if(s==="<")this.state="maybe-close",this.buffer="<";else t.push({type:"reasoning",content:s});break;case"maybe-close":if(this.buffer+=s,"</think>".startsWith(this.buffer)){if(this.buffer==="</think>")this.state="text",this.buffer="",this.closed=!0}else t.push({type:"reasoning",content:this.buffer}),this.buffer="",this.state="reasoning";break}}let r=[];for(let n of t){let s=r[r.length-1];if(s&&s.type===n.type)s.content+=n.content;else r.push({...n})}for(let n of r)if(n.type==="text")this.textAccumulated+=n.content;return r}flush(){if(!this.buffer)return[];let e=this.state==="maybe-close"?"reasoning":"text",t=[{type:e,content:this.buffer}];if(e==="text")this.textAccumulated+=this.buffer;return this.buffer="",t}reset(e){this.accumulated="",this.buffer="",this.state="text",this.closed=!1,this.hasStarted=!1,this.inString=!1,this.escape=!1,this.feed(e)}getTextWithoutThink(){return this.textAccumulated.trim()}};function zr(e,t,r){let n=[],s=e;if(!t.length)return{toolCalls:n,cleanText:s};let a=t.map((w)=>w.toLowerCase()),i=[],o=0,u=!1,l=!1,h=-1;for(let w=0;w<e.length;w++){let k=e[w];if(l){l=!1;continue}if(k==="\\"){l=!0;continue}if(k==='"'){u=!u;continue}if(u)continue;if(k==="{"){if(o===0)h=w;o++}else if(k==="}"){if(o--,o<0)o=0;if(o===0&&h!==-1){let A=e.substring(h,w+1);try{let E=JSON.parse(A);if(E&&typeof E==="object"&&"name"in E&&"arguments"in E){let B=String(E.name).toLowerCase(),oe=a.indexOf(B);if(oe!==-1)n.push({id:r(),name:t[oe],input:JSON.stringify(E.arguments)}),i.push(A)}}catch(E){}h=-1}}}for(let w of i)s=s.replace(w,"");return{toolCalls:n,cleanText:s.trim()}}function at(e){if(!e)return'"..."';let t=e.type;if(t==="array")return`[${e.items?at(e.items):'"..."'}]`;if(t==="object"){let r=e.properties;if(!r)return"{}";return`{${Object.entries(r).slice(0,3).map(([s,a])=>`"${s}": ${at(a)}`).join(", ")}}`}if(t==="number"||t==="integer")return"0";if(t==="boolean")return"true";return'"..."'}var qr={question:"Ask the user a question",bash:"Execute a bash command",read:"Read a file",glob:"Find files by pattern",grep:"Search file contents with regex",edit:"Edit a file with string replacement",write:"Write/create a file",task:"Launch a sub-agent for complex tasks",webfetch:"Fetch content from a URL",todowrite:"Create/manage a task list",skill:"Load a specialized skill"};function Ts(e,t){if(qr[e])return qr[e];if(!t)return e;return t.replace(/[\r\n]+/g," ").split(/[.!?。]/)[0].trim().substring(0,60)}function Es(e){if(!(e==null?void 0:e.length))return{prompt:"",toolNames:[]};let t=e.filter((a)=>a.type==="function").map((a)=>({name:a.name,description:a.description,parameters:a.inputSchema}));if(!t.length)return{prompt:"",toolNames:[]};let r=t.map((a)=>a.name);return{prompt:`
4
+
5
+ # Tools
6
+ Call tools with JSON format:
7
+
8
+ ${t.map((a)=>{let i=a.parameters,o=(i==null?void 0:i.properties)?Object.entries(i.properties).map(([l,h])=>`"${l}": ${at(h)}`).join(", "):"",u=Ts(a.name,a.description);return`- ${a.name}: ${u}
9
+ {"name": "${a.name}", "arguments": {${o}}}`}).join(`
10
+ `)}`,toolNames:r}}async function As(e,t,r,n,s,a,i){try{let o;if(typeof e==="string"){let E=Buffer.from(e,"base64");o=new Blob([E],{type:t})}else o=new Blob([e],{type:t});let u=new FormData;u.append("file",o,r),u.append("user",n);let{"content-type":l,"Content-Type":h,...w}=a(),k=await fetch(`${s}/files/upload`,{method:"POST",headers:{...w},body:u});if(!k.ok){let E=await k.text().catch(()=>"");i==null||i.error("Dify file upload failed",{status:k.status,statusText:k.statusText,body:E});return}return(await k.json()).id}catch(o){i==null||i.error("Dify file upload error",{error:String(o)});return}}async function Is(e,t,r,n,s){let a=[];for(let o of e){if(!Array.isArray(o.content))continue;for(let u of o.content){if(!u||typeof u!=="object"||u.type!=="file")continue;let l=u.mediaType||u.mimeType||"";if(!l)continue;let h,w=u.filename||`file.${l.split("/")[1]||"bin"}`;if(typeof u.data==="string"){let k=u.data.match(/^data:[^;]+;base64,(.+)$/);h=k?k[1]:u.data}else if(u.data instanceof Uint8Array)h=u.data;if(h){let k=As(h,l,w,t,r,n,s).then((A)=>{if(A)return{type:l.startsWith("image/")?"image":"document",transfer_method:"local_file",upload_file_id:A};else{s==null||s.warn("Dify file upload skipped, attachment will be missing",{filename:w,mimeType:l});return}});a.push(k)}}}return(await Promise.all(a)).filter((o)=>o!==void 0)}function Cs(e){if(!e)return"";let t=e.trim(),r=t.match(/<env>([\s\S]*?)<\/env>/),n=t.match(/<directories>([\s\S]*?)<\/directories>/),s=t.match(/^You are\b[^.]*\./m);if(r||s||n){let a=[];if(s)a.push(s[0]);if(r)a.push(`<env>${r[1]}</env>`);if(n)a.push(`<directories>${n[1]}</directories>`);return a.join(`
11
+
12
+
13
+
14
+ `)}return t}function Ps(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function st(e,t){for(let r of t){let n=e[r];if(typeof n==="string"&&n)return n}return}function Rs(e,t){if(!Array.isArray(e))return[];return e.map((r,n)=>{var s,a;let i=Ps(r)?r:{},o=(s=st(i,["segment_id","document_id","id"]))!=null?s:`retriever-resource-${n+1}`,u=(a=st(i,["document_name","title","dataset_name","segment_id","id"]))!=null?a:`Retriever resource ${n+1}`,l=st(i,["document_name","filename"]);return{type:"source",sourceType:"document",id:o,mediaType:"text/plain",title:u,...l?{filename:l}:{},providerMetadata:{difyWorkflowData:{...t,retrieverResource:r}}}})}var Os=class{constructor(e,t,r){this.settings=t,this.specificationVersion="v2",this.supportedUrls={};var n;if(this.modelId=e,this.config=r,this.generateId=Or,this.chatMessagesEndpoint=`${this.config.baseURL}/chat-messages`,this.logger=t.logger===!1?void 0:(n=t.logger)!=null?n:is,!this.settings.responseMode)this.settings.responseMode="streaming"}createErrorHandler(){return Br({errorSchema:us,errorToMessage:(e)=>{var t;return(t=this.logger)==null||t.error("Dify API error",e),`Dify API error: ${e.message}`}})}get provider(){return this.config.provider}async doGenerate(e){var t,r;let{abortSignal:n}=e,{body:s,toolNames:a,requestHeaders:i}=await this.getRequestBody(e),o={...s,response_mode:"blocking"};if(this.settings.logMessages)(t=this.logger)==null||t.info("",{body:o});let{responseHeaders:u,value:l}=await nt({url:this.chatMessagesEndpoint,headers:rt(this.config.headers(),i!=null?i:e.headers),body:o,abortSignal:n,failedResponseHandler:this.createErrorHandler(),successfulResponseHandler:Ur(os),fetch:this.config.fetch}),h=l;if(this.settings.logMessages)(r=this.logger)==null||r.info("",{answer:h.answer,conversation_id:h.conversation_id});let w=[];if(h.answer){let{toolCalls:A,cleanText:E}=zr(h.answer,a,this.generateId);if(E)w.push({type:"text",text:E});for(let B of A)w.push({type:"tool-call",toolCallId:B.id,toolName:B.name,input:B.input})}let k=w.some((A)=>A.type==="tool-call");return{content:w,finishReason:k?"tool-calls":"stop",usage:{inputTokens:h.metadata.usage.prompt_tokens,outputTokens:h.metadata.usage.completion_tokens,totalTokens:h.metadata.usage.total_tokens},warnings:[],providerMetadata:{difyWorkflowData:{conversationId:h.conversation_id,messageId:h.message_id}},request:{body:JSON.stringify(o)},response:{id:h.id,timestamp:new Date,headers:u}}}async doStream(e){var t,r;if(this.settings.logMessages)(t=this.logger)==null||t.info("",{options:e});let{abortSignal:n}=e,{body:s,toolNames:a,requestHeaders:i}=await this.getRequestBody(e),o={...s,response_mode:"streaming"};if(this.settings.logMessages)(r=this.logger)==null||r.info("",{body:o});let{responseHeaders:u,value:l}=await nt({url:this.chatMessagesEndpoint,headers:rt(this.config.headers(),i!=null?i:e.headers),body:o,failedResponseHandler:this.createErrorHandler(),successfulResponseHandler:Vr(ks),abortSignal:n,fetch:this.config.fetch}),h,w,k,A=!1,E=!1,B=new Ss,oe=this.generateId,z=this.logger,Re=this.settings.logMessages;function Oe(){let O={};if(h)O.conversationId=h;if(w)O.messageId=w;if(k)O.taskId=k;return O}function C(){let O=Oe();return Object.keys(O).length?{providerMetadata:{difyWorkflowData:O}}:{}}function Je(O,S){for(let Q of O)if(Q.type==="reasoning"){if(A)S.enqueue({type:"text-end",id:"0",...C()}),A=!1;if(!E)E=!0,S.enqueue({type:"reasoning-start",id:"r0",...C()});S.enqueue({type:"reasoning-delta",id:"r0",delta:Q.content,...C()})}else if(Q.content){if(E)S.enqueue({type:"reasoning-end",id:"r0",...C()}),E=!1;if(!A)A=!0,S.enqueue({type:"text-start",id:"0",...C()});S.enqueue({type:"text-delta",id:"0",delta:Q.content,...C()})}}return{stream:l.pipeThrough(new TransformStream({transform(O,S){var Q,$e,it,ot,ut,ct,lt,dt,ft,ht,pt;if(!O.success){z==null||z.error("Dify stream parse error",{error:String(O.error)}),S.enqueue({type:"error",error:O.error});return}let T=O.value;if(Re)z==null||z.info("",{data:T});if(T.conversation_id)h=T.conversation_id;if(T.message_id)w=T.message_id;if(T.task_id)k=T.task_id;switch(T.event){case"workflow_finished":case"message_end":{let Z=0,ue=0,ne=0;if(T.event==="workflow_finished"){let R=T.data||{};Z=0,ue=(Q=R.total_tokens)!=null?Q:0,ne=($e=R.total_tokens)!=null?$e:0}else{let R=((it=T.metadata)==null?void 0:it.usage)||{};Z=(ot=R.prompt_tokens)!=null?ot:0,ue=(ut=R.completion_tokens)!=null?ut:0,ne=(ct=R.total_tokens)!=null?ct:0}let Wr=B.getTextWithoutThink(),{toolCalls:Ge}=zr(Wr,a,oe),mt=Ge.length>0;if(Re)z==null||z.info("",{toolCalls:Ge});if(Je(B.flush(),S),E)S.enqueue({type:"reasoning-end",id:"r0",...C()}),E=!1;if(A)S.enqueue({type:"text-end",id:"0",...C()}),A=!1;else if(!mt)S.enqueue({type:"text-start",id:"0",...C()}),S.enqueue({type:"text-end",id:"0",...C()});if(T.event==="message_end")for(let R of Rs((lt=T.metadata)==null?void 0:lt.retriever_resources,Oe()))S.enqueue(R);for(let R of Ge)S.enqueue({type:"tool-input-start",id:R.id,toolName:R.name,...C()}),S.enqueue({type:"tool-input-delta",id:R.id,delta:R.input,...C()}),S.enqueue({type:"tool-input-end",id:R.id,...C()}),S.enqueue({type:"tool-call",toolCallId:R.id,toolName:R.name,input:R.input,...C()});S.enqueue({type:"finish",finishReason:mt?"tool-calls":"stop",...C(),usage:{inputTokens:Z,outputTokens:ue,totalTokens:ne}});break}case"message":case"agent_message":{if("answer"in T&&typeof T.answer==="string"&&T.answer){if(Je(B.feed(T.answer),S),"id"in T&&typeof T.id==="string")S.enqueue({type:"response-metadata",id:T.id})}break}case"agent_thought":break;case"message_replace":{if("answer"in T&&typeof T.answer==="string"&&T.answer){if(B.reset(T.answer),A)S.enqueue({type:"text-end",id:"0",...C()}),A=!1;S.enqueue({type:"text-start",id:"0",...C()}),S.enqueue({type:"text-delta",id:"0",delta:T.answer,...C()}),A=!0}break}case"message_file":case"ping":break;case"error":{let Z=T,ue=(ft=(dt=Z.message)!=null?dt:Z.msg)!=null?ft:"Unknown Dify error",ne=(pt=(ht=Z.code)!=null?ht:Z.status)!=null?pt:"";z==null||z.error("Dify stream error",{code:ne,message:ue}),S.enqueue({type:"error",error:Error(`Dify error${ne?` (${ne})`:""}: ${ue}`)});break}}}})),request:{body:JSON.stringify(o)},response:{headers:u}}}async getRequestBody(e){var t,r,n,s,a;let i=e,o=(t=e.prompt)!=null?t:i.messages;if(!o||!o.length)throw(r=this.logger)==null||r.error("No messages provided",{prompt:e.prompt}),new P({message:"No messages provided",url:this.chatMessagesEndpoint,requestBodyValues:e});let u=this.findConversationId(e.headers,o),l=this.buildQuery(o,u);if(!l)throw(n=this.logger)==null||n.error("No user message found",{messageCount:o.length,roles:o.map(($e)=>$e.role)}),new P({message:"No user message found",url:this.chatMessagesEndpoint,requestBodyValues:{messageCount:o.length}});let h=(a=(s=e.headers)==null?void 0:s["user-id"])!=null?a:"you_should_pass_user-id",{"chat-id":w,"user-id":k,...A}=e.headers||{},E=await Is(o,h,this.config.baseURL,this.config.headers,this.logger),B=this.extractSystemPrompt(o),oe=this.settings.injectToolsPrompt!==!1,{prompt:z,toolNames:Re}=Es(e.tools),Oe=oe?z:"",C=!u,O=[C?B:"",l,C?Oe:""].filter(Boolean).join(`
15
+
16
+ `);return{body:{inputs:this.settings.inputs||{},query:O,response_mode:this.settings.responseMode,conversation_id:u,user:h,...E.length?{files:E}:{}},toolNames:Re,requestHeaders:A}}findConversationId(e,t){var r,n;if(e==null?void 0:e["chat-id"])return e["chat-id"];for(let s=t.length-1;s>=0;s--){let a=t[s];if(Array.isArray(a.content))for(let i of a.content){let o=((r=i==null?void 0:i.providerMetadata)==null?void 0:r.difyWorkflowData)||((n=i==null?void 0:i.callProviderMetadata)==null?void 0:n.difyWorkflowData);if(o==null?void 0:o.conversationId)return o.conversationId}}return}buildQuery(e,t){let r=0;if(t){r=e.length;for(let n=e.length-1;n>=0;n--){let s=e[n];if(s.role==="tool"){r=n;continue}if(s.role==="user"){r=n;break}break}}return e.slice(r).filter((n)=>n.role==="user"||n.role==="tool"||!t&&n.role==="assistant").map((n)=>{if(n.role==="tool")return this.extractToolResult(n);return this.extractTextFromMessage(n)}).filter(Boolean).join(`
17
+
18
+ `)}extractSystemPrompt(e){let t=e.find((n)=>n.role==="system"),r=t?this.extractTextFromMessage(t):"";return Cs(r)}extractTextFromMessage(e){if(typeof e.content==="string")return e.content;if(Array.isArray(e.content))return e.content.map((t)=>{if(typeof t==="string")return t;if((t==null?void 0:t.type)==="text"&&t.text)return t.text;return""}).filter(Boolean).join(" ");return""}extractToolResult(e){var t,r,n;let s=e.content;if(!Array.isArray(s))return"";let a=[];for(let i of s)if((i==null?void 0:i.type)==="tool-result"){let o=i.toolName||"tool",u=(n=(r=(t=i.output)!=null?t:i.result)!=null?r:i.content)!=null?n:i.text,l=u!==void 0&&typeof u==="object"&&u!==null&&"value"in u?u.value:u,h=l===void 0?"[completed]":typeof l==="string"?l:JSON.stringify(l);a.push(`[${o} result]: ${h}`)}return a.join(`
19
+ `)}};function pl(e={}){let t=(n,s={})=>new Os(n,s,{provider:"dify.chat",baseURL:e.baseURL||"https://api.dify.ai/v1",headers:()=>({Authorization:`Bearer ${Nr({apiKey:s.apiKey,environmentVariableName:"DIFY_API_KEY",description:"Dify API Key"})}`,"Content-Type":"application/json",...e.headers})}),r=function(n,s){if(new.target)throw Error("The model factory function cannot be called with the new keyword.");return t(n,s)};return r.chat=t,r}var fi=pl();
20
+ export{pl};
@@ -0,0 +1 @@
1
+ import{xt,xc,Qm,kn,bc,Di}from"./index-6k6ep10s.js";export{xc as SpanStatusCode,Qm as context,xt as createContextKey,kn as metrics,bc as propagation,Di as trace};