@mastra/core 1.0.0-beta.5 → 1.0.0-beta.7

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 (421) hide show
  1. package/CHANGELOG.md +448 -0
  2. package/dist/agent/agent-legacy.d.ts +17 -20
  3. package/dist/agent/agent-legacy.d.ts.map +1 -1
  4. package/dist/agent/agent-types.test-d.d.ts +2 -0
  5. package/dist/agent/agent-types.test-d.d.ts.map +1 -0
  6. package/dist/agent/agent.d.ts +4 -4
  7. package/dist/agent/agent.d.ts.map +1 -1
  8. package/dist/agent/agent.types.d.ts +1 -1
  9. package/dist/agent/agent.types.d.ts.map +1 -1
  10. package/dist/agent/index.cjs +9 -9
  11. package/dist/agent/index.js +2 -2
  12. package/dist/agent/message-list/index.cjs +3 -3
  13. package/dist/agent/message-list/index.d.ts +49 -0
  14. package/dist/agent/message-list/index.d.ts.map +1 -1
  15. package/dist/agent/message-list/index.js +1 -1
  16. package/dist/agent/save-queue/index.d.ts +3 -1
  17. package/dist/agent/save-queue/index.d.ts.map +1 -1
  18. package/dist/agent/test-utils.d.ts +37 -0
  19. package/dist/agent/test-utils.d.ts.map +1 -1
  20. package/dist/agent/trip-wire.d.ts.map +1 -1
  21. package/dist/agent/types.d.ts +18 -3
  22. package/dist/agent/types.d.ts.map +1 -1
  23. package/dist/agent/utils.d.ts.map +1 -1
  24. package/dist/agent/workflows/prepare-stream/index.d.ts +10 -10
  25. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  26. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts +1 -3
  27. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  28. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +4 -4
  29. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts.map +1 -1
  30. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +4 -4
  31. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  32. package/dist/agent/workflows/prepare-stream/schema.d.ts +14 -14
  33. package/dist/agent/workflows/prepare-stream/schema.d.ts.map +1 -1
  34. package/dist/base.cjs +2 -2
  35. package/dist/base.js +1 -1
  36. package/dist/bundler/index.cjs +2 -2
  37. package/dist/bundler/index.js +1 -1
  38. package/dist/cache/index.cjs +3 -3
  39. package/dist/cache/index.js +1 -1
  40. package/dist/{chunk-556MJ7CL.cjs → chunk-26YAGTXK.cjs} +43 -37
  41. package/dist/chunk-26YAGTXK.cjs.map +1 -0
  42. package/dist/{chunk-OJNJA5ZI.js → chunk-3CKZSDTQ.js} +3 -3
  43. package/dist/{chunk-OJNJA5ZI.js.map → chunk-3CKZSDTQ.js.map} +1 -1
  44. package/dist/{chunk-E7K4FTLN.cjs → chunk-3EYBRHB2.cjs} +18 -2
  45. package/dist/chunk-3EYBRHB2.cjs.map +1 -0
  46. package/dist/{chunk-X7F4CSGR.cjs → chunk-3JA6VPNM.cjs} +2 -2
  47. package/dist/chunk-3JA6VPNM.cjs.map +1 -0
  48. package/dist/{chunk-TQTAMPSC.js → chunk-3N3QE4ZK.js} +3 -3
  49. package/dist/chunk-3N3QE4ZK.js.map +1 -0
  50. package/dist/{chunk-BMAFVZ2D.cjs → chunk-4AP234N6.cjs} +4 -4
  51. package/dist/{chunk-BMAFVZ2D.cjs.map → chunk-4AP234N6.cjs.map} +1 -1
  52. package/dist/{chunk-XIDKHXNR.js → chunk-4F6RAJFU.js} +33 -6
  53. package/dist/chunk-4F6RAJFU.js.map +1 -0
  54. package/dist/{chunk-B5J5HYDN.js → chunk-4GTU7MB2.js} +160 -8
  55. package/dist/chunk-4GTU7MB2.js.map +1 -0
  56. package/dist/{chunk-ISMGVGUM.cjs → chunk-4JKEUSCC.cjs} +4 -4
  57. package/dist/{chunk-ISMGVGUM.cjs.map → chunk-4JKEUSCC.cjs.map} +1 -1
  58. package/dist/{chunk-KJIQGPQR.js → chunk-5T53HHNP.js} +24 -10
  59. package/dist/chunk-5T53HHNP.js.map +1 -0
  60. package/dist/{chunk-CBAB7GOD.cjs → chunk-6BJ7XHRH.cjs} +2 -2
  61. package/dist/{chunk-CBAB7GOD.cjs.map → chunk-6BJ7XHRH.cjs.map} +1 -1
  62. package/dist/{chunk-RROQ46B6.cjs → chunk-6C2PU6J4.cjs} +31 -47
  63. package/dist/chunk-6C2PU6J4.cjs.map +1 -0
  64. package/dist/{chunk-J7O6WENZ.cjs → chunk-6TBWJV35.js} +5 -5
  65. package/dist/chunk-6TBWJV35.js.map +1 -0
  66. package/dist/{chunk-DSNPWVIG.cjs → chunk-AF74UXR5.cjs} +4 -3
  67. package/dist/chunk-AF74UXR5.cjs.map +1 -0
  68. package/dist/chunk-AZQMPE7G.cjs +4981 -0
  69. package/dist/chunk-AZQMPE7G.cjs.map +1 -0
  70. package/dist/{chunk-HNHZGFZY.cjs → chunk-CZEJQSWB.cjs} +10 -2
  71. package/dist/chunk-CZEJQSWB.cjs.map +1 -0
  72. package/dist/{chunk-KEXGB7FK.cjs → chunk-DGV2FWB4.cjs} +7 -7
  73. package/dist/{chunk-KEXGB7FK.cjs.map → chunk-DGV2FWB4.cjs.map} +1 -1
  74. package/dist/{chunk-YDFX3JR2.js → chunk-DMPHPHMU.js} +174 -12
  75. package/dist/chunk-DMPHPHMU.js.map +1 -0
  76. package/dist/{chunk-76K3IYWM.js → chunk-EE5NIGJ4.js} +3 -3
  77. package/dist/{chunk-76K3IYWM.js.map → chunk-EE5NIGJ4.js.map} +1 -1
  78. package/dist/{chunk-Y63IFHEZ.cjs → chunk-EOPEDKLG.cjs} +4 -4
  79. package/dist/chunk-EOPEDKLG.cjs.map +1 -0
  80. package/dist/{chunk-T2CJRA6E.js → chunk-EPMSC67U.js} +145 -19
  81. package/dist/chunk-EPMSC67U.js.map +1 -0
  82. package/dist/{chunk-NZAXAFI3.js → chunk-F2GAJSBI.js} +3 -3
  83. package/dist/{chunk-NZAXAFI3.js.map → chunk-F2GAJSBI.js.map} +1 -1
  84. package/dist/{chunk-5O52O25J.js → chunk-F54IK3GJ.js} +2 -2
  85. package/dist/chunk-F54IK3GJ.js.map +1 -0
  86. package/dist/{chunk-KIZIOFZC.js → chunk-FNSFXWDN.js} +17 -3
  87. package/dist/chunk-FNSFXWDN.js.map +1 -0
  88. package/dist/{chunk-ZTTMSCLU.js → chunk-G32WDDGV.js} +85 -9
  89. package/dist/chunk-G32WDDGV.js.map +1 -0
  90. package/dist/{chunk-5SA2EZ33.js → chunk-GZ6MCDK2.js} +147 -15
  91. package/dist/chunk-GZ6MCDK2.js.map +1 -0
  92. package/dist/{chunk-NHP6ZIDG.cjs → chunk-HJNEZRI4.cjs} +28 -174
  93. package/dist/chunk-HJNEZRI4.cjs.map +1 -0
  94. package/dist/{chunk-S6URFGCZ.js → chunk-LSHPJWM5.js} +3 -3
  95. package/dist/{chunk-S6URFGCZ.js.map → chunk-LSHPJWM5.js.map} +1 -1
  96. package/dist/{chunk-XJQX54QP.cjs → chunk-M7CQULF7.cjs} +97 -16
  97. package/dist/chunk-M7CQULF7.cjs.map +1 -0
  98. package/dist/{chunk-D7CJ4HIQ.js → chunk-NAKPEQEQ.js} +10 -156
  99. package/dist/chunk-NAKPEQEQ.js.map +1 -0
  100. package/dist/{chunk-KJ2SW6VA.js → chunk-NRUZYMHE.js} +4 -3
  101. package/dist/chunk-NRUZYMHE.js.map +1 -0
  102. package/dist/{chunk-KWWD3U7G.cjs → chunk-PJ7AYWAX.cjs} +155 -29
  103. package/dist/chunk-PJ7AYWAX.cjs.map +1 -0
  104. package/dist/{chunk-7ZADRRDW.js → chunk-PK2A5WBG.js} +3 -3
  105. package/dist/chunk-PK2A5WBG.js.map +1 -0
  106. package/dist/{chunk-XBO6W7LZ.js → chunk-POM7FCH5.js} +6166 -4133
  107. package/dist/chunk-POM7FCH5.js.map +1 -0
  108. package/dist/{chunk-X7JMA3IY.js → chunk-PSCMWPLC.js} +2 -2
  109. package/dist/{chunk-X7JMA3IY.js.map → chunk-PSCMWPLC.js.map} +1 -1
  110. package/dist/{chunk-KP42JLXE.cjs → chunk-RBBEMTMA.cjs} +6199 -4154
  111. package/dist/chunk-RBBEMTMA.cjs.map +1 -0
  112. package/dist/chunk-TLLXRG2Z.js +4959 -0
  113. package/dist/chunk-TLLXRG2Z.js.map +1 -0
  114. package/dist/{chunk-SVLMF4UZ.cjs → chunk-TQB2HMEC.cjs} +45 -44
  115. package/dist/chunk-TQB2HMEC.cjs.map +1 -0
  116. package/dist/{chunk-Y6ROD72V.cjs → chunk-UIGRFDO6.cjs} +4 -4
  117. package/dist/{chunk-Y6ROD72V.cjs.map → chunk-UIGRFDO6.cjs.map} +1 -1
  118. package/dist/{chunk-PC6EKOWK.js → chunk-URBPEE67.js} +19 -31
  119. package/dist/chunk-URBPEE67.js.map +1 -0
  120. package/dist/{chunk-VYJXTHII.cjs → chunk-URMN7TTH.cjs} +148 -16
  121. package/dist/chunk-URMN7TTH.cjs.map +1 -0
  122. package/dist/{chunk-GRBGQ2GE.js → chunk-UVHSM2GU.cjs} +9 -3
  123. package/dist/chunk-UVHSM2GU.cjs.map +1 -0
  124. package/dist/{chunk-U3VE2EVB.cjs → chunk-VBKMNIWK.cjs} +30 -16
  125. package/dist/chunk-VBKMNIWK.cjs.map +1 -0
  126. package/dist/{chunk-V537VSV4.cjs → chunk-Y24HI6ND.cjs} +37 -10
  127. package/dist/chunk-Y24HI6ND.cjs.map +1 -0
  128. package/dist/{chunk-DQIZ5FFX.cjs → chunk-YBEW5YWC.cjs} +177 -15
  129. package/dist/chunk-YBEW5YWC.cjs.map +1 -0
  130. package/dist/{chunk-OUUPUAGA.cjs → chunk-YUXTDKYN.cjs} +168 -15
  131. package/dist/chunk-YUXTDKYN.cjs.map +1 -0
  132. package/dist/{chunk-IITXXVYI.cjs → chunk-YWMMBIOM.cjs} +10 -10
  133. package/dist/{chunk-IITXXVYI.cjs.map → chunk-YWMMBIOM.cjs.map} +1 -1
  134. package/dist/{chunk-3B2OPLGG.js → chunk-Z4Y554NX.js} +13 -7
  135. package/dist/chunk-Z4Y554NX.js.map +1 -0
  136. package/dist/{chunk-3ZQ7LX73.js → chunk-Z57R5WS4.js} +4 -4
  137. package/dist/{chunk-3ZQ7LX73.js.map → chunk-Z57R5WS4.js.map} +1 -1
  138. package/dist/{chunk-QM5SRDJX.js → chunk-ZUWJCGLM.js} +5 -4
  139. package/dist/chunk-ZUWJCGLM.js.map +1 -0
  140. package/dist/deployer/index.cjs +2 -2
  141. package/dist/deployer/index.js +1 -1
  142. package/dist/di/index.cjs +10 -2
  143. package/dist/di/index.d.ts +1 -1
  144. package/dist/di/index.d.ts.map +1 -1
  145. package/dist/di/index.js +1 -1
  146. package/dist/evals/base.d.ts +9 -1
  147. package/dist/evals/base.d.ts.map +1 -1
  148. package/dist/evals/index.cjs +9 -9
  149. package/dist/evals/index.js +2 -2
  150. package/dist/evals/scoreTraces/index.cjs +5 -5
  151. package/dist/evals/scoreTraces/index.js +2 -2
  152. package/dist/evals/types.d.ts +8 -8
  153. package/dist/index.cjs +2 -2
  154. package/dist/index.js +1 -1
  155. package/dist/integration/index.cjs +2 -2
  156. package/dist/integration/index.js +1 -1
  157. package/dist/llm/index.cjs +15 -15
  158. package/dist/llm/index.js +5 -5
  159. package/dist/llm/model/aisdk/v5/model.d.ts.map +1 -1
  160. package/dist/llm/model/gateways/constants.d.ts.map +1 -1
  161. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
  162. package/dist/llm/model/model.d.ts.map +1 -1
  163. package/dist/llm/model/model.loop.d.ts +1 -1
  164. package/dist/llm/model/model.loop.d.ts.map +1 -1
  165. package/dist/llm/model/provider-options.d.ts +4 -1
  166. package/dist/llm/model/provider-options.d.ts.map +1 -1
  167. package/dist/llm/model/provider-registry.d.ts.map +1 -1
  168. package/dist/llm/model/provider-types.generated.d.ts +39 -1
  169. package/dist/logger/constants.d.ts +1 -0
  170. package/dist/logger/constants.d.ts.map +1 -1
  171. package/dist/logger/index.cjs +11 -11
  172. package/dist/logger/index.js +2 -2
  173. package/dist/logger/transport.d.ts +1 -1
  174. package/dist/logger/transport.d.ts.map +1 -1
  175. package/dist/loop/index.cjs +2 -2
  176. package/dist/loop/index.js +1 -1
  177. package/dist/loop/loop.d.ts.map +1 -1
  178. package/dist/loop/network/index.d.ts +2 -2
  179. package/dist/loop/network/index.d.ts.map +1 -1
  180. package/dist/loop/test-utils/fullStream.d.ts.map +1 -1
  181. package/dist/loop/types.d.ts +5 -2
  182. package/dist/loop/types.d.ts.map +1 -1
  183. package/dist/loop/workflows/agentic-execution/index.d.ts +96 -96
  184. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +65 -65
  185. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  186. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +32 -32
  187. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  188. package/dist/loop/workflows/agentic-loop/index.d.ts +97 -97
  189. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  190. package/dist/loop/workflows/schema.d.ts +32 -32
  191. package/dist/loop/workflows/stream.d.ts +1 -1
  192. package/dist/loop/workflows/stream.d.ts.map +1 -1
  193. package/dist/mastra/index.cjs +2 -2
  194. package/dist/mastra/index.d.ts +55 -0
  195. package/dist/mastra/index.d.ts.map +1 -1
  196. package/dist/mastra/index.js +1 -1
  197. package/dist/mcp/index.cjs +4 -4
  198. package/dist/mcp/index.js +2 -2
  199. package/dist/memory/index.cjs +21 -382
  200. package/dist/memory/index.cjs.map +1 -1
  201. package/dist/memory/index.js +1 -382
  202. package/dist/memory/index.js.map +1 -1
  203. package/dist/memory/memory.d.ts +22 -18
  204. package/dist/memory/memory.d.ts.map +1 -1
  205. package/dist/memory/mock.d.ts +6 -1
  206. package/dist/memory/mock.d.ts.map +1 -1
  207. package/dist/memory/types.d.ts +69 -11
  208. package/dist/memory/types.d.ts.map +1 -1
  209. package/dist/models-dev-6GD3644V.js +3 -0
  210. package/dist/{models-dev-F6MTIYTO.js.map → models-dev-6GD3644V.js.map} +1 -1
  211. package/dist/models-dev-IUQBXJSS.cjs +12 -0
  212. package/dist/{models-dev-XIVR5EJV.cjs.map → models-dev-IUQBXJSS.cjs.map} +1 -1
  213. package/dist/netlify-GXJ5D5DD.js +3 -0
  214. package/dist/{netlify-RX3JXCFQ.js.map → netlify-GXJ5D5DD.js.map} +1 -1
  215. package/dist/netlify-KJLY3GFS.cjs +12 -0
  216. package/dist/{netlify-MXBOGAJR.cjs.map → netlify-KJLY3GFS.cjs.map} +1 -1
  217. package/dist/observability/index.cjs +16 -8
  218. package/dist/observability/index.js +1 -1
  219. package/dist/observability/types/tracing.d.ts +183 -3
  220. package/dist/observability/types/tracing.d.ts.map +1 -1
  221. package/dist/observability/utils.d.ts +47 -1
  222. package/dist/observability/utils.d.ts.map +1 -1
  223. package/dist/processors/index.cjs +35 -11
  224. package/dist/processors/index.d.ts +99 -21
  225. package/dist/processors/index.d.ts.map +1 -1
  226. package/dist/processors/index.js +1 -1
  227. package/dist/processors/memory/index.d.ts +7 -0
  228. package/dist/processors/memory/index.d.ts.map +1 -0
  229. package/dist/processors/memory/message-history.d.ts +43 -0
  230. package/dist/processors/memory/message-history.d.ts.map +1 -0
  231. package/dist/processors/memory/semantic-recall.d.ts +152 -0
  232. package/dist/processors/memory/semantic-recall.d.ts.map +1 -0
  233. package/dist/processors/memory/working-memory.d.ts +65 -0
  234. package/dist/processors/memory/working-memory.d.ts.map +1 -0
  235. package/dist/processors/processors/index.d.ts +2 -1
  236. package/dist/processors/processors/index.d.ts.map +1 -1
  237. package/dist/processors/processors/language-detector.d.ts +14 -0
  238. package/dist/processors/processors/language-detector.d.ts.map +1 -1
  239. package/dist/processors/processors/moderation.d.ts +14 -0
  240. package/dist/processors/processors/moderation.d.ts.map +1 -1
  241. package/dist/processors/processors/pii-detector.d.ts +14 -0
  242. package/dist/processors/processors/pii-detector.d.ts.map +1 -1
  243. package/dist/processors/processors/prompt-injection-detector.d.ts +14 -0
  244. package/dist/processors/processors/prompt-injection-detector.d.ts.map +1 -1
  245. package/dist/processors/processors/structured-output.d.ts +2 -1
  246. package/dist/processors/processors/structured-output.d.ts.map +1 -1
  247. package/dist/processors/processors/token-limiter.d.ts +21 -11
  248. package/dist/processors/processors/token-limiter.d.ts.map +1 -1
  249. package/dist/processors/processors/tool-call-filter.d.ts +28 -0
  250. package/dist/processors/processors/tool-call-filter.d.ts.map +1 -0
  251. package/dist/processors/runner.d.ts +35 -4
  252. package/dist/processors/runner.d.ts.map +1 -1
  253. package/dist/provider-registry-7IFOXWPR.cjs +40 -0
  254. package/dist/{provider-registry-NBRXBOQT.cjs.map → provider-registry-7IFOXWPR.cjs.map} +1 -1
  255. package/dist/provider-registry-ZTMZMTVV.js +3 -0
  256. package/dist/{provider-registry-3LUCE7FT.js.map → provider-registry-ZTMZMTVV.js.map} +1 -1
  257. package/dist/provider-registry.json +111 -6
  258. package/dist/{registry-generator-DEPPRYYJ.cjs → registry-generator-34SC4TAU.cjs} +2 -2
  259. package/dist/registry-generator-34SC4TAU.cjs.map +1 -0
  260. package/dist/{registry-generator-FLW6NV42.js → registry-generator-UMTNPBJX.js} +2 -2
  261. package/dist/registry-generator-UMTNPBJX.js.map +1 -0
  262. package/dist/relevance/index.cjs +2 -2
  263. package/dist/relevance/index.js +1 -1
  264. package/dist/request-context/index.cjs +10 -2
  265. package/dist/request-context/index.d.ts +26 -0
  266. package/dist/request-context/index.d.ts.map +1 -1
  267. package/dist/request-context/index.js +1 -1
  268. package/dist/server/base.d.ts +51 -0
  269. package/dist/server/base.d.ts.map +1 -0
  270. package/dist/server/index.cjs +81 -2
  271. package/dist/server/index.cjs.map +1 -1
  272. package/dist/server/index.d.ts +3 -0
  273. package/dist/server/index.d.ts.map +1 -1
  274. package/dist/server/index.js +79 -2
  275. package/dist/server/index.js.map +1 -1
  276. package/dist/server/simple-auth.d.ts +27 -0
  277. package/dist/server/simple-auth.d.ts.map +1 -0
  278. package/dist/storage/base.d.ts +22 -1
  279. package/dist/storage/base.d.ts.map +1 -1
  280. package/dist/storage/domains/memory/inmemory.d.ts.map +1 -1
  281. package/dist/storage/index.cjs +49 -29
  282. package/dist/storage/index.js +1 -1
  283. package/dist/storage/storageWithInit.d.ts.map +1 -1
  284. package/dist/storage/types.d.ts +1 -1
  285. package/dist/storage/types.d.ts.map +1 -1
  286. package/dist/storage/utils.d.ts +82 -0
  287. package/dist/storage/utils.d.ts.map +1 -1
  288. package/dist/stream/MastraAgentNetworkStream.d.ts +1 -1
  289. package/dist/stream/MastraAgentNetworkStream.d.ts.map +1 -1
  290. package/dist/stream/MastraWorkflowStream.d.ts +1 -1
  291. package/dist/stream/MastraWorkflowStream.d.ts.map +1 -1
  292. package/dist/stream/RunOutput.d.ts +2 -2
  293. package/dist/stream/RunOutput.d.ts.map +1 -1
  294. package/dist/stream/aisdk/v5/execute.d.ts +3 -2
  295. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  296. package/dist/stream/aisdk/v5/input.d.ts +4 -1
  297. package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
  298. package/dist/stream/aisdk/v5/output.d.ts +1 -1
  299. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  300. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  301. package/dist/stream/base/base.d.ts +1 -1
  302. package/dist/stream/base/base.d.ts.map +1 -1
  303. package/dist/stream/base/output-format-handlers.d.ts +1 -1
  304. package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
  305. package/dist/stream/base/output.d.ts +1 -1
  306. package/dist/stream/base/output.d.ts.map +1 -1
  307. package/dist/stream/index.cjs +11 -11
  308. package/dist/stream/index.js +2 -2
  309. package/dist/stream/types.d.ts +2 -0
  310. package/dist/stream/types.d.ts.map +1 -1
  311. package/dist/test-utils/llm-mock.cjs +44 -10
  312. package/dist/test-utils/llm-mock.cjs.map +1 -1
  313. package/dist/test-utils/llm-mock.d.ts +3 -0
  314. package/dist/test-utils/llm-mock.d.ts.map +1 -1
  315. package/dist/test-utils/llm-mock.js +36 -6
  316. package/dist/test-utils/llm-mock.js.map +1 -1
  317. package/dist/tools/index.cjs +6 -6
  318. package/dist/tools/index.js +2 -2
  319. package/dist/tools/is-vercel-tool.cjs +2 -2
  320. package/dist/tools/is-vercel-tool.js +1 -1
  321. package/dist/tools/stream.d.ts +18 -2
  322. package/dist/tools/stream.d.ts.map +1 -1
  323. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  324. package/dist/tools/tool.d.ts +13 -0
  325. package/dist/tools/tool.d.ts.map +1 -1
  326. package/dist/tools/types.d.ts +24 -3
  327. package/dist/tools/types.d.ts.map +1 -1
  328. package/dist/tools/validation.d.ts +1 -1
  329. package/dist/tools/validation.d.ts.map +1 -1
  330. package/dist/tts/index.cjs +2 -2
  331. package/dist/tts/index.js +1 -1
  332. package/dist/utils.cjs +22 -22
  333. package/dist/utils.d.ts +1 -1
  334. package/dist/utils.d.ts.map +1 -1
  335. package/dist/utils.js +1 -1
  336. package/dist/vector/index.cjs +4 -4
  337. package/dist/vector/index.js +2 -2
  338. package/dist/voice/index.cjs +6 -6
  339. package/dist/voice/index.js +1 -1
  340. package/dist/workflows/default.d.ts +176 -281
  341. package/dist/workflows/default.d.ts.map +1 -1
  342. package/dist/workflows/evented/index.cjs +10 -10
  343. package/dist/workflows/evented/index.js +1 -1
  344. package/dist/workflows/evented/step-executor.d.ts +1 -1
  345. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  346. package/dist/workflows/execution-engine.d.ts +4 -2
  347. package/dist/workflows/execution-engine.d.ts.map +1 -1
  348. package/dist/workflows/handlers/control-flow.d.ts +135 -0
  349. package/dist/workflows/handlers/control-flow.d.ts.map +1 -0
  350. package/dist/workflows/handlers/entry.d.ts +45 -0
  351. package/dist/workflows/handlers/entry.d.ts.map +1 -0
  352. package/dist/workflows/handlers/sleep.d.ts +62 -0
  353. package/dist/workflows/handlers/sleep.d.ts.map +1 -0
  354. package/dist/workflows/handlers/step.d.ts +60 -0
  355. package/dist/workflows/handlers/step.d.ts.map +1 -0
  356. package/dist/workflows/index.cjs +20 -20
  357. package/dist/workflows/index.js +1 -1
  358. package/dist/workflows/step.d.ts +2 -2
  359. package/dist/workflows/step.d.ts.map +1 -1
  360. package/dist/workflows/types.d.ts +158 -3
  361. package/dist/workflows/types.d.ts.map +1 -1
  362. package/dist/workflows/workflow.d.ts +8 -6
  363. package/dist/workflows/workflow.d.ts.map +1 -1
  364. package/package.json +8 -5
  365. package/src/llm/model/provider-types.generated.d.ts +39 -1
  366. package/dist/chunk-3B2OPLGG.js.map +0 -1
  367. package/dist/chunk-3PSWNGBF.js +0 -3
  368. package/dist/chunk-3PSWNGBF.js.map +0 -1
  369. package/dist/chunk-436FFEF6.js +0 -34
  370. package/dist/chunk-436FFEF6.js.map +0 -1
  371. package/dist/chunk-556MJ7CL.cjs.map +0 -1
  372. package/dist/chunk-5O52O25J.js.map +0 -1
  373. package/dist/chunk-5SA2EZ33.js.map +0 -1
  374. package/dist/chunk-7ZADRRDW.js.map +0 -1
  375. package/dist/chunk-B5J5HYDN.js.map +0 -1
  376. package/dist/chunk-D7CJ4HIQ.js.map +0 -1
  377. package/dist/chunk-DQIZ5FFX.cjs.map +0 -1
  378. package/dist/chunk-DSNPWVIG.cjs.map +0 -1
  379. package/dist/chunk-E7K4FTLN.cjs.map +0 -1
  380. package/dist/chunk-GRBGQ2GE.js.map +0 -1
  381. package/dist/chunk-HNHZGFZY.cjs.map +0 -1
  382. package/dist/chunk-J7O6WENZ.cjs.map +0 -1
  383. package/dist/chunk-KIZIOFZC.js.map +0 -1
  384. package/dist/chunk-KJ2SW6VA.js.map +0 -1
  385. package/dist/chunk-KJIQGPQR.js.map +0 -1
  386. package/dist/chunk-KP42JLXE.cjs.map +0 -1
  387. package/dist/chunk-KWWD3U7G.cjs.map +0 -1
  388. package/dist/chunk-NHP6ZIDG.cjs.map +0 -1
  389. package/dist/chunk-OUUPUAGA.cjs.map +0 -1
  390. package/dist/chunk-PC6EKOWK.js.map +0 -1
  391. package/dist/chunk-PE3V7GUL.cjs +0 -4
  392. package/dist/chunk-PE3V7GUL.cjs.map +0 -1
  393. package/dist/chunk-QGWNF2QJ.cjs +0 -1697
  394. package/dist/chunk-QGWNF2QJ.cjs.map +0 -1
  395. package/dist/chunk-QM5SRDJX.js.map +0 -1
  396. package/dist/chunk-RROQ46B6.cjs.map +0 -1
  397. package/dist/chunk-SVLMF4UZ.cjs.map +0 -1
  398. package/dist/chunk-T2CJRA6E.js.map +0 -1
  399. package/dist/chunk-T2UNO766.js +0 -1694
  400. package/dist/chunk-T2UNO766.js.map +0 -1
  401. package/dist/chunk-TQTAMPSC.js.map +0 -1
  402. package/dist/chunk-U3VE2EVB.cjs.map +0 -1
  403. package/dist/chunk-V3VLOOSW.cjs +0 -36
  404. package/dist/chunk-V3VLOOSW.cjs.map +0 -1
  405. package/dist/chunk-V537VSV4.cjs.map +0 -1
  406. package/dist/chunk-VYJXTHII.cjs.map +0 -1
  407. package/dist/chunk-X7F4CSGR.cjs.map +0 -1
  408. package/dist/chunk-XBO6W7LZ.js.map +0 -1
  409. package/dist/chunk-XIDKHXNR.js.map +0 -1
  410. package/dist/chunk-XJQX54QP.cjs.map +0 -1
  411. package/dist/chunk-Y63IFHEZ.cjs.map +0 -1
  412. package/dist/chunk-YDFX3JR2.js.map +0 -1
  413. package/dist/chunk-ZTTMSCLU.js.map +0 -1
  414. package/dist/models-dev-F6MTIYTO.js +0 -3
  415. package/dist/models-dev-XIVR5EJV.cjs +0 -12
  416. package/dist/netlify-MXBOGAJR.cjs +0 -12
  417. package/dist/netlify-RX3JXCFQ.js +0 -3
  418. package/dist/provider-registry-3LUCE7FT.js +0 -3
  419. package/dist/provider-registry-NBRXBOQT.cjs +0 -40
  420. package/dist/registry-generator-DEPPRYYJ.cjs.map +0 -1
  421. package/dist/registry-generator-FLW6NV42.js.map +0 -1
@@ -0,0 +1,4981 @@
1
+ 'use strict';
2
+
3
+ var chunkCZEJQSWB_cjs = require('./chunk-CZEJQSWB.cjs');
4
+ var z4 = require('zod/v4');
5
+ var v3 = require('zod/v3');
6
+ var aiSdkProviderV5 = require('@openrouter/ai-sdk-provider-v5');
7
+
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule) return e;
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
18
+ });
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+
26
+ var z4__namespace = /*#__PURE__*/_interopNamespace(z4);
27
+
28
+ function combineHeaders2(...headers) {
29
+ return headers.reduce(
30
+ (combinedHeaders, currentHeaders) => ({
31
+ ...combinedHeaders,
32
+ ...currentHeaders != null ? currentHeaders : {}
33
+ }),
34
+ {}
35
+ );
36
+ }
37
+ function extractResponseHeaders(response) {
38
+ return Object.fromEntries([...response.headers]);
39
+ }
40
+ var createIdGenerator = ({
41
+ prefix,
42
+ size = 16,
43
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
44
+ separator = "-"
45
+ } = {}) => {
46
+ const generator = () => {
47
+ const alphabetLength = alphabet.length;
48
+ const chars = new Array(size);
49
+ for (let i = 0; i < size; i++) {
50
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
51
+ }
52
+ return chars.join("");
53
+ };
54
+ if (prefix == null) {
55
+ return generator;
56
+ }
57
+ if (alphabet.includes(separator)) {
58
+ throw new chunkCZEJQSWB_cjs.InvalidArgumentError({
59
+ argument: "separator",
60
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
61
+ });
62
+ }
63
+ return () => `${prefix}${separator}${generator()}`;
64
+ };
65
+ var generateId2 = createIdGenerator();
66
+ function isAbortError(error) {
67
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
68
+ error.name === "TimeoutError");
69
+ }
70
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
71
+ function handleFetchError({
72
+ error,
73
+ url,
74
+ requestBodyValues
75
+ }) {
76
+ if (isAbortError(error)) {
77
+ return error;
78
+ }
79
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
80
+ const cause = error.cause;
81
+ if (cause != null) {
82
+ return new chunkCZEJQSWB_cjs.APICallError({
83
+ message: `Cannot connect to API: ${cause.message}`,
84
+ cause,
85
+ url,
86
+ requestBodyValues,
87
+ isRetryable: true
88
+ // retry when network error
89
+ });
90
+ }
91
+ }
92
+ return error;
93
+ }
94
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
95
+ var _a, _b, _c;
96
+ if (globalThisAny.window) {
97
+ return `runtime/browser`;
98
+ }
99
+ if ((_a = globalThisAny.navigator) == null ? void 0 : _a.userAgent) {
100
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
101
+ }
102
+ if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) {
103
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
104
+ }
105
+ if (globalThisAny.EdgeRuntime) {
106
+ return `runtime/vercel-edge`;
107
+ }
108
+ return "runtime/unknown";
109
+ }
110
+ function normalizeHeaders(headers) {
111
+ if (headers == null) {
112
+ return {};
113
+ }
114
+ const normalized = {};
115
+ if (headers instanceof Headers) {
116
+ headers.forEach((value, key) => {
117
+ normalized[key.toLowerCase()] = value;
118
+ });
119
+ } else {
120
+ if (!Array.isArray(headers)) {
121
+ headers = Object.entries(headers);
122
+ }
123
+ for (const [key, value] of headers) {
124
+ if (value != null) {
125
+ normalized[key.toLowerCase()] = value;
126
+ }
127
+ }
128
+ }
129
+ return normalized;
130
+ }
131
+ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
132
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
133
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
134
+ normalizedHeaders.set(
135
+ "user-agent",
136
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
137
+ );
138
+ return Object.fromEntries(normalizedHeaders.entries());
139
+ }
140
+ var VERSION = "3.0.18" ;
141
+ function loadApiKey2({
142
+ apiKey,
143
+ environmentVariableName,
144
+ apiKeyParameterName = "apiKey",
145
+ description
146
+ }) {
147
+ if (typeof apiKey === "string") {
148
+ return apiKey;
149
+ }
150
+ if (apiKey != null) {
151
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
152
+ message: `${description} API key must be a string.`
153
+ });
154
+ }
155
+ if (typeof process === "undefined") {
156
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
157
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
158
+ });
159
+ }
160
+ apiKey = process.env[environmentVariableName];
161
+ if (apiKey == null) {
162
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
163
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
164
+ });
165
+ }
166
+ if (typeof apiKey !== "string") {
167
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
168
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
169
+ });
170
+ }
171
+ return apiKey;
172
+ }
173
+ var suspectProtoRx = /"__proto__"\s*:/;
174
+ var suspectConstructorRx = /"constructor"\s*:/;
175
+ function _parse(text) {
176
+ const obj = JSON.parse(text);
177
+ if (obj === null || typeof obj !== "object") {
178
+ return obj;
179
+ }
180
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
181
+ return obj;
182
+ }
183
+ return filter(obj);
184
+ }
185
+ function filter(obj) {
186
+ let next = [obj];
187
+ while (next.length) {
188
+ const nodes = next;
189
+ next = [];
190
+ for (const node of nodes) {
191
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
192
+ throw new SyntaxError("Object contains forbidden prototype property");
193
+ }
194
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
195
+ throw new SyntaxError("Object contains forbidden prototype property");
196
+ }
197
+ for (const key in node) {
198
+ const value = node[key];
199
+ if (value && typeof value === "object") {
200
+ next.push(value);
201
+ }
202
+ }
203
+ }
204
+ }
205
+ return obj;
206
+ }
207
+ function secureJsonParse(text) {
208
+ const { stackTraceLimit } = Error;
209
+ try {
210
+ Error.stackTraceLimit = 0;
211
+ } catch (e) {
212
+ return _parse(text);
213
+ }
214
+ try {
215
+ return _parse(text);
216
+ } finally {
217
+ Error.stackTraceLimit = stackTraceLimit;
218
+ }
219
+ }
220
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
221
+ function validator(validate) {
222
+ return { [validatorSymbol]: true, validate };
223
+ }
224
+ function isValidator(value) {
225
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
226
+ }
227
+ function asValidator(value) {
228
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
229
+ }
230
+ function standardSchemaValidator(standardSchema) {
231
+ return validator(async (value) => {
232
+ const result = await standardSchema["~standard"].validate(value);
233
+ return result.issues == null ? { success: true, value: result.value } : {
234
+ success: false,
235
+ error: new chunkCZEJQSWB_cjs.TypeValidationError({
236
+ value,
237
+ cause: result.issues
238
+ })
239
+ };
240
+ });
241
+ }
242
+ async function validateTypes({
243
+ value,
244
+ schema
245
+ }) {
246
+ const result = await safeValidateTypes({ value, schema });
247
+ if (!result.success) {
248
+ throw chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error });
249
+ }
250
+ return result.value;
251
+ }
252
+ async function safeValidateTypes({
253
+ value,
254
+ schema
255
+ }) {
256
+ const validator22 = asValidator(schema);
257
+ try {
258
+ if (validator22.validate == null) {
259
+ return { success: true, value, rawValue: value };
260
+ }
261
+ const result = await validator22.validate(value);
262
+ if (result.success) {
263
+ return { success: true, value: result.value, rawValue: value };
264
+ }
265
+ return {
266
+ success: false,
267
+ error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error }),
268
+ rawValue: value
269
+ };
270
+ } catch (error) {
271
+ return {
272
+ success: false,
273
+ error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: error }),
274
+ rawValue: value
275
+ };
276
+ }
277
+ }
278
+ async function parseJSON({
279
+ text,
280
+ schema
281
+ }) {
282
+ try {
283
+ const value = secureJsonParse(text);
284
+ if (schema == null) {
285
+ return value;
286
+ }
287
+ return validateTypes({ value, schema });
288
+ } catch (error) {
289
+ if (chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) || chunkCZEJQSWB_cjs.TypeValidationError.isInstance(error)) {
290
+ throw error;
291
+ }
292
+ throw new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error });
293
+ }
294
+ }
295
+ async function safeParseJSON({
296
+ text,
297
+ schema
298
+ }) {
299
+ try {
300
+ const value = secureJsonParse(text);
301
+ if (schema == null) {
302
+ return { success: true, value, rawValue: value };
303
+ }
304
+ return await safeValidateTypes({ value, schema });
305
+ } catch (error) {
306
+ return {
307
+ success: false,
308
+ error: chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) ? error : new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error }),
309
+ rawValue: void 0
310
+ };
311
+ }
312
+ }
313
+ function isParsableJson(input) {
314
+ try {
315
+ secureJsonParse(input);
316
+ return true;
317
+ } catch (e) {
318
+ return false;
319
+ }
320
+ }
321
+ function parseJsonEventStream({
322
+ stream,
323
+ schema
324
+ }) {
325
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new chunkCZEJQSWB_cjs.EventSourceParserStream()).pipeThrough(
326
+ new TransformStream({
327
+ async transform({ data }, controller) {
328
+ if (data === "[DONE]") {
329
+ return;
330
+ }
331
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
332
+ }
333
+ })
334
+ );
335
+ }
336
+ async function parseProviderOptions2({
337
+ provider,
338
+ providerOptions,
339
+ schema
340
+ }) {
341
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
342
+ return void 0;
343
+ }
344
+ const parsedProviderOptions = await safeValidateTypes({
345
+ value: providerOptions[provider],
346
+ schema
347
+ });
348
+ if (!parsedProviderOptions.success) {
349
+ throw new chunkCZEJQSWB_cjs.InvalidArgumentError({
350
+ argument: "providerOptions",
351
+ message: `invalid ${provider} provider options`,
352
+ cause: parsedProviderOptions.error
353
+ });
354
+ }
355
+ return parsedProviderOptions.value;
356
+ }
357
+ var getOriginalFetch2 = () => globalThis.fetch;
358
+ var postJsonToApi2 = async ({
359
+ url,
360
+ headers,
361
+ body,
362
+ failedResponseHandler,
363
+ successfulResponseHandler,
364
+ abortSignal,
365
+ fetch: fetch2
366
+ }) => postToApi({
367
+ url,
368
+ headers: {
369
+ "Content-Type": "application/json",
370
+ ...headers
371
+ },
372
+ body: {
373
+ content: JSON.stringify(body),
374
+ values: body
375
+ },
376
+ failedResponseHandler,
377
+ successfulResponseHandler,
378
+ abortSignal,
379
+ fetch: fetch2
380
+ });
381
+ var postToApi = async ({
382
+ url,
383
+ headers = {},
384
+ body,
385
+ successfulResponseHandler,
386
+ failedResponseHandler,
387
+ abortSignal,
388
+ fetch: fetch2 = getOriginalFetch2()
389
+ }) => {
390
+ try {
391
+ const response = await fetch2(url, {
392
+ method: "POST",
393
+ headers: withUserAgentSuffix2(
394
+ headers,
395
+ `ai-sdk/provider-utils/${VERSION}`,
396
+ getRuntimeEnvironmentUserAgent()
397
+ ),
398
+ body: body.content,
399
+ signal: abortSignal
400
+ });
401
+ const responseHeaders = extractResponseHeaders(response);
402
+ if (!response.ok) {
403
+ let errorInformation;
404
+ try {
405
+ errorInformation = await failedResponseHandler({
406
+ response,
407
+ url,
408
+ requestBodyValues: body.values
409
+ });
410
+ } catch (error) {
411
+ if (isAbortError(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
412
+ throw error;
413
+ }
414
+ throw new chunkCZEJQSWB_cjs.APICallError({
415
+ message: "Failed to process error response",
416
+ cause: error,
417
+ statusCode: response.status,
418
+ url,
419
+ responseHeaders,
420
+ requestBodyValues: body.values
421
+ });
422
+ }
423
+ throw errorInformation.value;
424
+ }
425
+ try {
426
+ return await successfulResponseHandler({
427
+ response,
428
+ url,
429
+ requestBodyValues: body.values
430
+ });
431
+ } catch (error) {
432
+ if (error instanceof Error) {
433
+ if (isAbortError(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
434
+ throw error;
435
+ }
436
+ }
437
+ throw new chunkCZEJQSWB_cjs.APICallError({
438
+ message: "Failed to process successful response",
439
+ cause: error,
440
+ statusCode: response.status,
441
+ url,
442
+ responseHeaders,
443
+ requestBodyValues: body.values
444
+ });
445
+ }
446
+ } catch (error) {
447
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
448
+ }
449
+ };
450
+ var createJsonErrorResponseHandler2 = ({
451
+ errorSchema,
452
+ errorToMessage: errorToMessage2,
453
+ isRetryable
454
+ }) => async ({ response, url, requestBodyValues }) => {
455
+ const responseBody = await response.text();
456
+ const responseHeaders = extractResponseHeaders(response);
457
+ if (responseBody.trim() === "") {
458
+ return {
459
+ responseHeaders,
460
+ value: new chunkCZEJQSWB_cjs.APICallError({
461
+ message: response.statusText,
462
+ url,
463
+ requestBodyValues,
464
+ statusCode: response.status,
465
+ responseHeaders,
466
+ responseBody,
467
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
468
+ })
469
+ };
470
+ }
471
+ try {
472
+ const parsedError = await parseJSON({
473
+ text: responseBody,
474
+ schema: errorSchema
475
+ });
476
+ return {
477
+ responseHeaders,
478
+ value: new chunkCZEJQSWB_cjs.APICallError({
479
+ message: errorToMessage2(parsedError),
480
+ url,
481
+ requestBodyValues,
482
+ statusCode: response.status,
483
+ responseHeaders,
484
+ responseBody,
485
+ data: parsedError,
486
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
487
+ })
488
+ };
489
+ } catch (parseError) {
490
+ return {
491
+ responseHeaders,
492
+ value: new chunkCZEJQSWB_cjs.APICallError({
493
+ message: response.statusText,
494
+ url,
495
+ requestBodyValues,
496
+ statusCode: response.status,
497
+ responseHeaders,
498
+ responseBody,
499
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
500
+ })
501
+ };
502
+ }
503
+ };
504
+ var createEventSourceResponseHandler2 = (chunkSchema) => async ({ response }) => {
505
+ const responseHeaders = extractResponseHeaders(response);
506
+ if (response.body == null) {
507
+ throw new chunkCZEJQSWB_cjs.EmptyResponseBodyError({});
508
+ }
509
+ return {
510
+ responseHeaders,
511
+ value: parseJsonEventStream({
512
+ stream: response.body,
513
+ schema: chunkSchema
514
+ })
515
+ };
516
+ };
517
+ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
518
+ const responseBody = await response.text();
519
+ const parsedResult = await safeParseJSON({
520
+ text: responseBody,
521
+ schema: responseSchema
522
+ });
523
+ const responseHeaders = extractResponseHeaders(response);
524
+ if (!parsedResult.success) {
525
+ throw new chunkCZEJQSWB_cjs.APICallError({
526
+ message: "Invalid JSON response",
527
+ cause: parsedResult.error,
528
+ statusCode: response.status,
529
+ responseHeaders,
530
+ responseBody,
531
+ url,
532
+ requestBodyValues
533
+ });
534
+ }
535
+ return {
536
+ responseHeaders,
537
+ value: parsedResult.value,
538
+ rawValue: parsedResult.rawValue
539
+ };
540
+ };
541
+ var getRelativePath = (pathA, pathB) => {
542
+ let i = 0;
543
+ for (; i < pathA.length && i < pathB.length; i++) {
544
+ if (pathA[i] !== pathB[i]) break;
545
+ }
546
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
547
+ };
548
+ var ignoreOverride = Symbol(
549
+ "Let zodToJsonSchema decide on which parser to use"
550
+ );
551
+ var defaultOptions = {
552
+ name: void 0,
553
+ $refStrategy: "root",
554
+ basePath: ["#"],
555
+ effectStrategy: "input",
556
+ pipeStrategy: "all",
557
+ dateStrategy: "format:date-time",
558
+ mapStrategy: "entries",
559
+ removeAdditionalStrategy: "passthrough",
560
+ allowedAdditionalProperties: true,
561
+ rejectedAdditionalProperties: false,
562
+ definitionPath: "definitions",
563
+ strictUnions: false,
564
+ definitions: {},
565
+ errorMessages: false,
566
+ patternStrategy: "escape",
567
+ applyRegexFlags: false,
568
+ emailStrategy: "format:email",
569
+ base64Strategy: "contentEncoding:base64",
570
+ nameStrategy: "ref"
571
+ };
572
+ var getDefaultOptions = (options) => typeof options === "string" ? {
573
+ ...defaultOptions,
574
+ name: options
575
+ } : {
576
+ ...defaultOptions,
577
+ ...options
578
+ };
579
+ function parseAnyDef() {
580
+ return {};
581
+ }
582
+ function parseArrayDef(def, refs) {
583
+ var _a, _b, _c;
584
+ const res = {
585
+ type: "array"
586
+ };
587
+ if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) {
588
+ res.items = parseDef(def.type._def, {
589
+ ...refs,
590
+ currentPath: [...refs.currentPath, "items"]
591
+ });
592
+ }
593
+ if (def.minLength) {
594
+ res.minItems = def.minLength.value;
595
+ }
596
+ if (def.maxLength) {
597
+ res.maxItems = def.maxLength.value;
598
+ }
599
+ if (def.exactLength) {
600
+ res.minItems = def.exactLength.value;
601
+ res.maxItems = def.exactLength.value;
602
+ }
603
+ return res;
604
+ }
605
+ function parseBigintDef(def) {
606
+ const res = {
607
+ type: "integer",
608
+ format: "int64"
609
+ };
610
+ if (!def.checks) return res;
611
+ for (const check of def.checks) {
612
+ switch (check.kind) {
613
+ case "min":
614
+ if (check.inclusive) {
615
+ res.minimum = check.value;
616
+ } else {
617
+ res.exclusiveMinimum = check.value;
618
+ }
619
+ break;
620
+ case "max":
621
+ if (check.inclusive) {
622
+ res.maximum = check.value;
623
+ } else {
624
+ res.exclusiveMaximum = check.value;
625
+ }
626
+ break;
627
+ case "multipleOf":
628
+ res.multipleOf = check.value;
629
+ break;
630
+ }
631
+ }
632
+ return res;
633
+ }
634
+ function parseBooleanDef() {
635
+ return { type: "boolean" };
636
+ }
637
+ function parseBrandedDef(_def, refs) {
638
+ return parseDef(_def.type._def, refs);
639
+ }
640
+ var parseCatchDef = (def, refs) => {
641
+ return parseDef(def.innerType._def, refs);
642
+ };
643
+ function parseDateDef(def, refs, overrideDateStrategy) {
644
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
645
+ if (Array.isArray(strategy)) {
646
+ return {
647
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
648
+ };
649
+ }
650
+ switch (strategy) {
651
+ case "string":
652
+ case "format:date-time":
653
+ return {
654
+ type: "string",
655
+ format: "date-time"
656
+ };
657
+ case "format:date":
658
+ return {
659
+ type: "string",
660
+ format: "date"
661
+ };
662
+ case "integer":
663
+ return integerDateParser(def);
664
+ }
665
+ }
666
+ var integerDateParser = (def) => {
667
+ const res = {
668
+ type: "integer",
669
+ format: "unix-time"
670
+ };
671
+ for (const check of def.checks) {
672
+ switch (check.kind) {
673
+ case "min":
674
+ res.minimum = check.value;
675
+ break;
676
+ case "max":
677
+ res.maximum = check.value;
678
+ break;
679
+ }
680
+ }
681
+ return res;
682
+ };
683
+ function parseDefaultDef(_def, refs) {
684
+ return {
685
+ ...parseDef(_def.innerType._def, refs),
686
+ default: _def.defaultValue()
687
+ };
688
+ }
689
+ function parseEffectsDef(_def, refs) {
690
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
691
+ }
692
+ function parseEnumDef(def) {
693
+ return {
694
+ type: "string",
695
+ enum: Array.from(def.values)
696
+ };
697
+ }
698
+ var isJsonSchema7AllOfType = (type) => {
699
+ if ("type" in type && type.type === "string") return false;
700
+ return "allOf" in type;
701
+ };
702
+ function parseIntersectionDef(def, refs) {
703
+ const allOf = [
704
+ parseDef(def.left._def, {
705
+ ...refs,
706
+ currentPath: [...refs.currentPath, "allOf", "0"]
707
+ }),
708
+ parseDef(def.right._def, {
709
+ ...refs,
710
+ currentPath: [...refs.currentPath, "allOf", "1"]
711
+ })
712
+ ].filter((x) => !!x);
713
+ const mergedAllOf = [];
714
+ allOf.forEach((schema) => {
715
+ if (isJsonSchema7AllOfType(schema)) {
716
+ mergedAllOf.push(...schema.allOf);
717
+ } else {
718
+ let nestedSchema = schema;
719
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
720
+ const { additionalProperties, ...rest } = schema;
721
+ nestedSchema = rest;
722
+ }
723
+ mergedAllOf.push(nestedSchema);
724
+ }
725
+ });
726
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
727
+ }
728
+ function parseLiteralDef(def) {
729
+ const parsedType = typeof def.value;
730
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
731
+ return {
732
+ type: Array.isArray(def.value) ? "array" : "object"
733
+ };
734
+ }
735
+ return {
736
+ type: parsedType === "bigint" ? "integer" : parsedType,
737
+ const: def.value
738
+ };
739
+ }
740
+ var emojiRegex = void 0;
741
+ var zodPatterns = {
742
+ /**
743
+ * `c` was changed to `[cC]` to replicate /i flag
744
+ */
745
+ cuid: /^[cC][^\s-]{8,}$/,
746
+ cuid2: /^[0-9a-z]+$/,
747
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
748
+ /**
749
+ * `a-z` was added to replicate /i flag
750
+ */
751
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
752
+ /**
753
+ * Constructed a valid Unicode RegExp
754
+ *
755
+ * Lazily instantiate since this type of regex isn't supported
756
+ * in all envs (e.g. React Native).
757
+ *
758
+ * See:
759
+ * https://github.com/colinhacks/zod/issues/2433
760
+ * Fix in Zod:
761
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
762
+ */
763
+ emoji: () => {
764
+ if (emojiRegex === void 0) {
765
+ emojiRegex = RegExp(
766
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
767
+ "u"
768
+ );
769
+ }
770
+ return emojiRegex;
771
+ },
772
+ /**
773
+ * Unused
774
+ */
775
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
776
+ /**
777
+ * Unused
778
+ */
779
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
780
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
781
+ /**
782
+ * Unused
783
+ */
784
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
785
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
786
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
787
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
788
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
789
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
790
+ };
791
+ function parseStringDef(def, refs) {
792
+ const res = {
793
+ type: "string"
794
+ };
795
+ if (def.checks) {
796
+ for (const check of def.checks) {
797
+ switch (check.kind) {
798
+ case "min":
799
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
800
+ break;
801
+ case "max":
802
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
803
+ break;
804
+ case "email":
805
+ switch (refs.emailStrategy) {
806
+ case "format:email":
807
+ addFormat(res, "email", check.message, refs);
808
+ break;
809
+ case "format:idn-email":
810
+ addFormat(res, "idn-email", check.message, refs);
811
+ break;
812
+ case "pattern:zod":
813
+ addPattern(res, zodPatterns.email, check.message, refs);
814
+ break;
815
+ }
816
+ break;
817
+ case "url":
818
+ addFormat(res, "uri", check.message, refs);
819
+ break;
820
+ case "uuid":
821
+ addFormat(res, "uuid", check.message, refs);
822
+ break;
823
+ case "regex":
824
+ addPattern(res, check.regex, check.message, refs);
825
+ break;
826
+ case "cuid":
827
+ addPattern(res, zodPatterns.cuid, check.message, refs);
828
+ break;
829
+ case "cuid2":
830
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
831
+ break;
832
+ case "startsWith":
833
+ addPattern(
834
+ res,
835
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
836
+ check.message,
837
+ refs
838
+ );
839
+ break;
840
+ case "endsWith":
841
+ addPattern(
842
+ res,
843
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
844
+ check.message,
845
+ refs
846
+ );
847
+ break;
848
+ case "datetime":
849
+ addFormat(res, "date-time", check.message, refs);
850
+ break;
851
+ case "date":
852
+ addFormat(res, "date", check.message, refs);
853
+ break;
854
+ case "time":
855
+ addFormat(res, "time", check.message, refs);
856
+ break;
857
+ case "duration":
858
+ addFormat(res, "duration", check.message, refs);
859
+ break;
860
+ case "length":
861
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
862
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
863
+ break;
864
+ case "includes": {
865
+ addPattern(
866
+ res,
867
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
868
+ check.message,
869
+ refs
870
+ );
871
+ break;
872
+ }
873
+ case "ip": {
874
+ if (check.version !== "v6") {
875
+ addFormat(res, "ipv4", check.message, refs);
876
+ }
877
+ if (check.version !== "v4") {
878
+ addFormat(res, "ipv6", check.message, refs);
879
+ }
880
+ break;
881
+ }
882
+ case "base64url":
883
+ addPattern(res, zodPatterns.base64url, check.message, refs);
884
+ break;
885
+ case "jwt":
886
+ addPattern(res, zodPatterns.jwt, check.message, refs);
887
+ break;
888
+ case "cidr": {
889
+ if (check.version !== "v6") {
890
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
891
+ }
892
+ if (check.version !== "v4") {
893
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
894
+ }
895
+ break;
896
+ }
897
+ case "emoji":
898
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
899
+ break;
900
+ case "ulid": {
901
+ addPattern(res, zodPatterns.ulid, check.message, refs);
902
+ break;
903
+ }
904
+ case "base64": {
905
+ switch (refs.base64Strategy) {
906
+ case "format:binary": {
907
+ addFormat(res, "binary", check.message, refs);
908
+ break;
909
+ }
910
+ case "contentEncoding:base64": {
911
+ res.contentEncoding = "base64";
912
+ break;
913
+ }
914
+ case "pattern:zod": {
915
+ addPattern(res, zodPatterns.base64, check.message, refs);
916
+ break;
917
+ }
918
+ }
919
+ break;
920
+ }
921
+ case "nanoid": {
922
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
923
+ }
924
+ }
925
+ }
926
+ }
927
+ return res;
928
+ }
929
+ function escapeLiteralCheckValue(literal, refs) {
930
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
931
+ }
932
+ var ALPHA_NUMERIC = new Set(
933
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
934
+ );
935
+ function escapeNonAlphaNumeric(source) {
936
+ let result = "";
937
+ for (let i = 0; i < source.length; i++) {
938
+ if (!ALPHA_NUMERIC.has(source[i])) {
939
+ result += "\\";
940
+ }
941
+ result += source[i];
942
+ }
943
+ return result;
944
+ }
945
+ function addFormat(schema, value, message, refs) {
946
+ var _a;
947
+ if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
948
+ if (!schema.anyOf) {
949
+ schema.anyOf = [];
950
+ }
951
+ if (schema.format) {
952
+ schema.anyOf.push({
953
+ format: schema.format
954
+ });
955
+ delete schema.format;
956
+ }
957
+ schema.anyOf.push({
958
+ format: value,
959
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
960
+ });
961
+ } else {
962
+ schema.format = value;
963
+ }
964
+ }
965
+ function addPattern(schema, regex, message, refs) {
966
+ var _a;
967
+ if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
968
+ if (!schema.allOf) {
969
+ schema.allOf = [];
970
+ }
971
+ if (schema.pattern) {
972
+ schema.allOf.push({
973
+ pattern: schema.pattern
974
+ });
975
+ delete schema.pattern;
976
+ }
977
+ schema.allOf.push({
978
+ pattern: stringifyRegExpWithFlags(regex, refs),
979
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
980
+ });
981
+ } else {
982
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
983
+ }
984
+ }
985
+ function stringifyRegExpWithFlags(regex, refs) {
986
+ var _a;
987
+ if (!refs.applyRegexFlags || !regex.flags) {
988
+ return regex.source;
989
+ }
990
+ const flags = {
991
+ i: regex.flags.includes("i"),
992
+ // Case-insensitive
993
+ m: regex.flags.includes("m"),
994
+ // `^` and `$` matches adjacent to newline characters
995
+ s: regex.flags.includes("s")
996
+ // `.` matches newlines
997
+ };
998
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
999
+ let pattern = "";
1000
+ let isEscaped = false;
1001
+ let inCharGroup = false;
1002
+ let inCharRange = false;
1003
+ for (let i = 0; i < source.length; i++) {
1004
+ if (isEscaped) {
1005
+ pattern += source[i];
1006
+ isEscaped = false;
1007
+ continue;
1008
+ }
1009
+ if (flags.i) {
1010
+ if (inCharGroup) {
1011
+ if (source[i].match(/[a-z]/)) {
1012
+ if (inCharRange) {
1013
+ pattern += source[i];
1014
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1015
+ inCharRange = false;
1016
+ } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
1017
+ pattern += source[i];
1018
+ inCharRange = true;
1019
+ } else {
1020
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1021
+ }
1022
+ continue;
1023
+ }
1024
+ } else if (source[i].match(/[a-z]/)) {
1025
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1026
+ continue;
1027
+ }
1028
+ }
1029
+ if (flags.m) {
1030
+ if (source[i] === "^") {
1031
+ pattern += `(^|(?<=[\r
1032
+ ]))`;
1033
+ continue;
1034
+ } else if (source[i] === "$") {
1035
+ pattern += `($|(?=[\r
1036
+ ]))`;
1037
+ continue;
1038
+ }
1039
+ }
1040
+ if (flags.s && source[i] === ".") {
1041
+ pattern += inCharGroup ? `${source[i]}\r
1042
+ ` : `[${source[i]}\r
1043
+ ]`;
1044
+ continue;
1045
+ }
1046
+ pattern += source[i];
1047
+ if (source[i] === "\\") {
1048
+ isEscaped = true;
1049
+ } else if (inCharGroup && source[i] === "]") {
1050
+ inCharGroup = false;
1051
+ } else if (!inCharGroup && source[i] === "[") {
1052
+ inCharGroup = true;
1053
+ }
1054
+ }
1055
+ return pattern;
1056
+ }
1057
+ function parseRecordDef(def, refs) {
1058
+ var _a, _b, _c, _d, _e, _f;
1059
+ const schema = {
1060
+ type: "object",
1061
+ additionalProperties: (_a = parseDef(def.valueType._def, {
1062
+ ...refs,
1063
+ currentPath: [...refs.currentPath, "additionalProperties"]
1064
+ })) != null ? _a : refs.allowedAdditionalProperties
1065
+ };
1066
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1067
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1068
+ return {
1069
+ ...schema,
1070
+ propertyNames: keyType
1071
+ };
1072
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === v3.ZodFirstPartyTypeKind.ZodEnum) {
1073
+ return {
1074
+ ...schema,
1075
+ propertyNames: {
1076
+ enum: def.keyType._def.values
1077
+ }
1078
+ };
1079
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === v3.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1080
+ const { type, ...keyType } = parseBrandedDef(
1081
+ def.keyType._def,
1082
+ refs
1083
+ );
1084
+ return {
1085
+ ...schema,
1086
+ propertyNames: keyType
1087
+ };
1088
+ }
1089
+ return schema;
1090
+ }
1091
+ function parseMapDef(def, refs) {
1092
+ if (refs.mapStrategy === "record") {
1093
+ return parseRecordDef(def, refs);
1094
+ }
1095
+ const keys = parseDef(def.keyType._def, {
1096
+ ...refs,
1097
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1098
+ }) || parseAnyDef();
1099
+ const values = parseDef(def.valueType._def, {
1100
+ ...refs,
1101
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1102
+ }) || parseAnyDef();
1103
+ return {
1104
+ type: "array",
1105
+ maxItems: 125,
1106
+ items: {
1107
+ type: "array",
1108
+ items: [keys, values],
1109
+ minItems: 2,
1110
+ maxItems: 2
1111
+ }
1112
+ };
1113
+ }
1114
+ function parseNativeEnumDef(def) {
1115
+ const object = def.values;
1116
+ const actualKeys = Object.keys(def.values).filter((key) => {
1117
+ return typeof object[object[key]] !== "number";
1118
+ });
1119
+ const actualValues = actualKeys.map((key) => object[key]);
1120
+ const parsedTypes = Array.from(
1121
+ new Set(actualValues.map((values) => typeof values))
1122
+ );
1123
+ return {
1124
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1125
+ enum: actualValues
1126
+ };
1127
+ }
1128
+ function parseNeverDef() {
1129
+ return { not: parseAnyDef() };
1130
+ }
1131
+ function parseNullDef() {
1132
+ return {
1133
+ type: "null"
1134
+ };
1135
+ }
1136
+ var primitiveMappings = {
1137
+ ZodString: "string",
1138
+ ZodNumber: "number",
1139
+ ZodBigInt: "integer",
1140
+ ZodBoolean: "boolean",
1141
+ ZodNull: "null"
1142
+ };
1143
+ function parseUnionDef(def, refs) {
1144
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1145
+ if (options.every(
1146
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1147
+ )) {
1148
+ const types = options.reduce((types2, x) => {
1149
+ const type = primitiveMappings[x._def.typeName];
1150
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1151
+ }, []);
1152
+ return {
1153
+ type: types.length > 1 ? types : types[0]
1154
+ };
1155
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1156
+ const types = options.reduce(
1157
+ (acc, x) => {
1158
+ const type = typeof x._def.value;
1159
+ switch (type) {
1160
+ case "string":
1161
+ case "number":
1162
+ case "boolean":
1163
+ return [...acc, type];
1164
+ case "bigint":
1165
+ return [...acc, "integer"];
1166
+ case "object":
1167
+ if (x._def.value === null) return [...acc, "null"];
1168
+ case "symbol":
1169
+ case "undefined":
1170
+ case "function":
1171
+ default:
1172
+ return acc;
1173
+ }
1174
+ },
1175
+ []
1176
+ );
1177
+ if (types.length === options.length) {
1178
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1179
+ return {
1180
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1181
+ enum: options.reduce(
1182
+ (acc, x) => {
1183
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1184
+ },
1185
+ []
1186
+ )
1187
+ };
1188
+ }
1189
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1190
+ return {
1191
+ type: "string",
1192
+ enum: options.reduce(
1193
+ (acc, x) => [
1194
+ ...acc,
1195
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1196
+ ],
1197
+ []
1198
+ )
1199
+ };
1200
+ }
1201
+ return asAnyOf(def, refs);
1202
+ }
1203
+ var asAnyOf = (def, refs) => {
1204
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1205
+ (x, i) => parseDef(x._def, {
1206
+ ...refs,
1207
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1208
+ })
1209
+ ).filter(
1210
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1211
+ );
1212
+ return anyOf.length ? { anyOf } : void 0;
1213
+ };
1214
+ function parseNullableDef(def, refs) {
1215
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1216
+ def.innerType._def.typeName
1217
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1218
+ return {
1219
+ type: [
1220
+ primitiveMappings[def.innerType._def.typeName],
1221
+ "null"
1222
+ ]
1223
+ };
1224
+ }
1225
+ const base = parseDef(def.innerType._def, {
1226
+ ...refs,
1227
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1228
+ });
1229
+ return base && { anyOf: [base, { type: "null" }] };
1230
+ }
1231
+ function parseNumberDef(def) {
1232
+ const res = {
1233
+ type: "number"
1234
+ };
1235
+ if (!def.checks) return res;
1236
+ for (const check of def.checks) {
1237
+ switch (check.kind) {
1238
+ case "int":
1239
+ res.type = "integer";
1240
+ break;
1241
+ case "min":
1242
+ if (check.inclusive) {
1243
+ res.minimum = check.value;
1244
+ } else {
1245
+ res.exclusiveMinimum = check.value;
1246
+ }
1247
+ break;
1248
+ case "max":
1249
+ if (check.inclusive) {
1250
+ res.maximum = check.value;
1251
+ } else {
1252
+ res.exclusiveMaximum = check.value;
1253
+ }
1254
+ break;
1255
+ case "multipleOf":
1256
+ res.multipleOf = check.value;
1257
+ break;
1258
+ }
1259
+ }
1260
+ return res;
1261
+ }
1262
+ function parseObjectDef(def, refs) {
1263
+ const result = {
1264
+ type: "object",
1265
+ properties: {}
1266
+ };
1267
+ const required = [];
1268
+ const shape = def.shape();
1269
+ for (const propName in shape) {
1270
+ let propDef = shape[propName];
1271
+ if (propDef === void 0 || propDef._def === void 0) {
1272
+ continue;
1273
+ }
1274
+ const propOptional = safeIsOptional(propDef);
1275
+ const parsedDef = parseDef(propDef._def, {
1276
+ ...refs,
1277
+ currentPath: [...refs.currentPath, "properties", propName],
1278
+ propertyPath: [...refs.currentPath, "properties", propName]
1279
+ });
1280
+ if (parsedDef === void 0) {
1281
+ continue;
1282
+ }
1283
+ result.properties[propName] = parsedDef;
1284
+ if (!propOptional) {
1285
+ required.push(propName);
1286
+ }
1287
+ }
1288
+ if (required.length) {
1289
+ result.required = required;
1290
+ }
1291
+ const additionalProperties = decideAdditionalProperties(def, refs);
1292
+ if (additionalProperties !== void 0) {
1293
+ result.additionalProperties = additionalProperties;
1294
+ }
1295
+ return result;
1296
+ }
1297
+ function decideAdditionalProperties(def, refs) {
1298
+ if (def.catchall._def.typeName !== "ZodNever") {
1299
+ return parseDef(def.catchall._def, {
1300
+ ...refs,
1301
+ currentPath: [...refs.currentPath, "additionalProperties"]
1302
+ });
1303
+ }
1304
+ switch (def.unknownKeys) {
1305
+ case "passthrough":
1306
+ return refs.allowedAdditionalProperties;
1307
+ case "strict":
1308
+ return refs.rejectedAdditionalProperties;
1309
+ case "strip":
1310
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1311
+ }
1312
+ }
1313
+ function safeIsOptional(schema) {
1314
+ try {
1315
+ return schema.isOptional();
1316
+ } catch (e) {
1317
+ return true;
1318
+ }
1319
+ }
1320
+ var parseOptionalDef = (def, refs) => {
1321
+ var _a;
1322
+ if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
1323
+ return parseDef(def.innerType._def, refs);
1324
+ }
1325
+ const innerSchema = parseDef(def.innerType._def, {
1326
+ ...refs,
1327
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1328
+ });
1329
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1330
+ };
1331
+ var parsePipelineDef = (def, refs) => {
1332
+ if (refs.pipeStrategy === "input") {
1333
+ return parseDef(def.in._def, refs);
1334
+ } else if (refs.pipeStrategy === "output") {
1335
+ return parseDef(def.out._def, refs);
1336
+ }
1337
+ const a = parseDef(def.in._def, {
1338
+ ...refs,
1339
+ currentPath: [...refs.currentPath, "allOf", "0"]
1340
+ });
1341
+ const b = parseDef(def.out._def, {
1342
+ ...refs,
1343
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1344
+ });
1345
+ return {
1346
+ allOf: [a, b].filter((x) => x !== void 0)
1347
+ };
1348
+ };
1349
+ function parsePromiseDef(def, refs) {
1350
+ return parseDef(def.type._def, refs);
1351
+ }
1352
+ function parseSetDef(def, refs) {
1353
+ const items = parseDef(def.valueType._def, {
1354
+ ...refs,
1355
+ currentPath: [...refs.currentPath, "items"]
1356
+ });
1357
+ const schema = {
1358
+ type: "array",
1359
+ uniqueItems: true,
1360
+ items
1361
+ };
1362
+ if (def.minSize) {
1363
+ schema.minItems = def.minSize.value;
1364
+ }
1365
+ if (def.maxSize) {
1366
+ schema.maxItems = def.maxSize.value;
1367
+ }
1368
+ return schema;
1369
+ }
1370
+ function parseTupleDef(def, refs) {
1371
+ if (def.rest) {
1372
+ return {
1373
+ type: "array",
1374
+ minItems: def.items.length,
1375
+ items: def.items.map(
1376
+ (x, i) => parseDef(x._def, {
1377
+ ...refs,
1378
+ currentPath: [...refs.currentPath, "items", `${i}`]
1379
+ })
1380
+ ).reduce(
1381
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1382
+ []
1383
+ ),
1384
+ additionalItems: parseDef(def.rest._def, {
1385
+ ...refs,
1386
+ currentPath: [...refs.currentPath, "additionalItems"]
1387
+ })
1388
+ };
1389
+ } else {
1390
+ return {
1391
+ type: "array",
1392
+ minItems: def.items.length,
1393
+ maxItems: def.items.length,
1394
+ items: def.items.map(
1395
+ (x, i) => parseDef(x._def, {
1396
+ ...refs,
1397
+ currentPath: [...refs.currentPath, "items", `${i}`]
1398
+ })
1399
+ ).reduce(
1400
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1401
+ []
1402
+ )
1403
+ };
1404
+ }
1405
+ }
1406
+ function parseUndefinedDef() {
1407
+ return {
1408
+ not: parseAnyDef()
1409
+ };
1410
+ }
1411
+ function parseUnknownDef() {
1412
+ return parseAnyDef();
1413
+ }
1414
+ var parseReadonlyDef = (def, refs) => {
1415
+ return parseDef(def.innerType._def, refs);
1416
+ };
1417
+ var selectParser = (def, typeName, refs) => {
1418
+ switch (typeName) {
1419
+ case v3.ZodFirstPartyTypeKind.ZodString:
1420
+ return parseStringDef(def, refs);
1421
+ case v3.ZodFirstPartyTypeKind.ZodNumber:
1422
+ return parseNumberDef(def);
1423
+ case v3.ZodFirstPartyTypeKind.ZodObject:
1424
+ return parseObjectDef(def, refs);
1425
+ case v3.ZodFirstPartyTypeKind.ZodBigInt:
1426
+ return parseBigintDef(def);
1427
+ case v3.ZodFirstPartyTypeKind.ZodBoolean:
1428
+ return parseBooleanDef();
1429
+ case v3.ZodFirstPartyTypeKind.ZodDate:
1430
+ return parseDateDef(def, refs);
1431
+ case v3.ZodFirstPartyTypeKind.ZodUndefined:
1432
+ return parseUndefinedDef();
1433
+ case v3.ZodFirstPartyTypeKind.ZodNull:
1434
+ return parseNullDef();
1435
+ case v3.ZodFirstPartyTypeKind.ZodArray:
1436
+ return parseArrayDef(def, refs);
1437
+ case v3.ZodFirstPartyTypeKind.ZodUnion:
1438
+ case v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
1439
+ return parseUnionDef(def, refs);
1440
+ case v3.ZodFirstPartyTypeKind.ZodIntersection:
1441
+ return parseIntersectionDef(def, refs);
1442
+ case v3.ZodFirstPartyTypeKind.ZodTuple:
1443
+ return parseTupleDef(def, refs);
1444
+ case v3.ZodFirstPartyTypeKind.ZodRecord:
1445
+ return parseRecordDef(def, refs);
1446
+ case v3.ZodFirstPartyTypeKind.ZodLiteral:
1447
+ return parseLiteralDef(def);
1448
+ case v3.ZodFirstPartyTypeKind.ZodEnum:
1449
+ return parseEnumDef(def);
1450
+ case v3.ZodFirstPartyTypeKind.ZodNativeEnum:
1451
+ return parseNativeEnumDef(def);
1452
+ case v3.ZodFirstPartyTypeKind.ZodNullable:
1453
+ return parseNullableDef(def, refs);
1454
+ case v3.ZodFirstPartyTypeKind.ZodOptional:
1455
+ return parseOptionalDef(def, refs);
1456
+ case v3.ZodFirstPartyTypeKind.ZodMap:
1457
+ return parseMapDef(def, refs);
1458
+ case v3.ZodFirstPartyTypeKind.ZodSet:
1459
+ return parseSetDef(def, refs);
1460
+ case v3.ZodFirstPartyTypeKind.ZodLazy:
1461
+ return () => def.getter()._def;
1462
+ case v3.ZodFirstPartyTypeKind.ZodPromise:
1463
+ return parsePromiseDef(def, refs);
1464
+ case v3.ZodFirstPartyTypeKind.ZodNaN:
1465
+ case v3.ZodFirstPartyTypeKind.ZodNever:
1466
+ return parseNeverDef();
1467
+ case v3.ZodFirstPartyTypeKind.ZodEffects:
1468
+ return parseEffectsDef(def, refs);
1469
+ case v3.ZodFirstPartyTypeKind.ZodAny:
1470
+ return parseAnyDef();
1471
+ case v3.ZodFirstPartyTypeKind.ZodUnknown:
1472
+ return parseUnknownDef();
1473
+ case v3.ZodFirstPartyTypeKind.ZodDefault:
1474
+ return parseDefaultDef(def, refs);
1475
+ case v3.ZodFirstPartyTypeKind.ZodBranded:
1476
+ return parseBrandedDef(def, refs);
1477
+ case v3.ZodFirstPartyTypeKind.ZodReadonly:
1478
+ return parseReadonlyDef(def, refs);
1479
+ case v3.ZodFirstPartyTypeKind.ZodCatch:
1480
+ return parseCatchDef(def, refs);
1481
+ case v3.ZodFirstPartyTypeKind.ZodPipeline:
1482
+ return parsePipelineDef(def, refs);
1483
+ case v3.ZodFirstPartyTypeKind.ZodFunction:
1484
+ case v3.ZodFirstPartyTypeKind.ZodVoid:
1485
+ case v3.ZodFirstPartyTypeKind.ZodSymbol:
1486
+ return void 0;
1487
+ default:
1488
+ return /* @__PURE__ */ ((_) => void 0)();
1489
+ }
1490
+ };
1491
+ function parseDef(def, refs, forceResolution = false) {
1492
+ var _a;
1493
+ const seenItem = refs.seen.get(def);
1494
+ if (refs.override) {
1495
+ const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(
1496
+ refs,
1497
+ def,
1498
+ refs,
1499
+ seenItem,
1500
+ forceResolution
1501
+ );
1502
+ if (overrideResult !== ignoreOverride) {
1503
+ return overrideResult;
1504
+ }
1505
+ }
1506
+ if (seenItem && !forceResolution) {
1507
+ const seenSchema = get$ref(seenItem, refs);
1508
+ if (seenSchema !== void 0) {
1509
+ return seenSchema;
1510
+ }
1511
+ }
1512
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1513
+ refs.seen.set(def, newItem);
1514
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1515
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1516
+ if (jsonSchema2) {
1517
+ addMeta(def, refs, jsonSchema2);
1518
+ }
1519
+ if (refs.postProcess) {
1520
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1521
+ newItem.jsonSchema = jsonSchema2;
1522
+ return postProcessResult;
1523
+ }
1524
+ newItem.jsonSchema = jsonSchema2;
1525
+ return jsonSchema2;
1526
+ }
1527
+ var get$ref = (item, refs) => {
1528
+ switch (refs.$refStrategy) {
1529
+ case "root":
1530
+ return { $ref: item.path.join("/") };
1531
+ case "relative":
1532
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1533
+ case "none":
1534
+ case "seen": {
1535
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1536
+ console.warn(
1537
+ `Recursive reference detected at ${refs.currentPath.join(
1538
+ "/"
1539
+ )}! Defaulting to any`
1540
+ );
1541
+ return parseAnyDef();
1542
+ }
1543
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1544
+ }
1545
+ }
1546
+ };
1547
+ var addMeta = (def, refs, jsonSchema2) => {
1548
+ if (def.description) {
1549
+ jsonSchema2.description = def.description;
1550
+ }
1551
+ return jsonSchema2;
1552
+ };
1553
+ var getRefs = (options) => {
1554
+ const _options = getDefaultOptions(options);
1555
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1556
+ return {
1557
+ ..._options,
1558
+ currentPath,
1559
+ propertyPath: void 0,
1560
+ seen: new Map(
1561
+ Object.entries(_options.definitions).map(([name, def]) => [
1562
+ def._def,
1563
+ {
1564
+ def: def._def,
1565
+ path: [..._options.basePath, _options.definitionPath, name],
1566
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1567
+ jsonSchema: void 0
1568
+ }
1569
+ ])
1570
+ )
1571
+ };
1572
+ };
1573
+ var zodToJsonSchema = (schema, options) => {
1574
+ var _a;
1575
+ const refs = getRefs(options);
1576
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1577
+ (acc, [name2, schema2]) => {
1578
+ var _a2;
1579
+ return {
1580
+ ...acc,
1581
+ [name2]: (_a2 = parseDef(
1582
+ schema2._def,
1583
+ {
1584
+ ...refs,
1585
+ currentPath: [...refs.basePath, refs.definitionPath, name2]
1586
+ },
1587
+ true
1588
+ )) != null ? _a2 : parseAnyDef()
1589
+ };
1590
+ },
1591
+ {}
1592
+ ) : void 0;
1593
+ const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1594
+ const main = (_a = parseDef(
1595
+ schema._def,
1596
+ name === void 0 ? refs : {
1597
+ ...refs,
1598
+ currentPath: [...refs.basePath, refs.definitionPath, name]
1599
+ },
1600
+ false
1601
+ )) != null ? _a : parseAnyDef();
1602
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1603
+ if (title !== void 0) {
1604
+ main.title = title;
1605
+ }
1606
+ const combined = name === void 0 ? definitions ? {
1607
+ ...main,
1608
+ [refs.definitionPath]: definitions
1609
+ } : main : {
1610
+ $ref: [
1611
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1612
+ refs.definitionPath,
1613
+ name
1614
+ ].join("/"),
1615
+ [refs.definitionPath]: {
1616
+ ...definitions,
1617
+ [name]: main
1618
+ }
1619
+ };
1620
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1621
+ return combined;
1622
+ };
1623
+ var zod_to_json_schema_default = zodToJsonSchema;
1624
+ function zod3Schema(zodSchema2, options) {
1625
+ var _a;
1626
+ const useReferences = (_a = void 0 ) != null ? _a : false;
1627
+ return jsonSchema(
1628
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1629
+ () => zod_to_json_schema_default(zodSchema2, {
1630
+ $refStrategy: useReferences ? "root" : "none"
1631
+ }),
1632
+ {
1633
+ validate: async (value) => {
1634
+ const result = await zodSchema2.safeParseAsync(value);
1635
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1636
+ }
1637
+ }
1638
+ );
1639
+ }
1640
+ function zod4Schema(zodSchema2, options) {
1641
+ var _a;
1642
+ const useReferences = (_a = void 0 ) != null ? _a : false;
1643
+ return jsonSchema(
1644
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1645
+ () => z4__namespace.toJSONSchema(zodSchema2, {
1646
+ target: "draft-7",
1647
+ io: "output",
1648
+ reused: useReferences ? "ref" : "inline"
1649
+ }),
1650
+ {
1651
+ validate: async (value) => {
1652
+ const result = await z4__namespace.safeParseAsync(zodSchema2, value);
1653
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1654
+ }
1655
+ }
1656
+ );
1657
+ }
1658
+ function isZod4Schema(zodSchema2) {
1659
+ return "_zod" in zodSchema2;
1660
+ }
1661
+ function zodSchema(zodSchema2, options) {
1662
+ if (isZod4Schema(zodSchema2)) {
1663
+ return zod4Schema(zodSchema2);
1664
+ } else {
1665
+ return zod3Schema(zodSchema2);
1666
+ }
1667
+ }
1668
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1669
+ function lazySchema(createSchema) {
1670
+ let schema;
1671
+ return () => {
1672
+ if (schema == null) {
1673
+ schema = createSchema();
1674
+ }
1675
+ return schema;
1676
+ };
1677
+ }
1678
+ function jsonSchema(jsonSchema2, {
1679
+ validate
1680
+ } = {}) {
1681
+ return {
1682
+ [schemaSymbol]: true,
1683
+ _type: void 0,
1684
+ // should never be used directly
1685
+ [validatorSymbol]: true,
1686
+ get jsonSchema() {
1687
+ if (typeof jsonSchema2 === "function") {
1688
+ jsonSchema2 = jsonSchema2();
1689
+ }
1690
+ return jsonSchema2;
1691
+ },
1692
+ validate
1693
+ };
1694
+ }
1695
+ function withoutTrailingSlash2(url) {
1696
+ return url == null ? void 0 : url.replace(/\/$/, "");
1697
+ }
1698
+ function convertToDeepSeekChatMessages({
1699
+ prompt,
1700
+ responseFormat
1701
+ }) {
1702
+ const messages = [];
1703
+ const warnings = [];
1704
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
1705
+ if (responseFormat.schema == null) {
1706
+ messages.push({
1707
+ role: "system",
1708
+ content: "Return JSON."
1709
+ });
1710
+ } else {
1711
+ messages.push({
1712
+ role: "system",
1713
+ content: "Return JSON that conforms to the following schema: " + JSON.stringify(responseFormat.schema)
1714
+ });
1715
+ }
1716
+ }
1717
+ let lastUserMessageIndex = -1;
1718
+ for (let i = prompt.length - 1; i >= 0; i--) {
1719
+ if (prompt[i].role === "user") {
1720
+ lastUserMessageIndex = i;
1721
+ break;
1722
+ }
1723
+ }
1724
+ let index = -1;
1725
+ for (const { role, content } of prompt) {
1726
+ index++;
1727
+ switch (role) {
1728
+ case "system": {
1729
+ messages.push({ role: "system", content });
1730
+ break;
1731
+ }
1732
+ case "user": {
1733
+ let userContent = "";
1734
+ for (const part of content) {
1735
+ if (part.type === "text") {
1736
+ userContent += part.text;
1737
+ } else {
1738
+ warnings.push({
1739
+ type: "other",
1740
+ message: `Unsupported user message part type: ${part.type}`
1741
+ });
1742
+ }
1743
+ }
1744
+ messages.push({
1745
+ role: "user",
1746
+ content: userContent
1747
+ });
1748
+ break;
1749
+ }
1750
+ case "assistant": {
1751
+ let text = "";
1752
+ let reasoning;
1753
+ const toolCalls = [];
1754
+ for (const part of content) {
1755
+ switch (part.type) {
1756
+ case "text": {
1757
+ text += part.text;
1758
+ break;
1759
+ }
1760
+ case "reasoning": {
1761
+ if (index <= lastUserMessageIndex) {
1762
+ break;
1763
+ }
1764
+ if (reasoning == null) {
1765
+ reasoning = part.text;
1766
+ } else {
1767
+ reasoning += part.text;
1768
+ }
1769
+ break;
1770
+ }
1771
+ case "tool-call": {
1772
+ toolCalls.push({
1773
+ id: part.toolCallId,
1774
+ type: "function",
1775
+ function: {
1776
+ name: part.toolName,
1777
+ arguments: JSON.stringify(part.input)
1778
+ }
1779
+ });
1780
+ break;
1781
+ }
1782
+ }
1783
+ }
1784
+ messages.push({
1785
+ role: "assistant",
1786
+ content: text,
1787
+ reasoning_content: reasoning,
1788
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
1789
+ });
1790
+ break;
1791
+ }
1792
+ case "tool": {
1793
+ for (const toolResponse of content) {
1794
+ const output = toolResponse.output;
1795
+ let contentValue;
1796
+ switch (output.type) {
1797
+ case "text":
1798
+ case "error-text":
1799
+ contentValue = output.value;
1800
+ break;
1801
+ case "content":
1802
+ case "json":
1803
+ case "error-json":
1804
+ contentValue = JSON.stringify(output.value);
1805
+ break;
1806
+ }
1807
+ messages.push({
1808
+ role: "tool",
1809
+ tool_call_id: toolResponse.toolCallId,
1810
+ content: contentValue
1811
+ });
1812
+ }
1813
+ break;
1814
+ }
1815
+ default: {
1816
+ warnings.push({
1817
+ type: "other",
1818
+ message: `Unsupported message role: ${role}`
1819
+ });
1820
+ break;
1821
+ }
1822
+ }
1823
+ }
1824
+ return { messages, warnings };
1825
+ }
1826
+ var tokenUsageSchema = z4.z.object({
1827
+ prompt_tokens: z4.z.number().nullish(),
1828
+ completion_tokens: z4.z.number().nullish(),
1829
+ prompt_cache_hit_tokens: z4.z.number().nullish(),
1830
+ prompt_cache_miss_tokens: z4.z.number().nullish(),
1831
+ total_tokens: z4.z.number().nullish(),
1832
+ completion_tokens_details: z4.z.object({
1833
+ reasoning_tokens: z4.z.number().nullish()
1834
+ }).nullish()
1835
+ }).nullish();
1836
+ var deepSeekErrorSchema = z4.z.object({
1837
+ error: z4.z.object({
1838
+ message: z4.z.string(),
1839
+ type: z4.z.string().nullish(),
1840
+ param: z4.z.any().nullish(),
1841
+ code: z4.z.union([z4.z.string(), z4.z.number()]).nullish()
1842
+ })
1843
+ });
1844
+ var deepseekChatResponseSchema = z4.z.object({
1845
+ id: z4.z.string().nullish(),
1846
+ created: z4.z.number().nullish(),
1847
+ model: z4.z.string().nullish(),
1848
+ choices: z4.z.array(
1849
+ z4.z.object({
1850
+ message: z4.z.object({
1851
+ role: z4.z.literal("assistant").nullish(),
1852
+ content: z4.z.string().nullish(),
1853
+ reasoning_content: z4.z.string().nullish(),
1854
+ tool_calls: z4.z.array(
1855
+ z4.z.object({
1856
+ id: z4.z.string().nullish(),
1857
+ function: z4.z.object({
1858
+ name: z4.z.string(),
1859
+ arguments: z4.z.string()
1860
+ })
1861
+ })
1862
+ ).nullish()
1863
+ }),
1864
+ finish_reason: z4.z.string().nullish()
1865
+ })
1866
+ ),
1867
+ usage: tokenUsageSchema
1868
+ });
1869
+ var deepseekChatChunkSchema = lazySchema(
1870
+ () => zodSchema(
1871
+ z4.z.union([
1872
+ z4.z.object({
1873
+ id: z4.z.string().nullish(),
1874
+ created: z4.z.number().nullish(),
1875
+ model: z4.z.string().nullish(),
1876
+ choices: z4.z.array(
1877
+ z4.z.object({
1878
+ delta: z4.z.object({
1879
+ role: z4.z.enum(["assistant"]).nullish(),
1880
+ content: z4.z.string().nullish(),
1881
+ reasoning_content: z4.z.string().nullish(),
1882
+ tool_calls: z4.z.array(
1883
+ z4.z.object({
1884
+ index: z4.z.number(),
1885
+ id: z4.z.string().nullish(),
1886
+ function: z4.z.object({
1887
+ name: z4.z.string().nullish(),
1888
+ arguments: z4.z.string().nullish()
1889
+ })
1890
+ })
1891
+ ).nullish()
1892
+ }).nullish(),
1893
+ finish_reason: z4.z.string().nullish()
1894
+ })
1895
+ ),
1896
+ usage: tokenUsageSchema
1897
+ }),
1898
+ deepSeekErrorSchema
1899
+ ])
1900
+ )
1901
+ );
1902
+ var deepseekChatOptions = z4.z.object({
1903
+ /**
1904
+ * Type of thinking to use. Defaults to `enabled`.
1905
+ */
1906
+ thinking: z4.z.object({
1907
+ type: z4.z.enum(["enabled", "disabled"]).optional()
1908
+ }).optional()
1909
+ });
1910
+ function prepareTools({
1911
+ tools,
1912
+ toolChoice
1913
+ }) {
1914
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
1915
+ const toolWarnings = [];
1916
+ if (tools == null) {
1917
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
1918
+ }
1919
+ const deepseekTools = [];
1920
+ for (const tool of tools) {
1921
+ if (tool.type === "provider-defined") {
1922
+ toolWarnings.push({
1923
+ type: "unsupported-tool",
1924
+ tool
1925
+ });
1926
+ } else {
1927
+ deepseekTools.push({
1928
+ type: "function",
1929
+ function: {
1930
+ name: tool.name,
1931
+ description: tool.description,
1932
+ parameters: tool.inputSchema
1933
+ }
1934
+ });
1935
+ }
1936
+ }
1937
+ if (toolChoice == null) {
1938
+ return { tools: deepseekTools, toolChoice: void 0, toolWarnings };
1939
+ }
1940
+ const type = toolChoice.type;
1941
+ switch (type) {
1942
+ case "auto":
1943
+ case "none":
1944
+ case "required":
1945
+ return { tools: deepseekTools, toolChoice: type, toolWarnings };
1946
+ case "tool":
1947
+ return {
1948
+ tools: deepseekTools,
1949
+ toolChoice: {
1950
+ type: "function",
1951
+ function: { name: toolChoice.toolName }
1952
+ },
1953
+ toolWarnings
1954
+ };
1955
+ default: {
1956
+ const _exhaustiveCheck = type;
1957
+ throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
1958
+ functionality: `tool choice type: ${_exhaustiveCheck}`
1959
+ });
1960
+ }
1961
+ }
1962
+ }
1963
+ function getResponseMetadata({
1964
+ id,
1965
+ model,
1966
+ created
1967
+ }) {
1968
+ return {
1969
+ id: id != null ? id : void 0,
1970
+ modelId: model != null ? model : void 0,
1971
+ timestamp: created != null ? new Date(created * 1e3) : void 0
1972
+ };
1973
+ }
1974
+ function mapDeepSeekFinishReason(finishReason) {
1975
+ switch (finishReason) {
1976
+ case "stop":
1977
+ return "stop";
1978
+ case "length":
1979
+ return "length";
1980
+ case "content_filter":
1981
+ return "content-filter";
1982
+ case "tool_calls":
1983
+ return "tool-calls";
1984
+ case "insufficient_system_resource":
1985
+ return "error";
1986
+ default:
1987
+ return "unknown";
1988
+ }
1989
+ }
1990
+ var DeepSeekChatLanguageModel = class {
1991
+ constructor(modelId, config) {
1992
+ this.specificationVersion = "v2";
1993
+ this.supportedUrls = {};
1994
+ this.modelId = modelId;
1995
+ this.config = config;
1996
+ this.failedResponseHandler = createJsonErrorResponseHandler2({
1997
+ errorSchema: deepSeekErrorSchema,
1998
+ errorToMessage: (error) => error.error.message
1999
+ });
2000
+ }
2001
+ get provider() {
2002
+ return this.config.provider;
2003
+ }
2004
+ get providerOptionsName() {
2005
+ return this.config.provider.split(".")[0].trim();
2006
+ }
2007
+ async getArgs({
2008
+ prompt,
2009
+ maxOutputTokens,
2010
+ temperature,
2011
+ topP,
2012
+ topK,
2013
+ frequencyPenalty,
2014
+ presencePenalty,
2015
+ providerOptions,
2016
+ stopSequences,
2017
+ responseFormat,
2018
+ tools,
2019
+ toolChoice,
2020
+ seed
2021
+ }) {
2022
+ var _a, _b;
2023
+ const deepseekOptions = (_a = await parseProviderOptions2({
2024
+ provider: this.providerOptionsName,
2025
+ providerOptions,
2026
+ schema: deepseekChatOptions
2027
+ })) != null ? _a : {};
2028
+ const { messages, warnings } = convertToDeepSeekChatMessages({
2029
+ prompt,
2030
+ responseFormat
2031
+ });
2032
+ if (topK != null) {
2033
+ warnings.push({ type: "unsupported-setting", setting: "topK" });
2034
+ }
2035
+ if (seed != null) {
2036
+ warnings.push({ type: "unsupported-setting", setting: "seed" });
2037
+ }
2038
+ const {
2039
+ tools: deepseekTools,
2040
+ toolChoice: deepseekToolChoices,
2041
+ toolWarnings
2042
+ } = prepareTools({
2043
+ tools,
2044
+ toolChoice
2045
+ });
2046
+ return {
2047
+ args: {
2048
+ model: this.modelId,
2049
+ max_tokens: maxOutputTokens,
2050
+ temperature,
2051
+ top_p: topP,
2052
+ frequency_penalty: frequencyPenalty,
2053
+ presence_penalty: presencePenalty,
2054
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { type: "json_object" } : void 0,
2055
+ stop: stopSequences,
2056
+ messages,
2057
+ tools: deepseekTools,
2058
+ tool_choice: deepseekToolChoices,
2059
+ thinking: ((_b = deepseekOptions.thinking) == null ? void 0 : _b.type) != null ? { type: deepseekOptions.thinking.type } : void 0
2060
+ },
2061
+ warnings: [...warnings, ...toolWarnings]
2062
+ };
2063
+ }
2064
+ async doGenerate(options) {
2065
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2066
+ const { args, warnings } = await this.getArgs({ ...options });
2067
+ const {
2068
+ responseHeaders,
2069
+ value: responseBody,
2070
+ rawValue: rawResponse
2071
+ } = await postJsonToApi2({
2072
+ url: this.config.url({
2073
+ path: "/chat/completions",
2074
+ modelId: this.modelId
2075
+ }),
2076
+ headers: combineHeaders2(this.config.headers(), options.headers),
2077
+ body: args,
2078
+ failedResponseHandler: this.failedResponseHandler,
2079
+ successfulResponseHandler: createJsonResponseHandler2(
2080
+ deepseekChatResponseSchema
2081
+ ),
2082
+ abortSignal: options.abortSignal,
2083
+ fetch: this.config.fetch
2084
+ });
2085
+ const choice = responseBody.choices[0];
2086
+ const content = [];
2087
+ const reasoning = choice.message.reasoning_content;
2088
+ if (reasoning != null && reasoning.length > 0) {
2089
+ content.push({
2090
+ type: "reasoning",
2091
+ text: reasoning
2092
+ });
2093
+ }
2094
+ if (choice.message.tool_calls != null) {
2095
+ for (const toolCall of choice.message.tool_calls) {
2096
+ content.push({
2097
+ type: "tool-call",
2098
+ toolCallId: (_a = toolCall.id) != null ? _a : generateId2(),
2099
+ toolName: toolCall.function.name,
2100
+ input: toolCall.function.arguments
2101
+ });
2102
+ }
2103
+ }
2104
+ const text = choice.message.content;
2105
+ if (text != null && text.length > 0) {
2106
+ content.push({ type: "text", text });
2107
+ }
2108
+ return {
2109
+ content,
2110
+ finishReason: mapDeepSeekFinishReason(choice.finish_reason),
2111
+ usage: {
2112
+ inputTokens: (_c = (_b = responseBody.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : void 0,
2113
+ outputTokens: (_e = (_d = responseBody.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : void 0,
2114
+ totalTokens: (_g = (_f = responseBody.usage) == null ? void 0 : _f.total_tokens) != null ? _g : void 0,
2115
+ reasoningTokens: (_j = (_i = (_h = responseBody.usage) == null ? void 0 : _h.completion_tokens_details) == null ? void 0 : _i.reasoning_tokens) != null ? _j : void 0,
2116
+ cachedInputTokens: (_l = (_k = responseBody.usage) == null ? void 0 : _k.prompt_cache_hit_tokens) != null ? _l : void 0
2117
+ },
2118
+ providerMetadata: {
2119
+ [this.providerOptionsName]: {
2120
+ promptCacheHitTokens: (_n = (_m = responseBody.usage) == null ? void 0 : _m.prompt_cache_hit_tokens) != null ? _n : null,
2121
+ promptCacheMissTokens: (_p = (_o = responseBody.usage) == null ? void 0 : _o.prompt_cache_miss_tokens) != null ? _p : null
2122
+ }
2123
+ },
2124
+ request: { body: args },
2125
+ response: {
2126
+ ...getResponseMetadata(responseBody),
2127
+ headers: responseHeaders,
2128
+ body: rawResponse
2129
+ },
2130
+ warnings
2131
+ };
2132
+ }
2133
+ async doStream(options) {
2134
+ const { args, warnings } = await this.getArgs({ ...options });
2135
+ const body = {
2136
+ ...args,
2137
+ stream: true,
2138
+ stream_options: { include_usage: true }
2139
+ };
2140
+ const { responseHeaders, value: response } = await postJsonToApi2({
2141
+ url: this.config.url({
2142
+ path: "/chat/completions",
2143
+ modelId: this.modelId
2144
+ }),
2145
+ headers: combineHeaders2(this.config.headers(), options.headers),
2146
+ body,
2147
+ failedResponseHandler: this.failedResponseHandler,
2148
+ successfulResponseHandler: createEventSourceResponseHandler2(
2149
+ deepseekChatChunkSchema
2150
+ ),
2151
+ abortSignal: options.abortSignal,
2152
+ fetch: this.config.fetch
2153
+ });
2154
+ const toolCalls = [];
2155
+ let finishReason = "unknown";
2156
+ let usage = void 0;
2157
+ let isFirstChunk = true;
2158
+ const providerOptionsName = this.providerOptionsName;
2159
+ let isActiveReasoning = false;
2160
+ let isActiveText = false;
2161
+ return {
2162
+ stream: response.pipeThrough(
2163
+ new TransformStream({
2164
+ start(controller) {
2165
+ controller.enqueue({ type: "stream-start", warnings });
2166
+ },
2167
+ transform(chunk, controller) {
2168
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
2169
+ if (options.includeRawChunks) {
2170
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2171
+ }
2172
+ if (!chunk.success) {
2173
+ finishReason = "error";
2174
+ controller.enqueue({ type: "error", error: chunk.error });
2175
+ return;
2176
+ }
2177
+ const value = chunk.value;
2178
+ if ("error" in value) {
2179
+ finishReason = "error";
2180
+ controller.enqueue({ type: "error", error: value.error.message });
2181
+ return;
2182
+ }
2183
+ if (isFirstChunk) {
2184
+ isFirstChunk = false;
2185
+ controller.enqueue({
2186
+ type: "response-metadata",
2187
+ ...getResponseMetadata(value)
2188
+ });
2189
+ }
2190
+ if (value.usage != null) {
2191
+ usage = value.usage;
2192
+ }
2193
+ const choice = value.choices[0];
2194
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
2195
+ finishReason = mapDeepSeekFinishReason(choice.finish_reason);
2196
+ }
2197
+ if ((choice == null ? void 0 : choice.delta) == null) {
2198
+ return;
2199
+ }
2200
+ const delta = choice.delta;
2201
+ const reasoningContent = delta.reasoning_content;
2202
+ if (reasoningContent) {
2203
+ if (!isActiveReasoning) {
2204
+ controller.enqueue({
2205
+ type: "reasoning-start",
2206
+ id: "reasoning-0"
2207
+ });
2208
+ isActiveReasoning = true;
2209
+ }
2210
+ controller.enqueue({
2211
+ type: "reasoning-delta",
2212
+ id: "reasoning-0",
2213
+ delta: reasoningContent
2214
+ });
2215
+ }
2216
+ if (delta.content) {
2217
+ if (!isActiveText) {
2218
+ controller.enqueue({ type: "text-start", id: "txt-0" });
2219
+ isActiveText = true;
2220
+ }
2221
+ if (isActiveReasoning) {
2222
+ controller.enqueue({
2223
+ type: "reasoning-end",
2224
+ id: "reasoning-0"
2225
+ });
2226
+ isActiveReasoning = false;
2227
+ }
2228
+ controller.enqueue({
2229
+ type: "text-delta",
2230
+ id: "txt-0",
2231
+ delta: delta.content
2232
+ });
2233
+ }
2234
+ if (delta.tool_calls != null) {
2235
+ if (isActiveReasoning) {
2236
+ controller.enqueue({
2237
+ type: "reasoning-end",
2238
+ id: "reasoning-0"
2239
+ });
2240
+ isActiveReasoning = false;
2241
+ }
2242
+ for (const toolCallDelta of delta.tool_calls) {
2243
+ const index = toolCallDelta.index;
2244
+ if (toolCalls[index] == null) {
2245
+ if (toolCallDelta.id == null) {
2246
+ throw new chunkCZEJQSWB_cjs.InvalidResponseDataError({
2247
+ data: toolCallDelta,
2248
+ message: `Expected 'id' to be a string.`
2249
+ });
2250
+ }
2251
+ if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
2252
+ throw new chunkCZEJQSWB_cjs.InvalidResponseDataError({
2253
+ data: toolCallDelta,
2254
+ message: `Expected 'function.name' to be a string.`
2255
+ });
2256
+ }
2257
+ controller.enqueue({
2258
+ type: "tool-input-start",
2259
+ id: toolCallDelta.id,
2260
+ toolName: toolCallDelta.function.name
2261
+ });
2262
+ toolCalls[index] = {
2263
+ id: toolCallDelta.id,
2264
+ type: "function",
2265
+ function: {
2266
+ name: toolCallDelta.function.name,
2267
+ arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
2268
+ },
2269
+ hasFinished: false
2270
+ };
2271
+ const toolCall2 = toolCalls[index];
2272
+ if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null) {
2273
+ if (toolCall2.function.arguments.length > 0) {
2274
+ controller.enqueue({
2275
+ type: "tool-input-delta",
2276
+ id: toolCall2.id,
2277
+ delta: toolCall2.function.arguments
2278
+ });
2279
+ }
2280
+ if (isParsableJson(toolCall2.function.arguments)) {
2281
+ controller.enqueue({
2282
+ type: "tool-input-end",
2283
+ id: toolCall2.id
2284
+ });
2285
+ controller.enqueue({
2286
+ type: "tool-call",
2287
+ toolCallId: (_e = toolCall2.id) != null ? _e : generateId2(),
2288
+ toolName: toolCall2.function.name,
2289
+ input: toolCall2.function.arguments
2290
+ });
2291
+ toolCall2.hasFinished = true;
2292
+ }
2293
+ }
2294
+ continue;
2295
+ }
2296
+ const toolCall = toolCalls[index];
2297
+ if (toolCall.hasFinished) {
2298
+ continue;
2299
+ }
2300
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
2301
+ toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
2302
+ }
2303
+ controller.enqueue({
2304
+ type: "tool-input-delta",
2305
+ id: toolCall.id,
2306
+ delta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
2307
+ });
2308
+ if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
2309
+ controller.enqueue({
2310
+ type: "tool-input-end",
2311
+ id: toolCall.id
2312
+ });
2313
+ controller.enqueue({
2314
+ type: "tool-call",
2315
+ toolCallId: (_l = toolCall.id) != null ? _l : generateId2(),
2316
+ toolName: toolCall.function.name,
2317
+ input: toolCall.function.arguments
2318
+ });
2319
+ toolCall.hasFinished = true;
2320
+ }
2321
+ }
2322
+ }
2323
+ },
2324
+ flush(controller) {
2325
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2326
+ if (isActiveReasoning) {
2327
+ controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
2328
+ }
2329
+ if (isActiveText) {
2330
+ controller.enqueue({ type: "text-end", id: "txt-0" });
2331
+ }
2332
+ for (const toolCall of toolCalls.filter(
2333
+ (toolCall2) => !toolCall2.hasFinished
2334
+ )) {
2335
+ controller.enqueue({
2336
+ type: "tool-input-end",
2337
+ id: toolCall.id
2338
+ });
2339
+ controller.enqueue({
2340
+ type: "tool-call",
2341
+ toolCallId: (_a = toolCall.id) != null ? _a : generateId2(),
2342
+ toolName: toolCall.function.name,
2343
+ input: toolCall.function.arguments
2344
+ });
2345
+ }
2346
+ controller.enqueue({
2347
+ type: "finish",
2348
+ finishReason,
2349
+ usage: {
2350
+ inputTokens: (_b = usage == null ? void 0 : usage.prompt_tokens) != null ? _b : void 0,
2351
+ outputTokens: (_c = usage == null ? void 0 : usage.completion_tokens) != null ? _c : void 0,
2352
+ totalTokens: (_d = usage == null ? void 0 : usage.total_tokens) != null ? _d : void 0,
2353
+ reasoningTokens: (_f = (_e = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : void 0,
2354
+ cachedInputTokens: (_g = usage == null ? void 0 : usage.prompt_cache_hit_tokens) != null ? _g : void 0
2355
+ },
2356
+ providerMetadata: {
2357
+ [providerOptionsName]: {
2358
+ promptCacheHitTokens: (_h = usage == null ? void 0 : usage.prompt_cache_hit_tokens) != null ? _h : null,
2359
+ promptCacheMissTokens: (_i = usage == null ? void 0 : usage.prompt_cache_miss_tokens) != null ? _i : null
2360
+ }
2361
+ }
2362
+ });
2363
+ }
2364
+ })
2365
+ ),
2366
+ request: { body },
2367
+ response: { headers: responseHeaders }
2368
+ };
2369
+ }
2370
+ };
2371
+ var VERSION2 = "1.0.31" ;
2372
+ function createDeepSeek(options = {}) {
2373
+ var _a;
2374
+ const baseURL = withoutTrailingSlash2(
2375
+ (_a = options.baseURL) != null ? _a : "https://api.deepseek.com"
2376
+ );
2377
+ const getHeaders = () => withUserAgentSuffix2(
2378
+ {
2379
+ Authorization: `Bearer ${loadApiKey2({
2380
+ apiKey: options.apiKey,
2381
+ environmentVariableName: "DEEPSEEK_API_KEY",
2382
+ description: "DeepSeek API key"
2383
+ })}`,
2384
+ ...options.headers
2385
+ },
2386
+ `ai-sdk/deepseek/${VERSION2}`
2387
+ );
2388
+ const createLanguageModel = (modelId) => {
2389
+ return new DeepSeekChatLanguageModel(modelId, {
2390
+ provider: `deepseek.chat`,
2391
+ url: ({ path }) => `${baseURL}${path}`,
2392
+ headers: getHeaders,
2393
+ fetch: options.fetch
2394
+ });
2395
+ };
2396
+ const provider = (modelId) => createLanguageModel(modelId);
2397
+ provider.languageModel = createLanguageModel;
2398
+ provider.chat = createLanguageModel;
2399
+ provider.textEmbeddingModel = (modelId) => {
2400
+ throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
2401
+ };
2402
+ provider.imageModel = (modelId) => {
2403
+ throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
2404
+ };
2405
+ return provider;
2406
+ }
2407
+ createDeepSeek();
2408
+ function convertToMistralChatMessages(prompt) {
2409
+ const messages = [];
2410
+ for (let i = 0; i < prompt.length; i++) {
2411
+ const { role, content } = prompt[i];
2412
+ const isLastMessage = i === prompt.length - 1;
2413
+ switch (role) {
2414
+ case "system": {
2415
+ messages.push({ role: "system", content });
2416
+ break;
2417
+ }
2418
+ case "user": {
2419
+ messages.push({
2420
+ role: "user",
2421
+ content: content.map((part) => {
2422
+ switch (part.type) {
2423
+ case "text": {
2424
+ return { type: "text", text: part.text };
2425
+ }
2426
+ case "file": {
2427
+ if (part.mediaType.startsWith("image/")) {
2428
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
2429
+ return {
2430
+ type: "image_url",
2431
+ image_url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkCZEJQSWB_cjs.convertToBase64(part.data)}`
2432
+ };
2433
+ } else if (part.mediaType === "application/pdf") {
2434
+ return {
2435
+ type: "document_url",
2436
+ document_url: part.data.toString()
2437
+ };
2438
+ } else {
2439
+ throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
2440
+ functionality: "Only images and PDF file parts are supported"
2441
+ });
2442
+ }
2443
+ }
2444
+ }
2445
+ })
2446
+ });
2447
+ break;
2448
+ }
2449
+ case "assistant": {
2450
+ let text = "";
2451
+ const toolCalls = [];
2452
+ for (const part of content) {
2453
+ switch (part.type) {
2454
+ case "text": {
2455
+ text += part.text;
2456
+ break;
2457
+ }
2458
+ case "tool-call": {
2459
+ toolCalls.push({
2460
+ id: part.toolCallId,
2461
+ type: "function",
2462
+ function: {
2463
+ name: part.toolName,
2464
+ arguments: JSON.stringify(part.input)
2465
+ }
2466
+ });
2467
+ break;
2468
+ }
2469
+ case "reasoning": {
2470
+ text += part.text;
2471
+ break;
2472
+ }
2473
+ default: {
2474
+ throw new Error(
2475
+ `Unsupported content type in assistant message: ${part.type}`
2476
+ );
2477
+ }
2478
+ }
2479
+ }
2480
+ messages.push({
2481
+ role: "assistant",
2482
+ content: text,
2483
+ prefix: isLastMessage ? true : void 0,
2484
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
2485
+ });
2486
+ break;
2487
+ }
2488
+ case "tool": {
2489
+ for (const toolResponse of content) {
2490
+ const output = toolResponse.output;
2491
+ let contentValue;
2492
+ switch (output.type) {
2493
+ case "text":
2494
+ case "error-text":
2495
+ contentValue = output.value;
2496
+ break;
2497
+ case "content":
2498
+ case "json":
2499
+ case "error-json":
2500
+ contentValue = JSON.stringify(output.value);
2501
+ break;
2502
+ }
2503
+ messages.push({
2504
+ role: "tool",
2505
+ name: toolResponse.toolName,
2506
+ tool_call_id: toolResponse.toolCallId,
2507
+ content: contentValue
2508
+ });
2509
+ }
2510
+ break;
2511
+ }
2512
+ default: {
2513
+ const _exhaustiveCheck = role;
2514
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
2515
+ }
2516
+ }
2517
+ }
2518
+ return messages;
2519
+ }
2520
+ function getResponseMetadata2({
2521
+ id,
2522
+ model,
2523
+ created
2524
+ }) {
2525
+ return {
2526
+ id: id != null ? id : void 0,
2527
+ modelId: model != null ? model : void 0,
2528
+ timestamp: created != null ? new Date(created * 1e3) : void 0
2529
+ };
2530
+ }
2531
+ function mapMistralFinishReason(finishReason) {
2532
+ switch (finishReason) {
2533
+ case "stop":
2534
+ return "stop";
2535
+ case "length":
2536
+ case "model_length":
2537
+ return "length";
2538
+ case "tool_calls":
2539
+ return "tool-calls";
2540
+ default:
2541
+ return "unknown";
2542
+ }
2543
+ }
2544
+ var mistralLanguageModelOptions = z4.z.object({
2545
+ /**
2546
+ Whether to inject a safety prompt before all conversations.
2547
+
2548
+ Defaults to `false`.
2549
+ */
2550
+ safePrompt: z4.z.boolean().optional(),
2551
+ documentImageLimit: z4.z.number().optional(),
2552
+ documentPageLimit: z4.z.number().optional(),
2553
+ /**
2554
+ * Whether to use structured outputs.
2555
+ *
2556
+ * @default true
2557
+ */
2558
+ structuredOutputs: z4.z.boolean().optional(),
2559
+ /**
2560
+ * Whether to use strict JSON schema validation.
2561
+ *
2562
+ * @default false
2563
+ */
2564
+ strictJsonSchema: z4.z.boolean().optional(),
2565
+ /**
2566
+ * Whether to enable parallel function calling during tool use.
2567
+ * When set to false, the model will use at most one tool per response.
2568
+ *
2569
+ * @default true
2570
+ */
2571
+ parallelToolCalls: z4.z.boolean().optional()
2572
+ });
2573
+ var mistralErrorDataSchema = z4.z.object({
2574
+ object: z4.z.literal("error"),
2575
+ message: z4.z.string(),
2576
+ type: z4.z.string(),
2577
+ param: z4.z.string().nullable(),
2578
+ code: z4.z.string().nullable()
2579
+ });
2580
+ var mistralFailedResponseHandler = chunkCZEJQSWB_cjs.createJsonErrorResponseHandler({
2581
+ errorSchema: mistralErrorDataSchema,
2582
+ errorToMessage: (data) => data.message
2583
+ });
2584
+ function prepareTools2({
2585
+ tools,
2586
+ toolChoice
2587
+ }) {
2588
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
2589
+ const toolWarnings = [];
2590
+ if (tools == null) {
2591
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
2592
+ }
2593
+ const mistralTools = [];
2594
+ for (const tool of tools) {
2595
+ if (tool.type === "provider-defined") {
2596
+ toolWarnings.push({ type: "unsupported-tool", tool });
2597
+ } else {
2598
+ mistralTools.push({
2599
+ type: "function",
2600
+ function: {
2601
+ name: tool.name,
2602
+ description: tool.description,
2603
+ parameters: tool.inputSchema
2604
+ }
2605
+ });
2606
+ }
2607
+ }
2608
+ if (toolChoice == null) {
2609
+ return { tools: mistralTools, toolChoice: void 0, toolWarnings };
2610
+ }
2611
+ const type = toolChoice.type;
2612
+ switch (type) {
2613
+ case "auto":
2614
+ case "none":
2615
+ return { tools: mistralTools, toolChoice: type, toolWarnings };
2616
+ case "required":
2617
+ return { tools: mistralTools, toolChoice: "any", toolWarnings };
2618
+ // mistral does not support tool mode directly,
2619
+ // so we filter the tools and force the tool choice through 'any'
2620
+ case "tool":
2621
+ return {
2622
+ tools: mistralTools.filter(
2623
+ (tool) => tool.function.name === toolChoice.toolName
2624
+ ),
2625
+ toolChoice: "any",
2626
+ toolWarnings
2627
+ };
2628
+ default: {
2629
+ const _exhaustiveCheck = type;
2630
+ throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
2631
+ functionality: `tool choice type: ${_exhaustiveCheck}`
2632
+ });
2633
+ }
2634
+ }
2635
+ }
2636
+ var MistralChatLanguageModel = class {
2637
+ constructor(modelId, config) {
2638
+ this.specificationVersion = "v2";
2639
+ this.supportedUrls = {
2640
+ "application/pdf": [/^https:\/\/.*$/]
2641
+ };
2642
+ var _a;
2643
+ this.modelId = modelId;
2644
+ this.config = config;
2645
+ this.generateId = (_a = config.generateId) != null ? _a : chunkCZEJQSWB_cjs.generateId;
2646
+ }
2647
+ get provider() {
2648
+ return this.config.provider;
2649
+ }
2650
+ async getArgs({
2651
+ prompt,
2652
+ maxOutputTokens,
2653
+ temperature,
2654
+ topP,
2655
+ topK,
2656
+ frequencyPenalty,
2657
+ presencePenalty,
2658
+ stopSequences,
2659
+ responseFormat,
2660
+ seed,
2661
+ providerOptions,
2662
+ tools,
2663
+ toolChoice
2664
+ }) {
2665
+ var _a, _b, _c, _d;
2666
+ const warnings = [];
2667
+ const options = (_a = await chunkCZEJQSWB_cjs.parseProviderOptions({
2668
+ provider: "mistral",
2669
+ providerOptions,
2670
+ schema: mistralLanguageModelOptions
2671
+ })) != null ? _a : {};
2672
+ if (topK != null) {
2673
+ warnings.push({
2674
+ type: "unsupported-setting",
2675
+ setting: "topK"
2676
+ });
2677
+ }
2678
+ if (frequencyPenalty != null) {
2679
+ warnings.push({
2680
+ type: "unsupported-setting",
2681
+ setting: "frequencyPenalty"
2682
+ });
2683
+ }
2684
+ if (presencePenalty != null) {
2685
+ warnings.push({
2686
+ type: "unsupported-setting",
2687
+ setting: "presencePenalty"
2688
+ });
2689
+ }
2690
+ if (stopSequences != null) {
2691
+ warnings.push({
2692
+ type: "unsupported-setting",
2693
+ setting: "stopSequences"
2694
+ });
2695
+ }
2696
+ const structuredOutputs = (_b = options.structuredOutputs) != null ? _b : true;
2697
+ const strictJsonSchema = (_c = options.strictJsonSchema) != null ? _c : false;
2698
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && !(responseFormat == null ? void 0 : responseFormat.schema)) {
2699
+ prompt = chunkCZEJQSWB_cjs.injectJsonInstructionIntoMessages({
2700
+ messages: prompt,
2701
+ schema: responseFormat.schema
2702
+ });
2703
+ }
2704
+ const baseArgs = {
2705
+ // model id:
2706
+ model: this.modelId,
2707
+ // model specific settings:
2708
+ safe_prompt: options.safePrompt,
2709
+ // standardized settings:
2710
+ max_tokens: maxOutputTokens,
2711
+ temperature,
2712
+ top_p: topP,
2713
+ random_seed: seed,
2714
+ // response format:
2715
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? {
2716
+ type: "json_schema",
2717
+ json_schema: {
2718
+ schema: responseFormat.schema,
2719
+ strict: strictJsonSchema,
2720
+ name: (_d = responseFormat.name) != null ? _d : "response",
2721
+ description: responseFormat.description
2722
+ }
2723
+ } : { type: "json_object" } : void 0,
2724
+ // mistral-specific provider options:
2725
+ document_image_limit: options.documentImageLimit,
2726
+ document_page_limit: options.documentPageLimit,
2727
+ // messages:
2728
+ messages: convertToMistralChatMessages(prompt)
2729
+ };
2730
+ const {
2731
+ tools: mistralTools,
2732
+ toolChoice: mistralToolChoice,
2733
+ toolWarnings
2734
+ } = prepareTools2({
2735
+ tools,
2736
+ toolChoice
2737
+ });
2738
+ return {
2739
+ args: {
2740
+ ...baseArgs,
2741
+ tools: mistralTools,
2742
+ tool_choice: mistralToolChoice,
2743
+ ...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {}
2744
+ },
2745
+ warnings: [...warnings, ...toolWarnings]
2746
+ };
2747
+ }
2748
+ async doGenerate(options) {
2749
+ const { args: body, warnings } = await this.getArgs(options);
2750
+ const {
2751
+ responseHeaders,
2752
+ value: response,
2753
+ rawValue: rawResponse
2754
+ } = await chunkCZEJQSWB_cjs.postJsonToApi({
2755
+ url: `${this.config.baseURL}/chat/completions`,
2756
+ headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
2757
+ body,
2758
+ failedResponseHandler: mistralFailedResponseHandler,
2759
+ successfulResponseHandler: chunkCZEJQSWB_cjs.createJsonResponseHandler(
2760
+ mistralChatResponseSchema
2761
+ ),
2762
+ abortSignal: options.abortSignal,
2763
+ fetch: this.config.fetch
2764
+ });
2765
+ const choice = response.choices[0];
2766
+ const content = [];
2767
+ if (choice.message.content != null && Array.isArray(choice.message.content)) {
2768
+ for (const part of choice.message.content) {
2769
+ if (part.type === "thinking") {
2770
+ const reasoningText = extractReasoningContent(part.thinking);
2771
+ if (reasoningText.length > 0) {
2772
+ content.push({ type: "reasoning", text: reasoningText });
2773
+ }
2774
+ } else if (part.type === "text") {
2775
+ if (part.text.length > 0) {
2776
+ content.push({ type: "text", text: part.text });
2777
+ }
2778
+ }
2779
+ }
2780
+ } else {
2781
+ const text = extractTextContent(choice.message.content);
2782
+ if (text != null && text.length > 0) {
2783
+ content.push({ type: "text", text });
2784
+ }
2785
+ }
2786
+ if (choice.message.tool_calls != null) {
2787
+ for (const toolCall of choice.message.tool_calls) {
2788
+ content.push({
2789
+ type: "tool-call",
2790
+ toolCallId: toolCall.id,
2791
+ toolName: toolCall.function.name,
2792
+ input: toolCall.function.arguments
2793
+ });
2794
+ }
2795
+ }
2796
+ return {
2797
+ content,
2798
+ finishReason: mapMistralFinishReason(choice.finish_reason),
2799
+ usage: {
2800
+ inputTokens: response.usage.prompt_tokens,
2801
+ outputTokens: response.usage.completion_tokens,
2802
+ totalTokens: response.usage.total_tokens
2803
+ },
2804
+ request: { body },
2805
+ response: {
2806
+ ...getResponseMetadata2(response),
2807
+ headers: responseHeaders,
2808
+ body: rawResponse
2809
+ },
2810
+ warnings
2811
+ };
2812
+ }
2813
+ async doStream(options) {
2814
+ const { args, warnings } = await this.getArgs(options);
2815
+ const body = { ...args, stream: true };
2816
+ const { responseHeaders, value: response } = await chunkCZEJQSWB_cjs.postJsonToApi({
2817
+ url: `${this.config.baseURL}/chat/completions`,
2818
+ headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
2819
+ body,
2820
+ failedResponseHandler: mistralFailedResponseHandler,
2821
+ successfulResponseHandler: chunkCZEJQSWB_cjs.createEventSourceResponseHandler(
2822
+ mistralChatChunkSchema
2823
+ ),
2824
+ abortSignal: options.abortSignal,
2825
+ fetch: this.config.fetch
2826
+ });
2827
+ let finishReason = "unknown";
2828
+ const usage = {
2829
+ inputTokens: void 0,
2830
+ outputTokens: void 0,
2831
+ totalTokens: void 0
2832
+ };
2833
+ let isFirstChunk = true;
2834
+ let activeText = false;
2835
+ let activeReasoningId = null;
2836
+ const generateId22 = this.generateId;
2837
+ return {
2838
+ stream: response.pipeThrough(
2839
+ new TransformStream({
2840
+ start(controller) {
2841
+ controller.enqueue({ type: "stream-start", warnings });
2842
+ },
2843
+ transform(chunk, controller) {
2844
+ if (options.includeRawChunks) {
2845
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2846
+ }
2847
+ if (!chunk.success) {
2848
+ controller.enqueue({ type: "error", error: chunk.error });
2849
+ return;
2850
+ }
2851
+ const value = chunk.value;
2852
+ if (isFirstChunk) {
2853
+ isFirstChunk = false;
2854
+ controller.enqueue({
2855
+ type: "response-metadata",
2856
+ ...getResponseMetadata2(value)
2857
+ });
2858
+ }
2859
+ if (value.usage != null) {
2860
+ usage.inputTokens = value.usage.prompt_tokens;
2861
+ usage.outputTokens = value.usage.completion_tokens;
2862
+ usage.totalTokens = value.usage.total_tokens;
2863
+ }
2864
+ const choice = value.choices[0];
2865
+ const delta = choice.delta;
2866
+ const textContent = extractTextContent(delta.content);
2867
+ if (delta.content != null && Array.isArray(delta.content)) {
2868
+ for (const part of delta.content) {
2869
+ if (part.type === "thinking") {
2870
+ const reasoningDelta = extractReasoningContent(part.thinking);
2871
+ if (reasoningDelta.length > 0) {
2872
+ if (activeReasoningId == null) {
2873
+ if (activeText) {
2874
+ controller.enqueue({ type: "text-end", id: "0" });
2875
+ activeText = false;
2876
+ }
2877
+ activeReasoningId = generateId22();
2878
+ controller.enqueue({
2879
+ type: "reasoning-start",
2880
+ id: activeReasoningId
2881
+ });
2882
+ }
2883
+ controller.enqueue({
2884
+ type: "reasoning-delta",
2885
+ id: activeReasoningId,
2886
+ delta: reasoningDelta
2887
+ });
2888
+ }
2889
+ }
2890
+ }
2891
+ }
2892
+ if (textContent != null && textContent.length > 0) {
2893
+ if (!activeText) {
2894
+ if (activeReasoningId != null) {
2895
+ controller.enqueue({
2896
+ type: "reasoning-end",
2897
+ id: activeReasoningId
2898
+ });
2899
+ activeReasoningId = null;
2900
+ }
2901
+ controller.enqueue({ type: "text-start", id: "0" });
2902
+ activeText = true;
2903
+ }
2904
+ controller.enqueue({
2905
+ type: "text-delta",
2906
+ id: "0",
2907
+ delta: textContent
2908
+ });
2909
+ }
2910
+ if ((delta == null ? void 0 : delta.tool_calls) != null) {
2911
+ for (const toolCall of delta.tool_calls) {
2912
+ const toolCallId = toolCall.id;
2913
+ const toolName = toolCall.function.name;
2914
+ const input = toolCall.function.arguments;
2915
+ controller.enqueue({
2916
+ type: "tool-input-start",
2917
+ id: toolCallId,
2918
+ toolName
2919
+ });
2920
+ controller.enqueue({
2921
+ type: "tool-input-delta",
2922
+ id: toolCallId,
2923
+ delta: input
2924
+ });
2925
+ controller.enqueue({
2926
+ type: "tool-input-end",
2927
+ id: toolCallId
2928
+ });
2929
+ controller.enqueue({
2930
+ type: "tool-call",
2931
+ toolCallId,
2932
+ toolName,
2933
+ input
2934
+ });
2935
+ }
2936
+ }
2937
+ if (choice.finish_reason != null) {
2938
+ finishReason = mapMistralFinishReason(choice.finish_reason);
2939
+ }
2940
+ },
2941
+ flush(controller) {
2942
+ if (activeReasoningId != null) {
2943
+ controller.enqueue({
2944
+ type: "reasoning-end",
2945
+ id: activeReasoningId
2946
+ });
2947
+ }
2948
+ if (activeText) {
2949
+ controller.enqueue({ type: "text-end", id: "0" });
2950
+ }
2951
+ controller.enqueue({
2952
+ type: "finish",
2953
+ finishReason,
2954
+ usage
2955
+ });
2956
+ }
2957
+ })
2958
+ ),
2959
+ request: { body },
2960
+ response: { headers: responseHeaders }
2961
+ };
2962
+ }
2963
+ };
2964
+ function extractReasoningContent(thinking) {
2965
+ return thinking.filter((chunk) => chunk.type === "text").map((chunk) => chunk.text).join("");
2966
+ }
2967
+ function extractTextContent(content) {
2968
+ if (typeof content === "string") {
2969
+ return content;
2970
+ }
2971
+ if (content == null) {
2972
+ return void 0;
2973
+ }
2974
+ const textContent = [];
2975
+ for (const chunk of content) {
2976
+ const { type } = chunk;
2977
+ switch (type) {
2978
+ case "text":
2979
+ textContent.push(chunk.text);
2980
+ break;
2981
+ case "thinking":
2982
+ case "image_url":
2983
+ case "reference":
2984
+ break;
2985
+ default: {
2986
+ const _exhaustiveCheck = type;
2987
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
2988
+ }
2989
+ }
2990
+ }
2991
+ return textContent.length ? textContent.join("") : void 0;
2992
+ }
2993
+ var mistralContentSchema = z4.z.union([
2994
+ z4.z.string(),
2995
+ z4.z.array(
2996
+ z4.z.discriminatedUnion("type", [
2997
+ z4.z.object({
2998
+ type: z4.z.literal("text"),
2999
+ text: z4.z.string()
3000
+ }),
3001
+ z4.z.object({
3002
+ type: z4.z.literal("image_url"),
3003
+ image_url: z4.z.union([
3004
+ z4.z.string(),
3005
+ z4.z.object({
3006
+ url: z4.z.string(),
3007
+ detail: z4.z.string().nullable()
3008
+ })
3009
+ ])
3010
+ }),
3011
+ z4.z.object({
3012
+ type: z4.z.literal("reference"),
3013
+ reference_ids: z4.z.array(z4.z.number())
3014
+ }),
3015
+ z4.z.object({
3016
+ type: z4.z.literal("thinking"),
3017
+ thinking: z4.z.array(
3018
+ z4.z.object({
3019
+ type: z4.z.literal("text"),
3020
+ text: z4.z.string()
3021
+ })
3022
+ )
3023
+ })
3024
+ ])
3025
+ )
3026
+ ]).nullish();
3027
+ var mistralUsageSchema = z4.z.object({
3028
+ prompt_tokens: z4.z.number(),
3029
+ completion_tokens: z4.z.number(),
3030
+ total_tokens: z4.z.number()
3031
+ });
3032
+ var mistralChatResponseSchema = z4.z.object({
3033
+ id: z4.z.string().nullish(),
3034
+ created: z4.z.number().nullish(),
3035
+ model: z4.z.string().nullish(),
3036
+ choices: z4.z.array(
3037
+ z4.z.object({
3038
+ message: z4.z.object({
3039
+ role: z4.z.literal("assistant"),
3040
+ content: mistralContentSchema,
3041
+ tool_calls: z4.z.array(
3042
+ z4.z.object({
3043
+ id: z4.z.string(),
3044
+ function: z4.z.object({ name: z4.z.string(), arguments: z4.z.string() })
3045
+ })
3046
+ ).nullish()
3047
+ }),
3048
+ index: z4.z.number(),
3049
+ finish_reason: z4.z.string().nullish()
3050
+ })
3051
+ ),
3052
+ object: z4.z.literal("chat.completion"),
3053
+ usage: mistralUsageSchema
3054
+ });
3055
+ var mistralChatChunkSchema = z4.z.object({
3056
+ id: z4.z.string().nullish(),
3057
+ created: z4.z.number().nullish(),
3058
+ model: z4.z.string().nullish(),
3059
+ choices: z4.z.array(
3060
+ z4.z.object({
3061
+ delta: z4.z.object({
3062
+ role: z4.z.enum(["assistant"]).optional(),
3063
+ content: mistralContentSchema,
3064
+ tool_calls: z4.z.array(
3065
+ z4.z.object({
3066
+ id: z4.z.string(),
3067
+ function: z4.z.object({ name: z4.z.string(), arguments: z4.z.string() })
3068
+ })
3069
+ ).nullish()
3070
+ }),
3071
+ finish_reason: z4.z.string().nullish(),
3072
+ index: z4.z.number()
3073
+ })
3074
+ ),
3075
+ usage: mistralUsageSchema.nullish()
3076
+ });
3077
+ var MistralEmbeddingModel = class {
3078
+ constructor(modelId, config) {
3079
+ this.specificationVersion = "v2";
3080
+ this.maxEmbeddingsPerCall = 32;
3081
+ this.supportsParallelCalls = false;
3082
+ this.modelId = modelId;
3083
+ this.config = config;
3084
+ }
3085
+ get provider() {
3086
+ return this.config.provider;
3087
+ }
3088
+ async doEmbed({
3089
+ values,
3090
+ abortSignal,
3091
+ headers
3092
+ }) {
3093
+ if (values.length > this.maxEmbeddingsPerCall) {
3094
+ throw new chunkCZEJQSWB_cjs.TooManyEmbeddingValuesForCallError({
3095
+ provider: this.provider,
3096
+ modelId: this.modelId,
3097
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
3098
+ values
3099
+ });
3100
+ }
3101
+ const {
3102
+ responseHeaders,
3103
+ value: response,
3104
+ rawValue
3105
+ } = await chunkCZEJQSWB_cjs.postJsonToApi({
3106
+ url: `${this.config.baseURL}/embeddings`,
3107
+ headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), headers),
3108
+ body: {
3109
+ model: this.modelId,
3110
+ input: values,
3111
+ encoding_format: "float"
3112
+ },
3113
+ failedResponseHandler: mistralFailedResponseHandler,
3114
+ successfulResponseHandler: chunkCZEJQSWB_cjs.createJsonResponseHandler(
3115
+ MistralTextEmbeddingResponseSchema
3116
+ ),
3117
+ abortSignal,
3118
+ fetch: this.config.fetch
3119
+ });
3120
+ return {
3121
+ embeddings: response.data.map((item) => item.embedding),
3122
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
3123
+ response: { headers: responseHeaders, body: rawValue }
3124
+ };
3125
+ }
3126
+ };
3127
+ var MistralTextEmbeddingResponseSchema = z4.z.object({
3128
+ data: z4.z.array(z4.z.object({ embedding: z4.z.array(z4.z.number()) })),
3129
+ usage: z4.z.object({ prompt_tokens: z4.z.number() }).nullish()
3130
+ });
3131
+ var VERSION3 = "2.0.24" ;
3132
+ function createMistral(options = {}) {
3133
+ var _a;
3134
+ const baseURL = (_a = chunkCZEJQSWB_cjs.withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.mistral.ai/v1";
3135
+ const getHeaders = () => chunkCZEJQSWB_cjs.withUserAgentSuffix(
3136
+ {
3137
+ Authorization: `Bearer ${chunkCZEJQSWB_cjs.loadApiKey({
3138
+ apiKey: options.apiKey,
3139
+ environmentVariableName: "MISTRAL_API_KEY",
3140
+ description: "Mistral"
3141
+ })}`,
3142
+ ...options.headers
3143
+ },
3144
+ `ai-sdk/mistral/${VERSION3}`
3145
+ );
3146
+ const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, {
3147
+ provider: "mistral.chat",
3148
+ baseURL,
3149
+ headers: getHeaders,
3150
+ fetch: options.fetch,
3151
+ generateId: options.generateId
3152
+ });
3153
+ const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, {
3154
+ provider: "mistral.embedding",
3155
+ baseURL,
3156
+ headers: getHeaders,
3157
+ fetch: options.fetch
3158
+ });
3159
+ const provider = function(modelId) {
3160
+ if (new.target) {
3161
+ throw new Error(
3162
+ "The Mistral model function cannot be called with the new keyword."
3163
+ );
3164
+ }
3165
+ return createChatModel(modelId);
3166
+ };
3167
+ provider.languageModel = createChatModel;
3168
+ provider.chat = createChatModel;
3169
+ provider.embedding = createEmbeddingModel;
3170
+ provider.textEmbedding = createEmbeddingModel;
3171
+ provider.textEmbeddingModel = createEmbeddingModel;
3172
+ provider.imageModel = (modelId) => {
3173
+ throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
3174
+ };
3175
+ return provider;
3176
+ }
3177
+ createMistral();
3178
+
3179
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
3180
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
3181
+
3182
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.5_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
3183
+ function combineHeaders3(...headers) {
3184
+ return headers.reduce(
3185
+ (combinedHeaders, currentHeaders) => ({
3186
+ ...combinedHeaders,
3187
+ ...currentHeaders != null ? currentHeaders : {}
3188
+ }),
3189
+ {}
3190
+ );
3191
+ }
3192
+ function extractResponseHeaders2(response) {
3193
+ return Object.fromEntries([...response.headers]);
3194
+ }
3195
+ var createIdGenerator2 = ({
3196
+ prefix,
3197
+ size = 16,
3198
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
3199
+ separator = "-"
3200
+ } = {}) => {
3201
+ const generator = () => {
3202
+ const alphabetLength = alphabet.length;
3203
+ const chars = new Array(size);
3204
+ for (let i = 0; i < size; i++) {
3205
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
3206
+ }
3207
+ return chars.join("");
3208
+ };
3209
+ if (prefix == null) {
3210
+ return generator;
3211
+ }
3212
+ if (alphabet.includes(separator)) {
3213
+ throw new chunkCZEJQSWB_cjs.InvalidArgumentError({
3214
+ argument: "separator",
3215
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
3216
+ });
3217
+ }
3218
+ return () => `${prefix}${separator}${generator()}`;
3219
+ };
3220
+ var generateId3 = createIdGenerator2();
3221
+ function isAbortError2(error) {
3222
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
3223
+ error.name === "TimeoutError");
3224
+ }
3225
+ var FETCH_FAILED_ERROR_MESSAGES2 = ["fetch failed", "failed to fetch"];
3226
+ function handleFetchError2({
3227
+ error,
3228
+ url,
3229
+ requestBodyValues
3230
+ }) {
3231
+ if (isAbortError2(error)) {
3232
+ return error;
3233
+ }
3234
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES2.includes(error.message.toLowerCase())) {
3235
+ const cause = error.cause;
3236
+ if (cause != null) {
3237
+ return new chunkCZEJQSWB_cjs.APICallError({
3238
+ message: `Cannot connect to API: ${cause.message}`,
3239
+ cause,
3240
+ url,
3241
+ requestBodyValues,
3242
+ isRetryable: true
3243
+ // retry when network error
3244
+ });
3245
+ }
3246
+ }
3247
+ return error;
3248
+ }
3249
+ function removeUndefinedEntries(record) {
3250
+ return Object.fromEntries(
3251
+ Object.entries(record).filter(([_key, value]) => value != null)
3252
+ );
3253
+ }
3254
+ function loadApiKey3({
3255
+ apiKey,
3256
+ environmentVariableName,
3257
+ apiKeyParameterName = "apiKey",
3258
+ description
3259
+ }) {
3260
+ if (typeof apiKey === "string") {
3261
+ return apiKey;
3262
+ }
3263
+ if (apiKey != null) {
3264
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3265
+ message: `${description} API key must be a string.`
3266
+ });
3267
+ }
3268
+ if (typeof process === "undefined") {
3269
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3270
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
3271
+ });
3272
+ }
3273
+ apiKey = process.env[environmentVariableName];
3274
+ if (apiKey == null) {
3275
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3276
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
3277
+ });
3278
+ }
3279
+ if (typeof apiKey !== "string") {
3280
+ throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3281
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
3282
+ });
3283
+ }
3284
+ return apiKey;
3285
+ }
3286
+ var suspectProtoRx2 = /"__proto__"\s*:/;
3287
+ var suspectConstructorRx2 = /"constructor"\s*:/;
3288
+ function _parse2(text) {
3289
+ const obj = JSON.parse(text);
3290
+ if (obj === null || typeof obj !== "object") {
3291
+ return obj;
3292
+ }
3293
+ if (suspectProtoRx2.test(text) === false && suspectConstructorRx2.test(text) === false) {
3294
+ return obj;
3295
+ }
3296
+ return filter2(obj);
3297
+ }
3298
+ function filter2(obj) {
3299
+ let next = [obj];
3300
+ while (next.length) {
3301
+ const nodes = next;
3302
+ next = [];
3303
+ for (const node of nodes) {
3304
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
3305
+ throw new SyntaxError("Object contains forbidden prototype property");
3306
+ }
3307
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
3308
+ throw new SyntaxError("Object contains forbidden prototype property");
3309
+ }
3310
+ for (const key in node) {
3311
+ const value = node[key];
3312
+ if (value && typeof value === "object") {
3313
+ next.push(value);
3314
+ }
3315
+ }
3316
+ }
3317
+ }
3318
+ return obj;
3319
+ }
3320
+ function secureJsonParse2(text) {
3321
+ const { stackTraceLimit } = Error;
3322
+ Error.stackTraceLimit = 0;
3323
+ try {
3324
+ return _parse2(text);
3325
+ } finally {
3326
+ Error.stackTraceLimit = stackTraceLimit;
3327
+ }
3328
+ }
3329
+ var validatorSymbol2 = Symbol.for("vercel.ai.validator");
3330
+ function validator2(validate) {
3331
+ return { [validatorSymbol2]: true, validate };
3332
+ }
3333
+ function isValidator2(value) {
3334
+ return typeof value === "object" && value !== null && validatorSymbol2 in value && value[validatorSymbol2] === true && "validate" in value;
3335
+ }
3336
+ function asValidator2(value) {
3337
+ return isValidator2(value) ? value : standardSchemaValidator2(value);
3338
+ }
3339
+ function standardSchemaValidator2(standardSchema) {
3340
+ return validator2(async (value) => {
3341
+ const result = await standardSchema["~standard"].validate(value);
3342
+ return result.issues == null ? { success: true, value: result.value } : {
3343
+ success: false,
3344
+ error: new chunkCZEJQSWB_cjs.TypeValidationError({
3345
+ value,
3346
+ cause: result.issues
3347
+ })
3348
+ };
3349
+ });
3350
+ }
3351
+ async function validateTypes2({
3352
+ value,
3353
+ schema
3354
+ }) {
3355
+ const result = await safeValidateTypes2({ value, schema });
3356
+ if (!result.success) {
3357
+ throw chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error });
3358
+ }
3359
+ return result.value;
3360
+ }
3361
+ async function safeValidateTypes2({
3362
+ value,
3363
+ schema
3364
+ }) {
3365
+ const validator22 = asValidator2(schema);
3366
+ try {
3367
+ if (validator22.validate == null) {
3368
+ return { success: true, value, rawValue: value };
3369
+ }
3370
+ const result = await validator22.validate(value);
3371
+ if (result.success) {
3372
+ return { success: true, value: result.value, rawValue: value };
3373
+ }
3374
+ return {
3375
+ success: false,
3376
+ error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error }),
3377
+ rawValue: value
3378
+ };
3379
+ } catch (error) {
3380
+ return {
3381
+ success: false,
3382
+ error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: error }),
3383
+ rawValue: value
3384
+ };
3385
+ }
3386
+ }
3387
+ async function parseJSON2({
3388
+ text,
3389
+ schema
3390
+ }) {
3391
+ try {
3392
+ const value = secureJsonParse2(text);
3393
+ if (schema == null) {
3394
+ return value;
3395
+ }
3396
+ return validateTypes2({ value, schema });
3397
+ } catch (error) {
3398
+ if (chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) || chunkCZEJQSWB_cjs.TypeValidationError.isInstance(error)) {
3399
+ throw error;
3400
+ }
3401
+ throw new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error });
3402
+ }
3403
+ }
3404
+ async function safeParseJSON2({
3405
+ text,
3406
+ schema
3407
+ }) {
3408
+ try {
3409
+ const value = secureJsonParse2(text);
3410
+ if (schema == null) {
3411
+ return { success: true, value, rawValue: value };
3412
+ }
3413
+ return await safeValidateTypes2({ value, schema });
3414
+ } catch (error) {
3415
+ return {
3416
+ success: false,
3417
+ error: chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) ? error : new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error }),
3418
+ rawValue: void 0
3419
+ };
3420
+ }
3421
+ }
3422
+ function parseJsonEventStream2({
3423
+ stream,
3424
+ schema
3425
+ }) {
3426
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new chunkCZEJQSWB_cjs.EventSourceParserStream()).pipeThrough(
3427
+ new TransformStream({
3428
+ async transform({ data }, controller) {
3429
+ if (data === "[DONE]") {
3430
+ return;
3431
+ }
3432
+ controller.enqueue(await safeParseJSON2({ text: data, schema }));
3433
+ }
3434
+ })
3435
+ );
3436
+ }
3437
+ var getOriginalFetch22 = () => globalThis.fetch;
3438
+ var postJsonToApi3 = async ({
3439
+ url,
3440
+ headers,
3441
+ body,
3442
+ failedResponseHandler,
3443
+ successfulResponseHandler,
3444
+ abortSignal,
3445
+ fetch: fetch2
3446
+ }) => postToApi2({
3447
+ url,
3448
+ headers: {
3449
+ "Content-Type": "application/json",
3450
+ ...headers
3451
+ },
3452
+ body: {
3453
+ content: JSON.stringify(body),
3454
+ values: body
3455
+ },
3456
+ failedResponseHandler,
3457
+ successfulResponseHandler,
3458
+ abortSignal,
3459
+ fetch: fetch2
3460
+ });
3461
+ var postToApi2 = async ({
3462
+ url,
3463
+ headers = {},
3464
+ body,
3465
+ successfulResponseHandler,
3466
+ failedResponseHandler,
3467
+ abortSignal,
3468
+ fetch: fetch2 = getOriginalFetch22()
3469
+ }) => {
3470
+ try {
3471
+ const response = await fetch2(url, {
3472
+ method: "POST",
3473
+ headers: removeUndefinedEntries(headers),
3474
+ body: body.content,
3475
+ signal: abortSignal
3476
+ });
3477
+ const responseHeaders = extractResponseHeaders2(response);
3478
+ if (!response.ok) {
3479
+ let errorInformation;
3480
+ try {
3481
+ errorInformation = await failedResponseHandler({
3482
+ response,
3483
+ url,
3484
+ requestBodyValues: body.values
3485
+ });
3486
+ } catch (error) {
3487
+ if (isAbortError2(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
3488
+ throw error;
3489
+ }
3490
+ throw new chunkCZEJQSWB_cjs.APICallError({
3491
+ message: "Failed to process error response",
3492
+ cause: error,
3493
+ statusCode: response.status,
3494
+ url,
3495
+ responseHeaders,
3496
+ requestBodyValues: body.values
3497
+ });
3498
+ }
3499
+ throw errorInformation.value;
3500
+ }
3501
+ try {
3502
+ return await successfulResponseHandler({
3503
+ response,
3504
+ url,
3505
+ requestBodyValues: body.values
3506
+ });
3507
+ } catch (error) {
3508
+ if (error instanceof Error) {
3509
+ if (isAbortError2(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
3510
+ throw error;
3511
+ }
3512
+ }
3513
+ throw new chunkCZEJQSWB_cjs.APICallError({
3514
+ message: "Failed to process successful response",
3515
+ cause: error,
3516
+ statusCode: response.status,
3517
+ url,
3518
+ responseHeaders,
3519
+ requestBodyValues: body.values
3520
+ });
3521
+ }
3522
+ } catch (error) {
3523
+ throw handleFetchError2({ error, url, requestBodyValues: body.values });
3524
+ }
3525
+ };
3526
+ var createJsonErrorResponseHandler3 = ({
3527
+ errorSchema,
3528
+ errorToMessage: errorToMessage2,
3529
+ isRetryable
3530
+ }) => async ({ response, url, requestBodyValues }) => {
3531
+ const responseBody = await response.text();
3532
+ const responseHeaders = extractResponseHeaders2(response);
3533
+ if (responseBody.trim() === "") {
3534
+ return {
3535
+ responseHeaders,
3536
+ value: new chunkCZEJQSWB_cjs.APICallError({
3537
+ message: response.statusText,
3538
+ url,
3539
+ requestBodyValues,
3540
+ statusCode: response.status,
3541
+ responseHeaders,
3542
+ responseBody,
3543
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
3544
+ })
3545
+ };
3546
+ }
3547
+ try {
3548
+ const parsedError = await parseJSON2({
3549
+ text: responseBody,
3550
+ schema: errorSchema
3551
+ });
3552
+ return {
3553
+ responseHeaders,
3554
+ value: new chunkCZEJQSWB_cjs.APICallError({
3555
+ message: errorToMessage2(parsedError),
3556
+ url,
3557
+ requestBodyValues,
3558
+ statusCode: response.status,
3559
+ responseHeaders,
3560
+ responseBody,
3561
+ data: parsedError,
3562
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
3563
+ })
3564
+ };
3565
+ } catch (parseError) {
3566
+ return {
3567
+ responseHeaders,
3568
+ value: new chunkCZEJQSWB_cjs.APICallError({
3569
+ message: response.statusText,
3570
+ url,
3571
+ requestBodyValues,
3572
+ statusCode: response.status,
3573
+ responseHeaders,
3574
+ responseBody,
3575
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
3576
+ })
3577
+ };
3578
+ }
3579
+ };
3580
+ var createEventSourceResponseHandler3 = (chunkSchema) => async ({ response }) => {
3581
+ const responseHeaders = extractResponseHeaders2(response);
3582
+ if (response.body == null) {
3583
+ throw new chunkCZEJQSWB_cjs.EmptyResponseBodyError({});
3584
+ }
3585
+ return {
3586
+ responseHeaders,
3587
+ value: parseJsonEventStream2({
3588
+ stream: response.body,
3589
+ schema: chunkSchema
3590
+ })
3591
+ };
3592
+ };
3593
+ var createJsonResponseHandler3 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
3594
+ const responseBody = await response.text();
3595
+ const parsedResult = await safeParseJSON2({
3596
+ text: responseBody,
3597
+ schema: responseSchema
3598
+ });
3599
+ const responseHeaders = extractResponseHeaders2(response);
3600
+ if (!parsedResult.success) {
3601
+ throw new chunkCZEJQSWB_cjs.APICallError({
3602
+ message: "Invalid JSON response",
3603
+ cause: parsedResult.error,
3604
+ statusCode: response.status,
3605
+ responseHeaders,
3606
+ responseBody,
3607
+ url,
3608
+ requestBodyValues
3609
+ });
3610
+ }
3611
+ return {
3612
+ responseHeaders,
3613
+ value: parsedResult.value,
3614
+ rawValue: parsedResult.rawValue
3615
+ };
3616
+ };
3617
+ var { btoa: btoa2} = globalThis;
3618
+ function convertUint8ArrayToBase64(array) {
3619
+ let latin1string = "";
3620
+ for (let i = 0; i < array.length; i++) {
3621
+ latin1string += String.fromCodePoint(array[i]);
3622
+ }
3623
+ return btoa2(latin1string);
3624
+ }
3625
+ function withoutTrailingSlash3(url) {
3626
+ return url == null ? void 0 : url.replace(/\/$/, "");
3627
+ }
3628
+ function convertToPerplexityMessages(prompt) {
3629
+ const messages = [];
3630
+ for (const { role, content } of prompt) {
3631
+ switch (role) {
3632
+ case "system": {
3633
+ messages.push({ role: "system", content });
3634
+ break;
3635
+ }
3636
+ case "user":
3637
+ case "assistant": {
3638
+ const hasImage = content.some(
3639
+ (part) => part.type === "file" && part.mediaType.startsWith("image/")
3640
+ );
3641
+ const messageContent = content.map((part) => {
3642
+ var _a;
3643
+ switch (part.type) {
3644
+ case "text": {
3645
+ return {
3646
+ type: "text",
3647
+ text: part.text
3648
+ };
3649
+ }
3650
+ case "file": {
3651
+ return part.data instanceof URL ? {
3652
+ type: "image_url",
3653
+ image_url: {
3654
+ url: part.data.toString()
3655
+ }
3656
+ } : {
3657
+ type: "image_url",
3658
+ image_url: {
3659
+ url: `data:${(_a = part.mediaType) != null ? _a : "image/jpeg"};base64,${typeof part.data === "string" ? part.data : convertUint8ArrayToBase64(part.data)}`
3660
+ }
3661
+ };
3662
+ }
3663
+ }
3664
+ }).filter(Boolean);
3665
+ messages.push({
3666
+ role,
3667
+ content: hasImage ? messageContent : messageContent.filter((part) => part.type === "text").map((part) => part.text).join("")
3668
+ });
3669
+ break;
3670
+ }
3671
+ case "tool": {
3672
+ throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
3673
+ functionality: "Tool messages"
3674
+ });
3675
+ }
3676
+ default: {
3677
+ const _exhaustiveCheck = role;
3678
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
3679
+ }
3680
+ }
3681
+ }
3682
+ return messages;
3683
+ }
3684
+ function mapPerplexityFinishReason(finishReason) {
3685
+ switch (finishReason) {
3686
+ case "stop":
3687
+ case "length":
3688
+ return finishReason;
3689
+ default:
3690
+ return "unknown";
3691
+ }
3692
+ }
3693
+ var PerplexityLanguageModel = class {
3694
+ constructor(modelId, config) {
3695
+ this.specificationVersion = "v2";
3696
+ this.provider = "perplexity";
3697
+ this.supportedUrls = {
3698
+ // No URLs are supported.
3699
+ };
3700
+ this.modelId = modelId;
3701
+ this.config = config;
3702
+ }
3703
+ getArgs({
3704
+ prompt,
3705
+ maxOutputTokens,
3706
+ temperature,
3707
+ topP,
3708
+ topK,
3709
+ frequencyPenalty,
3710
+ presencePenalty,
3711
+ stopSequences,
3712
+ responseFormat,
3713
+ seed,
3714
+ providerOptions
3715
+ }) {
3716
+ var _a;
3717
+ const warnings = [];
3718
+ if (topK != null) {
3719
+ warnings.push({
3720
+ type: "unsupported-setting",
3721
+ setting: "topK"
3722
+ });
3723
+ }
3724
+ if (stopSequences != null) {
3725
+ warnings.push({
3726
+ type: "unsupported-setting",
3727
+ setting: "stopSequences"
3728
+ });
3729
+ }
3730
+ if (seed != null) {
3731
+ warnings.push({
3732
+ type: "unsupported-setting",
3733
+ setting: "seed"
3734
+ });
3735
+ }
3736
+ return {
3737
+ args: {
3738
+ // model id:
3739
+ model: this.modelId,
3740
+ // standardized settings:
3741
+ frequency_penalty: frequencyPenalty,
3742
+ max_tokens: maxOutputTokens,
3743
+ presence_penalty: presencePenalty,
3744
+ temperature,
3745
+ top_k: topK,
3746
+ top_p: topP,
3747
+ // response format:
3748
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? {
3749
+ type: "json_schema",
3750
+ json_schema: { schema: responseFormat.schema }
3751
+ } : void 0,
3752
+ // provider extensions
3753
+ ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},
3754
+ // messages:
3755
+ messages: convertToPerplexityMessages(prompt)
3756
+ },
3757
+ warnings
3758
+ };
3759
+ }
3760
+ async doGenerate(options) {
3761
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3762
+ const { args: body, warnings } = this.getArgs(options);
3763
+ const {
3764
+ responseHeaders,
3765
+ value: response,
3766
+ rawValue: rawResponse
3767
+ } = await postJsonToApi3({
3768
+ url: `${this.config.baseURL}/chat/completions`,
3769
+ headers: combineHeaders3(this.config.headers(), options.headers),
3770
+ body,
3771
+ failedResponseHandler: createJsonErrorResponseHandler3({
3772
+ errorSchema: perplexityErrorSchema,
3773
+ errorToMessage
3774
+ }),
3775
+ successfulResponseHandler: createJsonResponseHandler3(
3776
+ perplexityResponseSchema
3777
+ ),
3778
+ abortSignal: options.abortSignal,
3779
+ fetch: this.config.fetch
3780
+ });
3781
+ const choice = response.choices[0];
3782
+ const content = [];
3783
+ const text = choice.message.content;
3784
+ if (text.length > 0) {
3785
+ content.push({ type: "text", text });
3786
+ }
3787
+ if (response.citations != null) {
3788
+ for (const url of response.citations) {
3789
+ content.push({
3790
+ type: "source",
3791
+ sourceType: "url",
3792
+ id: this.config.generateId(),
3793
+ url
3794
+ });
3795
+ }
3796
+ }
3797
+ return {
3798
+ content,
3799
+ finishReason: mapPerplexityFinishReason(choice.finish_reason),
3800
+ usage: {
3801
+ inputTokens: (_a = response.usage) == null ? void 0 : _a.prompt_tokens,
3802
+ outputTokens: (_b = response.usage) == null ? void 0 : _b.completion_tokens,
3803
+ totalTokens: (_d = (_c = response.usage) == null ? void 0 : _c.total_tokens) != null ? _d : void 0
3804
+ },
3805
+ request: { body },
3806
+ response: {
3807
+ ...getResponseMetadata3(response),
3808
+ headers: responseHeaders,
3809
+ body: rawResponse
3810
+ },
3811
+ warnings,
3812
+ providerMetadata: {
3813
+ perplexity: {
3814
+ images: (_f = (_e = response.images) == null ? void 0 : _e.map((image) => ({
3815
+ imageUrl: image.image_url,
3816
+ originUrl: image.origin_url,
3817
+ height: image.height,
3818
+ width: image.width
3819
+ }))) != null ? _f : null,
3820
+ usage: {
3821
+ citationTokens: (_h = (_g = response.usage) == null ? void 0 : _g.citation_tokens) != null ? _h : null,
3822
+ numSearchQueries: (_j = (_i = response.usage) == null ? void 0 : _i.num_search_queries) != null ? _j : null
3823
+ }
3824
+ }
3825
+ }
3826
+ };
3827
+ }
3828
+ async doStream(options) {
3829
+ const { args, warnings } = this.getArgs(options);
3830
+ const body = { ...args, stream: true };
3831
+ const { responseHeaders, value: response } = await postJsonToApi3({
3832
+ url: `${this.config.baseURL}/chat/completions`,
3833
+ headers: combineHeaders3(this.config.headers(), options.headers),
3834
+ body,
3835
+ failedResponseHandler: createJsonErrorResponseHandler3({
3836
+ errorSchema: perplexityErrorSchema,
3837
+ errorToMessage
3838
+ }),
3839
+ successfulResponseHandler: createEventSourceResponseHandler3(
3840
+ perplexityChunkSchema
3841
+ ),
3842
+ abortSignal: options.abortSignal,
3843
+ fetch: this.config.fetch
3844
+ });
3845
+ let finishReason = "unknown";
3846
+ const usage = {
3847
+ inputTokens: void 0,
3848
+ outputTokens: void 0,
3849
+ totalTokens: void 0
3850
+ };
3851
+ const providerMetadata = {
3852
+ perplexity: {
3853
+ usage: {
3854
+ citationTokens: null,
3855
+ numSearchQueries: null
3856
+ },
3857
+ images: null
3858
+ }
3859
+ };
3860
+ let isFirstChunk = true;
3861
+ let isActive = false;
3862
+ const self = this;
3863
+ return {
3864
+ stream: response.pipeThrough(
3865
+ new TransformStream({
3866
+ start(controller) {
3867
+ controller.enqueue({ type: "stream-start", warnings });
3868
+ },
3869
+ transform(chunk, controller) {
3870
+ var _a, _b, _c;
3871
+ if (options.includeRawChunks) {
3872
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
3873
+ }
3874
+ if (!chunk.success) {
3875
+ controller.enqueue({ type: "error", error: chunk.error });
3876
+ return;
3877
+ }
3878
+ const value = chunk.value;
3879
+ if (isFirstChunk) {
3880
+ controller.enqueue({
3881
+ type: "response-metadata",
3882
+ ...getResponseMetadata3(value)
3883
+ });
3884
+ (_a = value.citations) == null ? void 0 : _a.forEach((url) => {
3885
+ controller.enqueue({
3886
+ type: "source",
3887
+ sourceType: "url",
3888
+ id: self.config.generateId(),
3889
+ url
3890
+ });
3891
+ });
3892
+ isFirstChunk = false;
3893
+ }
3894
+ if (value.usage != null) {
3895
+ usage.inputTokens = value.usage.prompt_tokens;
3896
+ usage.outputTokens = value.usage.completion_tokens;
3897
+ providerMetadata.perplexity.usage = {
3898
+ citationTokens: (_b = value.usage.citation_tokens) != null ? _b : null,
3899
+ numSearchQueries: (_c = value.usage.num_search_queries) != null ? _c : null
3900
+ };
3901
+ }
3902
+ if (value.images != null) {
3903
+ providerMetadata.perplexity.images = value.images.map((image) => ({
3904
+ imageUrl: image.image_url,
3905
+ originUrl: image.origin_url,
3906
+ height: image.height,
3907
+ width: image.width
3908
+ }));
3909
+ }
3910
+ const choice = value.choices[0];
3911
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
3912
+ finishReason = mapPerplexityFinishReason(choice.finish_reason);
3913
+ }
3914
+ if ((choice == null ? void 0 : choice.delta) == null) {
3915
+ return;
3916
+ }
3917
+ const delta = choice.delta;
3918
+ const textContent = delta.content;
3919
+ if (textContent != null) {
3920
+ if (!isActive) {
3921
+ controller.enqueue({ type: "text-start", id: "0" });
3922
+ isActive = true;
3923
+ }
3924
+ controller.enqueue({
3925
+ type: "text-delta",
3926
+ id: "0",
3927
+ delta: textContent
3928
+ });
3929
+ }
3930
+ },
3931
+ flush(controller) {
3932
+ if (isActive) {
3933
+ controller.enqueue({ type: "text-end", id: "0" });
3934
+ }
3935
+ controller.enqueue({
3936
+ type: "finish",
3937
+ finishReason,
3938
+ usage,
3939
+ providerMetadata
3940
+ });
3941
+ }
3942
+ })
3943
+ ),
3944
+ request: { body },
3945
+ response: { headers: responseHeaders }
3946
+ };
3947
+ }
3948
+ };
3949
+ function getResponseMetadata3({
3950
+ id,
3951
+ model,
3952
+ created
3953
+ }) {
3954
+ return {
3955
+ id,
3956
+ modelId: model,
3957
+ timestamp: new Date(created * 1e3)
3958
+ };
3959
+ }
3960
+ var perplexityUsageSchema = z4.z.object({
3961
+ prompt_tokens: z4.z.number(),
3962
+ completion_tokens: z4.z.number(),
3963
+ total_tokens: z4.z.number().nullish(),
3964
+ citation_tokens: z4.z.number().nullish(),
3965
+ num_search_queries: z4.z.number().nullish()
3966
+ });
3967
+ var perplexityImageSchema = z4.z.object({
3968
+ image_url: z4.z.string(),
3969
+ origin_url: z4.z.string(),
3970
+ height: z4.z.number(),
3971
+ width: z4.z.number()
3972
+ });
3973
+ var perplexityResponseSchema = z4.z.object({
3974
+ id: z4.z.string(),
3975
+ created: z4.z.number(),
3976
+ model: z4.z.string(),
3977
+ choices: z4.z.array(
3978
+ z4.z.object({
3979
+ message: z4.z.object({
3980
+ role: z4.z.literal("assistant"),
3981
+ content: z4.z.string()
3982
+ }),
3983
+ finish_reason: z4.z.string().nullish()
3984
+ })
3985
+ ),
3986
+ citations: z4.z.array(z4.z.string()).nullish(),
3987
+ images: z4.z.array(perplexityImageSchema).nullish(),
3988
+ usage: perplexityUsageSchema.nullish()
3989
+ });
3990
+ var perplexityChunkSchema = z4.z.object({
3991
+ id: z4.z.string(),
3992
+ created: z4.z.number(),
3993
+ model: z4.z.string(),
3994
+ choices: z4.z.array(
3995
+ z4.z.object({
3996
+ delta: z4.z.object({
3997
+ role: z4.z.literal("assistant"),
3998
+ content: z4.z.string()
3999
+ }),
4000
+ finish_reason: z4.z.string().nullish()
4001
+ })
4002
+ ),
4003
+ citations: z4.z.array(z4.z.string()).nullish(),
4004
+ images: z4.z.array(perplexityImageSchema).nullish(),
4005
+ usage: perplexityUsageSchema.nullish()
4006
+ });
4007
+ var perplexityErrorSchema = z4.z.object({
4008
+ error: z4.z.object({
4009
+ code: z4.z.number(),
4010
+ message: z4.z.string().nullish(),
4011
+ type: z4.z.string().nullish()
4012
+ })
4013
+ });
4014
+ var errorToMessage = (data) => {
4015
+ var _a, _b;
4016
+ return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : "unknown error";
4017
+ };
4018
+ function createPerplexity(options = {}) {
4019
+ const getHeaders = () => ({
4020
+ Authorization: `Bearer ${loadApiKey3({
4021
+ apiKey: options.apiKey,
4022
+ environmentVariableName: "PERPLEXITY_API_KEY",
4023
+ description: "Perplexity"
4024
+ })}`,
4025
+ ...options.headers
4026
+ });
4027
+ const createLanguageModel = (modelId) => {
4028
+ var _a;
4029
+ return new PerplexityLanguageModel(modelId, {
4030
+ baseURL: withoutTrailingSlash3(
4031
+ (_a = options.baseURL) != null ? _a : "https://api.perplexity.ai"
4032
+ ),
4033
+ headers: getHeaders,
4034
+ generateId: generateId3,
4035
+ fetch: options.fetch
4036
+ });
4037
+ };
4038
+ const provider = (modelId) => createLanguageModel(modelId);
4039
+ provider.languageModel = createLanguageModel;
4040
+ provider.textEmbeddingModel = (modelId) => {
4041
+ throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
4042
+ };
4043
+ provider.imageModel = (modelId) => {
4044
+ throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
4045
+ };
4046
+ return provider;
4047
+ }
4048
+ createPerplexity();
4049
+ function convertToXaiChatMessages(prompt) {
4050
+ const messages = [];
4051
+ const warnings = [];
4052
+ for (const { role, content } of prompt) {
4053
+ switch (role) {
4054
+ case "system": {
4055
+ messages.push({ role: "system", content });
4056
+ break;
4057
+ }
4058
+ case "user": {
4059
+ if (content.length === 1 && content[0].type === "text") {
4060
+ messages.push({ role: "user", content: content[0].text });
4061
+ break;
4062
+ }
4063
+ messages.push({
4064
+ role: "user",
4065
+ content: content.map((part) => {
4066
+ switch (part.type) {
4067
+ case "text": {
4068
+ return { type: "text", text: part.text };
4069
+ }
4070
+ case "file": {
4071
+ if (part.mediaType.startsWith("image/")) {
4072
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
4073
+ return {
4074
+ type: "image_url",
4075
+ image_url: {
4076
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkCZEJQSWB_cjs.convertToBase64(part.data)}`
4077
+ }
4078
+ };
4079
+ } else {
4080
+ throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
4081
+ functionality: `file part media type ${part.mediaType}`
4082
+ });
4083
+ }
4084
+ }
4085
+ }
4086
+ })
4087
+ });
4088
+ break;
4089
+ }
4090
+ case "assistant": {
4091
+ let text = "";
4092
+ const toolCalls = [];
4093
+ for (const part of content) {
4094
+ switch (part.type) {
4095
+ case "text": {
4096
+ text += part.text;
4097
+ break;
4098
+ }
4099
+ case "tool-call": {
4100
+ toolCalls.push({
4101
+ id: part.toolCallId,
4102
+ type: "function",
4103
+ function: {
4104
+ name: part.toolName,
4105
+ arguments: JSON.stringify(part.input)
4106
+ }
4107
+ });
4108
+ break;
4109
+ }
4110
+ }
4111
+ }
4112
+ messages.push({
4113
+ role: "assistant",
4114
+ content: text,
4115
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
4116
+ });
4117
+ break;
4118
+ }
4119
+ case "tool": {
4120
+ for (const toolResponse of content) {
4121
+ const output = toolResponse.output;
4122
+ let contentValue;
4123
+ switch (output.type) {
4124
+ case "text":
4125
+ case "error-text":
4126
+ contentValue = output.value;
4127
+ break;
4128
+ case "content":
4129
+ case "json":
4130
+ case "error-json":
4131
+ contentValue = JSON.stringify(output.value);
4132
+ break;
4133
+ }
4134
+ messages.push({
4135
+ role: "tool",
4136
+ tool_call_id: toolResponse.toolCallId,
4137
+ content: contentValue
4138
+ });
4139
+ }
4140
+ break;
4141
+ }
4142
+ default: {
4143
+ const _exhaustiveCheck = role;
4144
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
4145
+ }
4146
+ }
4147
+ }
4148
+ return { messages, warnings };
4149
+ }
4150
+ function getResponseMetadata4({
4151
+ id,
4152
+ model,
4153
+ created
4154
+ }) {
4155
+ return {
4156
+ id: id != null ? id : void 0,
4157
+ modelId: model != null ? model : void 0,
4158
+ timestamp: created != null ? new Date(created * 1e3) : void 0
4159
+ };
4160
+ }
4161
+ function mapXaiFinishReason(finishReason) {
4162
+ switch (finishReason) {
4163
+ case "stop":
4164
+ return "stop";
4165
+ case "length":
4166
+ return "length";
4167
+ case "tool_calls":
4168
+ case "function_call":
4169
+ return "tool-calls";
4170
+ case "content_filter":
4171
+ return "content-filter";
4172
+ default:
4173
+ return "unknown";
4174
+ }
4175
+ }
4176
+ var webSourceSchema = z4.z.object({
4177
+ type: z4.z.literal("web"),
4178
+ country: z4.z.string().length(2).optional(),
4179
+ excludedWebsites: z4.z.array(z4.z.string()).max(5).optional(),
4180
+ allowedWebsites: z4.z.array(z4.z.string()).max(5).optional(),
4181
+ safeSearch: z4.z.boolean().optional()
4182
+ });
4183
+ var xSourceSchema = z4.z.object({
4184
+ type: z4.z.literal("x"),
4185
+ excludedXHandles: z4.z.array(z4.z.string()).optional(),
4186
+ includedXHandles: z4.z.array(z4.z.string()).optional(),
4187
+ postFavoriteCount: z4.z.number().int().optional(),
4188
+ postViewCount: z4.z.number().int().optional(),
4189
+ /**
4190
+ * @deprecated use `includedXHandles` instead
4191
+ */
4192
+ xHandles: z4.z.array(z4.z.string()).optional()
4193
+ });
4194
+ var newsSourceSchema = z4.z.object({
4195
+ type: z4.z.literal("news"),
4196
+ country: z4.z.string().length(2).optional(),
4197
+ excludedWebsites: z4.z.array(z4.z.string()).max(5).optional(),
4198
+ safeSearch: z4.z.boolean().optional()
4199
+ });
4200
+ var rssSourceSchema = z4.z.object({
4201
+ type: z4.z.literal("rss"),
4202
+ links: z4.z.array(z4.z.string().url()).max(1)
4203
+ // currently only supports one RSS link
4204
+ });
4205
+ var searchSourceSchema = z4.z.discriminatedUnion("type", [
4206
+ webSourceSchema,
4207
+ xSourceSchema,
4208
+ newsSourceSchema,
4209
+ rssSourceSchema
4210
+ ]);
4211
+ var xaiProviderOptions = z4.z.object({
4212
+ reasoningEffort: z4.z.enum(["low", "high"]).optional(),
4213
+ /**
4214
+ * Whether to enable parallel function calling during tool use.
4215
+ * When true, the model can call multiple functions in parallel.
4216
+ * When false, the model will call functions sequentially.
4217
+ * Defaults to true.
4218
+ */
4219
+ parallel_function_calling: z4.z.boolean().optional(),
4220
+ searchParameters: z4.z.object({
4221
+ /**
4222
+ * search mode preference
4223
+ * - "off": disables search completely
4224
+ * - "auto": model decides whether to search (default)
4225
+ * - "on": always enables search
4226
+ */
4227
+ mode: z4.z.enum(["off", "auto", "on"]),
4228
+ /**
4229
+ * whether to return citations in the response
4230
+ * defaults to true
4231
+ */
4232
+ returnCitations: z4.z.boolean().optional(),
4233
+ /**
4234
+ * start date for search data (ISO8601 format: YYYY-MM-DD)
4235
+ */
4236
+ fromDate: z4.z.string().optional(),
4237
+ /**
4238
+ * end date for search data (ISO8601 format: YYYY-MM-DD)
4239
+ */
4240
+ toDate: z4.z.string().optional(),
4241
+ /**
4242
+ * maximum number of search results to consider
4243
+ * defaults to 20
4244
+ */
4245
+ maxSearchResults: z4.z.number().min(1).max(50).optional(),
4246
+ /**
4247
+ * data sources to search from
4248
+ * defaults to ["web", "x"] if not specified
4249
+ */
4250
+ sources: z4.z.array(searchSourceSchema).optional()
4251
+ }).optional()
4252
+ });
4253
+ var xaiErrorDataSchema = z4.z.object({
4254
+ error: z4.z.object({
4255
+ message: z4.z.string(),
4256
+ type: z4.z.string().nullish(),
4257
+ param: z4.z.any().nullish(),
4258
+ code: z4.z.union([z4.z.string(), z4.z.number()]).nullish()
4259
+ })
4260
+ });
4261
+ var xaiFailedResponseHandler = chunkCZEJQSWB_cjs.createJsonErrorResponseHandler({
4262
+ errorSchema: xaiErrorDataSchema,
4263
+ errorToMessage: (data) => data.error.message
4264
+ });
4265
+ function prepareTools3({
4266
+ tools,
4267
+ toolChoice
4268
+ }) {
4269
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
4270
+ const toolWarnings = [];
4271
+ if (tools == null) {
4272
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
4273
+ }
4274
+ const xaiTools = [];
4275
+ for (const tool of tools) {
4276
+ if (tool.type === "provider-defined") {
4277
+ toolWarnings.push({ type: "unsupported-tool", tool });
4278
+ } else {
4279
+ xaiTools.push({
4280
+ type: "function",
4281
+ function: {
4282
+ name: tool.name,
4283
+ description: tool.description,
4284
+ parameters: tool.inputSchema
4285
+ }
4286
+ });
4287
+ }
4288
+ }
4289
+ if (toolChoice == null) {
4290
+ return { tools: xaiTools, toolChoice: void 0, toolWarnings };
4291
+ }
4292
+ const type = toolChoice.type;
4293
+ switch (type) {
4294
+ case "auto":
4295
+ case "none":
4296
+ return { tools: xaiTools, toolChoice: type, toolWarnings };
4297
+ case "required":
4298
+ return { tools: xaiTools, toolChoice: "required", toolWarnings };
4299
+ case "tool":
4300
+ return {
4301
+ tools: xaiTools,
4302
+ toolChoice: {
4303
+ type: "function",
4304
+ function: { name: toolChoice.toolName }
4305
+ },
4306
+ toolWarnings
4307
+ };
4308
+ default: {
4309
+ const _exhaustiveCheck = type;
4310
+ throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
4311
+ functionality: `tool choice type: ${_exhaustiveCheck}`
4312
+ });
4313
+ }
4314
+ }
4315
+ }
4316
+ var XaiChatLanguageModel = class {
4317
+ constructor(modelId, config) {
4318
+ this.specificationVersion = "v2";
4319
+ this.supportedUrls = {
4320
+ "image/*": [/^https?:\/\/.*$/]
4321
+ };
4322
+ this.modelId = modelId;
4323
+ this.config = config;
4324
+ }
4325
+ get provider() {
4326
+ return this.config.provider;
4327
+ }
4328
+ async getArgs({
4329
+ prompt,
4330
+ maxOutputTokens,
4331
+ temperature,
4332
+ topP,
4333
+ topK,
4334
+ frequencyPenalty,
4335
+ presencePenalty,
4336
+ stopSequences,
4337
+ seed,
4338
+ responseFormat,
4339
+ providerOptions,
4340
+ tools,
4341
+ toolChoice
4342
+ }) {
4343
+ var _a, _b, _c;
4344
+ const warnings = [];
4345
+ const options = (_a = await chunkCZEJQSWB_cjs.parseProviderOptions({
4346
+ provider: "xai",
4347
+ providerOptions,
4348
+ schema: xaiProviderOptions
4349
+ })) != null ? _a : {};
4350
+ if (topK != null) {
4351
+ warnings.push({
4352
+ type: "unsupported-setting",
4353
+ setting: "topK"
4354
+ });
4355
+ }
4356
+ if (frequencyPenalty != null) {
4357
+ warnings.push({
4358
+ type: "unsupported-setting",
4359
+ setting: "frequencyPenalty"
4360
+ });
4361
+ }
4362
+ if (presencePenalty != null) {
4363
+ warnings.push({
4364
+ type: "unsupported-setting",
4365
+ setting: "presencePenalty"
4366
+ });
4367
+ }
4368
+ if (stopSequences != null) {
4369
+ warnings.push({
4370
+ type: "unsupported-setting",
4371
+ setting: "stopSequences"
4372
+ });
4373
+ }
4374
+ const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
4375
+ warnings.push(...messageWarnings);
4376
+ const {
4377
+ tools: xaiTools,
4378
+ toolChoice: xaiToolChoice,
4379
+ toolWarnings
4380
+ } = prepareTools3({
4381
+ tools,
4382
+ toolChoice
4383
+ });
4384
+ warnings.push(...toolWarnings);
4385
+ const baseArgs = {
4386
+ // model id
4387
+ model: this.modelId,
4388
+ // standard generation settings
4389
+ max_tokens: maxOutputTokens,
4390
+ temperature,
4391
+ top_p: topP,
4392
+ seed,
4393
+ reasoning_effort: options.reasoningEffort,
4394
+ // parallel function calling
4395
+ parallel_function_calling: options.parallel_function_calling,
4396
+ // response format
4397
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
4398
+ type: "json_schema",
4399
+ json_schema: {
4400
+ name: (_b = responseFormat.name) != null ? _b : "response",
4401
+ schema: responseFormat.schema,
4402
+ strict: true
4403
+ }
4404
+ } : { type: "json_object" } : void 0,
4405
+ // search parameters
4406
+ search_parameters: options.searchParameters ? {
4407
+ mode: options.searchParameters.mode,
4408
+ return_citations: options.searchParameters.returnCitations,
4409
+ from_date: options.searchParameters.fromDate,
4410
+ to_date: options.searchParameters.toDate,
4411
+ max_search_results: options.searchParameters.maxSearchResults,
4412
+ sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
4413
+ var _a2;
4414
+ return {
4415
+ type: source.type,
4416
+ ...source.type === "web" && {
4417
+ country: source.country,
4418
+ excluded_websites: source.excludedWebsites,
4419
+ allowed_websites: source.allowedWebsites,
4420
+ safe_search: source.safeSearch
4421
+ },
4422
+ ...source.type === "x" && {
4423
+ excluded_x_handles: source.excludedXHandles,
4424
+ included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
4425
+ post_favorite_count: source.postFavoriteCount,
4426
+ post_view_count: source.postViewCount
4427
+ },
4428
+ ...source.type === "news" && {
4429
+ country: source.country,
4430
+ excluded_websites: source.excludedWebsites,
4431
+ safe_search: source.safeSearch
4432
+ },
4433
+ ...source.type === "rss" && {
4434
+ links: source.links
4435
+ }
4436
+ };
4437
+ })
4438
+ } : void 0,
4439
+ // messages in xai format
4440
+ messages,
4441
+ // tools in xai format
4442
+ tools: xaiTools,
4443
+ tool_choice: xaiToolChoice
4444
+ };
4445
+ return {
4446
+ args: baseArgs,
4447
+ warnings
4448
+ };
4449
+ }
4450
+ async doGenerate(options) {
4451
+ var _a, _b, _c;
4452
+ const { args: body, warnings } = await this.getArgs(options);
4453
+ const {
4454
+ responseHeaders,
4455
+ value: response,
4456
+ rawValue: rawResponse
4457
+ } = await chunkCZEJQSWB_cjs.postJsonToApi({
4458
+ url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
4459
+ headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
4460
+ body,
4461
+ failedResponseHandler: xaiFailedResponseHandler,
4462
+ successfulResponseHandler: chunkCZEJQSWB_cjs.createJsonResponseHandler(
4463
+ xaiChatResponseSchema
4464
+ ),
4465
+ abortSignal: options.abortSignal,
4466
+ fetch: this.config.fetch
4467
+ });
4468
+ const choice = response.choices[0];
4469
+ const content = [];
4470
+ if (choice.message.content != null && choice.message.content.length > 0) {
4471
+ let text = choice.message.content;
4472
+ const lastMessage = body.messages[body.messages.length - 1];
4473
+ if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
4474
+ text = "";
4475
+ }
4476
+ if (text.length > 0) {
4477
+ content.push({ type: "text", text });
4478
+ }
4479
+ }
4480
+ if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
4481
+ content.push({
4482
+ type: "reasoning",
4483
+ text: choice.message.reasoning_content
4484
+ });
4485
+ }
4486
+ if (choice.message.tool_calls != null) {
4487
+ for (const toolCall of choice.message.tool_calls) {
4488
+ content.push({
4489
+ type: "tool-call",
4490
+ toolCallId: toolCall.id,
4491
+ toolName: toolCall.function.name,
4492
+ input: toolCall.function.arguments
4493
+ });
4494
+ }
4495
+ }
4496
+ if (response.citations != null) {
4497
+ for (const url of response.citations) {
4498
+ content.push({
4499
+ type: "source",
4500
+ sourceType: "url",
4501
+ id: this.config.generateId(),
4502
+ url
4503
+ });
4504
+ }
4505
+ }
4506
+ return {
4507
+ content,
4508
+ finishReason: mapXaiFinishReason(choice.finish_reason),
4509
+ usage: {
4510
+ inputTokens: response.usage.prompt_tokens,
4511
+ outputTokens: response.usage.completion_tokens,
4512
+ totalTokens: response.usage.total_tokens,
4513
+ reasoningTokens: (_c = (_b = response.usage.completion_tokens_details) == null ? void 0 : _b.reasoning_tokens) != null ? _c : void 0
4514
+ },
4515
+ request: { body },
4516
+ response: {
4517
+ ...getResponseMetadata4(response),
4518
+ headers: responseHeaders,
4519
+ body: rawResponse
4520
+ },
4521
+ warnings
4522
+ };
4523
+ }
4524
+ async doStream(options) {
4525
+ var _a;
4526
+ const { args, warnings } = await this.getArgs(options);
4527
+ const body = {
4528
+ ...args,
4529
+ stream: true,
4530
+ stream_options: {
4531
+ include_usage: true
4532
+ }
4533
+ };
4534
+ const { responseHeaders, value: response } = await chunkCZEJQSWB_cjs.postJsonToApi({
4535
+ url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
4536
+ headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
4537
+ body,
4538
+ failedResponseHandler: xaiFailedResponseHandler,
4539
+ successfulResponseHandler: chunkCZEJQSWB_cjs.createEventSourceResponseHandler(xaiChatChunkSchema),
4540
+ abortSignal: options.abortSignal,
4541
+ fetch: this.config.fetch
4542
+ });
4543
+ let finishReason = "unknown";
4544
+ const usage = {
4545
+ inputTokens: void 0,
4546
+ outputTokens: void 0,
4547
+ totalTokens: void 0
4548
+ };
4549
+ let isFirstChunk = true;
4550
+ const contentBlocks = {};
4551
+ const lastReasoningDeltas = {};
4552
+ const self = this;
4553
+ return {
4554
+ stream: response.pipeThrough(
4555
+ new TransformStream({
4556
+ start(controller) {
4557
+ controller.enqueue({ type: "stream-start", warnings });
4558
+ },
4559
+ transform(chunk, controller) {
4560
+ var _a2, _b;
4561
+ if (options.includeRawChunks) {
4562
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
4563
+ }
4564
+ if (!chunk.success) {
4565
+ controller.enqueue({ type: "error", error: chunk.error });
4566
+ return;
4567
+ }
4568
+ const value = chunk.value;
4569
+ if (isFirstChunk) {
4570
+ controller.enqueue({
4571
+ type: "response-metadata",
4572
+ ...getResponseMetadata4(value)
4573
+ });
4574
+ isFirstChunk = false;
4575
+ }
4576
+ if (value.citations != null) {
4577
+ for (const url of value.citations) {
4578
+ controller.enqueue({
4579
+ type: "source",
4580
+ sourceType: "url",
4581
+ id: self.config.generateId(),
4582
+ url
4583
+ });
4584
+ }
4585
+ }
4586
+ if (value.usage != null) {
4587
+ usage.inputTokens = value.usage.prompt_tokens;
4588
+ usage.outputTokens = value.usage.completion_tokens;
4589
+ usage.totalTokens = value.usage.total_tokens;
4590
+ usage.reasoningTokens = (_b = (_a2 = value.usage.completion_tokens_details) == null ? void 0 : _a2.reasoning_tokens) != null ? _b : void 0;
4591
+ }
4592
+ const choice = value.choices[0];
4593
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
4594
+ finishReason = mapXaiFinishReason(choice.finish_reason);
4595
+ }
4596
+ if ((choice == null ? void 0 : choice.delta) == null) {
4597
+ return;
4598
+ }
4599
+ const delta = choice.delta;
4600
+ const choiceIndex = choice.index;
4601
+ if (delta.content != null && delta.content.length > 0) {
4602
+ const textContent = delta.content;
4603
+ const lastMessage = body.messages[body.messages.length - 1];
4604
+ if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
4605
+ return;
4606
+ }
4607
+ const blockId = `text-${value.id || choiceIndex}`;
4608
+ if (contentBlocks[blockId] == null) {
4609
+ contentBlocks[blockId] = { type: "text" };
4610
+ controller.enqueue({
4611
+ type: "text-start",
4612
+ id: blockId
4613
+ });
4614
+ }
4615
+ controller.enqueue({
4616
+ type: "text-delta",
4617
+ id: blockId,
4618
+ delta: textContent
4619
+ });
4620
+ }
4621
+ if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
4622
+ const blockId = `reasoning-${value.id || choiceIndex}`;
4623
+ if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
4624
+ return;
4625
+ }
4626
+ lastReasoningDeltas[blockId] = delta.reasoning_content;
4627
+ if (contentBlocks[blockId] == null) {
4628
+ contentBlocks[blockId] = { type: "reasoning" };
4629
+ controller.enqueue({
4630
+ type: "reasoning-start",
4631
+ id: blockId
4632
+ });
4633
+ }
4634
+ controller.enqueue({
4635
+ type: "reasoning-delta",
4636
+ id: blockId,
4637
+ delta: delta.reasoning_content
4638
+ });
4639
+ }
4640
+ if (delta.tool_calls != null) {
4641
+ for (const toolCall of delta.tool_calls) {
4642
+ const toolCallId = toolCall.id;
4643
+ controller.enqueue({
4644
+ type: "tool-input-start",
4645
+ id: toolCallId,
4646
+ toolName: toolCall.function.name
4647
+ });
4648
+ controller.enqueue({
4649
+ type: "tool-input-delta",
4650
+ id: toolCallId,
4651
+ delta: toolCall.function.arguments
4652
+ });
4653
+ controller.enqueue({
4654
+ type: "tool-input-end",
4655
+ id: toolCallId
4656
+ });
4657
+ controller.enqueue({
4658
+ type: "tool-call",
4659
+ toolCallId,
4660
+ toolName: toolCall.function.name,
4661
+ input: toolCall.function.arguments
4662
+ });
4663
+ }
4664
+ }
4665
+ },
4666
+ flush(controller) {
4667
+ for (const [blockId, block] of Object.entries(contentBlocks)) {
4668
+ controller.enqueue({
4669
+ type: block.type === "text" ? "text-end" : "reasoning-end",
4670
+ id: blockId
4671
+ });
4672
+ }
4673
+ controller.enqueue({ type: "finish", finishReason, usage });
4674
+ }
4675
+ })
4676
+ ),
4677
+ request: { body },
4678
+ response: { headers: responseHeaders }
4679
+ };
4680
+ }
4681
+ };
4682
+ var xaiUsageSchema = z4.z.object({
4683
+ prompt_tokens: z4.z.number(),
4684
+ completion_tokens: z4.z.number(),
4685
+ total_tokens: z4.z.number(),
4686
+ completion_tokens_details: z4.z.object({
4687
+ reasoning_tokens: z4.z.number().nullish()
4688
+ }).nullish()
4689
+ });
4690
+ var xaiChatResponseSchema = z4.z.object({
4691
+ id: z4.z.string().nullish(),
4692
+ created: z4.z.number().nullish(),
4693
+ model: z4.z.string().nullish(),
4694
+ choices: z4.z.array(
4695
+ z4.z.object({
4696
+ message: z4.z.object({
4697
+ role: z4.z.literal("assistant"),
4698
+ content: z4.z.string().nullish(),
4699
+ reasoning_content: z4.z.string().nullish(),
4700
+ tool_calls: z4.z.array(
4701
+ z4.z.object({
4702
+ id: z4.z.string(),
4703
+ type: z4.z.literal("function"),
4704
+ function: z4.z.object({
4705
+ name: z4.z.string(),
4706
+ arguments: z4.z.string()
4707
+ })
4708
+ })
4709
+ ).nullish()
4710
+ }),
4711
+ index: z4.z.number(),
4712
+ finish_reason: z4.z.string().nullish()
4713
+ })
4714
+ ),
4715
+ object: z4.z.literal("chat.completion"),
4716
+ usage: xaiUsageSchema,
4717
+ citations: z4.z.array(z4.z.string().url()).nullish()
4718
+ });
4719
+ var xaiChatChunkSchema = z4.z.object({
4720
+ id: z4.z.string().nullish(),
4721
+ created: z4.z.number().nullish(),
4722
+ model: z4.z.string().nullish(),
4723
+ choices: z4.z.array(
4724
+ z4.z.object({
4725
+ delta: z4.z.object({
4726
+ role: z4.z.enum(["assistant"]).optional(),
4727
+ content: z4.z.string().nullish(),
4728
+ reasoning_content: z4.z.string().nullish(),
4729
+ tool_calls: z4.z.array(
4730
+ z4.z.object({
4731
+ id: z4.z.string(),
4732
+ type: z4.z.literal("function"),
4733
+ function: z4.z.object({
4734
+ name: z4.z.string(),
4735
+ arguments: z4.z.string()
4736
+ })
4737
+ })
4738
+ ).nullish()
4739
+ }),
4740
+ finish_reason: z4.z.string().nullish(),
4741
+ index: z4.z.number()
4742
+ })
4743
+ ),
4744
+ usage: xaiUsageSchema.nullish(),
4745
+ citations: z4.z.array(z4.z.string().url()).nullish()
4746
+ });
4747
+ var VERSION4 = "2.0.33" ;
4748
+ var xaiErrorStructure = {
4749
+ errorSchema: xaiErrorDataSchema,
4750
+ errorToMessage: (data) => data.error.message
4751
+ };
4752
+ function createXai(options = {}) {
4753
+ var _a;
4754
+ const baseURL = chunkCZEJQSWB_cjs.withoutTrailingSlash(
4755
+ (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
4756
+ );
4757
+ const getHeaders = () => chunkCZEJQSWB_cjs.withUserAgentSuffix(
4758
+ {
4759
+ Authorization: `Bearer ${chunkCZEJQSWB_cjs.loadApiKey({
4760
+ apiKey: options.apiKey,
4761
+ environmentVariableName: "XAI_API_KEY",
4762
+ description: "xAI API key"
4763
+ })}`,
4764
+ ...options.headers
4765
+ },
4766
+ `ai-sdk/xai/${VERSION4}`
4767
+ );
4768
+ const createLanguageModel = (modelId) => {
4769
+ return new XaiChatLanguageModel(modelId, {
4770
+ provider: "xai.chat",
4771
+ baseURL,
4772
+ headers: getHeaders,
4773
+ generateId: chunkCZEJQSWB_cjs.generateId,
4774
+ fetch: options.fetch
4775
+ });
4776
+ };
4777
+ const createImageModel = (modelId) => {
4778
+ return new chunkCZEJQSWB_cjs.OpenAICompatibleImageModel(modelId, {
4779
+ provider: "xai.image",
4780
+ url: ({ path }) => `${baseURL}${path}`,
4781
+ headers: getHeaders,
4782
+ fetch: options.fetch,
4783
+ errorStructure: xaiErrorStructure
4784
+ });
4785
+ };
4786
+ const provider = (modelId) => createLanguageModel(modelId);
4787
+ provider.languageModel = createLanguageModel;
4788
+ provider.chat = createLanguageModel;
4789
+ provider.textEmbeddingModel = (modelId) => {
4790
+ throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
4791
+ };
4792
+ provider.imageModel = createImageModel;
4793
+ provider.image = createImageModel;
4794
+ return provider;
4795
+ }
4796
+ createXai();
4797
+
4798
+ // src/llm/model/gateway-resolver.ts
4799
+ function parseModelRouterId(routerId, gatewayPrefix) {
4800
+ if (gatewayPrefix && !routerId.startsWith(`${gatewayPrefix}/`)) {
4801
+ throw new Error(`Expected ${gatewayPrefix}/ in model router ID ${routerId}`);
4802
+ }
4803
+ const idParts = routerId.split("/");
4804
+ if (gatewayPrefix === "azure-openai") {
4805
+ if (idParts.length < 2) {
4806
+ throw new Error(`Expected format azure-openai/deployment-name, but got ${routerId}`);
4807
+ }
4808
+ return {
4809
+ providerId: "azure-openai",
4810
+ modelId: idParts.slice(1).join("/")
4811
+ // Deployment name
4812
+ };
4813
+ }
4814
+ if (gatewayPrefix && idParts.length < 3) {
4815
+ throw new Error(
4816
+ `Expected atleast 3 id parts ${gatewayPrefix}/provider/model, but only saw ${idParts.length} in ${routerId}`
4817
+ );
4818
+ }
4819
+ const providerId = idParts.at(gatewayPrefix ? 1 : 0);
4820
+ const modelId = idParts.slice(gatewayPrefix ? 2 : 1).join(`/`);
4821
+ if (!routerId.includes(`/`) || !providerId || !modelId) {
4822
+ throw new Error(
4823
+ `Attempted to parse provider/model from ${routerId} but this ID doesn't appear to contain a provider`
4824
+ );
4825
+ }
4826
+ return {
4827
+ providerId,
4828
+ modelId
4829
+ };
4830
+ }
4831
+
4832
+ // src/llm/model/gateways/constants.ts
4833
+ var PROVIDERS_WITH_INSTALLED_PACKAGES = [
4834
+ "anthropic",
4835
+ "deepseek",
4836
+ "google",
4837
+ "mistral",
4838
+ "openai",
4839
+ "openrouter",
4840
+ "perplexity",
4841
+ "xai"
4842
+ ];
4843
+ var EXCLUDED_PROVIDERS = ["github-copilot"];
4844
+
4845
+ // src/llm/model/gateways/models-dev.ts
4846
+ var OPENAI_COMPATIBLE_OVERRIDES = {
4847
+ cerebras: {
4848
+ url: "https://api.cerebras.ai/v1"
4849
+ },
4850
+ mistral: {
4851
+ url: "https://api.mistral.ai/v1"
4852
+ },
4853
+ groq: {
4854
+ url: "https://api.groq.com/openai/v1"
4855
+ },
4856
+ togetherai: {
4857
+ url: "https://api.together.xyz/v1"
4858
+ },
4859
+ deepinfra: {
4860
+ url: "https://api.deepinfra.com/v1/openai"
4861
+ },
4862
+ vercel: {
4863
+ url: "https://ai-gateway.vercel.sh/v1",
4864
+ apiKeyEnvVar: "AI_GATEWAY_API_KEY"
4865
+ }
4866
+ };
4867
+ var ModelsDevGateway = class extends chunkCZEJQSWB_cjs.MastraModelGateway {
4868
+ id = "models.dev";
4869
+ name = "models.dev";
4870
+ providerConfigs = {};
4871
+ constructor(providerConfigs) {
4872
+ super();
4873
+ if (providerConfigs) this.providerConfigs = providerConfigs;
4874
+ }
4875
+ async fetchProviders() {
4876
+ const response = await fetch("https://models.dev/api.json");
4877
+ if (!response.ok) {
4878
+ throw new Error(`Failed to fetch from models.dev: ${response.statusText}`);
4879
+ }
4880
+ const data = await response.json();
4881
+ const providerConfigs = {};
4882
+ for (const [providerId, providerInfo] of Object.entries(data)) {
4883
+ if (EXCLUDED_PROVIDERS.includes(providerId)) continue;
4884
+ if (!providerInfo || typeof providerInfo !== "object" || !providerInfo.models) continue;
4885
+ const normalizedId = providerId;
4886
+ const isOpenAICompatible = providerInfo.npm === "@ai-sdk/openai-compatible" || providerInfo.npm === "@ai-sdk/gateway" || // Vercel AI Gateway is OpenAI-compatible
4887
+ normalizedId in OPENAI_COMPATIBLE_OVERRIDES;
4888
+ const hasInstalledPackage = PROVIDERS_WITH_INSTALLED_PACKAGES.includes(providerId);
4889
+ const hasApiAndEnv = providerInfo.api && providerInfo.env && providerInfo.env.length > 0;
4890
+ if (isOpenAICompatible || hasInstalledPackage || hasApiAndEnv) {
4891
+ const modelIds = Object.keys(providerInfo.models).sort();
4892
+ const url = providerInfo.api || OPENAI_COMPATIBLE_OVERRIDES[normalizedId]?.url;
4893
+ if (!hasInstalledPackage && !url) {
4894
+ continue;
4895
+ }
4896
+ const apiKeyEnvVar = providerInfo.env?.[0] || `${normalizedId.toUpperCase().replace(/-/g, "_")}_API_KEY`;
4897
+ const apiKeyHeader = !hasInstalledPackage ? OPENAI_COMPATIBLE_OVERRIDES[normalizedId]?.apiKeyHeader || "Authorization" : void 0;
4898
+ providerConfigs[normalizedId] = {
4899
+ url,
4900
+ apiKeyEnvVar,
4901
+ apiKeyHeader,
4902
+ name: providerInfo.name || providerId.charAt(0).toUpperCase() + providerId.slice(1),
4903
+ models: modelIds,
4904
+ docUrl: providerInfo.doc,
4905
+ // Include documentation URL if available
4906
+ gateway: `models.dev`
4907
+ };
4908
+ }
4909
+ }
4910
+ this.providerConfigs = providerConfigs;
4911
+ return providerConfigs;
4912
+ }
4913
+ buildUrl(routerId, envVars) {
4914
+ const { providerId } = parseModelRouterId(routerId);
4915
+ const config = this.providerConfigs[providerId];
4916
+ if (!config?.url) {
4917
+ return;
4918
+ }
4919
+ const baseUrlEnvVar = `${providerId.toUpperCase().replace(/-/g, "_")}_BASE_URL`;
4920
+ const customBaseUrl = envVars?.[baseUrlEnvVar] || process.env[baseUrlEnvVar];
4921
+ return customBaseUrl || config.url;
4922
+ }
4923
+ getApiKey(modelId) {
4924
+ const [provider, model] = modelId.split("/");
4925
+ if (!provider || !model) {
4926
+ throw new Error(`Could not identify provider from model id ${modelId}`);
4927
+ }
4928
+ const config = this.providerConfigs[provider];
4929
+ if (!config) {
4930
+ throw new Error(`Could not find config for provider ${provider} with model id ${modelId}`);
4931
+ }
4932
+ const apiKey = typeof config.apiKeyEnvVar === `string` ? process.env[config.apiKeyEnvVar] : void 0;
4933
+ if (!apiKey) {
4934
+ throw new Error(`Could not find API key process.env.${config.apiKeyEnvVar} for model id ${modelId}`);
4935
+ }
4936
+ return Promise.resolve(apiKey);
4937
+ }
4938
+ async resolveLanguageModel({
4939
+ modelId,
4940
+ providerId,
4941
+ apiKey,
4942
+ headers
4943
+ }) {
4944
+ const baseURL = this.buildUrl(`${providerId}/${modelId}`);
4945
+ switch (providerId) {
4946
+ case "openai":
4947
+ return chunkCZEJQSWB_cjs.createOpenAI({ apiKey }).responses(modelId);
4948
+ case "gemini":
4949
+ case "google":
4950
+ return chunkCZEJQSWB_cjs.createGoogleGenerativeAI({
4951
+ apiKey
4952
+ }).chat(modelId);
4953
+ case "anthropic":
4954
+ return chunkCZEJQSWB_cjs.createAnthropic({ apiKey })(modelId);
4955
+ case "mistral":
4956
+ return createMistral({ apiKey })(modelId);
4957
+ case "openrouter":
4958
+ return aiSdkProviderV5.createOpenRouter({ apiKey, headers })(modelId);
4959
+ case "xai":
4960
+ return createXai({
4961
+ apiKey
4962
+ })(modelId);
4963
+ case "deepseek":
4964
+ return createDeepSeek({
4965
+ apiKey
4966
+ })(modelId);
4967
+ case "perplexity":
4968
+ return createPerplexity({ apiKey })(modelId);
4969
+ default:
4970
+ if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
4971
+ return chunkCZEJQSWB_cjs.createOpenAICompatible({ name: providerId, apiKey, baseURL, supportsStructuredOutputs: true }).chatModel(
4972
+ modelId
4973
+ );
4974
+ }
4975
+ }
4976
+ };
4977
+
4978
+ exports.ModelsDevGateway = ModelsDevGateway;
4979
+ exports.parseModelRouterId = parseModelRouterId;
4980
+ //# sourceMappingURL=chunk-AZQMPE7G.cjs.map
4981
+ //# sourceMappingURL=chunk-AZQMPE7G.cjs.map