@mastra/core 1.0.0-beta.6 → 1.0.0-beta.8

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