@llmgateway/ai-sdk-provider 2.5.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,6 +17,18 @@ var __spreadValues = (a, b) => {
17
17
  return a;
18
18
  };
19
19
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
20
32
 
21
33
  // src/schemas/reasoning-details.ts
22
34
  import { z } from "zod/v4";
@@ -44,11 +56,12 @@ var ReasoningDetailsWithUnknownSchema = z.union([
44
56
  ]);
45
57
  var ReasoningDetailArraySchema = z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
46
58
 
47
- // node_modules/.pnpm/@ai-sdk+provider@2.0.0-beta.1/node_modules/@ai-sdk/provider/dist/index.mjs
59
+ // node_modules/.pnpm/@ai-sdk+provider@3.0.2/node_modules/@ai-sdk/provider/dist/index.mjs
48
60
  var marker = "vercel.ai.error";
49
61
  var symbol = Symbol.for(marker);
50
62
  var _a;
51
- var _AISDKError = class _AISDKError2 extends Error {
63
+ var _b;
64
+ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
52
65
  /**
53
66
  * Creates an AI SDK Error.
54
67
  *
@@ -58,13 +71,13 @@ var _AISDKError = class _AISDKError2 extends Error {
58
71
  * @param {unknown} [params.cause] - The underlying cause of the error.
59
72
  */
60
73
  constructor({
61
- name: name14,
74
+ name: name142,
62
75
  message,
63
76
  cause
64
77
  }) {
65
78
  super(message);
66
79
  this[_a] = true;
67
- this.name = name14;
80
+ this.name = name142;
68
81
  this.cause = cause;
69
82
  }
70
83
  /**
@@ -73,20 +86,19 @@ var _AISDKError = class _AISDKError2 extends Error {
73
86
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
74
87
  */
75
88
  static isInstance(error) {
76
- return _AISDKError2.hasMarker(error, marker);
89
+ return _AISDKError.hasMarker(error, marker);
77
90
  }
78
- static hasMarker(error, marker15) {
79
- const markerSymbol = Symbol.for(marker15);
91
+ static hasMarker(error, marker152) {
92
+ const markerSymbol = Symbol.for(marker152);
80
93
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
81
94
  }
82
95
  };
83
- _a = symbol;
84
- var AISDKError = _AISDKError;
85
96
  var name = "AI_APICallError";
86
97
  var marker2 = `vercel.ai.error.${name}`;
87
98
  var symbol2 = Symbol.for(marker2);
88
99
  var _a2;
89
- var APICallError = class extends AISDKError {
100
+ var _b2;
101
+ var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
90
102
  constructor({
91
103
  message,
92
104
  url,
@@ -116,12 +128,12 @@ var APICallError = class extends AISDKError {
116
128
  return AISDKError.hasMarker(error, marker2);
117
129
  }
118
130
  };
119
- _a2 = symbol2;
120
131
  var name2 = "AI_EmptyResponseBodyError";
121
132
  var marker3 = `vercel.ai.error.${name2}`;
122
133
  var symbol3 = Symbol.for(marker3);
123
134
  var _a3;
124
- var EmptyResponseBodyError = class extends AISDKError {
135
+ var _b3;
136
+ var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
125
137
  // used in isInstance
126
138
  constructor({ message = "Empty response body" } = {}) {
127
139
  super({ name: name2, message });
@@ -131,7 +143,6 @@ var EmptyResponseBodyError = class extends AISDKError {
131
143
  return AISDKError.hasMarker(error, marker3);
132
144
  }
133
145
  };
134
- _a3 = symbol3;
135
146
  function getErrorMessage(error) {
136
147
  if (error == null) {
137
148
  return "unknown error";
@@ -148,7 +159,8 @@ var name3 = "AI_InvalidArgumentError";
148
159
  var marker4 = `vercel.ai.error.${name3}`;
149
160
  var symbol4 = Symbol.for(marker4);
150
161
  var _a4;
151
- var InvalidArgumentError = class extends AISDKError {
162
+ var _b4;
163
+ var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
152
164
  constructor({
153
165
  message,
154
166
  cause,
@@ -162,12 +174,12 @@ var InvalidArgumentError = class extends AISDKError {
162
174
  return AISDKError.hasMarker(error, marker4);
163
175
  }
164
176
  };
165
- _a4 = symbol4;
166
177
  var name4 = "AI_InvalidPromptError";
167
178
  var marker5 = `vercel.ai.error.${name4}`;
168
179
  var symbol5 = Symbol.for(marker5);
169
180
  var _a5;
170
- var InvalidPromptError = class extends AISDKError {
181
+ var _b5;
182
+ var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {
171
183
  constructor({
172
184
  prompt,
173
185
  message,
@@ -181,12 +193,12 @@ var InvalidPromptError = class extends AISDKError {
181
193
  return AISDKError.hasMarker(error, marker5);
182
194
  }
183
195
  };
184
- _a5 = symbol5;
185
196
  var name5 = "AI_InvalidResponseDataError";
186
197
  var marker6 = `vercel.ai.error.${name5}`;
187
198
  var symbol6 = Symbol.for(marker6);
188
199
  var _a6;
189
- var InvalidResponseDataError = class extends AISDKError {
200
+ var _b6;
201
+ var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {
190
202
  constructor({
191
203
  data,
192
204
  message = `Invalid response data: ${JSON.stringify(data)}.`
@@ -199,12 +211,12 @@ var InvalidResponseDataError = class extends AISDKError {
199
211
  return AISDKError.hasMarker(error, marker6);
200
212
  }
201
213
  };
202
- _a6 = symbol6;
203
214
  var name6 = "AI_JSONParseError";
204
215
  var marker7 = `vercel.ai.error.${name6}`;
205
216
  var symbol7 = Symbol.for(marker7);
206
217
  var _a7;
207
- var JSONParseError = class extends AISDKError {
218
+ var _b7;
219
+ var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
208
220
  constructor({ text, cause }) {
209
221
  super({
210
222
  name: name6,
@@ -219,37 +231,101 @@ Error message: ${getErrorMessage(cause)}`,
219
231
  return AISDKError.hasMarker(error, marker7);
220
232
  }
221
233
  };
222
- _a7 = symbol7;
223
234
  var name7 = "AI_LoadAPIKeyError";
224
235
  var marker8 = `vercel.ai.error.${name7}`;
225
236
  var symbol8 = Symbol.for(marker8);
226
237
  var _a8;
227
- _a8 = symbol8;
238
+ var _b8;
239
+ var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {
240
+ // used in isInstance
241
+ constructor({ message }) {
242
+ super({ name: name7, message });
243
+ this[_a8] = true;
244
+ }
245
+ static isInstance(error) {
246
+ return AISDKError.hasMarker(error, marker8);
247
+ }
248
+ };
228
249
  var name8 = "AI_LoadSettingError";
229
250
  var marker9 = `vercel.ai.error.${name8}`;
230
251
  var symbol9 = Symbol.for(marker9);
231
252
  var _a9;
232
- _a9 = symbol9;
253
+ var _b9;
254
+ var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {
255
+ // used in isInstance
256
+ constructor({ message }) {
257
+ super({ name: name8, message });
258
+ this[_a9] = true;
259
+ }
260
+ static isInstance(error) {
261
+ return AISDKError.hasMarker(error, marker9);
262
+ }
263
+ };
233
264
  var name9 = "AI_NoContentGeneratedError";
234
265
  var marker10 = `vercel.ai.error.${name9}`;
235
266
  var symbol10 = Symbol.for(marker10);
236
267
  var _a10;
237
- _a10 = symbol10;
268
+ var _b10;
269
+ var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {
270
+ // used in isInstance
271
+ constructor({
272
+ message = "No content generated."
273
+ } = {}) {
274
+ super({ name: name9, message });
275
+ this[_a10] = true;
276
+ }
277
+ static isInstance(error) {
278
+ return AISDKError.hasMarker(error, marker10);
279
+ }
280
+ };
238
281
  var name10 = "AI_NoSuchModelError";
239
282
  var marker11 = `vercel.ai.error.${name10}`;
240
283
  var symbol11 = Symbol.for(marker11);
241
284
  var _a11;
242
- _a11 = symbol11;
285
+ var _b11;
286
+ var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
287
+ constructor({
288
+ errorName = name10,
289
+ modelId,
290
+ modelType,
291
+ message = `No such ${modelType}: ${modelId}`
292
+ }) {
293
+ super({ name: errorName, message });
294
+ this[_a11] = true;
295
+ this.modelId = modelId;
296
+ this.modelType = modelType;
297
+ }
298
+ static isInstance(error) {
299
+ return AISDKError.hasMarker(error, marker11);
300
+ }
301
+ };
243
302
  var name11 = "AI_TooManyEmbeddingValuesForCallError";
244
303
  var marker12 = `vercel.ai.error.${name11}`;
245
304
  var symbol12 = Symbol.for(marker12);
246
305
  var _a12;
247
- _a12 = symbol12;
306
+ var _b12;
307
+ var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {
308
+ constructor(options) {
309
+ super({
310
+ name: name11,
311
+ message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
312
+ });
313
+ this[_a12] = true;
314
+ this.provider = options.provider;
315
+ this.modelId = options.modelId;
316
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
317
+ this.values = options.values;
318
+ }
319
+ static isInstance(error) {
320
+ return AISDKError.hasMarker(error, marker12);
321
+ }
322
+ };
248
323
  var name12 = "AI_TypeValidationError";
249
324
  var marker13 = `vercel.ai.error.${name12}`;
250
325
  var symbol13 = Symbol.for(marker13);
251
326
  var _a13;
252
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
327
+ var _b13;
328
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
253
329
  constructor({ value, cause }) {
254
330
  super({
255
331
  name: name12,
@@ -277,16 +353,15 @@ Error message: ${getErrorMessage(cause)}`,
277
353
  value,
278
354
  cause
279
355
  }) {
280
- return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
356
+ return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
281
357
  }
282
358
  };
283
- _a13 = symbol13;
284
- var TypeValidationError = _TypeValidationError;
285
359
  var name13 = "AI_UnsupportedFunctionalityError";
286
360
  var marker14 = `vercel.ai.error.${name13}`;
287
361
  var symbol14 = Symbol.for(marker14);
288
362
  var _a14;
289
- var UnsupportedFunctionalityError = class extends AISDKError {
363
+ var _b14;
364
+ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
290
365
  constructor({
291
366
  functionality,
292
367
  message = `'${functionality}' functionality not supported.`
@@ -299,9 +374,16 @@ var UnsupportedFunctionalityError = class extends AISDKError {
299
374
  return AISDKError.hasMarker(error, marker14);
300
375
  }
301
376
  };
302
- _a14 = symbol14;
303
377
 
304
- // node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/index.js
378
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.4_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
379
+ import * as z4 from "zod/v4";
380
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
381
+ import { ZodFirstPartyTypeKind } from "zod/v3";
382
+ import {
383
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
384
+ } from "zod/v3";
385
+
386
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
305
387
  var ParseError = class extends Error {
306
388
  constructor(message, options) {
307
389
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
@@ -392,7 +474,7 @@ function splitLines(chunk) {
392
474
  const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
393
475
  `, searchIndex);
394
476
  let lineEnd = -1;
395
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
477
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
396
478
  incompleteLine = chunk.slice(searchIndex);
397
479
  break;
398
480
  } else {
@@ -404,7 +486,7 @@ function splitLines(chunk) {
404
486
  return [lines, incompleteLine];
405
487
  }
406
488
 
407
- // node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/stream.js
489
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
408
490
  var EventSourceParserStream = class extends TransformStream {
409
491
  constructor({ onError, onRetry, onComment } = {}) {
410
492
  let parser;
@@ -428,28 +510,7 @@ var EventSourceParserStream = class extends TransformStream {
428
510
  }
429
511
  };
430
512
 
431
- // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.0-beta.5_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
432
- import * as z4 from "zod/v4";
433
-
434
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/Options.js
435
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
436
-
437
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/selectParser.js
438
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod";
439
-
440
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
441
- import { ZodFirstPartyTypeKind } from "zod";
442
-
443
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
444
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2 } from "zod";
445
-
446
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
447
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
448
-
449
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
450
- import { ZodOptional } from "zod";
451
-
452
- // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.0-beta.5_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
513
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.4_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
453
514
  function combineHeaders(...headers) {
454
515
  return headers.reduce(
455
516
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
@@ -459,6 +520,37 @@ function combineHeaders(...headers) {
459
520
  function extractResponseHeaders(response) {
460
521
  return Object.fromEntries([...response.headers]);
461
522
  }
523
+ var { btoa, atob } = globalThis;
524
+ function convertUint8ArrayToBase64(array) {
525
+ let latin1string = "";
526
+ for (let i = 0; i < array.length; i++) {
527
+ latin1string += String.fromCodePoint(array[i]);
528
+ }
529
+ return btoa(latin1string);
530
+ }
531
+ var name14 = "AI_DownloadError";
532
+ var marker15 = `vercel.ai.error.${name14}`;
533
+ var symbol15 = Symbol.for(marker15);
534
+ var _a15;
535
+ var _b15;
536
+ var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
537
+ constructor({
538
+ url,
539
+ statusCode,
540
+ statusText,
541
+ cause,
542
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
543
+ }) {
544
+ super({ name: name14, message, cause });
545
+ this[_a15] = true;
546
+ this.url = url;
547
+ this.statusCode = statusCode;
548
+ this.statusText = statusText;
549
+ }
550
+ static isInstance(error) {
551
+ return AISDKError.hasMarker(error, marker15);
552
+ }
553
+ };
462
554
  var createIdGenerator = ({
463
555
  prefix,
464
556
  size = 16,
@@ -486,7 +578,7 @@ var createIdGenerator = ({
486
578
  };
487
579
  var generateId = createIdGenerator();
488
580
  function isAbortError(error) {
489
- return error instanceof Error && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
581
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
490
582
  error.name === "TimeoutError");
491
583
  }
492
584
  var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
@@ -513,11 +605,53 @@ function handleFetchError({
513
605
  }
514
606
  return error;
515
607
  }
516
- function removeUndefinedEntries(record) {
517
- return Object.fromEntries(
518
- Object.entries(record).filter(([_key, value]) => value != null)
608
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
609
+ var _a22, _b22, _c;
610
+ if (globalThisAny.window) {
611
+ return `runtime/browser`;
612
+ }
613
+ if ((_a22 = globalThisAny.navigator) == null ? void 0 : _a22.userAgent) {
614
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
615
+ }
616
+ if ((_c = (_b22 = globalThisAny.process) == null ? void 0 : _b22.versions) == null ? void 0 : _c.node) {
617
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
618
+ }
619
+ if (globalThisAny.EdgeRuntime) {
620
+ return `runtime/vercel-edge`;
621
+ }
622
+ return "runtime/unknown";
623
+ }
624
+ function normalizeHeaders(headers) {
625
+ if (headers == null) {
626
+ return {};
627
+ }
628
+ const normalized = {};
629
+ if (headers instanceof Headers) {
630
+ headers.forEach((value, key) => {
631
+ normalized[key.toLowerCase()] = value;
632
+ });
633
+ } else {
634
+ if (!Array.isArray(headers)) {
635
+ headers = Object.entries(headers);
636
+ }
637
+ for (const [key, value] of headers) {
638
+ if (value != null) {
639
+ normalized[key.toLowerCase()] = value;
640
+ }
641
+ }
642
+ }
643
+ return normalized;
644
+ }
645
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
646
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
647
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
648
+ normalizedHeaders.set(
649
+ "user-agent",
650
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
519
651
  );
652
+ return Object.fromEntries(normalizedHeaders.entries());
520
653
  }
654
+ var VERSION = true ? "4.0.4" : "0.0.0-test";
521
655
  var suspectProtoRx = /"__proto__"\s*:/;
522
656
  var suspectConstructorRx = /"constructor"\s*:/;
523
657
  function _parse(text) {
@@ -554,34 +688,1204 @@ function filter(obj) {
554
688
  }
555
689
  function secureJsonParse(text) {
556
690
  const { stackTraceLimit } = Error;
557
- Error.stackTraceLimit = 0;
691
+ try {
692
+ Error.stackTraceLimit = 0;
693
+ } catch (e) {
694
+ return _parse(text);
695
+ }
558
696
  try {
559
697
  return _parse(text);
560
698
  } finally {
561
699
  Error.stackTraceLimit = stackTraceLimit;
562
700
  }
563
701
  }
564
- var validatorSymbol = Symbol.for("vercel.ai.validator");
565
- function validator(validate) {
566
- return { [validatorSymbol]: true, validate };
702
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
703
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
704
+ jsonSchema2.additionalProperties = false;
705
+ const { properties } = jsonSchema2;
706
+ if (properties != null) {
707
+ for (const key of Object.keys(properties)) {
708
+ properties[key] = visit(properties[key]);
709
+ }
710
+ }
711
+ }
712
+ if (jsonSchema2.items != null) {
713
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
714
+ }
715
+ if (jsonSchema2.anyOf != null) {
716
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
717
+ }
718
+ if (jsonSchema2.allOf != null) {
719
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
720
+ }
721
+ if (jsonSchema2.oneOf != null) {
722
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
723
+ }
724
+ const { definitions } = jsonSchema2;
725
+ if (definitions != null) {
726
+ for (const key of Object.keys(definitions)) {
727
+ definitions[key] = visit(definitions[key]);
728
+ }
729
+ }
730
+ return jsonSchema2;
567
731
  }
568
- function isValidator(value) {
569
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
732
+ function visit(def) {
733
+ if (typeof def === "boolean") return def;
734
+ return addAdditionalPropertiesToJsonSchema(def);
570
735
  }
571
- function asValidator(value) {
572
- return isValidator(value) ? value : standardSchemaValidator(value);
736
+ var ignoreOverride = Symbol(
737
+ "Let zodToJsonSchema decide on which parser to use"
738
+ );
739
+ var defaultOptions = {
740
+ name: void 0,
741
+ $refStrategy: "root",
742
+ basePath: ["#"],
743
+ effectStrategy: "input",
744
+ pipeStrategy: "all",
745
+ dateStrategy: "format:date-time",
746
+ mapStrategy: "entries",
747
+ removeAdditionalStrategy: "passthrough",
748
+ allowedAdditionalProperties: true,
749
+ rejectedAdditionalProperties: false,
750
+ definitionPath: "definitions",
751
+ strictUnions: false,
752
+ definitions: {},
753
+ errorMessages: false,
754
+ patternStrategy: "escape",
755
+ applyRegexFlags: false,
756
+ emailStrategy: "format:email",
757
+ base64Strategy: "contentEncoding:base64",
758
+ nameStrategy: "ref"
759
+ };
760
+ var getDefaultOptions = (options) => typeof options === "string" ? __spreadProps(__spreadValues({}, defaultOptions), {
761
+ name: options
762
+ }) : __spreadValues(__spreadValues({}, defaultOptions), options);
763
+ function parseAnyDef() {
764
+ return {};
573
765
  }
574
- function standardSchemaValidator(standardSchema) {
575
- return validator(async (value) => {
576
- const result = await standardSchema["~standard"].validate(value);
577
- return result.issues == null ? { success: true, value: result.value } : {
578
- success: false,
579
- error: new TypeValidationError({
580
- value,
581
- cause: result.issues
582
- })
766
+ function parseArrayDef(def, refs) {
767
+ var _a22, _b22, _c;
768
+ const res = {
769
+ type: "array"
770
+ };
771
+ if (((_a22 = def.type) == null ? void 0 : _a22._def) && ((_c = (_b22 = def.type) == null ? void 0 : _b22._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
772
+ res.items = parseDef(def.type._def, __spreadProps(__spreadValues({}, refs), {
773
+ currentPath: [...refs.currentPath, "items"]
774
+ }));
775
+ }
776
+ if (def.minLength) {
777
+ res.minItems = def.minLength.value;
778
+ }
779
+ if (def.maxLength) {
780
+ res.maxItems = def.maxLength.value;
781
+ }
782
+ if (def.exactLength) {
783
+ res.minItems = def.exactLength.value;
784
+ res.maxItems = def.exactLength.value;
785
+ }
786
+ return res;
787
+ }
788
+ function parseBigintDef(def) {
789
+ const res = {
790
+ type: "integer",
791
+ format: "int64"
792
+ };
793
+ if (!def.checks) return res;
794
+ for (const check of def.checks) {
795
+ switch (check.kind) {
796
+ case "min":
797
+ if (check.inclusive) {
798
+ res.minimum = check.value;
799
+ } else {
800
+ res.exclusiveMinimum = check.value;
801
+ }
802
+ break;
803
+ case "max":
804
+ if (check.inclusive) {
805
+ res.maximum = check.value;
806
+ } else {
807
+ res.exclusiveMaximum = check.value;
808
+ }
809
+ break;
810
+ case "multipleOf":
811
+ res.multipleOf = check.value;
812
+ break;
813
+ }
814
+ }
815
+ return res;
816
+ }
817
+ function parseBooleanDef() {
818
+ return { type: "boolean" };
819
+ }
820
+ function parseBrandedDef(_def, refs) {
821
+ return parseDef(_def.type._def, refs);
822
+ }
823
+ var parseCatchDef = (def, refs) => {
824
+ return parseDef(def.innerType._def, refs);
825
+ };
826
+ function parseDateDef(def, refs, overrideDateStrategy) {
827
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
828
+ if (Array.isArray(strategy)) {
829
+ return {
830
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
831
+ };
832
+ }
833
+ switch (strategy) {
834
+ case "string":
835
+ case "format:date-time":
836
+ return {
837
+ type: "string",
838
+ format: "date-time"
839
+ };
840
+ case "format:date":
841
+ return {
842
+ type: "string",
843
+ format: "date"
844
+ };
845
+ case "integer":
846
+ return integerDateParser(def);
847
+ }
848
+ }
849
+ var integerDateParser = (def) => {
850
+ const res = {
851
+ type: "integer",
852
+ format: "unix-time"
853
+ };
854
+ for (const check of def.checks) {
855
+ switch (check.kind) {
856
+ case "min":
857
+ res.minimum = check.value;
858
+ break;
859
+ case "max":
860
+ res.maximum = check.value;
861
+ break;
862
+ }
863
+ }
864
+ return res;
865
+ };
866
+ function parseDefaultDef(_def, refs) {
867
+ return __spreadProps(__spreadValues({}, parseDef(_def.innerType._def, refs)), {
868
+ default: _def.defaultValue()
869
+ });
870
+ }
871
+ function parseEffectsDef(_def, refs) {
872
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
873
+ }
874
+ function parseEnumDef(def) {
875
+ return {
876
+ type: "string",
877
+ enum: Array.from(def.values)
878
+ };
879
+ }
880
+ var isJsonSchema7AllOfType = (type) => {
881
+ if ("type" in type && type.type === "string") return false;
882
+ return "allOf" in type;
883
+ };
884
+ function parseIntersectionDef(def, refs) {
885
+ const allOf = [
886
+ parseDef(def.left._def, __spreadProps(__spreadValues({}, refs), {
887
+ currentPath: [...refs.currentPath, "allOf", "0"]
888
+ })),
889
+ parseDef(def.right._def, __spreadProps(__spreadValues({}, refs), {
890
+ currentPath: [...refs.currentPath, "allOf", "1"]
891
+ }))
892
+ ].filter((x) => !!x);
893
+ const mergedAllOf = [];
894
+ allOf.forEach((schema) => {
895
+ if (isJsonSchema7AllOfType(schema)) {
896
+ mergedAllOf.push(...schema.allOf);
897
+ } else {
898
+ let nestedSchema = schema;
899
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
900
+ const _a16 = schema, { additionalProperties } = _a16, rest = __objRest(_a16, ["additionalProperties"]);
901
+ nestedSchema = rest;
902
+ }
903
+ mergedAllOf.push(nestedSchema);
904
+ }
905
+ });
906
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
907
+ }
908
+ function parseLiteralDef(def) {
909
+ const parsedType = typeof def.value;
910
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
911
+ return {
912
+ type: Array.isArray(def.value) ? "array" : "object"
913
+ };
914
+ }
915
+ return {
916
+ type: parsedType === "bigint" ? "integer" : parsedType,
917
+ const: def.value
918
+ };
919
+ }
920
+ var emojiRegex = void 0;
921
+ var zodPatterns = {
922
+ /**
923
+ * `c` was changed to `[cC]` to replicate /i flag
924
+ */
925
+ cuid: /^[cC][^\s-]{8,}$/,
926
+ cuid2: /^[0-9a-z]+$/,
927
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
928
+ /**
929
+ * `a-z` was added to replicate /i flag
930
+ */
931
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
932
+ /**
933
+ * Constructed a valid Unicode RegExp
934
+ *
935
+ * Lazily instantiate since this type of regex isn't supported
936
+ * in all envs (e.g. React Native).
937
+ *
938
+ * See:
939
+ * https://github.com/colinhacks/zod/issues/2433
940
+ * Fix in Zod:
941
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
942
+ */
943
+ emoji: () => {
944
+ if (emojiRegex === void 0) {
945
+ emojiRegex = RegExp(
946
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
947
+ "u"
948
+ );
949
+ }
950
+ return emojiRegex;
951
+ },
952
+ /**
953
+ * Unused
954
+ */
955
+ 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}$/,
956
+ /**
957
+ * Unused
958
+ */
959
+ 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])$/,
960
+ 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])$/,
961
+ /**
962
+ * Unused
963
+ */
964
+ 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})))$/,
965
+ 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])$/,
966
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
967
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
968
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
969
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
970
+ };
971
+ function parseStringDef(def, refs) {
972
+ const res = {
973
+ type: "string"
974
+ };
975
+ if (def.checks) {
976
+ for (const check of def.checks) {
977
+ switch (check.kind) {
978
+ case "min":
979
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
980
+ break;
981
+ case "max":
982
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
983
+ break;
984
+ case "email":
985
+ switch (refs.emailStrategy) {
986
+ case "format:email":
987
+ addFormat(res, "email", check.message, refs);
988
+ break;
989
+ case "format:idn-email":
990
+ addFormat(res, "idn-email", check.message, refs);
991
+ break;
992
+ case "pattern:zod":
993
+ addPattern(res, zodPatterns.email, check.message, refs);
994
+ break;
995
+ }
996
+ break;
997
+ case "url":
998
+ addFormat(res, "uri", check.message, refs);
999
+ break;
1000
+ case "uuid":
1001
+ addFormat(res, "uuid", check.message, refs);
1002
+ break;
1003
+ case "regex":
1004
+ addPattern(res, check.regex, check.message, refs);
1005
+ break;
1006
+ case "cuid":
1007
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1008
+ break;
1009
+ case "cuid2":
1010
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1011
+ break;
1012
+ case "startsWith":
1013
+ addPattern(
1014
+ res,
1015
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1016
+ check.message,
1017
+ refs
1018
+ );
1019
+ break;
1020
+ case "endsWith":
1021
+ addPattern(
1022
+ res,
1023
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1024
+ check.message,
1025
+ refs
1026
+ );
1027
+ break;
1028
+ case "datetime":
1029
+ addFormat(res, "date-time", check.message, refs);
1030
+ break;
1031
+ case "date":
1032
+ addFormat(res, "date", check.message, refs);
1033
+ break;
1034
+ case "time":
1035
+ addFormat(res, "time", check.message, refs);
1036
+ break;
1037
+ case "duration":
1038
+ addFormat(res, "duration", check.message, refs);
1039
+ break;
1040
+ case "length":
1041
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1042
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1043
+ break;
1044
+ case "includes": {
1045
+ addPattern(
1046
+ res,
1047
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1048
+ check.message,
1049
+ refs
1050
+ );
1051
+ break;
1052
+ }
1053
+ case "ip": {
1054
+ if (check.version !== "v6") {
1055
+ addFormat(res, "ipv4", check.message, refs);
1056
+ }
1057
+ if (check.version !== "v4") {
1058
+ addFormat(res, "ipv6", check.message, refs);
1059
+ }
1060
+ break;
1061
+ }
1062
+ case "base64url":
1063
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1064
+ break;
1065
+ case "jwt":
1066
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1067
+ break;
1068
+ case "cidr": {
1069
+ if (check.version !== "v6") {
1070
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1071
+ }
1072
+ if (check.version !== "v4") {
1073
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1074
+ }
1075
+ break;
1076
+ }
1077
+ case "emoji":
1078
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1079
+ break;
1080
+ case "ulid": {
1081
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1082
+ break;
1083
+ }
1084
+ case "base64": {
1085
+ switch (refs.base64Strategy) {
1086
+ case "format:binary": {
1087
+ addFormat(res, "binary", check.message, refs);
1088
+ break;
1089
+ }
1090
+ case "contentEncoding:base64": {
1091
+ res.contentEncoding = "base64";
1092
+ break;
1093
+ }
1094
+ case "pattern:zod": {
1095
+ addPattern(res, zodPatterns.base64, check.message, refs);
1096
+ break;
1097
+ }
1098
+ }
1099
+ break;
1100
+ }
1101
+ case "nanoid": {
1102
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1103
+ }
1104
+ case "toLowerCase":
1105
+ case "toUpperCase":
1106
+ case "trim":
1107
+ break;
1108
+ default:
1109
+ /* @__PURE__ */ ((_) => {
1110
+ })(check);
1111
+ }
1112
+ }
1113
+ }
1114
+ return res;
1115
+ }
1116
+ function escapeLiteralCheckValue(literal, refs) {
1117
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1118
+ }
1119
+ var ALPHA_NUMERIC = new Set(
1120
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1121
+ );
1122
+ function escapeNonAlphaNumeric(source) {
1123
+ let result = "";
1124
+ for (let i = 0; i < source.length; i++) {
1125
+ if (!ALPHA_NUMERIC.has(source[i])) {
1126
+ result += "\\";
1127
+ }
1128
+ result += source[i];
1129
+ }
1130
+ return result;
1131
+ }
1132
+ function addFormat(schema, value, message, refs) {
1133
+ var _a22;
1134
+ if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) {
1135
+ if (!schema.anyOf) {
1136
+ schema.anyOf = [];
1137
+ }
1138
+ if (schema.format) {
1139
+ schema.anyOf.push({
1140
+ format: schema.format
1141
+ });
1142
+ delete schema.format;
1143
+ }
1144
+ schema.anyOf.push(__spreadValues({
1145
+ format: value
1146
+ }, message && refs.errorMessages && { errorMessage: { format: message } }));
1147
+ } else {
1148
+ schema.format = value;
1149
+ }
1150
+ }
1151
+ function addPattern(schema, regex, message, refs) {
1152
+ var _a22;
1153
+ if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) {
1154
+ if (!schema.allOf) {
1155
+ schema.allOf = [];
1156
+ }
1157
+ if (schema.pattern) {
1158
+ schema.allOf.push({
1159
+ pattern: schema.pattern
1160
+ });
1161
+ delete schema.pattern;
1162
+ }
1163
+ schema.allOf.push(__spreadValues({
1164
+ pattern: stringifyRegExpWithFlags(regex, refs)
1165
+ }, message && refs.errorMessages && { errorMessage: { pattern: message } }));
1166
+ } else {
1167
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1168
+ }
1169
+ }
1170
+ function stringifyRegExpWithFlags(regex, refs) {
1171
+ var _a22;
1172
+ if (!refs.applyRegexFlags || !regex.flags) {
1173
+ return regex.source;
1174
+ }
1175
+ const flags = {
1176
+ i: regex.flags.includes("i"),
1177
+ // Case-insensitive
1178
+ m: regex.flags.includes("m"),
1179
+ // `^` and `$` matches adjacent to newline characters
1180
+ s: regex.flags.includes("s")
1181
+ // `.` matches newlines
1182
+ };
1183
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1184
+ let pattern = "";
1185
+ let isEscaped = false;
1186
+ let inCharGroup = false;
1187
+ let inCharRange = false;
1188
+ for (let i = 0; i < source.length; i++) {
1189
+ if (isEscaped) {
1190
+ pattern += source[i];
1191
+ isEscaped = false;
1192
+ continue;
1193
+ }
1194
+ if (flags.i) {
1195
+ if (inCharGroup) {
1196
+ if (source[i].match(/[a-z]/)) {
1197
+ if (inCharRange) {
1198
+ pattern += source[i];
1199
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1200
+ inCharRange = false;
1201
+ } else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) {
1202
+ pattern += source[i];
1203
+ inCharRange = true;
1204
+ } else {
1205
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1206
+ }
1207
+ continue;
1208
+ }
1209
+ } else if (source[i].match(/[a-z]/)) {
1210
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1211
+ continue;
1212
+ }
1213
+ }
1214
+ if (flags.m) {
1215
+ if (source[i] === "^") {
1216
+ pattern += `(^|(?<=[\r
1217
+ ]))`;
1218
+ continue;
1219
+ } else if (source[i] === "$") {
1220
+ pattern += `($|(?=[\r
1221
+ ]))`;
1222
+ continue;
1223
+ }
1224
+ }
1225
+ if (flags.s && source[i] === ".") {
1226
+ pattern += inCharGroup ? `${source[i]}\r
1227
+ ` : `[${source[i]}\r
1228
+ ]`;
1229
+ continue;
1230
+ }
1231
+ pattern += source[i];
1232
+ if (source[i] === "\\") {
1233
+ isEscaped = true;
1234
+ } else if (inCharGroup && source[i] === "]") {
1235
+ inCharGroup = false;
1236
+ } else if (!inCharGroup && source[i] === "[") {
1237
+ inCharGroup = true;
1238
+ }
1239
+ }
1240
+ try {
1241
+ new RegExp(pattern);
1242
+ } catch (e) {
1243
+ console.warn(
1244
+ `Could not convert regex pattern at ${refs.currentPath.join(
1245
+ "/"
1246
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1247
+ );
1248
+ return regex.source;
1249
+ }
1250
+ return pattern;
1251
+ }
1252
+ function parseRecordDef(def, refs) {
1253
+ var _a22, _b22, _c, _d, _e, _f;
1254
+ const schema = {
1255
+ type: "object",
1256
+ additionalProperties: (_a22 = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1257
+ currentPath: [...refs.currentPath, "additionalProperties"]
1258
+ }))) != null ? _a22 : refs.allowedAdditionalProperties
1259
+ };
1260
+ if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1261
+ const _a16 = parseStringDef(def.keyType._def, refs), { type } = _a16, keyType = __objRest(_a16, ["type"]);
1262
+ return __spreadProps(__spreadValues({}, schema), {
1263
+ propertyNames: keyType
1264
+ });
1265
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1266
+ return __spreadProps(__spreadValues({}, schema), {
1267
+ propertyNames: {
1268
+ enum: def.keyType._def.values
1269
+ }
1270
+ });
1271
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1272
+ const _b16 = parseBrandedDef(
1273
+ def.keyType._def,
1274
+ refs
1275
+ ), { type } = _b16, keyType = __objRest(_b16, ["type"]);
1276
+ return __spreadProps(__spreadValues({}, schema), {
1277
+ propertyNames: keyType
1278
+ });
1279
+ }
1280
+ return schema;
1281
+ }
1282
+ function parseMapDef(def, refs) {
1283
+ if (refs.mapStrategy === "record") {
1284
+ return parseRecordDef(def, refs);
1285
+ }
1286
+ const keys = parseDef(def.keyType._def, __spreadProps(__spreadValues({}, refs), {
1287
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1288
+ })) || parseAnyDef();
1289
+ const values = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1290
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1291
+ })) || parseAnyDef();
1292
+ return {
1293
+ type: "array",
1294
+ maxItems: 125,
1295
+ items: {
1296
+ type: "array",
1297
+ items: [keys, values],
1298
+ minItems: 2,
1299
+ maxItems: 2
1300
+ }
1301
+ };
1302
+ }
1303
+ function parseNativeEnumDef(def) {
1304
+ const object = def.values;
1305
+ const actualKeys = Object.keys(def.values).filter((key) => {
1306
+ return typeof object[object[key]] !== "number";
1307
+ });
1308
+ const actualValues = actualKeys.map((key) => object[key]);
1309
+ const parsedTypes = Array.from(
1310
+ new Set(actualValues.map((values) => typeof values))
1311
+ );
1312
+ return {
1313
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1314
+ enum: actualValues
1315
+ };
1316
+ }
1317
+ function parseNeverDef() {
1318
+ return { not: parseAnyDef() };
1319
+ }
1320
+ function parseNullDef() {
1321
+ return {
1322
+ type: "null"
1323
+ };
1324
+ }
1325
+ var primitiveMappings = {
1326
+ ZodString: "string",
1327
+ ZodNumber: "number",
1328
+ ZodBigInt: "integer",
1329
+ ZodBoolean: "boolean",
1330
+ ZodNull: "null"
1331
+ };
1332
+ function parseUnionDef(def, refs) {
1333
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1334
+ if (options.every(
1335
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1336
+ )) {
1337
+ const types = options.reduce((types2, x) => {
1338
+ const type = primitiveMappings[x._def.typeName];
1339
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1340
+ }, []);
1341
+ return {
1342
+ type: types.length > 1 ? types : types[0]
583
1343
  };
1344
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1345
+ const types = options.reduce(
1346
+ (acc, x) => {
1347
+ const type = typeof x._def.value;
1348
+ switch (type) {
1349
+ case "string":
1350
+ case "number":
1351
+ case "boolean":
1352
+ return [...acc, type];
1353
+ case "bigint":
1354
+ return [...acc, "integer"];
1355
+ case "object":
1356
+ if (x._def.value === null) return [...acc, "null"];
1357
+ case "symbol":
1358
+ case "undefined":
1359
+ case "function":
1360
+ default:
1361
+ return acc;
1362
+ }
1363
+ },
1364
+ []
1365
+ );
1366
+ if (types.length === options.length) {
1367
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1368
+ return {
1369
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1370
+ enum: options.reduce(
1371
+ (acc, x) => {
1372
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1373
+ },
1374
+ []
1375
+ )
1376
+ };
1377
+ }
1378
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1379
+ return {
1380
+ type: "string",
1381
+ enum: options.reduce(
1382
+ (acc, x) => [
1383
+ ...acc,
1384
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1385
+ ],
1386
+ []
1387
+ )
1388
+ };
1389
+ }
1390
+ return asAnyOf(def, refs);
1391
+ }
1392
+ var asAnyOf = (def, refs) => {
1393
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1394
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1395
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1396
+ }))
1397
+ ).filter(
1398
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1399
+ );
1400
+ return anyOf.length ? { anyOf } : void 0;
1401
+ };
1402
+ function parseNullableDef(def, refs) {
1403
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1404
+ def.innerType._def.typeName
1405
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1406
+ return {
1407
+ type: [
1408
+ primitiveMappings[def.innerType._def.typeName],
1409
+ "null"
1410
+ ]
1411
+ };
1412
+ }
1413
+ const base = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1414
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1415
+ }));
1416
+ return base && { anyOf: [base, { type: "null" }] };
1417
+ }
1418
+ function parseNumberDef(def) {
1419
+ const res = {
1420
+ type: "number"
1421
+ };
1422
+ if (!def.checks) return res;
1423
+ for (const check of def.checks) {
1424
+ switch (check.kind) {
1425
+ case "int":
1426
+ res.type = "integer";
1427
+ break;
1428
+ case "min":
1429
+ if (check.inclusive) {
1430
+ res.minimum = check.value;
1431
+ } else {
1432
+ res.exclusiveMinimum = check.value;
1433
+ }
1434
+ break;
1435
+ case "max":
1436
+ if (check.inclusive) {
1437
+ res.maximum = check.value;
1438
+ } else {
1439
+ res.exclusiveMaximum = check.value;
1440
+ }
1441
+ break;
1442
+ case "multipleOf":
1443
+ res.multipleOf = check.value;
1444
+ break;
1445
+ }
1446
+ }
1447
+ return res;
1448
+ }
1449
+ function parseObjectDef(def, refs) {
1450
+ const result = {
1451
+ type: "object",
1452
+ properties: {}
1453
+ };
1454
+ const required = [];
1455
+ const shape = def.shape();
1456
+ for (const propName in shape) {
1457
+ let propDef = shape[propName];
1458
+ if (propDef === void 0 || propDef._def === void 0) {
1459
+ continue;
1460
+ }
1461
+ const propOptional = safeIsOptional(propDef);
1462
+ const parsedDef = parseDef(propDef._def, __spreadProps(__spreadValues({}, refs), {
1463
+ currentPath: [...refs.currentPath, "properties", propName],
1464
+ propertyPath: [...refs.currentPath, "properties", propName]
1465
+ }));
1466
+ if (parsedDef === void 0) {
1467
+ continue;
1468
+ }
1469
+ result.properties[propName] = parsedDef;
1470
+ if (!propOptional) {
1471
+ required.push(propName);
1472
+ }
1473
+ }
1474
+ if (required.length) {
1475
+ result.required = required;
1476
+ }
1477
+ const additionalProperties = decideAdditionalProperties(def, refs);
1478
+ if (additionalProperties !== void 0) {
1479
+ result.additionalProperties = additionalProperties;
1480
+ }
1481
+ return result;
1482
+ }
1483
+ function decideAdditionalProperties(def, refs) {
1484
+ if (def.catchall._def.typeName !== "ZodNever") {
1485
+ return parseDef(def.catchall._def, __spreadProps(__spreadValues({}, refs), {
1486
+ currentPath: [...refs.currentPath, "additionalProperties"]
1487
+ }));
1488
+ }
1489
+ switch (def.unknownKeys) {
1490
+ case "passthrough":
1491
+ return refs.allowedAdditionalProperties;
1492
+ case "strict":
1493
+ return refs.rejectedAdditionalProperties;
1494
+ case "strip":
1495
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1496
+ }
1497
+ }
1498
+ function safeIsOptional(schema) {
1499
+ try {
1500
+ return schema.isOptional();
1501
+ } catch (e) {
1502
+ return true;
1503
+ }
1504
+ }
1505
+ var parseOptionalDef = (def, refs) => {
1506
+ var _a22;
1507
+ if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) {
1508
+ return parseDef(def.innerType._def, refs);
1509
+ }
1510
+ const innerSchema = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1511
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1512
+ }));
1513
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1514
+ };
1515
+ var parsePipelineDef = (def, refs) => {
1516
+ if (refs.pipeStrategy === "input") {
1517
+ return parseDef(def.in._def, refs);
1518
+ } else if (refs.pipeStrategy === "output") {
1519
+ return parseDef(def.out._def, refs);
1520
+ }
1521
+ const a = parseDef(def.in._def, __spreadProps(__spreadValues({}, refs), {
1522
+ currentPath: [...refs.currentPath, "allOf", "0"]
1523
+ }));
1524
+ const b = parseDef(def.out._def, __spreadProps(__spreadValues({}, refs), {
1525
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1526
+ }));
1527
+ return {
1528
+ allOf: [a, b].filter((x) => x !== void 0)
1529
+ };
1530
+ };
1531
+ function parsePromiseDef(def, refs) {
1532
+ return parseDef(def.type._def, refs);
1533
+ }
1534
+ function parseSetDef(def, refs) {
1535
+ const items = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1536
+ currentPath: [...refs.currentPath, "items"]
1537
+ }));
1538
+ const schema = {
1539
+ type: "array",
1540
+ uniqueItems: true,
1541
+ items
1542
+ };
1543
+ if (def.minSize) {
1544
+ schema.minItems = def.minSize.value;
1545
+ }
1546
+ if (def.maxSize) {
1547
+ schema.maxItems = def.maxSize.value;
1548
+ }
1549
+ return schema;
1550
+ }
1551
+ function parseTupleDef(def, refs) {
1552
+ if (def.rest) {
1553
+ return {
1554
+ type: "array",
1555
+ minItems: def.items.length,
1556
+ items: def.items.map(
1557
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1558
+ currentPath: [...refs.currentPath, "items", `${i}`]
1559
+ }))
1560
+ ).reduce(
1561
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1562
+ []
1563
+ ),
1564
+ additionalItems: parseDef(def.rest._def, __spreadProps(__spreadValues({}, refs), {
1565
+ currentPath: [...refs.currentPath, "additionalItems"]
1566
+ }))
1567
+ };
1568
+ } else {
1569
+ return {
1570
+ type: "array",
1571
+ minItems: def.items.length,
1572
+ maxItems: def.items.length,
1573
+ items: def.items.map(
1574
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1575
+ currentPath: [...refs.currentPath, "items", `${i}`]
1576
+ }))
1577
+ ).reduce(
1578
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1579
+ []
1580
+ )
1581
+ };
1582
+ }
1583
+ }
1584
+ function parseUndefinedDef() {
1585
+ return {
1586
+ not: parseAnyDef()
1587
+ };
1588
+ }
1589
+ function parseUnknownDef() {
1590
+ return parseAnyDef();
1591
+ }
1592
+ var parseReadonlyDef = (def, refs) => {
1593
+ return parseDef(def.innerType._def, refs);
1594
+ };
1595
+ var selectParser = (def, typeName, refs) => {
1596
+ switch (typeName) {
1597
+ case ZodFirstPartyTypeKind3.ZodString:
1598
+ return parseStringDef(def, refs);
1599
+ case ZodFirstPartyTypeKind3.ZodNumber:
1600
+ return parseNumberDef(def);
1601
+ case ZodFirstPartyTypeKind3.ZodObject:
1602
+ return parseObjectDef(def, refs);
1603
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1604
+ return parseBigintDef(def);
1605
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1606
+ return parseBooleanDef();
1607
+ case ZodFirstPartyTypeKind3.ZodDate:
1608
+ return parseDateDef(def, refs);
1609
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1610
+ return parseUndefinedDef();
1611
+ case ZodFirstPartyTypeKind3.ZodNull:
1612
+ return parseNullDef();
1613
+ case ZodFirstPartyTypeKind3.ZodArray:
1614
+ return parseArrayDef(def, refs);
1615
+ case ZodFirstPartyTypeKind3.ZodUnion:
1616
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1617
+ return parseUnionDef(def, refs);
1618
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1619
+ return parseIntersectionDef(def, refs);
1620
+ case ZodFirstPartyTypeKind3.ZodTuple:
1621
+ return parseTupleDef(def, refs);
1622
+ case ZodFirstPartyTypeKind3.ZodRecord:
1623
+ return parseRecordDef(def, refs);
1624
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1625
+ return parseLiteralDef(def);
1626
+ case ZodFirstPartyTypeKind3.ZodEnum:
1627
+ return parseEnumDef(def);
1628
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1629
+ return parseNativeEnumDef(def);
1630
+ case ZodFirstPartyTypeKind3.ZodNullable:
1631
+ return parseNullableDef(def, refs);
1632
+ case ZodFirstPartyTypeKind3.ZodOptional:
1633
+ return parseOptionalDef(def, refs);
1634
+ case ZodFirstPartyTypeKind3.ZodMap:
1635
+ return parseMapDef(def, refs);
1636
+ case ZodFirstPartyTypeKind3.ZodSet:
1637
+ return parseSetDef(def, refs);
1638
+ case ZodFirstPartyTypeKind3.ZodLazy:
1639
+ return () => def.getter()._def;
1640
+ case ZodFirstPartyTypeKind3.ZodPromise:
1641
+ return parsePromiseDef(def, refs);
1642
+ case ZodFirstPartyTypeKind3.ZodNaN:
1643
+ case ZodFirstPartyTypeKind3.ZodNever:
1644
+ return parseNeverDef();
1645
+ case ZodFirstPartyTypeKind3.ZodEffects:
1646
+ return parseEffectsDef(def, refs);
1647
+ case ZodFirstPartyTypeKind3.ZodAny:
1648
+ return parseAnyDef();
1649
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1650
+ return parseUnknownDef();
1651
+ case ZodFirstPartyTypeKind3.ZodDefault:
1652
+ return parseDefaultDef(def, refs);
1653
+ case ZodFirstPartyTypeKind3.ZodBranded:
1654
+ return parseBrandedDef(def, refs);
1655
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1656
+ return parseReadonlyDef(def, refs);
1657
+ case ZodFirstPartyTypeKind3.ZodCatch:
1658
+ return parseCatchDef(def, refs);
1659
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1660
+ return parsePipelineDef(def, refs);
1661
+ case ZodFirstPartyTypeKind3.ZodFunction:
1662
+ case ZodFirstPartyTypeKind3.ZodVoid:
1663
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1664
+ return void 0;
1665
+ default:
1666
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1667
+ }
1668
+ };
1669
+ var getRelativePath = (pathA, pathB) => {
1670
+ let i = 0;
1671
+ for (; i < pathA.length && i < pathB.length; i++) {
1672
+ if (pathA[i] !== pathB[i]) break;
1673
+ }
1674
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1675
+ };
1676
+ function parseDef(def, refs, forceResolution = false) {
1677
+ var _a22;
1678
+ const seenItem = refs.seen.get(def);
1679
+ if (refs.override) {
1680
+ const overrideResult = (_a22 = refs.override) == null ? void 0 : _a22.call(
1681
+ refs,
1682
+ def,
1683
+ refs,
1684
+ seenItem,
1685
+ forceResolution
1686
+ );
1687
+ if (overrideResult !== ignoreOverride) {
1688
+ return overrideResult;
1689
+ }
1690
+ }
1691
+ if (seenItem && !forceResolution) {
1692
+ const seenSchema = get$ref(seenItem, refs);
1693
+ if (seenSchema !== void 0) {
1694
+ return seenSchema;
1695
+ }
1696
+ }
1697
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1698
+ refs.seen.set(def, newItem);
1699
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1700
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1701
+ if (jsonSchema2) {
1702
+ addMeta(def, refs, jsonSchema2);
1703
+ }
1704
+ if (refs.postProcess) {
1705
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1706
+ newItem.jsonSchema = jsonSchema2;
1707
+ return postProcessResult;
1708
+ }
1709
+ newItem.jsonSchema = jsonSchema2;
1710
+ return jsonSchema2;
1711
+ }
1712
+ var get$ref = (item, refs) => {
1713
+ switch (refs.$refStrategy) {
1714
+ case "root":
1715
+ return { $ref: item.path.join("/") };
1716
+ case "relative":
1717
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1718
+ case "none":
1719
+ case "seen": {
1720
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1721
+ console.warn(
1722
+ `Recursive reference detected at ${refs.currentPath.join(
1723
+ "/"
1724
+ )}! Defaulting to any`
1725
+ );
1726
+ return parseAnyDef();
1727
+ }
1728
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1729
+ }
1730
+ }
1731
+ };
1732
+ var addMeta = (def, refs, jsonSchema2) => {
1733
+ if (def.description) {
1734
+ jsonSchema2.description = def.description;
1735
+ }
1736
+ return jsonSchema2;
1737
+ };
1738
+ var getRefs = (options) => {
1739
+ const _options = getDefaultOptions(options);
1740
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1741
+ return __spreadProps(__spreadValues({}, _options), {
1742
+ currentPath,
1743
+ propertyPath: void 0,
1744
+ seen: new Map(
1745
+ Object.entries(_options.definitions).map(([name22, def]) => [
1746
+ def._def,
1747
+ {
1748
+ def: def._def,
1749
+ path: [..._options.basePath, _options.definitionPath, name22],
1750
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1751
+ jsonSchema: void 0
1752
+ }
1753
+ ])
1754
+ )
584
1755
  });
1756
+ };
1757
+ var zod3ToJsonSchema = (schema, options) => {
1758
+ var _a22;
1759
+ const refs = getRefs(options);
1760
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1761
+ (acc, [name32, schema2]) => {
1762
+ var _a32;
1763
+ return __spreadProps(__spreadValues({}, acc), {
1764
+ [name32]: (_a32 = parseDef(
1765
+ schema2._def,
1766
+ __spreadProps(__spreadValues({}, refs), {
1767
+ currentPath: [...refs.basePath, refs.definitionPath, name32]
1768
+ }),
1769
+ true
1770
+ )) != null ? _a32 : parseAnyDef()
1771
+ });
1772
+ },
1773
+ {}
1774
+ ) : void 0;
1775
+ const name22 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1776
+ const main = (_a22 = parseDef(
1777
+ schema._def,
1778
+ name22 === void 0 ? refs : __spreadProps(__spreadValues({}, refs), {
1779
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
1780
+ }),
1781
+ false
1782
+ )) != null ? _a22 : parseAnyDef();
1783
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1784
+ if (title !== void 0) {
1785
+ main.title = title;
1786
+ }
1787
+ const combined = name22 === void 0 ? definitions ? __spreadProps(__spreadValues({}, main), {
1788
+ [refs.definitionPath]: definitions
1789
+ }) : main : {
1790
+ $ref: [
1791
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1792
+ refs.definitionPath,
1793
+ name22
1794
+ ].join("/"),
1795
+ [refs.definitionPath]: __spreadProps(__spreadValues({}, definitions), {
1796
+ [name22]: main
1797
+ })
1798
+ };
1799
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1800
+ return combined;
1801
+ };
1802
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1803
+ function jsonSchema(jsonSchema2, {
1804
+ validate
1805
+ } = {}) {
1806
+ return {
1807
+ [schemaSymbol]: true,
1808
+ _type: void 0,
1809
+ // should never be used directly
1810
+ get jsonSchema() {
1811
+ if (typeof jsonSchema2 === "function") {
1812
+ jsonSchema2 = jsonSchema2();
1813
+ }
1814
+ return jsonSchema2;
1815
+ },
1816
+ validate
1817
+ };
1818
+ }
1819
+ function isSchema(value) {
1820
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1821
+ }
1822
+ function asSchema(schema) {
1823
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
1824
+ }
1825
+ function standardSchema(standardSchema2) {
1826
+ return jsonSchema(
1827
+ () => standardSchema2["~standard"].jsonSchema.input({
1828
+ target: "draft-07"
1829
+ }),
1830
+ {
1831
+ validate: async (value) => {
1832
+ const result = await standardSchema2["~standard"].validate(value);
1833
+ return "value" in result ? { success: true, value: result.value } : {
1834
+ success: false,
1835
+ error: new TypeValidationError({
1836
+ value,
1837
+ cause: result.issues
1838
+ })
1839
+ };
1840
+ }
1841
+ }
1842
+ );
1843
+ }
1844
+ function zod3Schema(zodSchema2, options) {
1845
+ var _a22;
1846
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1847
+ return jsonSchema(
1848
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1849
+ () => zod3ToJsonSchema(zodSchema2, {
1850
+ $refStrategy: useReferences ? "root" : "none"
1851
+ }),
1852
+ {
1853
+ validate: async (value) => {
1854
+ const result = await zodSchema2.safeParseAsync(value);
1855
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1856
+ }
1857
+ }
1858
+ );
1859
+ }
1860
+ function zod4Schema(zodSchema2, options) {
1861
+ var _a22;
1862
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1863
+ return jsonSchema(
1864
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1865
+ () => addAdditionalPropertiesToJsonSchema(
1866
+ z4.toJSONSchema(zodSchema2, {
1867
+ target: "draft-7",
1868
+ io: "input",
1869
+ reused: useReferences ? "ref" : "inline"
1870
+ })
1871
+ ),
1872
+ {
1873
+ validate: async (value) => {
1874
+ const result = await z4.safeParseAsync(zodSchema2, value);
1875
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1876
+ }
1877
+ }
1878
+ );
1879
+ }
1880
+ function isZod4Schema(zodSchema2) {
1881
+ return "_zod" in zodSchema2;
1882
+ }
1883
+ function zodSchema(zodSchema2, options) {
1884
+ if (isZod4Schema(zodSchema2)) {
1885
+ return zod4Schema(zodSchema2, options);
1886
+ } else {
1887
+ return zod3Schema(zodSchema2, options);
1888
+ }
585
1889
  }
586
1890
  async function validateTypes({
587
1891
  value,
@@ -597,12 +1901,12 @@ async function safeValidateTypes({
597
1901
  value,
598
1902
  schema
599
1903
  }) {
600
- const validator2 = asValidator(schema);
1904
+ const actualSchema = asSchema(schema);
601
1905
  try {
602
- if (validator2.validate == null) {
1906
+ if (actualSchema.validate == null) {
603
1907
  return { success: true, value, rawValue: value };
604
1908
  }
605
- const result = await validator2.validate(value);
1909
+ const result = await actualSchema.validate(value);
606
1910
  if (result.success) {
607
1911
  return { success: true, value: result.value, rawValue: value };
608
1912
  }
@@ -685,7 +1989,7 @@ var postJsonToApi = async ({
685
1989
  failedResponseHandler,
686
1990
  successfulResponseHandler,
687
1991
  abortSignal,
688
- fetch
1992
+ fetch: fetch2
689
1993
  }) => postToApi({
690
1994
  url,
691
1995
  headers: __spreadValues({
@@ -698,7 +2002,7 @@ var postJsonToApi = async ({
698
2002
  failedResponseHandler,
699
2003
  successfulResponseHandler,
700
2004
  abortSignal,
701
- fetch
2005
+ fetch: fetch2
702
2006
  });
703
2007
  var postToApi = async ({
704
2008
  url,
@@ -707,12 +2011,16 @@ var postToApi = async ({
707
2011
  successfulResponseHandler,
708
2012
  failedResponseHandler,
709
2013
  abortSignal,
710
- fetch = getOriginalFetch2()
2014
+ fetch: fetch2 = getOriginalFetch2()
711
2015
  }) => {
712
2016
  try {
713
- const response = await fetch(url, {
2017
+ const response = await fetch2(url, {
714
2018
  method: "POST",
715
- headers: removeUndefinedEntries(headers),
2019
+ headers: withUserAgentSuffix(
2020
+ headers,
2021
+ `ai-sdk/provider-utils/${VERSION}`,
2022
+ getRuntimeEnvironmentUserAgent()
2023
+ ),
716
2024
  body: body.content,
717
2025
  signal: abortSignal
718
2026
  });
@@ -856,15 +2164,6 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
856
2164
  rawValue: parsedResult.rawValue
857
2165
  };
858
2166
  };
859
- var schemaSymbol = Symbol.for("vercel.ai.schema");
860
- var { btoa, atob } = globalThis;
861
- function convertUint8ArrayToBase64(array) {
862
- let latin1string = "";
863
- for (let i = 0; i < array.length; i++) {
864
- latin1string += String.fromCodePoint(array[i]);
865
- }
866
- return btoa(latin1string);
867
- }
868
2167
 
869
2168
  // src/schemas/error-response.ts
870
2169
  import { z as z2 } from "zod/v4";
@@ -916,10 +2215,10 @@ function getFileUrl({
916
2215
  part,
917
2216
  defaultMediaType
918
2217
  }) {
919
- var _a15, _b;
2218
+ var _a16, _b16;
920
2219
  if (part.data instanceof Uint8Array) {
921
2220
  const base64 = convertUint8ArrayToBase64(part.data);
922
- return `data:${(_a15 = part.mediaType) != null ? _a15 : defaultMediaType};base64,${base64}`;
2221
+ return `data:${(_a16 = part.mediaType) != null ? _a16 : defaultMediaType};base64,${base64}`;
923
2222
  }
924
2223
  const stringUrl = part.data.toString();
925
2224
  if (isUrl({
@@ -928,12 +2227,12 @@ function getFileUrl({
928
2227
  })) {
929
2228
  return stringUrl;
930
2229
  }
931
- return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b = part.mediaType) != null ? _b : defaultMediaType};base64,${stringUrl}`;
2230
+ return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b16 = part.mediaType) != null ? _b16 : defaultMediaType};base64,${stringUrl}`;
932
2231
  }
933
2232
  function getMediaType(dataUrl, defaultMediaType) {
934
- var _a15;
2233
+ var _a16;
935
2234
  const match = dataUrl.match(/^data:([^;]+)/);
936
- return match ? (_a15 = match[1]) != null ? _a15 : defaultMediaType : defaultMediaType;
2235
+ return match ? (_a16 = match[1]) != null ? _a16 : defaultMediaType : defaultMediaType;
937
2236
  }
938
2237
  function getBase64FromDataUrl(dataUrl) {
939
2238
  const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
@@ -941,14 +2240,14 @@ function getBase64FromDataUrl(dataUrl) {
941
2240
  }
942
2241
 
943
2242
  // src/chat/convert-to-llmgateway-chat-messages.ts
944
- function getCacheControl(providerMetadata) {
945
- var _a15, _b, _c;
946
- const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
947
- const llmgateway = providerMetadata == null ? void 0 : providerMetadata.llmgateway;
948
- return (_c = (_b = (_a15 = llmgateway == null ? void 0 : llmgateway.cacheControl) != null ? _a15 : llmgateway == null ? void 0 : llmgateway.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
2243
+ function getCacheControl(providerOptions) {
2244
+ var _a16, _b16, _c;
2245
+ const anthropic = providerOptions == null ? void 0 : providerOptions.anthropic;
2246
+ const llmgateway = providerOptions == null ? void 0 : providerOptions.llmgateway;
2247
+ return (_c = (_b16 = (_a16 = llmgateway == null ? void 0 : llmgateway.cacheControl) != null ? _a16 : llmgateway == null ? void 0 : llmgateway.cache_control) != null ? _b16 : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
949
2248
  }
950
2249
  function convertToLLMGatewayChatMessages(prompt) {
951
- var _a15, _b, _c;
2250
+ var _a16, _b16, _c;
952
2251
  const messages = [];
953
2252
  for (const { role, content, providerOptions } of prompt) {
954
2253
  switch (role) {
@@ -961,8 +2260,8 @@ function convertToLLMGatewayChatMessages(prompt) {
961
2260
  break;
962
2261
  }
963
2262
  case "user": {
964
- if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
965
- const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
2263
+ if (content.length === 1 && ((_a16 = content[0]) == null ? void 0 : _a16.type) === "text") {
2264
+ const cacheControl = (_b16 = getCacheControl(providerOptions)) != null ? _b16 : getCacheControl(content[0].providerOptions);
966
2265
  const contentWithCacheControl = cacheControl ? [
967
2266
  {
968
2267
  type: "text",
@@ -979,8 +2278,8 @@ function convertToLLMGatewayChatMessages(prompt) {
979
2278
  const messageCacheControl = getCacheControl(providerOptions);
980
2279
  const contentParts = content.map(
981
2280
  (part) => {
982
- var _a16, _b2, _c2, _d, _e, _f;
983
- const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
2281
+ var _a17, _b17, _c2, _d, _e, _f;
2282
+ const cacheControl = (_a17 = getCacheControl(part.providerOptions)) != null ? _a17 : messageCacheControl;
984
2283
  switch (part.type) {
985
2284
  case "text":
986
2285
  return {
@@ -990,7 +2289,7 @@ function convertToLLMGatewayChatMessages(prompt) {
990
2289
  cache_control: cacheControl
991
2290
  };
992
2291
  case "file": {
993
- if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
2292
+ if ((_b17 = part.mediaType) == null ? void 0 : _b17.startsWith("image/")) {
994
2293
  const url = getFileUrl({
995
2294
  part,
996
2295
  defaultMediaType: "image/jpeg"
@@ -1089,7 +2388,7 @@ function convertToLLMGatewayChatMessages(prompt) {
1089
2388
  role: "assistant",
1090
2389
  content: text,
1091
2390
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
1092
- reasoning: reasoning || void 0,
2391
+ reasoningText: reasoning || void 0,
1093
2392
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
1094
2393
  cache_control: getCacheControl(providerOptions)
1095
2394
  });
@@ -1194,6 +2493,7 @@ var LLMGatewayNonStreamChatCompletionResponseSchema = LLMGatewayChatCompletionBa
1194
2493
  role: z6.literal("assistant"),
1195
2494
  content: z6.string().nullable().optional(),
1196
2495
  reasoning: z6.string().nullable().optional(),
2496
+ reasoningText: z6.string().nullable().optional(),
1197
2497
  reasoning_details: ReasoningDetailArraySchema.nullish(),
1198
2498
  images: ImageResponseArraySchema.nullish(),
1199
2499
  tool_calls: z6.array(
@@ -1234,6 +2534,7 @@ var LLMGatewayStreamChatCompletionChunkSchema = z6.union([
1234
2534
  role: z6.enum(["assistant"]).optional(),
1235
2535
  content: z6.string().nullish(),
1236
2536
  reasoning: z6.string().nullish().optional(),
2537
+ reasoningText: z6.string().nullish().optional(),
1237
2538
  reasoning_details: ReasoningDetailArraySchema.nullish(),
1238
2539
  images: ImageResponseArraySchema.nullish(),
1239
2540
  tool_calls: z6.array(
@@ -1326,10 +2627,8 @@ var LLMGatewayChatLanguageModel = class {
1326
2627
  messages: convertToLLMGatewayChatMessages(prompt),
1327
2628
  // LLMGateway specific settings:
1328
2629
  include_reasoning: this.settings.includeReasoning,
1329
- reasoning: this.settings.reasoning,
1330
- reasoning_effort: this.settings.reasoning_effort,
1331
- usage: this.settings.usage,
1332
- image_config: this.settings.image_config
2630
+ reasoningText: this.settings.reasoningText,
2631
+ usage: this.settings.usage
1333
2632
  }, this.config.extraBody), this.settings.extraBody);
1334
2633
  if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
1335
2634
  if ("schema" in responseFormat && responseFormat.schema) {
@@ -1355,7 +2654,7 @@ var LLMGatewayChatLanguageModel = class {
1355
2654
  function: {
1356
2655
  name: tool.name,
1357
2656
  description: tool.type,
1358
- parameters: tool.inputSchema
2657
+ inputSchema: tool.inputSchema
1359
2658
  }
1360
2659
  }));
1361
2660
  return __spreadProps(__spreadValues({}, baseArgs), {
@@ -1366,10 +2665,11 @@ var LLMGatewayChatLanguageModel = class {
1366
2665
  return baseArgs;
1367
2666
  }
1368
2667
  async doGenerate(options) {
1369
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
2668
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
1370
2669
  const providerOptions = options.providerOptions || {};
1371
2670
  const llmgatewayOptions = providerOptions.llmgateway || {};
1372
2671
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), llmgatewayOptions);
2672
+ const includeUsageAccounting = ((_a16 = args.usage) == null ? void 0 : _a16.include) === true;
1373
2673
  const { value: response, responseHeaders } = await postJsonToApi({
1374
2674
  url: this.config.url({
1375
2675
  path: "/chat/completions",
@@ -1389,11 +2689,11 @@ var LLMGatewayChatLanguageModel = class {
1389
2689
  throw new Error("No choice in response");
1390
2690
  }
1391
2691
  const usageInfo = response.usage ? {
1392
- inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
1393
- outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
1394
- totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
1395
- reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
1396
- cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
2692
+ inputTokens: (_b16 = response.usage.prompt_tokens) != null ? _b16 : 0,
2693
+ outputTokens: (_c = response.usage.completion_tokens) != null ? _c : 0,
2694
+ totalTokens: ((_d = response.usage.prompt_tokens) != null ? _d : 0) + ((_e = response.usage.completion_tokens) != null ? _e : 0),
2695
+ reasoningTokens: (_g = (_f = response.usage.completion_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : 0,
2696
+ cachedInputTokens: (_i = (_h = response.usage.prompt_tokens_details) == null ? void 0 : _h.cached_tokens) != null ? _i : 0
1397
2697
  } : {
1398
2698
  inputTokens: 0,
1399
2699
  outputTokens: 0,
@@ -1401,7 +2701,7 @@ var LLMGatewayChatLanguageModel = class {
1401
2701
  reasoningTokens: 0,
1402
2702
  cachedInputTokens: 0
1403
2703
  };
1404
- const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
2704
+ const reasoningDetails = (_j = choice.message.reasoning_details) != null ? _j : [];
1405
2705
  const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
1406
2706
  switch (detail.type) {
1407
2707
  case "reasoning.text" /* Text */: {
@@ -1439,10 +2739,10 @@ var LLMGatewayChatLanguageModel = class {
1439
2739
  return null;
1440
2740
  }).filter(
1441
2741
  (p) => p !== null
1442
- ) : choice.message.reasoning ? [
2742
+ ) : choice.message.reasoningText ? [
1443
2743
  {
1444
2744
  type: "reasoning",
1445
- text: choice.message.reasoning
2745
+ text: choice.message.reasoningText
1446
2746
  }
1447
2747
  ] : [];
1448
2748
  const content = [];
@@ -1457,7 +2757,7 @@ var LLMGatewayChatLanguageModel = class {
1457
2757
  for (const toolCall of choice.message.tool_calls) {
1458
2758
  content.push({
1459
2759
  type: "tool-call",
1460
- toolCallId: (_j = toolCall.id) != null ? _j : generateId(),
2760
+ toolCallId: (_k = toolCall.id) != null ? _k : generateId(),
1461
2761
  toolName: toolCall.function.name,
1462
2762
  input: toolCall.function.arguments
1463
2763
  });
@@ -1482,7 +2782,7 @@ var LLMGatewayChatLanguageModel = class {
1482
2782
  url: annotation.url_citation.url,
1483
2783
  title: annotation.url_citation.title,
1484
2784
  providerMetadata: {
1485
- openrouter: {
2785
+ llmgateway: {
1486
2786
  content: annotation.url_citation.content || ""
1487
2787
  }
1488
2788
  }
@@ -1495,25 +2795,25 @@ var LLMGatewayChatLanguageModel = class {
1495
2795
  finishReason: mapLLMGatewayFinishReason(choice.finish_reason),
1496
2796
  usage: usageInfo,
1497
2797
  warnings: [],
1498
- providerMetadata: {
2798
+ providerMetadata: includeUsageAccounting ? {
1499
2799
  llmgateway: {
1500
2800
  usage: {
1501
- promptTokens: (_k = usageInfo.inputTokens) != null ? _k : 0,
1502
- completionTokens: (_l = usageInfo.outputTokens) != null ? _l : 0,
1503
- totalTokens: (_m = usageInfo.totalTokens) != null ? _m : 0,
1504
- cost: (_n = response.usage) == null ? void 0 : _n.cost,
2801
+ promptTokens: (_l = usageInfo.inputTokens) != null ? _l : 0,
2802
+ completionTokens: (_m = usageInfo.outputTokens) != null ? _m : 0,
2803
+ totalTokens: (_n = usageInfo.totalTokens) != null ? _n : 0,
2804
+ cost: (_o = response.usage) == null ? void 0 : _o.cost,
1505
2805
  promptTokensDetails: {
1506
- cachedTokens: (_q = (_p = (_o = response.usage) == null ? void 0 : _o.prompt_tokens_details) == null ? void 0 : _p.cached_tokens) != null ? _q : 0
2806
+ cachedTokens: (_r = (_q = (_p = response.usage) == null ? void 0 : _p.prompt_tokens_details) == null ? void 0 : _q.cached_tokens) != null ? _r : 0
1507
2807
  },
1508
2808
  completionTokensDetails: {
1509
- reasoningTokens: (_t = (_s = (_r = response.usage) == null ? void 0 : _r.completion_tokens_details) == null ? void 0 : _s.reasoning_tokens) != null ? _t : 0
2809
+ reasoningTokens: (_u = (_t = (_s = response.usage) == null ? void 0 : _s.completion_tokens_details) == null ? void 0 : _t.reasoning_tokens) != null ? _u : 0
1510
2810
  },
1511
2811
  costDetails: {
1512
- upstreamInferenceCost: (_w = (_v = (_u = response.usage) == null ? void 0 : _u.cost_details) == null ? void 0 : _v.upstream_inference_cost) != null ? _w : 0
2812
+ upstreamInferenceCost: (_x = (_w = (_v = response.usage) == null ? void 0 : _v.cost_details) == null ? void 0 : _w.upstream_inference_cost) != null ? _x : 0
1513
2813
  }
1514
2814
  }
1515
2815
  }
1516
- },
2816
+ } : void 0,
1517
2817
  request: { body: args },
1518
2818
  response: {
1519
2819
  id: response.id,
@@ -1523,7 +2823,6 @@ var LLMGatewayChatLanguageModel = class {
1523
2823
  };
1524
2824
  }
1525
2825
  async doStream(options) {
1526
- var _a15;
1527
2826
  const providerOptions = options.providerOptions || {};
1528
2827
  const llmgatewayOptions = providerOptions.llmgateway || {};
1529
2828
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), llmgatewayOptions);
@@ -1536,9 +2835,7 @@ var LLMGatewayChatLanguageModel = class {
1536
2835
  body: __spreadProps(__spreadValues({}, args), {
1537
2836
  stream: true,
1538
2837
  // only include stream_options when in strict compatibility mode:
1539
- stream_options: this.config.compatibility === "strict" ? __spreadValues({
1540
- include_usage: true
1541
- }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
2838
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
1542
2839
  }),
1543
2840
  failedResponseHandler: llmgatewayFailedResponseHandler,
1544
2841
  successfulResponseHandler: createEventSourceResponseHandler(
@@ -1566,7 +2863,7 @@ var LLMGatewayChatLanguageModel = class {
1566
2863
  stream: response.pipeThrough(
1567
2864
  new TransformStream({
1568
2865
  transform(chunk, controller) {
1569
- var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
2866
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1570
2867
  if (!chunk.success) {
1571
2868
  finishReason = "error";
1572
2869
  controller.enqueue({ type: "error", error: chunk.error });
@@ -1605,7 +2902,7 @@ var LLMGatewayChatLanguageModel = class {
1605
2902
  }
1606
2903
  llmgatewayUsage.completionTokens = value.usage.completion_tokens;
1607
2904
  if (value.usage.completion_tokens_details) {
1608
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
2905
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
1609
2906
  usage.reasoningTokens = reasoningTokens;
1610
2907
  llmgatewayUsage.completionTokensDetails = {
1611
2908
  reasoningTokens
@@ -1664,8 +2961,10 @@ var LLMGatewayChatLanguageModel = class {
1664
2961
  }
1665
2962
  }
1666
2963
  }
1667
- } else if (delta.reasoning != null) {
1668
- emitReasoningChunk(delta.reasoning);
2964
+ } else if (delta.reasoningText != null || "reasoning" in delta && typeof delta.reasoning === "string") {
2965
+ emitReasoningChunk(
2966
+ (_d = (_c = delta.reasoningText) != null ? _c : "reasoning" in delta && typeof delta.reasoning === "string" ? delta.reasoning : void 0) != null ? _d : ""
2967
+ );
1669
2968
  }
1670
2969
  if (delta.content != null) {
1671
2970
  if (!textStarted) {
@@ -1684,7 +2983,7 @@ var LLMGatewayChatLanguageModel = class {
1684
2983
  }
1685
2984
  if (delta.tool_calls != null) {
1686
2985
  for (const toolCallDelta of delta.tool_calls) {
1687
- const index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length - 1;
2986
+ const index = (_e = toolCallDelta.index) != null ? _e : toolCalls.length - 1;
1688
2987
  if (toolCalls[index] == null) {
1689
2988
  if (toolCallDelta.type !== "function") {
1690
2989
  throw new InvalidResponseDataError({
@@ -1698,7 +2997,7 @@ var LLMGatewayChatLanguageModel = class {
1698
2997
  message: `Expected 'id' to be a string.`
1699
2998
  });
1700
2999
  }
1701
- if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) {
3000
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.name) == null) {
1702
3001
  throw new InvalidResponseDataError({
1703
3002
  data: toolCallDelta,
1704
3003
  message: `Expected 'function.name' to be a string.`
@@ -1709,7 +3008,7 @@ var LLMGatewayChatLanguageModel = class {
1709
3008
  type: "function",
1710
3009
  function: {
1711
3010
  name: toolCallDelta.function.name,
1712
- arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
3011
+ arguments: (_g = toolCallDelta.function.arguments) != null ? _g : ""
1713
3012
  },
1714
3013
  inputStarted: false,
1715
3014
  sent: false
@@ -1718,7 +3017,7 @@ var LLMGatewayChatLanguageModel = class {
1718
3017
  if (toolCall2 == null) {
1719
3018
  throw new Error("Tool call is missing");
1720
3019
  }
1721
- if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
3020
+ if (((_h = toolCall2.function) == null ? void 0 : _h.name) != null && ((_i = toolCall2.function) == null ? void 0 : _i.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
1722
3021
  toolCall2.inputStarted = true;
1723
3022
  controller.enqueue({
1724
3023
  type: "tool-input-start",
@@ -1756,18 +3055,18 @@ var LLMGatewayChatLanguageModel = class {
1756
3055
  toolName: toolCall.function.name
1757
3056
  });
1758
3057
  }
1759
- if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
1760
- toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
3058
+ if (((_j = toolCallDelta.function) == null ? void 0 : _j.arguments) != null) {
3059
+ toolCall.function.arguments += (_l = (_k = toolCallDelta.function) == null ? void 0 : _k.arguments) != null ? _l : "";
1761
3060
  }
1762
3061
  controller.enqueue({
1763
3062
  type: "tool-input-delta",
1764
3063
  id: toolCall.id,
1765
- delta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
3064
+ delta: (_m = toolCallDelta.function.arguments) != null ? _m : ""
1766
3065
  });
1767
- if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson(toolCall.function.arguments)) {
3066
+ if (((_n = toolCall.function) == null ? void 0 : _n.name) != null && ((_o = toolCall.function) == null ? void 0 : _o.arguments) != null && isParsableJson(toolCall.function.arguments)) {
1768
3067
  controller.enqueue({
1769
3068
  type: "tool-call",
1770
- toolCallId: (_n = toolCall.id) != null ? _n : generateId(),
3069
+ toolCallId: (_p = toolCall.id) != null ? _p : generateId(),
1771
3070
  toolName: toolCall.function.name,
1772
3071
  input: toolCall.function.arguments
1773
3072
  });
@@ -1945,7 +3244,7 @@ var LLMGatewayCompletionChunkSchema = z7.union([
1945
3244
  choices: z7.array(
1946
3245
  z7.object({
1947
3246
  text: z7.string(),
1948
- reasoning: z7.string().nullish().optional(),
3247
+ reasoningText: z7.string().nullish().optional(),
1949
3248
  reasoning_details: ReasoningDetailArraySchema.nullish(),
1950
3249
  finish_reason: z7.string().nullish(),
1951
3250
  index: z7.number().nullish(),
@@ -2041,13 +3340,11 @@ var LLMGatewayCompletionLanguageModel = class {
2041
3340
  prompt: completionPrompt,
2042
3341
  // LLMGateway specific settings:
2043
3342
  include_reasoning: this.settings.includeReasoning,
2044
- reasoning: this.settings.reasoning,
2045
- reasoning_effort: this.settings.reasoning_effort,
2046
- image_config: this.settings.image_config
3343
+ reasoningText: this.settings.reasoningText
2047
3344
  }, this.config.extraBody), this.settings.extraBody);
2048
3345
  }
2049
3346
  async doGenerate(options) {
2050
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
3347
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
2051
3348
  const providerOptions = options.providerOptions || {};
2052
3349
  const llmgatewayOptions = providerOptions.llmgateway || {};
2053
3350
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), llmgatewayOptions);
@@ -2076,12 +3373,12 @@ var LLMGatewayCompletionLanguageModel = class {
2076
3373
  content: [
2077
3374
  {
2078
3375
  type: "text",
2079
- text: (_a15 = choice.text) != null ? _a15 : ""
3376
+ text: (_a16 = choice.text) != null ? _a16 : ""
2080
3377
  }
2081
3378
  ],
2082
3379
  finishReason: mapLLMGatewayFinishReason(choice.finish_reason),
2083
3380
  usage: {
2084
- inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
3381
+ inputTokens: (_c = (_b16 = response.usage) == null ? void 0 : _b16.prompt_tokens) != null ? _c : 0,
2085
3382
  outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
2086
3383
  totalTokens: ((_g = (_f = response.usage) == null ? void 0 : _f.prompt_tokens) != null ? _g : 0) + ((_i = (_h = response.usage) == null ? void 0 : _h.completion_tokens) != null ? _i : 0),
2087
3384
  reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
@@ -2128,7 +3425,7 @@ var LLMGatewayCompletionLanguageModel = class {
2128
3425
  stream: response.pipeThrough(
2129
3426
  new TransformStream({
2130
3427
  transform(chunk, controller) {
2131
- var _a15, _b;
3428
+ var _a16, _b16;
2132
3429
  if (!chunk.success) {
2133
3430
  finishReason = "error";
2134
3431
  controller.enqueue({ type: "error", error: chunk.error });
@@ -2146,7 +3443,7 @@ var LLMGatewayCompletionLanguageModel = class {
2146
3443
  usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
2147
3444
  llmgatewayUsage.promptTokens = value.usage.prompt_tokens;
2148
3445
  if (value.usage.prompt_tokens_details) {
2149
- const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
3446
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
2150
3447
  usage.cachedInputTokens = cachedInputTokens;
2151
3448
  llmgatewayUsage.promptTokensDetails = {
2152
3449
  cachedTokens: cachedInputTokens
@@ -2154,7 +3451,7 @@ var LLMGatewayCompletionLanguageModel = class {
2154
3451
  }
2155
3452
  llmgatewayUsage.completionTokens = value.usage.completion_tokens;
2156
3453
  if (value.usage.completion_tokens_details) {
2157
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
3454
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
2158
3455
  usage.reasoningTokens = reasoningTokens;
2159
3456
  llmgatewayUsage.completionTokensDetails = {
2160
3457
  reasoningTokens
@@ -2411,7 +3708,7 @@ var alibabaModels = [
2411
3708
  requestPrice: 0,
2412
3709
  contextSize: 262e3,
2413
3710
  maxOutput: 8192,
2414
- reasoning: false,
3711
+ reasoningText: false,
2415
3712
  streaming: true,
2416
3713
  vision: false,
2417
3714
  tools: true
@@ -2434,7 +3731,7 @@ var alibabaModels = [
2434
3731
  requestPrice: 0,
2435
3732
  contextSize: 262e3,
2436
3733
  maxOutput: 8192,
2437
- reasoning: true,
3734
+ reasoningText: true,
2438
3735
  streaming: true,
2439
3736
  vision: false,
2440
3737
  tools: true
@@ -2702,7 +3999,7 @@ var alibabaModels = [
2702
3999
  streaming: true,
2703
4000
  vision: false,
2704
4001
  tools: true,
2705
- reasoning: true
4002
+ reasoningText: true
2706
4003
  }
2707
4004
  ],
2708
4005
  jsonOutput: true
@@ -2766,7 +4063,7 @@ var alibabaModels = [
2766
4063
  requestPrice: 0,
2767
4064
  contextSize: 131072,
2768
4065
  maxOutput: 32768,
2769
- reasoning: true,
4066
+ reasoningText: true,
2770
4067
  reasoningOutput: "omit",
2771
4068
  streaming: true,
2772
4069
  vision: false,
@@ -2813,7 +4110,7 @@ var alibabaModels = [
2813
4110
  requestPrice: 0,
2814
4111
  contextSize: 256e3,
2815
4112
  maxOutput: 32800,
2816
- reasoning: true,
4113
+ reasoningText: true,
2817
4114
  reasoningOutput: "omit",
2818
4115
  streaming: true,
2819
4116
  vision: true,
@@ -2866,7 +4163,7 @@ var anthropicModels = [
2866
4163
  maxOutput: 8192,
2867
4164
  streaming: true,
2868
4165
  vision: false,
2869
- reasoning: true,
4166
+ reasoningText: true,
2870
4167
  tools: true
2871
4168
  }
2872
4169
  ]
@@ -2976,7 +4273,7 @@ var anthropicModels = [
2976
4273
  maxOutput: 32e3,
2977
4274
  streaming: true,
2978
4275
  vision: true,
2979
- reasoning: true,
4276
+ reasoningText: true,
2980
4277
  tools: true
2981
4278
  }
2982
4279
  ]
@@ -3581,7 +4878,7 @@ var googleModels = [
3581
4878
  contextSize: 1e6,
3582
4879
  maxOutput: void 0,
3583
4880
  streaming: true,
3584
- reasoning: false,
4881
+ reasoningText: false,
3585
4882
  vision: false,
3586
4883
  tools: false
3587
4884
  }
@@ -3603,7 +4900,7 @@ var googleModels = [
3603
4900
  contextSize: 1e6,
3604
4901
  maxOutput: void 0,
3605
4902
  streaming: true,
3606
- reasoning: false,
4903
+ reasoningText: false,
3607
4904
  vision: false,
3608
4905
  tools: false
3609
4906
  }
@@ -4329,7 +5626,7 @@ var openaiModels = [
4329
5626
  maxOutput: void 0,
4330
5627
  streaming: true,
4331
5628
  vision: true,
4332
- reasoning: true,
5629
+ reasoningText: true,
4333
5630
  tools: false
4334
5631
  }
4335
5632
  ],
@@ -4353,7 +5650,7 @@ var openaiModels = [
4353
5650
  streaming: false,
4354
5651
  vision: false,
4355
5652
  tools: false,
4356
- reasoning: false,
5653
+ reasoningText: false,
4357
5654
  supportsResponsesApi: false
4358
5655
  }
4359
5656
  ],
@@ -4468,7 +5765,7 @@ var openaiModels = [
4468
5765
  streaming: true,
4469
5766
  vision: false,
4470
5767
  tools: true,
4471
- reasoning: true
5768
+ reasoningText: true
4472
5769
  }
4473
5770
  ],
4474
5771
  jsonOutput: true
@@ -4491,7 +5788,7 @@ var openaiModels = [
4491
5788
  streaming: true,
4492
5789
  vision: false,
4493
5790
  tools: true,
4494
- reasoning: true
5791
+ reasoningText: true
4495
5792
  }
4496
5793
  ],
4497
5794
  jsonOutput: true
@@ -4512,7 +5809,7 @@ var openaiModels = [
4512
5809
  requestPrice: 0,
4513
5810
  contextSize: 4e5,
4514
5811
  maxOutput: 128e3,
4515
- reasoning: true,
5812
+ reasoningText: true,
4516
5813
  streaming: true,
4517
5814
  vision: true,
4518
5815
  tools: true,
@@ -4545,7 +5842,7 @@ var openaiModels = [
4545
5842
  requestPrice: 0,
4546
5843
  contextSize: 4e5,
4547
5844
  maxOutput: 128e3,
4548
- reasoning: true,
5845
+ reasoningText: true,
4549
5846
  streaming: true,
4550
5847
  vision: true,
4551
5848
  tools: true,
@@ -4578,7 +5875,7 @@ var openaiModels = [
4578
5875
  requestPrice: 0,
4579
5876
  contextSize: 4e5,
4580
5877
  maxOutput: 128e3,
4581
- reasoning: true,
5878
+ reasoningText: true,
4582
5879
  streaming: true,
4583
5880
  vision: false,
4584
5881
  tools: true,
@@ -5114,7 +6411,7 @@ var zaiModels = [
5114
6411
  contextSize: 128e3,
5115
6412
  maxOutput: void 0,
5116
6413
  streaming: true,
5117
- reasoning: true,
6414
+ reasoningText: true,
5118
6415
  vision: false,
5119
6416
  tools: true
5120
6417
  }
@@ -5137,7 +6434,7 @@ var zaiModels = [
5137
6434
  contextSize: 128e3,
5138
6435
  maxOutput: void 0,
5139
6436
  streaming: true,
5140
- reasoning: true,
6437
+ reasoningText: true,
5141
6438
  reasoningOutput: "omit",
5142
6439
  vision: true,
5143
6440
  tools: true
@@ -5161,7 +6458,7 @@ var zaiModels = [
5161
6458
  contextSize: 128e3,
5162
6459
  maxOutput: void 0,
5163
6460
  streaming: true,
5164
- reasoning: false,
6461
+ reasoningText: false,
5165
6462
  vision: false,
5166
6463
  tools: true
5167
6464
  }
@@ -5184,7 +6481,7 @@ var zaiModels = [
5184
6481
  contextSize: 128e3,
5185
6482
  maxOutput: void 0,
5186
6483
  streaming: true,
5187
- reasoning: true,
6484
+ reasoningText: true,
5188
6485
  vision: false,
5189
6486
  tools: true
5190
6487
  }
@@ -5207,7 +6504,7 @@ var zaiModels = [
5207
6504
  contextSize: 128e3,
5208
6505
  maxOutput: void 0,
5209
6506
  streaming: true,
5210
- reasoning: false,
6507
+ reasoningText: false,
5211
6508
  vision: false,
5212
6509
  tools: true
5213
6510
  }
@@ -5230,7 +6527,7 @@ var zaiModels = [
5230
6527
  contextSize: 128e3,
5231
6528
  maxOutput: void 0,
5232
6529
  streaming: true,
5233
- reasoning: false,
6530
+ reasoningText: false,
5234
6531
  vision: false,
5235
6532
  tools: true
5236
6533
  }
@@ -5253,7 +6550,7 @@ var zaiModels = [
5253
6550
  contextSize: 128e3,
5254
6551
  maxOutput: void 0,
5255
6552
  streaming: true,
5256
- reasoning: false,
6553
+ reasoningText: false,
5257
6554
  vision: false,
5258
6555
  tools: true
5259
6556
  }