@mastra/schema-compat 0.0.0-vector-query-tool-provider-options-20250828222356 → 0.0.0-vnext-20251104230439

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/dist/chunk-5WM4A32G.cjs +83 -0
  3. package/dist/chunk-5WM4A32G.cjs.map +1 -0
  4. package/dist/chunk-U2HXWNAF.js +77 -0
  5. package/dist/chunk-U2HXWNAF.js.map +1 -0
  6. package/dist/index.cjs +3652 -122
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +12 -10
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +3652 -123
  11. package/dist/index.js.map +1 -1
  12. package/dist/json-schema.d.ts +4 -0
  13. package/dist/json-schema.d.ts.map +1 -0
  14. package/dist/provider-compats/anthropic.d.ts +2 -2
  15. package/dist/provider-compats/deepseek.d.ts +2 -2
  16. package/dist/provider-compats/google.d.ts +2 -2
  17. package/dist/provider-compats/meta.d.ts +2 -2
  18. package/dist/provider-compats/openai-reasoning.d.ts +2 -2
  19. package/dist/provider-compats/openai-reasoning.d.ts.map +1 -1
  20. package/dist/provider-compats/openai.d.ts +2 -2
  21. package/dist/schema-compatibility-v3.d.ts +5 -37
  22. package/dist/schema-compatibility-v3.d.ts.map +1 -1
  23. package/dist/schema-compatibility-v4.d.ts +5 -37
  24. package/dist/schema-compatibility-v4.d.ts.map +1 -1
  25. package/dist/schema-compatibility.d.ts +6 -38
  26. package/dist/schema-compatibility.d.ts.map +1 -1
  27. package/dist/types.d.ts +1 -0
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/utils-test-suite.d.ts.map +1 -1
  30. package/dist/utils.d.ts +3 -3
  31. package/dist/utils.d.ts.map +1 -1
  32. package/dist/zod-to-json-test-suite.d.ts +6 -0
  33. package/dist/zod-to-json-test-suite.d.ts.map +1 -0
  34. package/dist/zod-to-json.cjs +2 -2
  35. package/dist/zod-to-json.d.ts +1 -1
  36. package/dist/zod-to-json.d.ts.map +1 -1
  37. package/dist/zod-to-json.js +1 -1
  38. package/package.json +20 -7
  39. package/.turbo/turbo-build.log +0 -4
  40. package/dist/chunk-MKYBUMTK.js +0 -27
  41. package/dist/chunk-MKYBUMTK.js.map +0 -1
  42. package/dist/chunk-V7Y3FXBJ.cjs +0 -33
  43. package/dist/chunk-V7Y3FXBJ.cjs.map +0 -1
  44. package/eslint.config.js +0 -6
  45. package/src/index.ts +0 -40
  46. package/src/provider-compats/anthropic.ts +0 -61
  47. package/src/provider-compats/deepseek.ts +0 -40
  48. package/src/provider-compats/google.ts +0 -49
  49. package/src/provider-compats/meta.ts +0 -41
  50. package/src/provider-compats/openai-reasoning.ts +0 -85
  51. package/src/provider-compats/openai.ts +0 -65
  52. package/src/provider-compats.test.ts +0 -407
  53. package/src/schema-compatibility-v3.ts +0 -664
  54. package/src/schema-compatibility-v4.test.ts +0 -476
  55. package/src/schema-compatibility-v4.ts +0 -706
  56. package/src/schema-compatibility.test.ts +0 -471
  57. package/src/schema-compatibility.ts +0 -471
  58. package/src/types.ts +0 -5
  59. package/src/utils-test-suite.ts +0 -467
  60. package/src/utils-v3.test.ts +0 -9
  61. package/src/utils-v4.test.ts +0 -9
  62. package/src/utils.ts +0 -211
  63. package/src/zod-to-json.ts +0 -28
  64. package/src/zodTypes.ts +0 -56
  65. package/tsconfig.build.json +0 -9
  66. package/tsconfig.json +0 -5
  67. package/tsup.config.ts +0 -22
  68. package/vitest.config.ts +0 -7
package/dist/index.cjs CHANGED
@@ -1,17 +1,3577 @@
1
1
  'use strict';
2
2
 
3
- var chunkV7Y3FXBJ_cjs = require('./chunk-V7Y3FXBJ.cjs');
3
+ var chunk5WM4A32G_cjs = require('./chunk-5WM4A32G.cjs');
4
4
  var zod = require('zod');
5
- var ai = require('ai');
6
5
  var zodFromJsonSchema = require('zod-from-json-schema');
7
6
  var zodFromJsonSchemaV3 = require('zod-from-json-schema-v3');
8
7
  var v4 = require('zod/v4');
9
8
 
10
- function convertZodSchemaToAISDKSchema(zodSchema, target = "jsonSchema7") {
11
- const jsonSchemaToUse = chunkV7Y3FXBJ_cjs.zodToJsonSchema(zodSchema, target);
12
- return ai.jsonSchema(jsonSchemaToUse, {
9
+ // ../_ai-sdk-v4/dist/chunk-EDUQOWHB.js
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __commonJS = (cb, mod) => function __require() {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
+ // If the importer is in node compatibility mode or this is not an ESM
29
+ // file that has been converted to a CommonJS file using a Babel-
30
+ // compatible transform (i.e. "__esModule" has not been set), then set
31
+ // "default" to the CommonJS "module.exports" for node compatibility.
32
+ __defProp(target, "default", { value: mod, enumerable: true }),
33
+ mod
34
+ ));
35
+ var require_secure_json_parse = __commonJS({
36
+ "../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports, module) {
37
+ var hasBuffer = typeof Buffer !== "undefined";
38
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
39
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
40
+ function _parse(text2, reviver, options) {
41
+ if (options == null) {
42
+ if (reviver !== null && typeof reviver === "object") {
43
+ options = reviver;
44
+ reviver = void 0;
45
+ }
46
+ }
47
+ if (hasBuffer && Buffer.isBuffer(text2)) {
48
+ text2 = text2.toString();
49
+ }
50
+ if (text2 && text2.charCodeAt(0) === 65279) {
51
+ text2 = text2.slice(1);
52
+ }
53
+ const obj = JSON.parse(text2, reviver);
54
+ if (obj === null || typeof obj !== "object") {
55
+ return obj;
56
+ }
57
+ const protoAction = options && options.protoAction || "error";
58
+ const constructorAction = options && options.constructorAction || "error";
59
+ if (protoAction === "ignore" && constructorAction === "ignore") {
60
+ return obj;
61
+ }
62
+ if (protoAction !== "ignore" && constructorAction !== "ignore") {
63
+ if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
64
+ return obj;
65
+ }
66
+ } else if (protoAction !== "ignore" && constructorAction === "ignore") {
67
+ if (suspectProtoRx.test(text2) === false) {
68
+ return obj;
69
+ }
70
+ } else {
71
+ if (suspectConstructorRx.test(text2) === false) {
72
+ return obj;
73
+ }
74
+ }
75
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
76
+ }
77
+ function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
78
+ let next = [obj];
79
+ while (next.length) {
80
+ const nodes = next;
81
+ next = [];
82
+ for (const node of nodes) {
83
+ if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
84
+ if (safe === true) {
85
+ return null;
86
+ } else if (protoAction === "error") {
87
+ throw new SyntaxError("Object contains forbidden prototype property");
88
+ }
89
+ delete node.__proto__;
90
+ }
91
+ if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
92
+ if (safe === true) {
93
+ return null;
94
+ } else if (constructorAction === "error") {
95
+ throw new SyntaxError("Object contains forbidden prototype property");
96
+ }
97
+ delete node.constructor;
98
+ }
99
+ for (const key in node) {
100
+ const value = node[key];
101
+ if (value && typeof value === "object") {
102
+ next.push(value);
103
+ }
104
+ }
105
+ }
106
+ }
107
+ return obj;
108
+ }
109
+ function parse(text2, reviver, options) {
110
+ const stackTraceLimit = Error.stackTraceLimit;
111
+ Error.stackTraceLimit = 0;
112
+ try {
113
+ return _parse(text2, reviver, options);
114
+ } finally {
115
+ Error.stackTraceLimit = stackTraceLimit;
116
+ }
117
+ }
118
+ function safeParse(text2, reviver) {
119
+ const stackTraceLimit = Error.stackTraceLimit;
120
+ Error.stackTraceLimit = 0;
121
+ try {
122
+ return _parse(text2, reviver, { safe: true });
123
+ } catch (_e) {
124
+ return null;
125
+ } finally {
126
+ Error.stackTraceLimit = stackTraceLimit;
127
+ }
128
+ }
129
+ module.exports = parse;
130
+ module.exports.default = parse;
131
+ module.exports.parse = parse;
132
+ module.exports.safeParse = safeParse;
133
+ module.exports.scan = filter;
134
+ }
135
+ });
136
+ var marker = "vercel.ai.error";
137
+ var symbol = Symbol.for(marker);
138
+ var _a;
139
+ var _AISDKError = class _AISDKError2 extends Error {
140
+ /**
141
+ * Creates an AI SDK Error.
142
+ *
143
+ * @param {Object} params - The parameters for creating the error.
144
+ * @param {string} params.name - The name of the error.
145
+ * @param {string} params.message - The error message.
146
+ * @param {unknown} [params.cause] - The underlying cause of the error.
147
+ */
148
+ constructor({
149
+ name: name142,
150
+ message,
151
+ cause
152
+ }) {
153
+ super(message);
154
+ this[_a] = true;
155
+ this.name = name142;
156
+ this.cause = cause;
157
+ }
158
+ /**
159
+ * Checks if the given error is an AI SDK Error.
160
+ * @param {unknown} error - The error to check.
161
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
162
+ */
163
+ static isInstance(error) {
164
+ return _AISDKError2.hasMarker(error, marker);
165
+ }
166
+ static hasMarker(error, marker15) {
167
+ const markerSymbol = Symbol.for(marker15);
168
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
169
+ }
170
+ };
171
+ _a = symbol;
172
+ var AISDKError = _AISDKError;
173
+ function getErrorMessage(error) {
174
+ if (error == null) {
175
+ return "unknown error";
176
+ }
177
+ if (typeof error === "string") {
178
+ return error;
179
+ }
180
+ if (error instanceof Error) {
181
+ return error.message;
182
+ }
183
+ return JSON.stringify(error);
184
+ }
185
+ var name3 = "AI_InvalidArgumentError";
186
+ var marker4 = `vercel.ai.error.${name3}`;
187
+ var symbol4 = Symbol.for(marker4);
188
+ var _a4;
189
+ var InvalidArgumentError = class extends AISDKError {
190
+ constructor({
191
+ message,
192
+ cause,
193
+ argument
194
+ }) {
195
+ super({ name: name3, message, cause });
196
+ this[_a4] = true;
197
+ this.argument = argument;
198
+ }
199
+ static isInstance(error) {
200
+ return AISDKError.hasMarker(error, marker4);
201
+ }
202
+ };
203
+ _a4 = symbol4;
204
+ var name6 = "AI_JSONParseError";
205
+ var marker7 = `vercel.ai.error.${name6}`;
206
+ var symbol7 = Symbol.for(marker7);
207
+ var _a7;
208
+ var JSONParseError = class extends AISDKError {
209
+ constructor({ text: text2, cause }) {
210
+ super({
211
+ name: name6,
212
+ message: `JSON parsing failed: Text: ${text2}.
213
+ Error message: ${getErrorMessage(cause)}`,
214
+ cause
215
+ });
216
+ this[_a7] = true;
217
+ this.text = text2;
218
+ }
219
+ static isInstance(error) {
220
+ return AISDKError.hasMarker(error, marker7);
221
+ }
222
+ };
223
+ _a7 = symbol7;
224
+ var name12 = "AI_TypeValidationError";
225
+ var marker13 = `vercel.ai.error.${name12}`;
226
+ var symbol13 = Symbol.for(marker13);
227
+ var _a13;
228
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
229
+ constructor({ value, cause }) {
230
+ super({
231
+ name: name12,
232
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
233
+ Error message: ${getErrorMessage(cause)}`,
234
+ cause
235
+ });
236
+ this[_a13] = true;
237
+ this.value = value;
238
+ }
239
+ static isInstance(error) {
240
+ return AISDKError.hasMarker(error, marker13);
241
+ }
242
+ /**
243
+ * Wraps an error into a TypeValidationError.
244
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
245
+ * Otherwise, it creates a new TypeValidationError.
246
+ *
247
+ * @param {Object} params - The parameters for wrapping the error.
248
+ * @param {unknown} params.value - The value that failed validation.
249
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
250
+ * @returns {TypeValidationError} A TypeValidationError instance.
251
+ */
252
+ static wrap({
253
+ value,
254
+ cause
255
+ }) {
256
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
257
+ }
258
+ };
259
+ _a13 = symbol13;
260
+ var TypeValidationError = _TypeValidationError;
261
+ var customAlphabet = (alphabet, defaultSize = 21) => {
262
+ return (size = defaultSize) => {
263
+ let id = "";
264
+ let i = size | 0;
265
+ while (i--) {
266
+ id += alphabet[Math.random() * alphabet.length | 0];
267
+ }
268
+ return id;
269
+ };
270
+ };
271
+ var import_secure_json_parse = __toESM(require_secure_json_parse());
272
+ function convertAsyncIteratorToReadableStream(iterator) {
273
+ return new ReadableStream({
274
+ /**
275
+ * Called when the consumer wants to pull more data from the stream.
276
+ *
277
+ * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
278
+ * @returns {Promise<void>}
279
+ */
280
+ async pull(controller) {
281
+ try {
282
+ const { value, done } = await iterator.next();
283
+ if (done) {
284
+ controller.close();
285
+ } else {
286
+ controller.enqueue(value);
287
+ }
288
+ } catch (error) {
289
+ controller.error(error);
290
+ }
291
+ },
292
+ /**
293
+ * Called when the consumer cancels the stream.
294
+ */
295
+ cancel() {
296
+ }
297
+ });
298
+ }
299
+ var createIdGenerator = ({
300
+ prefix,
301
+ size: defaultSize = 16,
302
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
303
+ separator = "-"
304
+ } = {}) => {
305
+ const generator = customAlphabet(alphabet, defaultSize);
306
+ if (prefix == null) {
307
+ return generator;
308
+ }
309
+ if (alphabet.includes(separator)) {
310
+ throw new InvalidArgumentError({
311
+ argument: "separator",
312
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
313
+ });
314
+ }
315
+ return (size) => `${prefix}${separator}${generator(size)}`;
316
+ };
317
+ createIdGenerator();
318
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
319
+ function validator(validate) {
320
+ return { [validatorSymbol]: true, validate };
321
+ }
322
+ function isValidator(value) {
323
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
324
+ }
325
+ function asValidator(value) {
326
+ return isValidator(value) ? value : zodValidator(value);
327
+ }
328
+ function zodValidator(zodSchema2) {
329
+ return validator((value) => {
330
+ const result = zodSchema2.safeParse(value);
331
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
332
+ });
333
+ }
334
+ function safeValidateTypes({
335
+ value,
336
+ schema
337
+ }) {
338
+ const validator2 = asValidator(schema);
339
+ try {
340
+ if (validator2.validate == null) {
341
+ return { success: true, value };
342
+ }
343
+ const result = validator2.validate(value);
344
+ if (result.success) {
345
+ return result;
346
+ }
347
+ return {
348
+ success: false,
349
+ error: TypeValidationError.wrap({ value, cause: result.error })
350
+ };
351
+ } catch (error) {
352
+ return {
353
+ success: false,
354
+ error: TypeValidationError.wrap({ value, cause: error })
355
+ };
356
+ }
357
+ }
358
+ function safeParseJSON({
359
+ text: text2,
360
+ schema
361
+ }) {
362
+ try {
363
+ const value = import_secure_json_parse.default.parse(text2);
364
+ if (schema == null) {
365
+ return { success: true, value, rawValue: value };
366
+ }
367
+ const validationResult = safeValidateTypes({ value, schema });
368
+ return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
369
+ } catch (error) {
370
+ return {
371
+ success: false,
372
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error })
373
+ };
374
+ }
375
+ }
376
+ var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
377
+ var defaultOptions = {
378
+ name: void 0,
379
+ $refStrategy: "root",
380
+ basePath: ["#"],
381
+ effectStrategy: "input",
382
+ pipeStrategy: "all",
383
+ dateStrategy: "format:date-time",
384
+ mapStrategy: "entries",
385
+ removeAdditionalStrategy: "passthrough",
386
+ allowedAdditionalProperties: true,
387
+ rejectedAdditionalProperties: false,
388
+ definitionPath: "definitions",
389
+ target: "jsonSchema7",
390
+ strictUnions: false,
391
+ definitions: {},
392
+ errorMessages: false,
393
+ markdownDescription: false,
394
+ patternStrategy: "escape",
395
+ applyRegexFlags: false,
396
+ emailStrategy: "format:email",
397
+ base64Strategy: "contentEncoding:base64",
398
+ nameStrategy: "ref",
399
+ openAiAnyTypeName: "OpenAiAnyType"
400
+ };
401
+ var getDefaultOptions = (options) => typeof options === "string" ? {
402
+ ...defaultOptions,
403
+ name: options
404
+ } : {
405
+ ...defaultOptions,
406
+ ...options
407
+ };
408
+ var getRefs = (options) => {
409
+ const _options = getDefaultOptions(options);
410
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
411
+ return {
412
+ ..._options,
413
+ flags: { hasReferencedOpenAiAnyType: false },
414
+ currentPath,
415
+ propertyPath: void 0,
416
+ seen: new Map(Object.entries(_options.definitions).map(([name17, def]) => [
417
+ def._def,
418
+ {
419
+ def: def._def,
420
+ path: [..._options.basePath, _options.definitionPath, name17],
421
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
422
+ jsonSchema: void 0
423
+ }
424
+ ]))
425
+ };
426
+ };
427
+ function addErrorMessage(res, key, errorMessage, refs) {
428
+ if (!refs?.errorMessages)
429
+ return;
430
+ if (errorMessage) {
431
+ res.errorMessage = {
432
+ ...res.errorMessage,
433
+ [key]: errorMessage
434
+ };
435
+ }
436
+ }
437
+ function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
438
+ res[key] = value;
439
+ addErrorMessage(res, key, errorMessage, refs);
440
+ }
441
+ var getRelativePath = (pathA, pathB) => {
442
+ let i = 0;
443
+ for (; i < pathA.length && i < pathB.length; i++) {
444
+ if (pathA[i] !== pathB[i])
445
+ break;
446
+ }
447
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
448
+ };
449
+ function parseAnyDef(refs) {
450
+ if (refs.target !== "openAi") {
451
+ return {};
452
+ }
453
+ const anyDefinitionPath = [
454
+ ...refs.basePath,
455
+ refs.definitionPath,
456
+ refs.openAiAnyTypeName
457
+ ];
458
+ refs.flags.hasReferencedOpenAiAnyType = true;
459
+ return {
460
+ $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
461
+ };
462
+ }
463
+ function parseArrayDef(def, refs) {
464
+ const res = {
465
+ type: "array"
466
+ };
467
+ if (def.type?._def && def.type?._def?.typeName !== zod.ZodFirstPartyTypeKind.ZodAny) {
468
+ res.items = parseDef(def.type._def, {
469
+ ...refs,
470
+ currentPath: [...refs.currentPath, "items"]
471
+ });
472
+ }
473
+ if (def.minLength) {
474
+ setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
475
+ }
476
+ if (def.maxLength) {
477
+ setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
478
+ }
479
+ if (def.exactLength) {
480
+ setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
481
+ setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
482
+ }
483
+ return res;
484
+ }
485
+ function parseBigintDef(def, refs) {
486
+ const res = {
487
+ type: "integer",
488
+ format: "int64"
489
+ };
490
+ if (!def.checks)
491
+ return res;
492
+ for (const check of def.checks) {
493
+ switch (check.kind) {
494
+ case "min":
495
+ if (refs.target === "jsonSchema7") {
496
+ if (check.inclusive) {
497
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
498
+ } else {
499
+ setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
500
+ }
501
+ } else {
502
+ if (!check.inclusive) {
503
+ res.exclusiveMinimum = true;
504
+ }
505
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
506
+ }
507
+ break;
508
+ case "max":
509
+ if (refs.target === "jsonSchema7") {
510
+ if (check.inclusive) {
511
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
512
+ } else {
513
+ setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
514
+ }
515
+ } else {
516
+ if (!check.inclusive) {
517
+ res.exclusiveMaximum = true;
518
+ }
519
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
520
+ }
521
+ break;
522
+ case "multipleOf":
523
+ setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
524
+ break;
525
+ }
526
+ }
527
+ return res;
528
+ }
529
+ function parseBooleanDef() {
530
+ return {
531
+ type: "boolean"
532
+ };
533
+ }
534
+ function parseBrandedDef(_def, refs) {
535
+ return parseDef(_def.type._def, refs);
536
+ }
537
+ var parseCatchDef = (def, refs) => {
538
+ return parseDef(def.innerType._def, refs);
539
+ };
540
+ function parseDateDef(def, refs, overrideDateStrategy) {
541
+ const strategy = overrideDateStrategy ?? refs.dateStrategy;
542
+ if (Array.isArray(strategy)) {
543
+ return {
544
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
545
+ };
546
+ }
547
+ switch (strategy) {
548
+ case "string":
549
+ case "format:date-time":
550
+ return {
551
+ type: "string",
552
+ format: "date-time"
553
+ };
554
+ case "format:date":
555
+ return {
556
+ type: "string",
557
+ format: "date"
558
+ };
559
+ case "integer":
560
+ return integerDateParser(def, refs);
561
+ }
562
+ }
563
+ var integerDateParser = (def, refs) => {
564
+ const res = {
565
+ type: "integer",
566
+ format: "unix-time"
567
+ };
568
+ if (refs.target === "openApi3") {
569
+ return res;
570
+ }
571
+ for (const check of def.checks) {
572
+ switch (check.kind) {
573
+ case "min":
574
+ setResponseValueAndErrors(
575
+ res,
576
+ "minimum",
577
+ check.value,
578
+ // This is in milliseconds
579
+ check.message,
580
+ refs
581
+ );
582
+ break;
583
+ case "max":
584
+ setResponseValueAndErrors(
585
+ res,
586
+ "maximum",
587
+ check.value,
588
+ // This is in milliseconds
589
+ check.message,
590
+ refs
591
+ );
592
+ break;
593
+ }
594
+ }
595
+ return res;
596
+ };
597
+ function parseDefaultDef(_def, refs) {
598
+ return {
599
+ ...parseDef(_def.innerType._def, refs),
600
+ default: _def.defaultValue()
601
+ };
602
+ }
603
+ function parseEffectsDef(_def, refs) {
604
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);
605
+ }
606
+ function parseEnumDef(def) {
607
+ return {
608
+ type: "string",
609
+ enum: Array.from(def.values)
610
+ };
611
+ }
612
+ var isJsonSchema7AllOfType = (type) => {
613
+ if ("type" in type && type.type === "string")
614
+ return false;
615
+ return "allOf" in type;
616
+ };
617
+ function parseIntersectionDef(def, refs) {
618
+ const allOf = [
619
+ parseDef(def.left._def, {
620
+ ...refs,
621
+ currentPath: [...refs.currentPath, "allOf", "0"]
622
+ }),
623
+ parseDef(def.right._def, {
624
+ ...refs,
625
+ currentPath: [...refs.currentPath, "allOf", "1"]
626
+ })
627
+ ].filter((x) => !!x);
628
+ let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
629
+ const mergedAllOf = [];
630
+ allOf.forEach((schema) => {
631
+ if (isJsonSchema7AllOfType(schema)) {
632
+ mergedAllOf.push(...schema.allOf);
633
+ if (schema.unevaluatedProperties === void 0) {
634
+ unevaluatedProperties = void 0;
635
+ }
636
+ } else {
637
+ let nestedSchema = schema;
638
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
639
+ const { additionalProperties, ...rest } = schema;
640
+ nestedSchema = rest;
641
+ } else {
642
+ unevaluatedProperties = void 0;
643
+ }
644
+ mergedAllOf.push(nestedSchema);
645
+ }
646
+ });
647
+ return mergedAllOf.length ? {
648
+ allOf: mergedAllOf,
649
+ ...unevaluatedProperties
650
+ } : void 0;
651
+ }
652
+ function parseLiteralDef(def, refs) {
653
+ const parsedType = typeof def.value;
654
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
655
+ return {
656
+ type: Array.isArray(def.value) ? "array" : "object"
657
+ };
658
+ }
659
+ if (refs.target === "openApi3") {
660
+ return {
661
+ type: parsedType === "bigint" ? "integer" : parsedType,
662
+ enum: [def.value]
663
+ };
664
+ }
665
+ return {
666
+ type: parsedType === "bigint" ? "integer" : parsedType,
667
+ const: def.value
668
+ };
669
+ }
670
+ var emojiRegex = void 0;
671
+ var zodPatterns = {
672
+ /**
673
+ * `c` was changed to `[cC]` to replicate /i flag
674
+ */
675
+ cuid: /^[cC][^\s-]{8,}$/,
676
+ cuid2: /^[0-9a-z]+$/,
677
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
678
+ /**
679
+ * `a-z` was added to replicate /i flag
680
+ */
681
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
682
+ /**
683
+ * Constructed a valid Unicode RegExp
684
+ *
685
+ * Lazily instantiate since this type of regex isn't supported
686
+ * in all envs (e.g. React Native).
687
+ *
688
+ * See:
689
+ * https://github.com/colinhacks/zod/issues/2433
690
+ * Fix in Zod:
691
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
692
+ */
693
+ emoji: () => {
694
+ if (emojiRegex === void 0) {
695
+ emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
696
+ }
697
+ return emojiRegex;
698
+ },
699
+ /**
700
+ * Unused
701
+ */
702
+ 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}$/,
703
+ /**
704
+ * Unused
705
+ */
706
+ 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])$/,
707
+ 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])$/,
708
+ /**
709
+ * Unused
710
+ */
711
+ 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})))$/,
712
+ 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])$/,
713
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
714
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
715
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
716
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
717
+ };
718
+ function parseStringDef(def, refs) {
719
+ const res = {
720
+ type: "string"
721
+ };
722
+ if (def.checks) {
723
+ for (const check of def.checks) {
724
+ switch (check.kind) {
725
+ case "min":
726
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
727
+ break;
728
+ case "max":
729
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
730
+ break;
731
+ case "email":
732
+ switch (refs.emailStrategy) {
733
+ case "format:email":
734
+ addFormat(res, "email", check.message, refs);
735
+ break;
736
+ case "format:idn-email":
737
+ addFormat(res, "idn-email", check.message, refs);
738
+ break;
739
+ case "pattern:zod":
740
+ addPattern(res, zodPatterns.email, check.message, refs);
741
+ break;
742
+ }
743
+ break;
744
+ case "url":
745
+ addFormat(res, "uri", check.message, refs);
746
+ break;
747
+ case "uuid":
748
+ addFormat(res, "uuid", check.message, refs);
749
+ break;
750
+ case "regex":
751
+ addPattern(res, check.regex, check.message, refs);
752
+ break;
753
+ case "cuid":
754
+ addPattern(res, zodPatterns.cuid, check.message, refs);
755
+ break;
756
+ case "cuid2":
757
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
758
+ break;
759
+ case "startsWith":
760
+ addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
761
+ break;
762
+ case "endsWith":
763
+ addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
764
+ break;
765
+ case "datetime":
766
+ addFormat(res, "date-time", check.message, refs);
767
+ break;
768
+ case "date":
769
+ addFormat(res, "date", check.message, refs);
770
+ break;
771
+ case "time":
772
+ addFormat(res, "time", check.message, refs);
773
+ break;
774
+ case "duration":
775
+ addFormat(res, "duration", check.message, refs);
776
+ break;
777
+ case "length":
778
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
779
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
780
+ break;
781
+ case "includes": {
782
+ addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
783
+ break;
784
+ }
785
+ case "ip": {
786
+ if (check.version !== "v6") {
787
+ addFormat(res, "ipv4", check.message, refs);
788
+ }
789
+ if (check.version !== "v4") {
790
+ addFormat(res, "ipv6", check.message, refs);
791
+ }
792
+ break;
793
+ }
794
+ case "base64url":
795
+ addPattern(res, zodPatterns.base64url, check.message, refs);
796
+ break;
797
+ case "jwt":
798
+ addPattern(res, zodPatterns.jwt, check.message, refs);
799
+ break;
800
+ case "cidr": {
801
+ if (check.version !== "v6") {
802
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
803
+ }
804
+ if (check.version !== "v4") {
805
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
806
+ }
807
+ break;
808
+ }
809
+ case "emoji":
810
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
811
+ break;
812
+ case "ulid": {
813
+ addPattern(res, zodPatterns.ulid, check.message, refs);
814
+ break;
815
+ }
816
+ case "base64": {
817
+ switch (refs.base64Strategy) {
818
+ case "format:binary": {
819
+ addFormat(res, "binary", check.message, refs);
820
+ break;
821
+ }
822
+ case "contentEncoding:base64": {
823
+ setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
824
+ break;
825
+ }
826
+ case "pattern:zod": {
827
+ addPattern(res, zodPatterns.base64, check.message, refs);
828
+ break;
829
+ }
830
+ }
831
+ break;
832
+ }
833
+ case "nanoid": {
834
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
835
+ }
836
+ }
837
+ }
838
+ }
839
+ return res;
840
+ }
841
+ function escapeLiteralCheckValue(literal, refs) {
842
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
843
+ }
844
+ var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
845
+ function escapeNonAlphaNumeric(source) {
846
+ let result = "";
847
+ for (let i = 0; i < source.length; i++) {
848
+ if (!ALPHA_NUMERIC.has(source[i])) {
849
+ result += "\\";
850
+ }
851
+ result += source[i];
852
+ }
853
+ return result;
854
+ }
855
+ function addFormat(schema, value, message, refs) {
856
+ if (schema.format || schema.anyOf?.some((x) => x.format)) {
857
+ if (!schema.anyOf) {
858
+ schema.anyOf = [];
859
+ }
860
+ if (schema.format) {
861
+ schema.anyOf.push({
862
+ format: schema.format,
863
+ ...schema.errorMessage && refs.errorMessages && {
864
+ errorMessage: { format: schema.errorMessage.format }
865
+ }
866
+ });
867
+ delete schema.format;
868
+ if (schema.errorMessage) {
869
+ delete schema.errorMessage.format;
870
+ if (Object.keys(schema.errorMessage).length === 0) {
871
+ delete schema.errorMessage;
872
+ }
873
+ }
874
+ }
875
+ schema.anyOf.push({
876
+ format: value,
877
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
878
+ });
879
+ } else {
880
+ setResponseValueAndErrors(schema, "format", value, message, refs);
881
+ }
882
+ }
883
+ function addPattern(schema, regex, message, refs) {
884
+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
885
+ if (!schema.allOf) {
886
+ schema.allOf = [];
887
+ }
888
+ if (schema.pattern) {
889
+ schema.allOf.push({
890
+ pattern: schema.pattern,
891
+ ...schema.errorMessage && refs.errorMessages && {
892
+ errorMessage: { pattern: schema.errorMessage.pattern }
893
+ }
894
+ });
895
+ delete schema.pattern;
896
+ if (schema.errorMessage) {
897
+ delete schema.errorMessage.pattern;
898
+ if (Object.keys(schema.errorMessage).length === 0) {
899
+ delete schema.errorMessage;
900
+ }
901
+ }
902
+ }
903
+ schema.allOf.push({
904
+ pattern: stringifyRegExpWithFlags(regex, refs),
905
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
906
+ });
907
+ } else {
908
+ setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
909
+ }
910
+ }
911
+ function stringifyRegExpWithFlags(regex, refs) {
912
+ if (!refs.applyRegexFlags || !regex.flags) {
913
+ return regex.source;
914
+ }
915
+ const flags = {
916
+ i: regex.flags.includes("i"),
917
+ m: regex.flags.includes("m"),
918
+ s: regex.flags.includes("s")
919
+ // `.` matches newlines
920
+ };
921
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
922
+ let pattern = "";
923
+ let isEscaped = false;
924
+ let inCharGroup = false;
925
+ let inCharRange = false;
926
+ for (let i = 0; i < source.length; i++) {
927
+ if (isEscaped) {
928
+ pattern += source[i];
929
+ isEscaped = false;
930
+ continue;
931
+ }
932
+ if (flags.i) {
933
+ if (inCharGroup) {
934
+ if (source[i].match(/[a-z]/)) {
935
+ if (inCharRange) {
936
+ pattern += source[i];
937
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
938
+ inCharRange = false;
939
+ } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
940
+ pattern += source[i];
941
+ inCharRange = true;
942
+ } else {
943
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
944
+ }
945
+ continue;
946
+ }
947
+ } else if (source[i].match(/[a-z]/)) {
948
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
949
+ continue;
950
+ }
951
+ }
952
+ if (flags.m) {
953
+ if (source[i] === "^") {
954
+ pattern += `(^|(?<=[\r
955
+ ]))`;
956
+ continue;
957
+ } else if (source[i] === "$") {
958
+ pattern += `($|(?=[\r
959
+ ]))`;
960
+ continue;
961
+ }
962
+ }
963
+ if (flags.s && source[i] === ".") {
964
+ pattern += inCharGroup ? `${source[i]}\r
965
+ ` : `[${source[i]}\r
966
+ ]`;
967
+ continue;
968
+ }
969
+ pattern += source[i];
970
+ if (source[i] === "\\") {
971
+ isEscaped = true;
972
+ } else if (inCharGroup && source[i] === "]") {
973
+ inCharGroup = false;
974
+ } else if (!inCharGroup && source[i] === "[") {
975
+ inCharGroup = true;
976
+ }
977
+ }
978
+ return pattern;
979
+ }
980
+ function parseRecordDef(def, refs) {
981
+ if (refs.target === "openAi") {
982
+ console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
983
+ }
984
+ if (refs.target === "openApi3" && def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodEnum) {
985
+ return {
986
+ type: "object",
987
+ required: def.keyType._def.values,
988
+ properties: def.keyType._def.values.reduce((acc, key) => ({
989
+ ...acc,
990
+ [key]: parseDef(def.valueType._def, {
991
+ ...refs,
992
+ currentPath: [...refs.currentPath, "properties", key]
993
+ }) ?? parseAnyDef(refs)
994
+ }), {}),
995
+ additionalProperties: refs.rejectedAdditionalProperties
996
+ };
997
+ }
998
+ const schema = {
999
+ type: "object",
1000
+ additionalProperties: parseDef(def.valueType._def, {
1001
+ ...refs,
1002
+ currentPath: [...refs.currentPath, "additionalProperties"]
1003
+ }) ?? refs.allowedAdditionalProperties
1004
+ };
1005
+ if (refs.target === "openApi3") {
1006
+ return schema;
1007
+ }
1008
+ if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
1009
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1010
+ return {
1011
+ ...schema,
1012
+ propertyNames: keyType
1013
+ };
1014
+ } else if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodEnum) {
1015
+ return {
1016
+ ...schema,
1017
+ propertyNames: {
1018
+ enum: def.keyType._def.values
1019
+ }
1020
+ };
1021
+ } else if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === zod.ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
1022
+ const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
1023
+ return {
1024
+ ...schema,
1025
+ propertyNames: keyType
1026
+ };
1027
+ }
1028
+ return schema;
1029
+ }
1030
+ function parseMapDef(def, refs) {
1031
+ if (refs.mapStrategy === "record") {
1032
+ return parseRecordDef(def, refs);
1033
+ }
1034
+ const keys = parseDef(def.keyType._def, {
1035
+ ...refs,
1036
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1037
+ }) || parseAnyDef(refs);
1038
+ const values = parseDef(def.valueType._def, {
1039
+ ...refs,
1040
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1041
+ }) || parseAnyDef(refs);
1042
+ return {
1043
+ type: "array",
1044
+ maxItems: 125,
1045
+ items: {
1046
+ type: "array",
1047
+ items: [keys, values],
1048
+ minItems: 2,
1049
+ maxItems: 2
1050
+ }
1051
+ };
1052
+ }
1053
+ function parseNativeEnumDef(def) {
1054
+ const object2 = def.values;
1055
+ const actualKeys = Object.keys(def.values).filter((key) => {
1056
+ return typeof object2[object2[key]] !== "number";
1057
+ });
1058
+ const actualValues = actualKeys.map((key) => object2[key]);
1059
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
1060
+ return {
1061
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1062
+ enum: actualValues
1063
+ };
1064
+ }
1065
+ function parseNeverDef(refs) {
1066
+ return refs.target === "openAi" ? void 0 : {
1067
+ not: parseAnyDef({
1068
+ ...refs,
1069
+ currentPath: [...refs.currentPath, "not"]
1070
+ })
1071
+ };
1072
+ }
1073
+ function parseNullDef(refs) {
1074
+ return refs.target === "openApi3" ? {
1075
+ enum: ["null"],
1076
+ nullable: true
1077
+ } : {
1078
+ type: "null"
1079
+ };
1080
+ }
1081
+ var primitiveMappings = {
1082
+ ZodString: "string",
1083
+ ZodNumber: "number",
1084
+ ZodBigInt: "integer",
1085
+ ZodBoolean: "boolean",
1086
+ ZodNull: "null"
1087
+ };
1088
+ function parseUnionDef(def, refs) {
1089
+ if (refs.target === "openApi3")
1090
+ return asAnyOf(def, refs);
1091
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1092
+ if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
1093
+ const types = options.reduce((types2, x) => {
1094
+ const type = primitiveMappings[x._def.typeName];
1095
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1096
+ }, []);
1097
+ return {
1098
+ type: types.length > 1 ? types : types[0]
1099
+ };
1100
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1101
+ const types = options.reduce((acc, x) => {
1102
+ const type = typeof x._def.value;
1103
+ switch (type) {
1104
+ case "string":
1105
+ case "number":
1106
+ case "boolean":
1107
+ return [...acc, type];
1108
+ case "bigint":
1109
+ return [...acc, "integer"];
1110
+ case "object":
1111
+ if (x._def.value === null)
1112
+ return [...acc, "null"];
1113
+ case "symbol":
1114
+ case "undefined":
1115
+ case "function":
1116
+ default:
1117
+ return acc;
1118
+ }
1119
+ }, []);
1120
+ if (types.length === options.length) {
1121
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1122
+ return {
1123
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1124
+ enum: options.reduce((acc, x) => {
1125
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1126
+ }, [])
1127
+ };
1128
+ }
1129
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1130
+ return {
1131
+ type: "string",
1132
+ enum: options.reduce((acc, x) => [
1133
+ ...acc,
1134
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1135
+ ], [])
1136
+ };
1137
+ }
1138
+ return asAnyOf(def, refs);
1139
+ }
1140
+ var asAnyOf = (def, refs) => {
1141
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
1142
+ ...refs,
1143
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1144
+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
1145
+ return anyOf.length ? { anyOf } : void 0;
1146
+ };
1147
+ function parseNullableDef(def, refs) {
1148
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1149
+ if (refs.target === "openApi3") {
1150
+ return {
1151
+ type: primitiveMappings[def.innerType._def.typeName],
1152
+ nullable: true
1153
+ };
1154
+ }
1155
+ return {
1156
+ type: [
1157
+ primitiveMappings[def.innerType._def.typeName],
1158
+ "null"
1159
+ ]
1160
+ };
1161
+ }
1162
+ if (refs.target === "openApi3") {
1163
+ const base2 = parseDef(def.innerType._def, {
1164
+ ...refs,
1165
+ currentPath: [...refs.currentPath]
1166
+ });
1167
+ if (base2 && "$ref" in base2)
1168
+ return { allOf: [base2], nullable: true };
1169
+ return base2 && { ...base2, nullable: true };
1170
+ }
1171
+ const base = parseDef(def.innerType._def, {
1172
+ ...refs,
1173
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1174
+ });
1175
+ return base && { anyOf: [base, { type: "null" }] };
1176
+ }
1177
+ function parseNumberDef(def, refs) {
1178
+ const res = {
1179
+ type: "number"
1180
+ };
1181
+ if (!def.checks)
1182
+ return res;
1183
+ for (const check of def.checks) {
1184
+ switch (check.kind) {
1185
+ case "int":
1186
+ res.type = "integer";
1187
+ addErrorMessage(res, "type", check.message, refs);
1188
+ break;
1189
+ case "min":
1190
+ if (refs.target === "jsonSchema7") {
1191
+ if (check.inclusive) {
1192
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1193
+ } else {
1194
+ setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
1195
+ }
1196
+ } else {
1197
+ if (!check.inclusive) {
1198
+ res.exclusiveMinimum = true;
1199
+ }
1200
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1201
+ }
1202
+ break;
1203
+ case "max":
1204
+ if (refs.target === "jsonSchema7") {
1205
+ if (check.inclusive) {
1206
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1207
+ } else {
1208
+ setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
1209
+ }
1210
+ } else {
1211
+ if (!check.inclusive) {
1212
+ res.exclusiveMaximum = true;
1213
+ }
1214
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1215
+ }
1216
+ break;
1217
+ case "multipleOf":
1218
+ setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
1219
+ break;
1220
+ }
1221
+ }
1222
+ return res;
1223
+ }
1224
+ function parseObjectDef(def, refs) {
1225
+ const forceOptionalIntoNullable = refs.target === "openAi";
1226
+ const result = {
1227
+ type: "object",
1228
+ properties: {}
1229
+ };
1230
+ const required = [];
1231
+ const shape = def.shape();
1232
+ for (const propName in shape) {
1233
+ let propDef = shape[propName];
1234
+ if (propDef === void 0 || propDef._def === void 0) {
1235
+ continue;
1236
+ }
1237
+ let propOptional = safeIsOptional(propDef);
1238
+ if (propOptional && forceOptionalIntoNullable) {
1239
+ if (propDef._def.typeName === "ZodOptional") {
1240
+ propDef = propDef._def.innerType;
1241
+ }
1242
+ if (!propDef.isNullable()) {
1243
+ propDef = propDef.nullable();
1244
+ }
1245
+ propOptional = false;
1246
+ }
1247
+ const parsedDef = parseDef(propDef._def, {
1248
+ ...refs,
1249
+ currentPath: [...refs.currentPath, "properties", propName],
1250
+ propertyPath: [...refs.currentPath, "properties", propName]
1251
+ });
1252
+ if (parsedDef === void 0) {
1253
+ continue;
1254
+ }
1255
+ result.properties[propName] = parsedDef;
1256
+ if (!propOptional) {
1257
+ required.push(propName);
1258
+ }
1259
+ }
1260
+ if (required.length) {
1261
+ result.required = required;
1262
+ }
1263
+ const additionalProperties = decideAdditionalProperties(def, refs);
1264
+ if (additionalProperties !== void 0) {
1265
+ result.additionalProperties = additionalProperties;
1266
+ }
1267
+ return result;
1268
+ }
1269
+ function decideAdditionalProperties(def, refs) {
1270
+ if (def.catchall._def.typeName !== "ZodNever") {
1271
+ return parseDef(def.catchall._def, {
1272
+ ...refs,
1273
+ currentPath: [...refs.currentPath, "additionalProperties"]
1274
+ });
1275
+ }
1276
+ switch (def.unknownKeys) {
1277
+ case "passthrough":
1278
+ return refs.allowedAdditionalProperties;
1279
+ case "strict":
1280
+ return refs.rejectedAdditionalProperties;
1281
+ case "strip":
1282
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1283
+ }
1284
+ }
1285
+ function safeIsOptional(schema) {
1286
+ try {
1287
+ return schema.isOptional();
1288
+ } catch {
1289
+ return true;
1290
+ }
1291
+ }
1292
+ var parseOptionalDef = (def, refs) => {
1293
+ if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
1294
+ return parseDef(def.innerType._def, refs);
1295
+ }
1296
+ const innerSchema = parseDef(def.innerType._def, {
1297
+ ...refs,
1298
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1299
+ });
1300
+ return innerSchema ? {
1301
+ anyOf: [
1302
+ {
1303
+ not: parseAnyDef(refs)
1304
+ },
1305
+ innerSchema
1306
+ ]
1307
+ } : parseAnyDef(refs);
1308
+ };
1309
+ var parsePipelineDef = (def, refs) => {
1310
+ if (refs.pipeStrategy === "input") {
1311
+ return parseDef(def.in._def, refs);
1312
+ } else if (refs.pipeStrategy === "output") {
1313
+ return parseDef(def.out._def, refs);
1314
+ }
1315
+ const a = parseDef(def.in._def, {
1316
+ ...refs,
1317
+ currentPath: [...refs.currentPath, "allOf", "0"]
1318
+ });
1319
+ const b = parseDef(def.out._def, {
1320
+ ...refs,
1321
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1322
+ });
1323
+ return {
1324
+ allOf: [a, b].filter((x) => x !== void 0)
1325
+ };
1326
+ };
1327
+ function parsePromiseDef(def, refs) {
1328
+ return parseDef(def.type._def, refs);
1329
+ }
1330
+ function parseSetDef(def, refs) {
1331
+ const items = parseDef(def.valueType._def, {
1332
+ ...refs,
1333
+ currentPath: [...refs.currentPath, "items"]
1334
+ });
1335
+ const schema = {
1336
+ type: "array",
1337
+ uniqueItems: true,
1338
+ items
1339
+ };
1340
+ if (def.minSize) {
1341
+ setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
1342
+ }
1343
+ if (def.maxSize) {
1344
+ setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
1345
+ }
1346
+ return schema;
1347
+ }
1348
+ function parseTupleDef(def, refs) {
1349
+ if (def.rest) {
1350
+ return {
1351
+ type: "array",
1352
+ minItems: def.items.length,
1353
+ items: def.items.map((x, i) => parseDef(x._def, {
1354
+ ...refs,
1355
+ currentPath: [...refs.currentPath, "items", `${i}`]
1356
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
1357
+ additionalItems: parseDef(def.rest._def, {
1358
+ ...refs,
1359
+ currentPath: [...refs.currentPath, "additionalItems"]
1360
+ })
1361
+ };
1362
+ } else {
1363
+ return {
1364
+ type: "array",
1365
+ minItems: def.items.length,
1366
+ maxItems: def.items.length,
1367
+ items: def.items.map((x, i) => parseDef(x._def, {
1368
+ ...refs,
1369
+ currentPath: [...refs.currentPath, "items", `${i}`]
1370
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
1371
+ };
1372
+ }
1373
+ }
1374
+ function parseUndefinedDef(refs) {
1375
+ return {
1376
+ not: parseAnyDef(refs)
1377
+ };
1378
+ }
1379
+ function parseUnknownDef(refs) {
1380
+ return parseAnyDef(refs);
1381
+ }
1382
+ var parseReadonlyDef = (def, refs) => {
1383
+ return parseDef(def.innerType._def, refs);
1384
+ };
1385
+ var selectParser = (def, typeName, refs) => {
1386
+ switch (typeName) {
1387
+ case zod.ZodFirstPartyTypeKind.ZodString:
1388
+ return parseStringDef(def, refs);
1389
+ case zod.ZodFirstPartyTypeKind.ZodNumber:
1390
+ return parseNumberDef(def, refs);
1391
+ case zod.ZodFirstPartyTypeKind.ZodObject:
1392
+ return parseObjectDef(def, refs);
1393
+ case zod.ZodFirstPartyTypeKind.ZodBigInt:
1394
+ return parseBigintDef(def, refs);
1395
+ case zod.ZodFirstPartyTypeKind.ZodBoolean:
1396
+ return parseBooleanDef();
1397
+ case zod.ZodFirstPartyTypeKind.ZodDate:
1398
+ return parseDateDef(def, refs);
1399
+ case zod.ZodFirstPartyTypeKind.ZodUndefined:
1400
+ return parseUndefinedDef(refs);
1401
+ case zod.ZodFirstPartyTypeKind.ZodNull:
1402
+ return parseNullDef(refs);
1403
+ case zod.ZodFirstPartyTypeKind.ZodArray:
1404
+ return parseArrayDef(def, refs);
1405
+ case zod.ZodFirstPartyTypeKind.ZodUnion:
1406
+ case zod.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
1407
+ return parseUnionDef(def, refs);
1408
+ case zod.ZodFirstPartyTypeKind.ZodIntersection:
1409
+ return parseIntersectionDef(def, refs);
1410
+ case zod.ZodFirstPartyTypeKind.ZodTuple:
1411
+ return parseTupleDef(def, refs);
1412
+ case zod.ZodFirstPartyTypeKind.ZodRecord:
1413
+ return parseRecordDef(def, refs);
1414
+ case zod.ZodFirstPartyTypeKind.ZodLiteral:
1415
+ return parseLiteralDef(def, refs);
1416
+ case zod.ZodFirstPartyTypeKind.ZodEnum:
1417
+ return parseEnumDef(def);
1418
+ case zod.ZodFirstPartyTypeKind.ZodNativeEnum:
1419
+ return parseNativeEnumDef(def);
1420
+ case zod.ZodFirstPartyTypeKind.ZodNullable:
1421
+ return parseNullableDef(def, refs);
1422
+ case zod.ZodFirstPartyTypeKind.ZodOptional:
1423
+ return parseOptionalDef(def, refs);
1424
+ case zod.ZodFirstPartyTypeKind.ZodMap:
1425
+ return parseMapDef(def, refs);
1426
+ case zod.ZodFirstPartyTypeKind.ZodSet:
1427
+ return parseSetDef(def, refs);
1428
+ case zod.ZodFirstPartyTypeKind.ZodLazy:
1429
+ return () => def.getter()._def;
1430
+ case zod.ZodFirstPartyTypeKind.ZodPromise:
1431
+ return parsePromiseDef(def, refs);
1432
+ case zod.ZodFirstPartyTypeKind.ZodNaN:
1433
+ case zod.ZodFirstPartyTypeKind.ZodNever:
1434
+ return parseNeverDef(refs);
1435
+ case zod.ZodFirstPartyTypeKind.ZodEffects:
1436
+ return parseEffectsDef(def, refs);
1437
+ case zod.ZodFirstPartyTypeKind.ZodAny:
1438
+ return parseAnyDef(refs);
1439
+ case zod.ZodFirstPartyTypeKind.ZodUnknown:
1440
+ return parseUnknownDef(refs);
1441
+ case zod.ZodFirstPartyTypeKind.ZodDefault:
1442
+ return parseDefaultDef(def, refs);
1443
+ case zod.ZodFirstPartyTypeKind.ZodBranded:
1444
+ return parseBrandedDef(def, refs);
1445
+ case zod.ZodFirstPartyTypeKind.ZodReadonly:
1446
+ return parseReadonlyDef(def, refs);
1447
+ case zod.ZodFirstPartyTypeKind.ZodCatch:
1448
+ return parseCatchDef(def, refs);
1449
+ case zod.ZodFirstPartyTypeKind.ZodPipeline:
1450
+ return parsePipelineDef(def, refs);
1451
+ case zod.ZodFirstPartyTypeKind.ZodFunction:
1452
+ case zod.ZodFirstPartyTypeKind.ZodVoid:
1453
+ case zod.ZodFirstPartyTypeKind.ZodSymbol:
1454
+ return void 0;
1455
+ default:
1456
+ return /* @__PURE__ */ ((_) => void 0)();
1457
+ }
1458
+ };
1459
+ function parseDef(def, refs, forceResolution = false) {
1460
+ const seenItem = refs.seen.get(def);
1461
+ if (refs.override) {
1462
+ const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
1463
+ if (overrideResult !== ignoreOverride) {
1464
+ return overrideResult;
1465
+ }
1466
+ }
1467
+ if (seenItem && !forceResolution) {
1468
+ const seenSchema = get$ref(seenItem, refs);
1469
+ if (seenSchema !== void 0) {
1470
+ return seenSchema;
1471
+ }
1472
+ }
1473
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1474
+ refs.seen.set(def, newItem);
1475
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1476
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1477
+ if (jsonSchema2) {
1478
+ addMeta(def, refs, jsonSchema2);
1479
+ }
1480
+ if (refs.postProcess) {
1481
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1482
+ newItem.jsonSchema = jsonSchema2;
1483
+ return postProcessResult;
1484
+ }
1485
+ newItem.jsonSchema = jsonSchema2;
1486
+ return jsonSchema2;
1487
+ }
1488
+ var get$ref = (item, refs) => {
1489
+ switch (refs.$refStrategy) {
1490
+ case "root":
1491
+ return { $ref: item.path.join("/") };
1492
+ case "relative":
1493
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1494
+ case "none":
1495
+ case "seen": {
1496
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1497
+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
1498
+ return parseAnyDef(refs);
1499
+ }
1500
+ return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;
1501
+ }
1502
+ }
1503
+ };
1504
+ var addMeta = (def, refs, jsonSchema2) => {
1505
+ if (def.description) {
1506
+ jsonSchema2.description = def.description;
1507
+ if (refs.markdownDescription) {
1508
+ jsonSchema2.markdownDescription = def.description;
1509
+ }
1510
+ }
1511
+ return jsonSchema2;
1512
+ };
1513
+ var zodToJsonSchema2 = (schema, options) => {
1514
+ const refs = getRefs(options);
1515
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name18, schema2]) => ({
1516
+ ...acc,
1517
+ [name18]: parseDef(schema2._def, {
1518
+ ...refs,
1519
+ currentPath: [...refs.basePath, refs.definitionPath, name18]
1520
+ }, true) ?? parseAnyDef(refs)
1521
+ }), {}) : void 0;
1522
+ const name17 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
1523
+ const main = parseDef(schema._def, name17 === void 0 ? refs : {
1524
+ ...refs,
1525
+ currentPath: [...refs.basePath, refs.definitionPath, name17]
1526
+ }, false) ?? parseAnyDef(refs);
1527
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1528
+ if (title !== void 0) {
1529
+ main.title = title;
1530
+ }
1531
+ if (refs.flags.hasReferencedOpenAiAnyType) {
1532
+ if (!definitions) {
1533
+ definitions = {};
1534
+ }
1535
+ if (!definitions[refs.openAiAnyTypeName]) {
1536
+ definitions[refs.openAiAnyTypeName] = {
1537
+ // Skipping "object" as no properties can be defined and additionalProperties must be "false"
1538
+ type: ["string", "number", "integer", "boolean", "array", "null"],
1539
+ items: {
1540
+ $ref: refs.$refStrategy === "relative" ? "1" : [
1541
+ ...refs.basePath,
1542
+ refs.definitionPath,
1543
+ refs.openAiAnyTypeName
1544
+ ].join("/")
1545
+ }
1546
+ };
1547
+ }
1548
+ }
1549
+ const combined = name17 === void 0 ? definitions ? {
1550
+ ...main,
1551
+ [refs.definitionPath]: definitions
1552
+ } : main : {
1553
+ $ref: [
1554
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1555
+ refs.definitionPath,
1556
+ name17
1557
+ ].join("/"),
1558
+ [refs.definitionPath]: {
1559
+ ...definitions,
1560
+ [name17]: main
1561
+ }
1562
+ };
1563
+ if (refs.target === "jsonSchema7") {
1564
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1565
+ } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
1566
+ combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
1567
+ }
1568
+ if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
1569
+ console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
1570
+ }
1571
+ return combined;
1572
+ };
1573
+ var esm_default = zodToJsonSchema2;
1574
+ function fixJson(input) {
1575
+ const stack = ["ROOT"];
1576
+ let lastValidIndex = -1;
1577
+ let literalStart = null;
1578
+ function processValueStart(char, i, swapState) {
1579
+ {
1580
+ switch (char) {
1581
+ case '"': {
1582
+ lastValidIndex = i;
1583
+ stack.pop();
1584
+ stack.push(swapState);
1585
+ stack.push("INSIDE_STRING");
1586
+ break;
1587
+ }
1588
+ case "f":
1589
+ case "t":
1590
+ case "n": {
1591
+ lastValidIndex = i;
1592
+ literalStart = i;
1593
+ stack.pop();
1594
+ stack.push(swapState);
1595
+ stack.push("INSIDE_LITERAL");
1596
+ break;
1597
+ }
1598
+ case "-": {
1599
+ stack.pop();
1600
+ stack.push(swapState);
1601
+ stack.push("INSIDE_NUMBER");
1602
+ break;
1603
+ }
1604
+ case "0":
1605
+ case "1":
1606
+ case "2":
1607
+ case "3":
1608
+ case "4":
1609
+ case "5":
1610
+ case "6":
1611
+ case "7":
1612
+ case "8":
1613
+ case "9": {
1614
+ lastValidIndex = i;
1615
+ stack.pop();
1616
+ stack.push(swapState);
1617
+ stack.push("INSIDE_NUMBER");
1618
+ break;
1619
+ }
1620
+ case "{": {
1621
+ lastValidIndex = i;
1622
+ stack.pop();
1623
+ stack.push(swapState);
1624
+ stack.push("INSIDE_OBJECT_START");
1625
+ break;
1626
+ }
1627
+ case "[": {
1628
+ lastValidIndex = i;
1629
+ stack.pop();
1630
+ stack.push(swapState);
1631
+ stack.push("INSIDE_ARRAY_START");
1632
+ break;
1633
+ }
1634
+ }
1635
+ }
1636
+ }
1637
+ function processAfterObjectValue(char, i) {
1638
+ switch (char) {
1639
+ case ",": {
1640
+ stack.pop();
1641
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
1642
+ break;
1643
+ }
1644
+ case "}": {
1645
+ lastValidIndex = i;
1646
+ stack.pop();
1647
+ break;
1648
+ }
1649
+ }
1650
+ }
1651
+ function processAfterArrayValue(char, i) {
1652
+ switch (char) {
1653
+ case ",": {
1654
+ stack.pop();
1655
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
1656
+ break;
1657
+ }
1658
+ case "]": {
1659
+ lastValidIndex = i;
1660
+ stack.pop();
1661
+ break;
1662
+ }
1663
+ }
1664
+ }
1665
+ for (let i = 0; i < input.length; i++) {
1666
+ const char = input[i];
1667
+ const currentState = stack[stack.length - 1];
1668
+ switch (currentState) {
1669
+ case "ROOT":
1670
+ processValueStart(char, i, "FINISH");
1671
+ break;
1672
+ case "INSIDE_OBJECT_START": {
1673
+ switch (char) {
1674
+ case '"': {
1675
+ stack.pop();
1676
+ stack.push("INSIDE_OBJECT_KEY");
1677
+ break;
1678
+ }
1679
+ case "}": {
1680
+ lastValidIndex = i;
1681
+ stack.pop();
1682
+ break;
1683
+ }
1684
+ }
1685
+ break;
1686
+ }
1687
+ case "INSIDE_OBJECT_AFTER_COMMA": {
1688
+ switch (char) {
1689
+ case '"': {
1690
+ stack.pop();
1691
+ stack.push("INSIDE_OBJECT_KEY");
1692
+ break;
1693
+ }
1694
+ }
1695
+ break;
1696
+ }
1697
+ case "INSIDE_OBJECT_KEY": {
1698
+ switch (char) {
1699
+ case '"': {
1700
+ stack.pop();
1701
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
1702
+ break;
1703
+ }
1704
+ }
1705
+ break;
1706
+ }
1707
+ case "INSIDE_OBJECT_AFTER_KEY": {
1708
+ switch (char) {
1709
+ case ":": {
1710
+ stack.pop();
1711
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
1712
+ break;
1713
+ }
1714
+ }
1715
+ break;
1716
+ }
1717
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
1718
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
1719
+ break;
1720
+ }
1721
+ case "INSIDE_OBJECT_AFTER_VALUE": {
1722
+ processAfterObjectValue(char, i);
1723
+ break;
1724
+ }
1725
+ case "INSIDE_STRING": {
1726
+ switch (char) {
1727
+ case '"': {
1728
+ stack.pop();
1729
+ lastValidIndex = i;
1730
+ break;
1731
+ }
1732
+ case "\\": {
1733
+ stack.push("INSIDE_STRING_ESCAPE");
1734
+ break;
1735
+ }
1736
+ default: {
1737
+ lastValidIndex = i;
1738
+ }
1739
+ }
1740
+ break;
1741
+ }
1742
+ case "INSIDE_ARRAY_START": {
1743
+ switch (char) {
1744
+ case "]": {
1745
+ lastValidIndex = i;
1746
+ stack.pop();
1747
+ break;
1748
+ }
1749
+ default: {
1750
+ lastValidIndex = i;
1751
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1752
+ break;
1753
+ }
1754
+ }
1755
+ break;
1756
+ }
1757
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1758
+ switch (char) {
1759
+ case ",": {
1760
+ stack.pop();
1761
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
1762
+ break;
1763
+ }
1764
+ case "]": {
1765
+ lastValidIndex = i;
1766
+ stack.pop();
1767
+ break;
1768
+ }
1769
+ default: {
1770
+ lastValidIndex = i;
1771
+ break;
1772
+ }
1773
+ }
1774
+ break;
1775
+ }
1776
+ case "INSIDE_ARRAY_AFTER_COMMA": {
1777
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1778
+ break;
1779
+ }
1780
+ case "INSIDE_STRING_ESCAPE": {
1781
+ stack.pop();
1782
+ lastValidIndex = i;
1783
+ break;
1784
+ }
1785
+ case "INSIDE_NUMBER": {
1786
+ switch (char) {
1787
+ case "0":
1788
+ case "1":
1789
+ case "2":
1790
+ case "3":
1791
+ case "4":
1792
+ case "5":
1793
+ case "6":
1794
+ case "7":
1795
+ case "8":
1796
+ case "9": {
1797
+ lastValidIndex = i;
1798
+ break;
1799
+ }
1800
+ case "e":
1801
+ case "E":
1802
+ case "-":
1803
+ case ".": {
1804
+ break;
1805
+ }
1806
+ case ",": {
1807
+ stack.pop();
1808
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1809
+ processAfterArrayValue(char, i);
1810
+ }
1811
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1812
+ processAfterObjectValue(char, i);
1813
+ }
1814
+ break;
1815
+ }
1816
+ case "}": {
1817
+ stack.pop();
1818
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1819
+ processAfterObjectValue(char, i);
1820
+ }
1821
+ break;
1822
+ }
1823
+ case "]": {
1824
+ stack.pop();
1825
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1826
+ processAfterArrayValue(char, i);
1827
+ }
1828
+ break;
1829
+ }
1830
+ default: {
1831
+ stack.pop();
1832
+ break;
1833
+ }
1834
+ }
1835
+ break;
1836
+ }
1837
+ case "INSIDE_LITERAL": {
1838
+ const partialLiteral = input.substring(literalStart, i + 1);
1839
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
1840
+ stack.pop();
1841
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1842
+ processAfterObjectValue(char, i);
1843
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1844
+ processAfterArrayValue(char, i);
1845
+ }
1846
+ } else {
1847
+ lastValidIndex = i;
1848
+ }
1849
+ break;
1850
+ }
1851
+ }
1852
+ }
1853
+ let result = input.slice(0, lastValidIndex + 1);
1854
+ for (let i = stack.length - 1; i >= 0; i--) {
1855
+ const state = stack[i];
1856
+ switch (state) {
1857
+ case "INSIDE_STRING": {
1858
+ result += '"';
1859
+ break;
1860
+ }
1861
+ case "INSIDE_OBJECT_KEY":
1862
+ case "INSIDE_OBJECT_AFTER_KEY":
1863
+ case "INSIDE_OBJECT_AFTER_COMMA":
1864
+ case "INSIDE_OBJECT_START":
1865
+ case "INSIDE_OBJECT_BEFORE_VALUE":
1866
+ case "INSIDE_OBJECT_AFTER_VALUE": {
1867
+ result += "}";
1868
+ break;
1869
+ }
1870
+ case "INSIDE_ARRAY_START":
1871
+ case "INSIDE_ARRAY_AFTER_COMMA":
1872
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1873
+ result += "]";
1874
+ break;
1875
+ }
1876
+ case "INSIDE_LITERAL": {
1877
+ const partialLiteral = input.substring(literalStart, input.length);
1878
+ if ("true".startsWith(partialLiteral)) {
1879
+ result += "true".slice(partialLiteral.length);
1880
+ } else if ("false".startsWith(partialLiteral)) {
1881
+ result += "false".slice(partialLiteral.length);
1882
+ } else if ("null".startsWith(partialLiteral)) {
1883
+ result += "null".slice(partialLiteral.length);
1884
+ }
1885
+ }
1886
+ }
1887
+ }
1888
+ return result;
1889
+ }
1890
+ function parsePartialJson(jsonText) {
1891
+ if (jsonText === void 0) {
1892
+ return { value: void 0, state: "undefined-input" };
1893
+ }
1894
+ let result = safeParseJSON({ text: jsonText });
1895
+ if (result.success) {
1896
+ return { value: result.value, state: "successful-parse" };
1897
+ }
1898
+ result = safeParseJSON({ text: fixJson(jsonText) });
1899
+ if (result.success) {
1900
+ return { value: result.value, state: "repaired-parse" };
1901
+ }
1902
+ return { value: void 0, state: "failed-parse" };
1903
+ }
1904
+ var textStreamPart2 = {
1905
+ code: "0",
1906
+ name: "text",
1907
+ parse: (value) => {
1908
+ if (typeof value !== "string") {
1909
+ throw new Error('"text" parts expect a string value.');
1910
+ }
1911
+ return { type: "text", value };
1912
+ }
1913
+ };
1914
+ var dataStreamPart = {
1915
+ code: "2",
1916
+ name: "data",
1917
+ parse: (value) => {
1918
+ if (!Array.isArray(value)) {
1919
+ throw new Error('"data" parts expect an array value.');
1920
+ }
1921
+ return { type: "data", value };
1922
+ }
1923
+ };
1924
+ var errorStreamPart2 = {
1925
+ code: "3",
1926
+ name: "error",
1927
+ parse: (value) => {
1928
+ if (typeof value !== "string") {
1929
+ throw new Error('"error" parts expect a string value.');
1930
+ }
1931
+ return { type: "error", value };
1932
+ }
1933
+ };
1934
+ var messageAnnotationsStreamPart = {
1935
+ code: "8",
1936
+ name: "message_annotations",
1937
+ parse: (value) => {
1938
+ if (!Array.isArray(value)) {
1939
+ throw new Error('"message_annotations" parts expect an array value.');
1940
+ }
1941
+ return { type: "message_annotations", value };
1942
+ }
1943
+ };
1944
+ var toolCallStreamPart = {
1945
+ code: "9",
1946
+ name: "tool_call",
1947
+ parse: (value) => {
1948
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
1949
+ throw new Error(
1950
+ '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
1951
+ );
1952
+ }
1953
+ return {
1954
+ type: "tool_call",
1955
+ value
1956
+ };
1957
+ }
1958
+ };
1959
+ var toolResultStreamPart = {
1960
+ code: "a",
1961
+ name: "tool_result",
1962
+ parse: (value) => {
1963
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) {
1964
+ throw new Error(
1965
+ '"tool_result" parts expect an object with a "toolCallId" and a "result" property.'
1966
+ );
1967
+ }
1968
+ return {
1969
+ type: "tool_result",
1970
+ value
1971
+ };
1972
+ }
1973
+ };
1974
+ var toolCallStreamingStartStreamPart = {
1975
+ code: "b",
1976
+ name: "tool_call_streaming_start",
1977
+ parse: (value) => {
1978
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") {
1979
+ throw new Error(
1980
+ '"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.'
1981
+ );
1982
+ }
1983
+ return {
1984
+ type: "tool_call_streaming_start",
1985
+ value
1986
+ };
1987
+ }
1988
+ };
1989
+ var toolCallDeltaStreamPart = {
1990
+ code: "c",
1991
+ name: "tool_call_delta",
1992
+ parse: (value) => {
1993
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") {
1994
+ throw new Error(
1995
+ '"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.'
1996
+ );
1997
+ }
1998
+ return {
1999
+ type: "tool_call_delta",
2000
+ value
2001
+ };
2002
+ }
2003
+ };
2004
+ var finishMessageStreamPart = {
2005
+ code: "d",
2006
+ name: "finish_message",
2007
+ parse: (value) => {
2008
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
2009
+ throw new Error(
2010
+ '"finish_message" parts expect an object with a "finishReason" property.'
2011
+ );
2012
+ }
2013
+ const result = {
2014
+ finishReason: value.finishReason
2015
+ };
2016
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
2017
+ result.usage = {
2018
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
2019
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
2020
+ };
2021
+ }
2022
+ return {
2023
+ type: "finish_message",
2024
+ value: result
2025
+ };
2026
+ }
2027
+ };
2028
+ var finishStepStreamPart = {
2029
+ code: "e",
2030
+ name: "finish_step",
2031
+ parse: (value) => {
2032
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
2033
+ throw new Error(
2034
+ '"finish_step" parts expect an object with a "finishReason" property.'
2035
+ );
2036
+ }
2037
+ const result = {
2038
+ finishReason: value.finishReason,
2039
+ isContinued: false
2040
+ };
2041
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
2042
+ result.usage = {
2043
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
2044
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
2045
+ };
2046
+ }
2047
+ if ("isContinued" in value && typeof value.isContinued === "boolean") {
2048
+ result.isContinued = value.isContinued;
2049
+ }
2050
+ return {
2051
+ type: "finish_step",
2052
+ value: result
2053
+ };
2054
+ }
2055
+ };
2056
+ var startStepStreamPart = {
2057
+ code: "f",
2058
+ name: "start_step",
2059
+ parse: (value) => {
2060
+ if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") {
2061
+ throw new Error(
2062
+ '"start_step" parts expect an object with an "id" property.'
2063
+ );
2064
+ }
2065
+ return {
2066
+ type: "start_step",
2067
+ value: {
2068
+ messageId: value.messageId
2069
+ }
2070
+ };
2071
+ }
2072
+ };
2073
+ var reasoningStreamPart = {
2074
+ code: "g",
2075
+ name: "reasoning",
2076
+ parse: (value) => {
2077
+ if (typeof value !== "string") {
2078
+ throw new Error('"reasoning" parts expect a string value.');
2079
+ }
2080
+ return { type: "reasoning", value };
2081
+ }
2082
+ };
2083
+ var sourcePart = {
2084
+ code: "h",
2085
+ name: "source",
2086
+ parse: (value) => {
2087
+ if (value == null || typeof value !== "object") {
2088
+ throw new Error('"source" parts expect a Source object.');
2089
+ }
2090
+ return {
2091
+ type: "source",
2092
+ value
2093
+ };
2094
+ }
2095
+ };
2096
+ var redactedReasoningStreamPart = {
2097
+ code: "i",
2098
+ name: "redacted_reasoning",
2099
+ parse: (value) => {
2100
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string") {
2101
+ throw new Error(
2102
+ '"redacted_reasoning" parts expect an object with a "data" property.'
2103
+ );
2104
+ }
2105
+ return { type: "redacted_reasoning", value: { data: value.data } };
2106
+ }
2107
+ };
2108
+ var reasoningSignatureStreamPart = {
2109
+ code: "j",
2110
+ name: "reasoning_signature",
2111
+ parse: (value) => {
2112
+ if (value == null || typeof value !== "object" || !("signature" in value) || typeof value.signature !== "string") {
2113
+ throw new Error(
2114
+ '"reasoning_signature" parts expect an object with a "signature" property.'
2115
+ );
2116
+ }
2117
+ return {
2118
+ type: "reasoning_signature",
2119
+ value: { signature: value.signature }
2120
+ };
2121
+ }
2122
+ };
2123
+ var fileStreamPart = {
2124
+ code: "k",
2125
+ name: "file",
2126
+ parse: (value) => {
2127
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string" || !("mimeType" in value) || typeof value.mimeType !== "string") {
2128
+ throw new Error(
2129
+ '"file" parts expect an object with a "data" and "mimeType" property.'
2130
+ );
2131
+ }
2132
+ return { type: "file", value };
2133
+ }
2134
+ };
2135
+ var dataStreamParts = [
2136
+ textStreamPart2,
2137
+ dataStreamPart,
2138
+ errorStreamPart2,
2139
+ messageAnnotationsStreamPart,
2140
+ toolCallStreamPart,
2141
+ toolResultStreamPart,
2142
+ toolCallStreamingStartStreamPart,
2143
+ toolCallDeltaStreamPart,
2144
+ finishMessageStreamPart,
2145
+ finishStepStreamPart,
2146
+ startStepStreamPart,
2147
+ reasoningStreamPart,
2148
+ sourcePart,
2149
+ redactedReasoningStreamPart,
2150
+ reasoningSignatureStreamPart,
2151
+ fileStreamPart
2152
+ ];
2153
+ Object.fromEntries(
2154
+ dataStreamParts.map((part) => [part.code, part])
2155
+ );
2156
+ Object.fromEntries(
2157
+ dataStreamParts.map((part) => [part.name, part.code])
2158
+ );
2159
+ function formatDataStreamPart(type, value) {
2160
+ const streamPart = dataStreamParts.find((part) => part.name === type);
2161
+ if (!streamPart) {
2162
+ throw new Error(`Invalid stream part type: ${type}`);
2163
+ }
2164
+ return `${streamPart.code}:${JSON.stringify(value)}
2165
+ `;
2166
+ }
2167
+ function zodSchema(zodSchema2, options) {
2168
+ var _a17;
2169
+ const useReferences = (_a17 = void 0) != null ? _a17 : false;
2170
+ return jsonSchema(
2171
+ esm_default(zodSchema2, {
2172
+ $refStrategy: useReferences ? "root" : "none",
2173
+ target: "jsonSchema7"
2174
+ // note: openai mode breaks various gemini conversions
2175
+ }),
2176
+ {
2177
+ validate: (value) => {
2178
+ const result = zodSchema2.safeParse(value);
2179
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2180
+ }
2181
+ }
2182
+ );
2183
+ }
2184
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
2185
+ function jsonSchema(jsonSchema2, {
2186
+ validate
2187
+ } = {}) {
2188
+ return {
2189
+ [schemaSymbol]: true,
2190
+ _type: void 0,
2191
+ // should never be used directly
2192
+ [validatorSymbol]: true,
2193
+ jsonSchema: jsonSchema2,
2194
+ validate
2195
+ };
2196
+ }
2197
+ function isSchema(value) {
2198
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2199
+ }
2200
+ function asSchema(schema) {
2201
+ return isSchema(schema) ? schema : zodSchema(schema);
2202
+ }
2203
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
2204
+ var VERSION = "1.9.0";
2205
+ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
2206
+ function _makeCompatibilityCheck(ownVersion) {
2207
+ var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
2208
+ var rejectedVersions = /* @__PURE__ */ new Set();
2209
+ var myVersionMatch = ownVersion.match(re);
2210
+ if (!myVersionMatch) {
2211
+ return function() {
2212
+ return false;
2213
+ };
2214
+ }
2215
+ var ownVersionParsed = {
2216
+ major: +myVersionMatch[1],
2217
+ minor: +myVersionMatch[2],
2218
+ patch: +myVersionMatch[3],
2219
+ prerelease: myVersionMatch[4]
2220
+ };
2221
+ if (ownVersionParsed.prerelease != null) {
2222
+ return function isExactmatch(globalVersion) {
2223
+ return globalVersion === ownVersion;
2224
+ };
2225
+ }
2226
+ function _reject(v) {
2227
+ rejectedVersions.add(v);
2228
+ return false;
2229
+ }
2230
+ function _accept(v) {
2231
+ acceptedVersions.add(v);
2232
+ return true;
2233
+ }
2234
+ return function isCompatible2(globalVersion) {
2235
+ if (acceptedVersions.has(globalVersion)) {
2236
+ return true;
2237
+ }
2238
+ if (rejectedVersions.has(globalVersion)) {
2239
+ return false;
2240
+ }
2241
+ var globalVersionMatch = globalVersion.match(re);
2242
+ if (!globalVersionMatch) {
2243
+ return _reject(globalVersion);
2244
+ }
2245
+ var globalVersionParsed = {
2246
+ major: +globalVersionMatch[1],
2247
+ minor: +globalVersionMatch[2],
2248
+ patch: +globalVersionMatch[3],
2249
+ prerelease: globalVersionMatch[4]
2250
+ };
2251
+ if (globalVersionParsed.prerelease != null) {
2252
+ return _reject(globalVersion);
2253
+ }
2254
+ if (ownVersionParsed.major !== globalVersionParsed.major) {
2255
+ return _reject(globalVersion);
2256
+ }
2257
+ if (ownVersionParsed.major === 0) {
2258
+ if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
2259
+ return _accept(globalVersion);
2260
+ }
2261
+ return _reject(globalVersion);
2262
+ }
2263
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
2264
+ return _accept(globalVersion);
2265
+ }
2266
+ return _reject(globalVersion);
2267
+ };
2268
+ }
2269
+ var isCompatible = _makeCompatibilityCheck(VERSION);
2270
+ var major = VERSION.split(".")[0];
2271
+ var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
2272
+ var _global = _globalThis;
2273
+ function registerGlobal(type, instance, diag, allowOverride) {
2274
+ var _a17;
2275
+ if (allowOverride === void 0) {
2276
+ allowOverride = false;
2277
+ }
2278
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a17 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a17 !== void 0 ? _a17 : {
2279
+ version: VERSION
2280
+ };
2281
+ if (!allowOverride && api[type]) {
2282
+ var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
2283
+ diag.error(err.stack || err.message);
2284
+ return false;
2285
+ }
2286
+ if (api.version !== VERSION) {
2287
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
2288
+ diag.error(err.stack || err.message);
2289
+ return false;
2290
+ }
2291
+ api[type] = instance;
2292
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
2293
+ return true;
2294
+ }
2295
+ function getGlobal(type) {
2296
+ var _a17, _b;
2297
+ var globalVersion = (_a17 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a17 === void 0 ? void 0 : _a17.version;
2298
+ if (!globalVersion || !isCompatible(globalVersion)) {
2299
+ return;
2300
+ }
2301
+ return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
2302
+ }
2303
+ function unregisterGlobal(type, diag) {
2304
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
2305
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
2306
+ if (api) {
2307
+ delete api[type];
2308
+ }
2309
+ }
2310
+ var __read = function(o, n) {
2311
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2312
+ if (!m) return o;
2313
+ var i = m.call(o), r, ar = [], e;
2314
+ try {
2315
+ while (!(r = i.next()).done) ar.push(r.value);
2316
+ } catch (error) {
2317
+ e = { error };
2318
+ } finally {
2319
+ try {
2320
+ if (r && !r.done && (m = i["return"])) m.call(i);
2321
+ } finally {
2322
+ if (e) throw e.error;
2323
+ }
2324
+ }
2325
+ return ar;
2326
+ };
2327
+ var __spreadArray = function(to, from, pack) {
2328
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2329
+ if (ar || !(i in from)) {
2330
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2331
+ ar[i] = from[i];
2332
+ }
2333
+ }
2334
+ return to.concat(ar || Array.prototype.slice.call(from));
2335
+ };
2336
+ var DiagComponentLogger = (
2337
+ /** @class */
2338
+ (function() {
2339
+ function DiagComponentLogger2(props) {
2340
+ this._namespace = props.namespace || "DiagComponentLogger";
2341
+ }
2342
+ DiagComponentLogger2.prototype.debug = function() {
2343
+ var args = [];
2344
+ for (var _i = 0; _i < arguments.length; _i++) {
2345
+ args[_i] = arguments[_i];
2346
+ }
2347
+ return logProxy("debug", this._namespace, args);
2348
+ };
2349
+ DiagComponentLogger2.prototype.error = function() {
2350
+ var args = [];
2351
+ for (var _i = 0; _i < arguments.length; _i++) {
2352
+ args[_i] = arguments[_i];
2353
+ }
2354
+ return logProxy("error", this._namespace, args);
2355
+ };
2356
+ DiagComponentLogger2.prototype.info = function() {
2357
+ var args = [];
2358
+ for (var _i = 0; _i < arguments.length; _i++) {
2359
+ args[_i] = arguments[_i];
2360
+ }
2361
+ return logProxy("info", this._namespace, args);
2362
+ };
2363
+ DiagComponentLogger2.prototype.warn = function() {
2364
+ var args = [];
2365
+ for (var _i = 0; _i < arguments.length; _i++) {
2366
+ args[_i] = arguments[_i];
2367
+ }
2368
+ return logProxy("warn", this._namespace, args);
2369
+ };
2370
+ DiagComponentLogger2.prototype.verbose = function() {
2371
+ var args = [];
2372
+ for (var _i = 0; _i < arguments.length; _i++) {
2373
+ args[_i] = arguments[_i];
2374
+ }
2375
+ return logProxy("verbose", this._namespace, args);
2376
+ };
2377
+ return DiagComponentLogger2;
2378
+ })()
2379
+ );
2380
+ function logProxy(funcName, namespace, args) {
2381
+ var logger = getGlobal("diag");
2382
+ if (!logger) {
2383
+ return;
2384
+ }
2385
+ args.unshift(namespace);
2386
+ return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
2387
+ }
2388
+ var DiagLogLevel;
2389
+ (function(DiagLogLevel2) {
2390
+ DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
2391
+ DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
2392
+ DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
2393
+ DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
2394
+ DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
2395
+ DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
2396
+ DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
2397
+ })(DiagLogLevel || (DiagLogLevel = {}));
2398
+ function createLogLevelDiagLogger(maxLevel, logger) {
2399
+ if (maxLevel < DiagLogLevel.NONE) {
2400
+ maxLevel = DiagLogLevel.NONE;
2401
+ } else if (maxLevel > DiagLogLevel.ALL) {
2402
+ maxLevel = DiagLogLevel.ALL;
2403
+ }
2404
+ logger = logger || {};
2405
+ function _filterFunc(funcName, theLevel) {
2406
+ var theFunc = logger[funcName];
2407
+ if (typeof theFunc === "function" && maxLevel >= theLevel) {
2408
+ return theFunc.bind(logger);
2409
+ }
2410
+ return function() {
2411
+ };
2412
+ }
2413
+ return {
2414
+ error: _filterFunc("error", DiagLogLevel.ERROR),
2415
+ warn: _filterFunc("warn", DiagLogLevel.WARN),
2416
+ info: _filterFunc("info", DiagLogLevel.INFO),
2417
+ debug: _filterFunc("debug", DiagLogLevel.DEBUG),
2418
+ verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
2419
+ };
2420
+ }
2421
+ var __read2 = function(o, n) {
2422
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2423
+ if (!m) return o;
2424
+ var i = m.call(o), r, ar = [], e;
2425
+ try {
2426
+ while (!(r = i.next()).done) ar.push(r.value);
2427
+ } catch (error) {
2428
+ e = { error };
2429
+ } finally {
2430
+ try {
2431
+ if (r && !r.done && (m = i["return"])) m.call(i);
2432
+ } finally {
2433
+ if (e) throw e.error;
2434
+ }
2435
+ }
2436
+ return ar;
2437
+ };
2438
+ var __spreadArray2 = function(to, from, pack) {
2439
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2440
+ if (ar || !(i in from)) {
2441
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2442
+ ar[i] = from[i];
2443
+ }
2444
+ }
2445
+ return to.concat(ar || Array.prototype.slice.call(from));
2446
+ };
2447
+ var API_NAME = "diag";
2448
+ var DiagAPI = (
2449
+ /** @class */
2450
+ (function() {
2451
+ function DiagAPI2() {
2452
+ function _logProxy(funcName) {
2453
+ return function() {
2454
+ var args = [];
2455
+ for (var _i = 0; _i < arguments.length; _i++) {
2456
+ args[_i] = arguments[_i];
2457
+ }
2458
+ var logger = getGlobal("diag");
2459
+ if (!logger)
2460
+ return;
2461
+ return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
2462
+ };
2463
+ }
2464
+ var self = this;
2465
+ var setLogger = function(logger, optionsOrLogLevel) {
2466
+ var _a17, _b, _c;
2467
+ if (optionsOrLogLevel === void 0) {
2468
+ optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
2469
+ }
2470
+ if (logger === self) {
2471
+ var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
2472
+ self.error((_a17 = err.stack) !== null && _a17 !== void 0 ? _a17 : err.message);
2473
+ return false;
2474
+ }
2475
+ if (typeof optionsOrLogLevel === "number") {
2476
+ optionsOrLogLevel = {
2477
+ logLevel: optionsOrLogLevel
2478
+ };
2479
+ }
2480
+ var oldLogger = getGlobal("diag");
2481
+ var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
2482
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
2483
+ var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
2484
+ oldLogger.warn("Current logger will be overwritten from " + stack);
2485
+ newLogger.warn("Current logger will overwrite one already registered from " + stack);
2486
+ }
2487
+ return registerGlobal("diag", newLogger, self, true);
2488
+ };
2489
+ self.setLogger = setLogger;
2490
+ self.disable = function() {
2491
+ unregisterGlobal(API_NAME, self);
2492
+ };
2493
+ self.createComponentLogger = function(options) {
2494
+ return new DiagComponentLogger(options);
2495
+ };
2496
+ self.verbose = _logProxy("verbose");
2497
+ self.debug = _logProxy("debug");
2498
+ self.info = _logProxy("info");
2499
+ self.warn = _logProxy("warn");
2500
+ self.error = _logProxy("error");
2501
+ }
2502
+ DiagAPI2.instance = function() {
2503
+ if (!this._instance) {
2504
+ this._instance = new DiagAPI2();
2505
+ }
2506
+ return this._instance;
2507
+ };
2508
+ return DiagAPI2;
2509
+ })()
2510
+ );
2511
+ function createContextKey(description) {
2512
+ return Symbol.for(description);
2513
+ }
2514
+ var BaseContext = (
2515
+ /** @class */
2516
+ /* @__PURE__ */ (function() {
2517
+ function BaseContext2(parentContext) {
2518
+ var self = this;
2519
+ self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
2520
+ self.getValue = function(key) {
2521
+ return self._currentContext.get(key);
2522
+ };
2523
+ self.setValue = function(key, value) {
2524
+ var context = new BaseContext2(self._currentContext);
2525
+ context._currentContext.set(key, value);
2526
+ return context;
2527
+ };
2528
+ self.deleteValue = function(key) {
2529
+ var context = new BaseContext2(self._currentContext);
2530
+ context._currentContext.delete(key);
2531
+ return context;
2532
+ };
2533
+ }
2534
+ return BaseContext2;
2535
+ })()
2536
+ );
2537
+ var ROOT_CONTEXT = new BaseContext();
2538
+ var __read3 = function(o, n) {
2539
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2540
+ if (!m) return o;
2541
+ var i = m.call(o), r, ar = [], e;
2542
+ try {
2543
+ while (!(r = i.next()).done) ar.push(r.value);
2544
+ } catch (error) {
2545
+ e = { error };
2546
+ } finally {
2547
+ try {
2548
+ if (r && !r.done && (m = i["return"])) m.call(i);
2549
+ } finally {
2550
+ if (e) throw e.error;
2551
+ }
2552
+ }
2553
+ return ar;
2554
+ };
2555
+ var __spreadArray3 = function(to, from, pack) {
2556
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2557
+ if (ar || !(i in from)) {
2558
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2559
+ ar[i] = from[i];
2560
+ }
2561
+ }
2562
+ return to.concat(ar || Array.prototype.slice.call(from));
2563
+ };
2564
+ var NoopContextManager = (
2565
+ /** @class */
2566
+ (function() {
2567
+ function NoopContextManager2() {
2568
+ }
2569
+ NoopContextManager2.prototype.active = function() {
2570
+ return ROOT_CONTEXT;
2571
+ };
2572
+ NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
2573
+ var args = [];
2574
+ for (var _i = 3; _i < arguments.length; _i++) {
2575
+ args[_i - 3] = arguments[_i];
2576
+ }
2577
+ return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
2578
+ };
2579
+ NoopContextManager2.prototype.bind = function(_context, target) {
2580
+ return target;
2581
+ };
2582
+ NoopContextManager2.prototype.enable = function() {
2583
+ return this;
2584
+ };
2585
+ NoopContextManager2.prototype.disable = function() {
2586
+ return this;
2587
+ };
2588
+ return NoopContextManager2;
2589
+ })()
2590
+ );
2591
+ var __read4 = function(o, n) {
2592
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2593
+ if (!m) return o;
2594
+ var i = m.call(o), r, ar = [], e;
2595
+ try {
2596
+ while (!(r = i.next()).done) ar.push(r.value);
2597
+ } catch (error) {
2598
+ e = { error };
2599
+ } finally {
2600
+ try {
2601
+ if (r && !r.done && (m = i["return"])) m.call(i);
2602
+ } finally {
2603
+ if (e) throw e.error;
2604
+ }
2605
+ }
2606
+ return ar;
2607
+ };
2608
+ var __spreadArray4 = function(to, from, pack) {
2609
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2610
+ if (ar || !(i in from)) {
2611
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2612
+ ar[i] = from[i];
2613
+ }
2614
+ }
2615
+ return to.concat(ar || Array.prototype.slice.call(from));
2616
+ };
2617
+ var API_NAME2 = "context";
2618
+ var NOOP_CONTEXT_MANAGER = new NoopContextManager();
2619
+ var ContextAPI = (
2620
+ /** @class */
2621
+ (function() {
2622
+ function ContextAPI2() {
2623
+ }
2624
+ ContextAPI2.getInstance = function() {
2625
+ if (!this._instance) {
2626
+ this._instance = new ContextAPI2();
2627
+ }
2628
+ return this._instance;
2629
+ };
2630
+ ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
2631
+ return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
2632
+ };
2633
+ ContextAPI2.prototype.active = function() {
2634
+ return this._getContextManager().active();
2635
+ };
2636
+ ContextAPI2.prototype.with = function(context, fn, thisArg) {
2637
+ var _a17;
2638
+ var args = [];
2639
+ for (var _i = 3; _i < arguments.length; _i++) {
2640
+ args[_i - 3] = arguments[_i];
2641
+ }
2642
+ return (_a17 = this._getContextManager()).with.apply(_a17, __spreadArray4([context, fn, thisArg], __read4(args), false));
2643
+ };
2644
+ ContextAPI2.prototype.bind = function(context, target) {
2645
+ return this._getContextManager().bind(context, target);
2646
+ };
2647
+ ContextAPI2.prototype._getContextManager = function() {
2648
+ return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
2649
+ };
2650
+ ContextAPI2.prototype.disable = function() {
2651
+ this._getContextManager().disable();
2652
+ unregisterGlobal(API_NAME2, DiagAPI.instance());
2653
+ };
2654
+ return ContextAPI2;
2655
+ })()
2656
+ );
2657
+ var TraceFlags;
2658
+ (function(TraceFlags2) {
2659
+ TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
2660
+ TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
2661
+ })(TraceFlags || (TraceFlags = {}));
2662
+ var INVALID_SPANID = "0000000000000000";
2663
+ var INVALID_TRACEID = "00000000000000000000000000000000";
2664
+ var INVALID_SPAN_CONTEXT = {
2665
+ traceId: INVALID_TRACEID,
2666
+ spanId: INVALID_SPANID,
2667
+ traceFlags: TraceFlags.NONE
2668
+ };
2669
+ var NonRecordingSpan = (
2670
+ /** @class */
2671
+ (function() {
2672
+ function NonRecordingSpan2(_spanContext) {
2673
+ if (_spanContext === void 0) {
2674
+ _spanContext = INVALID_SPAN_CONTEXT;
2675
+ }
2676
+ this._spanContext = _spanContext;
2677
+ }
2678
+ NonRecordingSpan2.prototype.spanContext = function() {
2679
+ return this._spanContext;
2680
+ };
2681
+ NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
2682
+ return this;
2683
+ };
2684
+ NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
2685
+ return this;
2686
+ };
2687
+ NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
2688
+ return this;
2689
+ };
2690
+ NonRecordingSpan2.prototype.addLink = function(_link) {
2691
+ return this;
2692
+ };
2693
+ NonRecordingSpan2.prototype.addLinks = function(_links) {
2694
+ return this;
2695
+ };
2696
+ NonRecordingSpan2.prototype.setStatus = function(_status) {
2697
+ return this;
2698
+ };
2699
+ NonRecordingSpan2.prototype.updateName = function(_name) {
2700
+ return this;
2701
+ };
2702
+ NonRecordingSpan2.prototype.end = function(_endTime) {
2703
+ };
2704
+ NonRecordingSpan2.prototype.isRecording = function() {
2705
+ return false;
2706
+ };
2707
+ NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
2708
+ };
2709
+ return NonRecordingSpan2;
2710
+ })()
2711
+ );
2712
+ var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
2713
+ function getSpan(context) {
2714
+ return context.getValue(SPAN_KEY) || void 0;
2715
+ }
2716
+ function getActiveSpan() {
2717
+ return getSpan(ContextAPI.getInstance().active());
2718
+ }
2719
+ function setSpan(context, span) {
2720
+ return context.setValue(SPAN_KEY, span);
2721
+ }
2722
+ function deleteSpan(context) {
2723
+ return context.deleteValue(SPAN_KEY);
2724
+ }
2725
+ function setSpanContext(context, spanContext) {
2726
+ return setSpan(context, new NonRecordingSpan(spanContext));
2727
+ }
2728
+ function getSpanContext(context) {
2729
+ var _a17;
2730
+ return (_a17 = getSpan(context)) === null || _a17 === void 0 ? void 0 : _a17.spanContext();
2731
+ }
2732
+ var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
2733
+ var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
2734
+ function isValidTraceId(traceId) {
2735
+ return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
2736
+ }
2737
+ function isValidSpanId(spanId) {
2738
+ return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
2739
+ }
2740
+ function isSpanContextValid(spanContext) {
2741
+ return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
2742
+ }
2743
+ function wrapSpanContext(spanContext) {
2744
+ return new NonRecordingSpan(spanContext);
2745
+ }
2746
+ var contextApi = ContextAPI.getInstance();
2747
+ var NoopTracer = (
2748
+ /** @class */
2749
+ (function() {
2750
+ function NoopTracer2() {
2751
+ }
2752
+ NoopTracer2.prototype.startSpan = function(name17, options, context) {
2753
+ if (context === void 0) {
2754
+ context = contextApi.active();
2755
+ }
2756
+ var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
2757
+ if (root) {
2758
+ return new NonRecordingSpan();
2759
+ }
2760
+ var parentFromContext = context && getSpanContext(context);
2761
+ if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
2762
+ return new NonRecordingSpan(parentFromContext);
2763
+ } else {
2764
+ return new NonRecordingSpan();
2765
+ }
2766
+ };
2767
+ NoopTracer2.prototype.startActiveSpan = function(name17, arg2, arg3, arg4) {
2768
+ var opts;
2769
+ var ctx;
2770
+ var fn;
2771
+ if (arguments.length < 2) {
2772
+ return;
2773
+ } else if (arguments.length === 2) {
2774
+ fn = arg2;
2775
+ } else if (arguments.length === 3) {
2776
+ opts = arg2;
2777
+ fn = arg3;
2778
+ } else {
2779
+ opts = arg2;
2780
+ ctx = arg3;
2781
+ fn = arg4;
2782
+ }
2783
+ var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
2784
+ var span = this.startSpan(name17, opts, parentContext);
2785
+ var contextWithSpanSet = setSpan(parentContext, span);
2786
+ return contextApi.with(contextWithSpanSet, fn, void 0, span);
2787
+ };
2788
+ return NoopTracer2;
2789
+ })()
2790
+ );
2791
+ function isSpanContext(spanContext) {
2792
+ return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
2793
+ }
2794
+ var NOOP_TRACER = new NoopTracer();
2795
+ var ProxyTracer = (
2796
+ /** @class */
2797
+ (function() {
2798
+ function ProxyTracer2(_provider, name17, version, options) {
2799
+ this._provider = _provider;
2800
+ this.name = name17;
2801
+ this.version = version;
2802
+ this.options = options;
2803
+ }
2804
+ ProxyTracer2.prototype.startSpan = function(name17, options, context) {
2805
+ return this._getTracer().startSpan(name17, options, context);
2806
+ };
2807
+ ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
2808
+ var tracer = this._getTracer();
2809
+ return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
2810
+ };
2811
+ ProxyTracer2.prototype._getTracer = function() {
2812
+ if (this._delegate) {
2813
+ return this._delegate;
2814
+ }
2815
+ var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
2816
+ if (!tracer) {
2817
+ return NOOP_TRACER;
2818
+ }
2819
+ this._delegate = tracer;
2820
+ return this._delegate;
2821
+ };
2822
+ return ProxyTracer2;
2823
+ })()
2824
+ );
2825
+ var NoopTracerProvider = (
2826
+ /** @class */
2827
+ (function() {
2828
+ function NoopTracerProvider2() {
2829
+ }
2830
+ NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
2831
+ return new NoopTracer();
2832
+ };
2833
+ return NoopTracerProvider2;
2834
+ })()
2835
+ );
2836
+ var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
2837
+ var ProxyTracerProvider = (
2838
+ /** @class */
2839
+ (function() {
2840
+ function ProxyTracerProvider2() {
2841
+ }
2842
+ ProxyTracerProvider2.prototype.getTracer = function(name17, version, options) {
2843
+ var _a17;
2844
+ return (_a17 = this.getDelegateTracer(name17, version, options)) !== null && _a17 !== void 0 ? _a17 : new ProxyTracer(this, name17, version, options);
2845
+ };
2846
+ ProxyTracerProvider2.prototype.getDelegate = function() {
2847
+ var _a17;
2848
+ return (_a17 = this._delegate) !== null && _a17 !== void 0 ? _a17 : NOOP_TRACER_PROVIDER;
2849
+ };
2850
+ ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
2851
+ this._delegate = delegate;
2852
+ };
2853
+ ProxyTracerProvider2.prototype.getDelegateTracer = function(name17, version, options) {
2854
+ var _a17;
2855
+ return (_a17 = this._delegate) === null || _a17 === void 0 ? void 0 : _a17.getTracer(name17, version, options);
2856
+ };
2857
+ return ProxyTracerProvider2;
2858
+ })()
2859
+ );
2860
+ var SpanStatusCode;
2861
+ (function(SpanStatusCode2) {
2862
+ SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
2863
+ SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
2864
+ SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
2865
+ })(SpanStatusCode || (SpanStatusCode = {}));
2866
+ var API_NAME3 = "trace";
2867
+ var TraceAPI = (
2868
+ /** @class */
2869
+ (function() {
2870
+ function TraceAPI2() {
2871
+ this._proxyTracerProvider = new ProxyTracerProvider();
2872
+ this.wrapSpanContext = wrapSpanContext;
2873
+ this.isSpanContextValid = isSpanContextValid;
2874
+ this.deleteSpan = deleteSpan;
2875
+ this.getSpan = getSpan;
2876
+ this.getActiveSpan = getActiveSpan;
2877
+ this.getSpanContext = getSpanContext;
2878
+ this.setSpan = setSpan;
2879
+ this.setSpanContext = setSpanContext;
2880
+ }
2881
+ TraceAPI2.getInstance = function() {
2882
+ if (!this._instance) {
2883
+ this._instance = new TraceAPI2();
2884
+ }
2885
+ return this._instance;
2886
+ };
2887
+ TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
2888
+ var success = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance());
2889
+ if (success) {
2890
+ this._proxyTracerProvider.setDelegate(provider);
2891
+ }
2892
+ return success;
2893
+ };
2894
+ TraceAPI2.prototype.getTracerProvider = function() {
2895
+ return getGlobal(API_NAME3) || this._proxyTracerProvider;
2896
+ };
2897
+ TraceAPI2.prototype.getTracer = function(name17, version) {
2898
+ return this.getTracerProvider().getTracer(name17, version);
2899
+ };
2900
+ TraceAPI2.prototype.disable = function() {
2901
+ unregisterGlobal(API_NAME3, DiagAPI.instance());
2902
+ this._proxyTracerProvider = new ProxyTracerProvider();
2903
+ };
2904
+ return TraceAPI2;
2905
+ })()
2906
+ );
2907
+ TraceAPI.getInstance();
2908
+ var __defProp2 = Object.defineProperty;
2909
+ var __export = (target, all) => {
2910
+ for (var name17 in all)
2911
+ __defProp2(target, name17, { get: all[name17], enumerable: true });
2912
+ };
2913
+ function prepareResponseHeaders(headers, {
2914
+ contentType,
2915
+ dataStreamVersion
2916
+ }) {
2917
+ const responseHeaders = new Headers(headers != null ? headers : {});
2918
+ if (!responseHeaders.has("Content-Type")) {
2919
+ responseHeaders.set("Content-Type", contentType);
2920
+ }
2921
+ {
2922
+ responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
2923
+ }
2924
+ return responseHeaders;
2925
+ }
2926
+ var name42 = "AI_NoObjectGeneratedError";
2927
+ var marker42 = `vercel.ai.error.${name42}`;
2928
+ var symbol42 = Symbol.for(marker42);
2929
+ var _a42;
2930
+ var NoObjectGeneratedError = class extends AISDKError {
2931
+ constructor({
2932
+ message = "No object generated.",
2933
+ cause,
2934
+ text: text2,
2935
+ response,
2936
+ usage,
2937
+ finishReason
2938
+ }) {
2939
+ super({ name: name42, message, cause });
2940
+ this[_a42] = true;
2941
+ this.text = text2;
2942
+ this.response = response;
2943
+ this.usage = usage;
2944
+ this.finishReason = finishReason;
2945
+ }
2946
+ static isInstance(error) {
2947
+ return AISDKError.hasMarker(error, marker42);
2948
+ }
2949
+ };
2950
+ _a42 = symbol42;
2951
+ var dataContentSchema = zod.z.union([
2952
+ zod.z.string(),
2953
+ zod.z.instanceof(Uint8Array),
2954
+ zod.z.instanceof(ArrayBuffer),
2955
+ zod.z.custom(
2956
+ // Buffer might not be available in some environments such as CloudFlare:
2957
+ (value) => {
2958
+ var _a17, _b;
2959
+ return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
2960
+ },
2961
+ { message: "Must be a Buffer" }
2962
+ )
2963
+ ]);
2964
+ var jsonValueSchema = zod.z.lazy(
2965
+ () => zod.z.union([
2966
+ zod.z.null(),
2967
+ zod.z.string(),
2968
+ zod.z.number(),
2969
+ zod.z.boolean(),
2970
+ zod.z.record(zod.z.string(), jsonValueSchema),
2971
+ zod.z.array(jsonValueSchema)
2972
+ ])
2973
+ );
2974
+ var providerMetadataSchema = zod.z.record(
2975
+ zod.z.string(),
2976
+ zod.z.record(zod.z.string(), jsonValueSchema)
2977
+ );
2978
+ var toolResultContentSchema = zod.z.array(
2979
+ zod.z.union([
2980
+ zod.z.object({ type: zod.z.literal("text"), text: zod.z.string() }),
2981
+ zod.z.object({
2982
+ type: zod.z.literal("image"),
2983
+ data: zod.z.string(),
2984
+ mimeType: zod.z.string().optional()
2985
+ })
2986
+ ])
2987
+ );
2988
+ var textPartSchema = zod.z.object({
2989
+ type: zod.z.literal("text"),
2990
+ text: zod.z.string(),
2991
+ providerOptions: providerMetadataSchema.optional(),
2992
+ experimental_providerMetadata: providerMetadataSchema.optional()
2993
+ });
2994
+ var imagePartSchema = zod.z.object({
2995
+ type: zod.z.literal("image"),
2996
+ image: zod.z.union([dataContentSchema, zod.z.instanceof(URL)]),
2997
+ mimeType: zod.z.string().optional(),
2998
+ providerOptions: providerMetadataSchema.optional(),
2999
+ experimental_providerMetadata: providerMetadataSchema.optional()
3000
+ });
3001
+ var filePartSchema = zod.z.object({
3002
+ type: zod.z.literal("file"),
3003
+ data: zod.z.union([dataContentSchema, zod.z.instanceof(URL)]),
3004
+ filename: zod.z.string().optional(),
3005
+ mimeType: zod.z.string(),
3006
+ providerOptions: providerMetadataSchema.optional(),
3007
+ experimental_providerMetadata: providerMetadataSchema.optional()
3008
+ });
3009
+ var reasoningPartSchema = zod.z.object({
3010
+ type: zod.z.literal("reasoning"),
3011
+ text: zod.z.string(),
3012
+ providerOptions: providerMetadataSchema.optional(),
3013
+ experimental_providerMetadata: providerMetadataSchema.optional()
3014
+ });
3015
+ var redactedReasoningPartSchema = zod.z.object({
3016
+ type: zod.z.literal("redacted-reasoning"),
3017
+ data: zod.z.string(),
3018
+ providerOptions: providerMetadataSchema.optional(),
3019
+ experimental_providerMetadata: providerMetadataSchema.optional()
3020
+ });
3021
+ var toolCallPartSchema = zod.z.object({
3022
+ type: zod.z.literal("tool-call"),
3023
+ toolCallId: zod.z.string(),
3024
+ toolName: zod.z.string(),
3025
+ args: zod.z.unknown(),
3026
+ providerOptions: providerMetadataSchema.optional(),
3027
+ experimental_providerMetadata: providerMetadataSchema.optional()
3028
+ });
3029
+ var toolResultPartSchema = zod.z.object({
3030
+ type: zod.z.literal("tool-result"),
3031
+ toolCallId: zod.z.string(),
3032
+ toolName: zod.z.string(),
3033
+ result: zod.z.unknown(),
3034
+ content: toolResultContentSchema.optional(),
3035
+ isError: zod.z.boolean().optional(),
3036
+ providerOptions: providerMetadataSchema.optional(),
3037
+ experimental_providerMetadata: providerMetadataSchema.optional()
3038
+ });
3039
+ var coreSystemMessageSchema = zod.z.object({
3040
+ role: zod.z.literal("system"),
3041
+ content: zod.z.string(),
3042
+ providerOptions: providerMetadataSchema.optional(),
3043
+ experimental_providerMetadata: providerMetadataSchema.optional()
3044
+ });
3045
+ var coreUserMessageSchema = zod.z.object({
3046
+ role: zod.z.literal("user"),
3047
+ content: zod.z.union([
3048
+ zod.z.string(),
3049
+ zod.z.array(zod.z.union([textPartSchema, imagePartSchema, filePartSchema]))
3050
+ ]),
3051
+ providerOptions: providerMetadataSchema.optional(),
3052
+ experimental_providerMetadata: providerMetadataSchema.optional()
3053
+ });
3054
+ var coreAssistantMessageSchema = zod.z.object({
3055
+ role: zod.z.literal("assistant"),
3056
+ content: zod.z.union([
3057
+ zod.z.string(),
3058
+ zod.z.array(
3059
+ zod.z.union([
3060
+ textPartSchema,
3061
+ filePartSchema,
3062
+ reasoningPartSchema,
3063
+ redactedReasoningPartSchema,
3064
+ toolCallPartSchema
3065
+ ])
3066
+ )
3067
+ ]),
3068
+ providerOptions: providerMetadataSchema.optional(),
3069
+ experimental_providerMetadata: providerMetadataSchema.optional()
3070
+ });
3071
+ var coreToolMessageSchema = zod.z.object({
3072
+ role: zod.z.literal("tool"),
3073
+ content: zod.z.array(toolResultPartSchema),
3074
+ providerOptions: providerMetadataSchema.optional(),
3075
+ experimental_providerMetadata: providerMetadataSchema.optional()
3076
+ });
3077
+ zod.z.union([
3078
+ coreSystemMessageSchema,
3079
+ coreUserMessageSchema,
3080
+ coreAssistantMessageSchema,
3081
+ coreToolMessageSchema
3082
+ ]);
3083
+ var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
3084
+ var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
3085
+ var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
3086
+ function injectJsonInstruction({
3087
+ prompt,
3088
+ schema,
3089
+ schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,
3090
+ schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
3091
+ }) {
3092
+ return [
3093
+ prompt != null && prompt.length > 0 ? prompt : void 0,
3094
+ prompt != null && prompt.length > 0 ? "" : void 0,
3095
+ // add a newline if prompt is not null
3096
+ schemaPrefix,
3097
+ schema != null ? JSON.stringify(schema) : void 0,
3098
+ schemaSuffix
3099
+ ].filter((line) => line != null).join("\n");
3100
+ }
3101
+ createIdGenerator({ prefix: "aiobj", size: 24 });
3102
+ createIdGenerator({ prefix: "aiobj", size: 24 });
3103
+ createIdGenerator({
3104
+ prefix: "aitxt",
3105
+ size: 24
3106
+ });
3107
+ createIdGenerator({
3108
+ prefix: "msg",
3109
+ size: 24
3110
+ });
3111
+ var output_exports = {};
3112
+ __export(output_exports, {
3113
+ object: () => object,
3114
+ text: () => text
3115
+ });
3116
+ var text = () => ({
3117
+ type: "text",
3118
+ responseFormat: () => ({ type: "text" }),
3119
+ injectIntoSystemPrompt({ system }) {
3120
+ return system;
3121
+ },
3122
+ parsePartial({ text: text2 }) {
3123
+ return { partial: text2 };
3124
+ },
3125
+ parseOutput({ text: text2 }) {
3126
+ return text2;
3127
+ }
3128
+ });
3129
+ var object = ({
3130
+ schema: inputSchema
3131
+ }) => {
3132
+ const schema = asSchema(inputSchema);
3133
+ return {
3134
+ type: "object",
3135
+ responseFormat: ({ model }) => ({
3136
+ type: "json",
3137
+ schema: model.supportsStructuredOutputs ? schema.jsonSchema : void 0
3138
+ }),
3139
+ injectIntoSystemPrompt({ system, model }) {
3140
+ return model.supportsStructuredOutputs ? system : injectJsonInstruction({
3141
+ prompt: system,
3142
+ schema: schema.jsonSchema
3143
+ });
3144
+ },
3145
+ parsePartial({ text: text2 }) {
3146
+ const result = parsePartialJson(text2);
3147
+ switch (result.state) {
3148
+ case "failed-parse":
3149
+ case "undefined-input":
3150
+ return void 0;
3151
+ case "repaired-parse":
3152
+ case "successful-parse":
3153
+ return {
3154
+ // Note: currently no validation of partial results:
3155
+ partial: result.value
3156
+ };
3157
+ default: {
3158
+ const _exhaustiveCheck = result.state;
3159
+ throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
3160
+ }
3161
+ }
3162
+ },
3163
+ parseOutput({ text: text2 }, context) {
3164
+ const parseResult = safeParseJSON({ text: text2 });
3165
+ if (!parseResult.success) {
3166
+ throw new NoObjectGeneratedError({
3167
+ message: "No object generated: could not parse the response.",
3168
+ cause: parseResult.error,
3169
+ text: text2,
3170
+ response: context.response,
3171
+ usage: context.usage,
3172
+ finishReason: context.finishReason
3173
+ });
3174
+ }
3175
+ const validationResult = safeValidateTypes({
3176
+ value: parseResult.value,
3177
+ schema
3178
+ });
3179
+ if (!validationResult.success) {
3180
+ throw new NoObjectGeneratedError({
3181
+ message: "No object generated: response did not match schema.",
3182
+ cause: validationResult.error,
3183
+ text: text2,
3184
+ response: context.response,
3185
+ usage: context.usage,
3186
+ finishReason: context.finishReason
3187
+ });
3188
+ }
3189
+ return validationResult.value;
3190
+ }
3191
+ };
3192
+ };
3193
+ function mergeStreams(stream1, stream2) {
3194
+ const reader1 = stream1.getReader();
3195
+ const reader2 = stream2.getReader();
3196
+ let lastRead1 = void 0;
3197
+ let lastRead2 = void 0;
3198
+ let stream1Done = false;
3199
+ let stream2Done = false;
3200
+ async function readStream1(controller) {
3201
+ try {
3202
+ if (lastRead1 == null) {
3203
+ lastRead1 = reader1.read();
3204
+ }
3205
+ const result = await lastRead1;
3206
+ lastRead1 = void 0;
3207
+ if (!result.done) {
3208
+ controller.enqueue(result.value);
3209
+ } else {
3210
+ controller.close();
3211
+ }
3212
+ } catch (error) {
3213
+ controller.error(error);
3214
+ }
3215
+ }
3216
+ async function readStream2(controller) {
3217
+ try {
3218
+ if (lastRead2 == null) {
3219
+ lastRead2 = reader2.read();
3220
+ }
3221
+ const result = await lastRead2;
3222
+ lastRead2 = void 0;
3223
+ if (!result.done) {
3224
+ controller.enqueue(result.value);
3225
+ } else {
3226
+ controller.close();
3227
+ }
3228
+ } catch (error) {
3229
+ controller.error(error);
3230
+ }
3231
+ }
3232
+ return new ReadableStream({
3233
+ async pull(controller) {
3234
+ try {
3235
+ if (stream1Done) {
3236
+ await readStream2(controller);
3237
+ return;
3238
+ }
3239
+ if (stream2Done) {
3240
+ await readStream1(controller);
3241
+ return;
3242
+ }
3243
+ if (lastRead1 == null) {
3244
+ lastRead1 = reader1.read();
3245
+ }
3246
+ if (lastRead2 == null) {
3247
+ lastRead2 = reader2.read();
3248
+ }
3249
+ const { result, reader } = await Promise.race([
3250
+ lastRead1.then((result2) => ({ result: result2, reader: reader1 })),
3251
+ lastRead2.then((result2) => ({ result: result2, reader: reader2 }))
3252
+ ]);
3253
+ if (!result.done) {
3254
+ controller.enqueue(result.value);
3255
+ }
3256
+ if (reader === reader1) {
3257
+ lastRead1 = void 0;
3258
+ if (result.done) {
3259
+ await readStream2(controller);
3260
+ stream1Done = true;
3261
+ }
3262
+ } else {
3263
+ lastRead2 = void 0;
3264
+ if (result.done) {
3265
+ stream2Done = true;
3266
+ await readStream1(controller);
3267
+ }
3268
+ }
3269
+ } catch (error) {
3270
+ controller.error(error);
3271
+ }
3272
+ },
3273
+ cancel() {
3274
+ reader1.cancel();
3275
+ reader2.cancel();
3276
+ }
3277
+ });
3278
+ }
3279
+ createIdGenerator({
3280
+ prefix: "aitxt",
3281
+ size: 24
3282
+ });
3283
+ createIdGenerator({
3284
+ prefix: "msg",
3285
+ size: 24
3286
+ });
3287
+ var ClientOrServerImplementationSchema = zod.z.object({
3288
+ name: zod.z.string(),
3289
+ version: zod.z.string()
3290
+ }).passthrough();
3291
+ var BaseParamsSchema = zod.z.object({
3292
+ _meta: zod.z.optional(zod.z.object({}).passthrough())
3293
+ }).passthrough();
3294
+ var ResultSchema = BaseParamsSchema;
3295
+ var RequestSchema = zod.z.object({
3296
+ method: zod.z.string(),
3297
+ params: zod.z.optional(BaseParamsSchema)
3298
+ });
3299
+ var ServerCapabilitiesSchema = zod.z.object({
3300
+ experimental: zod.z.optional(zod.z.object({}).passthrough()),
3301
+ logging: zod.z.optional(zod.z.object({}).passthrough()),
3302
+ prompts: zod.z.optional(
3303
+ zod.z.object({
3304
+ listChanged: zod.z.optional(zod.z.boolean())
3305
+ }).passthrough()
3306
+ ),
3307
+ resources: zod.z.optional(
3308
+ zod.z.object({
3309
+ subscribe: zod.z.optional(zod.z.boolean()),
3310
+ listChanged: zod.z.optional(zod.z.boolean())
3311
+ }).passthrough()
3312
+ ),
3313
+ tools: zod.z.optional(
3314
+ zod.z.object({
3315
+ listChanged: zod.z.optional(zod.z.boolean())
3316
+ }).passthrough()
3317
+ )
3318
+ }).passthrough();
3319
+ ResultSchema.extend({
3320
+ protocolVersion: zod.z.string(),
3321
+ capabilities: ServerCapabilitiesSchema,
3322
+ serverInfo: ClientOrServerImplementationSchema,
3323
+ instructions: zod.z.optional(zod.z.string())
3324
+ });
3325
+ var PaginatedResultSchema = ResultSchema.extend({
3326
+ nextCursor: zod.z.optional(zod.z.string())
3327
+ });
3328
+ var ToolSchema = zod.z.object({
3329
+ name: zod.z.string(),
3330
+ description: zod.z.optional(zod.z.string()),
3331
+ inputSchema: zod.z.object({
3332
+ type: zod.z.literal("object"),
3333
+ properties: zod.z.optional(zod.z.object({}).passthrough())
3334
+ }).passthrough()
3335
+ }).passthrough();
3336
+ PaginatedResultSchema.extend({
3337
+ tools: zod.z.array(ToolSchema)
3338
+ });
3339
+ var TextContentSchema = zod.z.object({
3340
+ type: zod.z.literal("text"),
3341
+ text: zod.z.string()
3342
+ }).passthrough();
3343
+ var ImageContentSchema = zod.z.object({
3344
+ type: zod.z.literal("image"),
3345
+ data: zod.z.string().base64(),
3346
+ mimeType: zod.z.string()
3347
+ }).passthrough();
3348
+ var ResourceContentsSchema = zod.z.object({
3349
+ /**
3350
+ * The URI of this resource.
3351
+ */
3352
+ uri: zod.z.string(),
3353
+ /**
3354
+ * The MIME type of this resource, if known.
3355
+ */
3356
+ mimeType: zod.z.optional(zod.z.string())
3357
+ }).passthrough();
3358
+ var TextResourceContentsSchema = ResourceContentsSchema.extend({
3359
+ text: zod.z.string()
3360
+ });
3361
+ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
3362
+ blob: zod.z.string().base64()
3363
+ });
3364
+ var EmbeddedResourceSchema = zod.z.object({
3365
+ type: zod.z.literal("resource"),
3366
+ resource: zod.z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
3367
+ }).passthrough();
3368
+ ResultSchema.extend({
3369
+ content: zod.z.array(
3370
+ zod.z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
3371
+ ),
3372
+ isError: zod.z.boolean().default(false).optional()
3373
+ }).or(
3374
+ ResultSchema.extend({
3375
+ toolResult: zod.z.unknown()
3376
+ })
3377
+ );
3378
+ var JSONRPC_VERSION = "2.0";
3379
+ var JSONRPCRequestSchema = zod.z.object({
3380
+ jsonrpc: zod.z.literal(JSONRPC_VERSION),
3381
+ id: zod.z.union([zod.z.string(), zod.z.number().int()])
3382
+ }).merge(RequestSchema).strict();
3383
+ var JSONRPCResponseSchema = zod.z.object({
3384
+ jsonrpc: zod.z.literal(JSONRPC_VERSION),
3385
+ id: zod.z.union([zod.z.string(), zod.z.number().int()]),
3386
+ result: ResultSchema
3387
+ }).strict();
3388
+ var JSONRPCErrorSchema = zod.z.object({
3389
+ jsonrpc: zod.z.literal(JSONRPC_VERSION),
3390
+ id: zod.z.union([zod.z.string(), zod.z.number().int()]),
3391
+ error: zod.z.object({
3392
+ code: zod.z.number().int(),
3393
+ message: zod.z.string(),
3394
+ data: zod.z.optional(zod.z.unknown())
3395
+ })
3396
+ }).strict();
3397
+ var JSONRPCNotificationSchema = zod.z.object({
3398
+ jsonrpc: zod.z.literal(JSONRPC_VERSION)
3399
+ }).merge(
3400
+ zod.z.object({
3401
+ method: zod.z.string(),
3402
+ params: zod.z.optional(BaseParamsSchema)
3403
+ })
3404
+ ).strict();
3405
+ zod.z.union([
3406
+ JSONRPCRequestSchema,
3407
+ JSONRPCNotificationSchema,
3408
+ JSONRPCResponseSchema,
3409
+ JSONRPCErrorSchema
3410
+ ]);
3411
+ var langchain_adapter_exports = {};
3412
+ __export(langchain_adapter_exports, {
3413
+ mergeIntoDataStream: () => mergeIntoDataStream,
3414
+ toDataStream: () => toDataStream,
3415
+ toDataStreamResponse: () => toDataStreamResponse
3416
+ });
3417
+ function createCallbacksTransformer(callbacks = {}) {
3418
+ const textEncoder = new TextEncoder();
3419
+ let aggregatedResponse = "";
3420
+ return new TransformStream({
3421
+ async start() {
3422
+ if (callbacks.onStart)
3423
+ await callbacks.onStart();
3424
+ },
3425
+ async transform(message, controller) {
3426
+ controller.enqueue(textEncoder.encode(message));
3427
+ aggregatedResponse += message;
3428
+ if (callbacks.onToken)
3429
+ await callbacks.onToken(message);
3430
+ if (callbacks.onText && typeof message === "string") {
3431
+ await callbacks.onText(message);
3432
+ }
3433
+ },
3434
+ async flush() {
3435
+ if (callbacks.onCompletion) {
3436
+ await callbacks.onCompletion(aggregatedResponse);
3437
+ }
3438
+ if (callbacks.onFinal) {
3439
+ await callbacks.onFinal(aggregatedResponse);
3440
+ }
3441
+ }
3442
+ });
3443
+ }
3444
+ function toDataStreamInternal(stream, callbacks) {
3445
+ return stream.pipeThrough(
3446
+ new TransformStream({
3447
+ transform: async (value, controller) => {
3448
+ var _a17;
3449
+ if (typeof value === "string") {
3450
+ controller.enqueue(value);
3451
+ return;
3452
+ }
3453
+ if ("event" in value) {
3454
+ if (value.event === "on_chat_model_stream") {
3455
+ forwardAIMessageChunk(
3456
+ (_a17 = value.data) == null ? void 0 : _a17.chunk,
3457
+ controller
3458
+ );
3459
+ }
3460
+ return;
3461
+ }
3462
+ forwardAIMessageChunk(value, controller);
3463
+ }
3464
+ })
3465
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
3466
+ new TransformStream({
3467
+ transform: async (chunk, controller) => {
3468
+ controller.enqueue(formatDataStreamPart("text", chunk));
3469
+ }
3470
+ })
3471
+ );
3472
+ }
3473
+ function toDataStream(stream, callbacks) {
3474
+ return toDataStreamInternal(stream, callbacks).pipeThrough(
3475
+ new TextEncoderStream()
3476
+ );
3477
+ }
3478
+ function toDataStreamResponse(stream, options) {
3479
+ var _a17;
3480
+ const dataStream = toDataStreamInternal(
3481
+ stream,
3482
+ options == null ? void 0 : options.callbacks
3483
+ ).pipeThrough(new TextEncoderStream());
3484
+ const data = options == null ? void 0 : options.data;
3485
+ const init = options == null ? void 0 : options.init;
3486
+ const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
3487
+ return new Response(responseStream, {
3488
+ status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
3489
+ statusText: init == null ? void 0 : init.statusText,
3490
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3491
+ contentType: "text/plain; charset=utf-8",
3492
+ dataStreamVersion: "v1"
3493
+ })
3494
+ });
3495
+ }
3496
+ function mergeIntoDataStream(stream, options) {
3497
+ options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
3498
+ }
3499
+ function forwardAIMessageChunk(chunk, controller) {
3500
+ if (typeof chunk.content === "string") {
3501
+ controller.enqueue(chunk.content);
3502
+ } else {
3503
+ const content = chunk.content;
3504
+ for (const item of content) {
3505
+ if (item.type === "text") {
3506
+ controller.enqueue(item.text);
3507
+ }
3508
+ }
3509
+ }
3510
+ }
3511
+ var llamaindex_adapter_exports = {};
3512
+ __export(llamaindex_adapter_exports, {
3513
+ mergeIntoDataStream: () => mergeIntoDataStream2,
3514
+ toDataStream: () => toDataStream2,
3515
+ toDataStreamResponse: () => toDataStreamResponse2
3516
+ });
3517
+ function toDataStreamInternal2(stream, callbacks) {
3518
+ const trimStart = trimStartOfStream();
3519
+ return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough(
3520
+ new TransformStream({
3521
+ async transform(message, controller) {
3522
+ controller.enqueue(trimStart(message.delta));
3523
+ }
3524
+ })
3525
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
3526
+ new TransformStream({
3527
+ transform: async (chunk, controller) => {
3528
+ controller.enqueue(formatDataStreamPart("text", chunk));
3529
+ }
3530
+ })
3531
+ );
3532
+ }
3533
+ function toDataStream2(stream, callbacks) {
3534
+ return toDataStreamInternal2(stream, callbacks).pipeThrough(
3535
+ new TextEncoderStream()
3536
+ );
3537
+ }
3538
+ function toDataStreamResponse2(stream, options = {}) {
3539
+ var _a17;
3540
+ const { init, data, callbacks } = options;
3541
+ const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
3542
+ new TextEncoderStream()
3543
+ );
3544
+ const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
3545
+ return new Response(responseStream, {
3546
+ status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
3547
+ statusText: init == null ? void 0 : init.statusText,
3548
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3549
+ contentType: "text/plain; charset=utf-8",
3550
+ dataStreamVersion: "v1"
3551
+ })
3552
+ });
3553
+ }
3554
+ function mergeIntoDataStream2(stream, options) {
3555
+ options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
3556
+ }
3557
+ function trimStartOfStream() {
3558
+ let isStreamStart = true;
3559
+ return (text2) => {
3560
+ if (isStreamStart) {
3561
+ text2 = text2.trimStart();
3562
+ if (text2)
3563
+ isStreamStart = false;
3564
+ }
3565
+ return text2;
3566
+ };
3567
+ }
3568
+
3569
+ // src/utils.ts
3570
+ function convertZodSchemaToAISDKSchema(zodSchema2, target = "jsonSchema7") {
3571
+ const jsonSchemaToUse = chunk5WM4A32G_cjs.zodToJsonSchema(zodSchema2, target);
3572
+ return jsonSchema(jsonSchemaToUse, {
13
3573
  validate: (value) => {
14
- const result = zodSchema.safeParse(value);
3574
+ const result = zodSchema2.safeParse(value);
15
3575
  return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
16
3576
  }
17
3577
  });
@@ -43,21 +3603,21 @@ function applyCompatLayer({
43
3603
  compatLayers,
44
3604
  mode
45
3605
  }) {
46
- let zodSchema;
3606
+ let zodSchema2;
47
3607
  if (!isZodType(schema)) {
48
- zodSchema = convertSchemaToZod(schema);
3608
+ zodSchema2 = convertSchemaToZod(schema);
49
3609
  } else {
50
- zodSchema = schema;
3610
+ zodSchema2 = schema;
51
3611
  }
52
3612
  for (const compat of compatLayers) {
53
3613
  if (compat.shouldApply()) {
54
- return mode === "jsonSchema" ? compat.processToJSONSchema(zodSchema) : compat.processToAISDKSchema(zodSchema);
3614
+ return mode === "jsonSchema" ? compat.processToJSONSchema(zodSchema2) : compat.processToAISDKSchema(zodSchema2);
55
3615
  }
56
3616
  }
57
3617
  if (mode === "jsonSchema") {
58
- return chunkV7Y3FXBJ_cjs.zodToJsonSchema(zodSchema, "jsonSchema7");
3618
+ return chunk5WM4A32G_cjs.zodToJsonSchema(zodSchema2, "jsonSchema7");
59
3619
  } else {
60
- return convertZodSchemaToAISDKSchema(zodSchema);
3620
+ return convertZodSchemaToAISDKSchema(zodSchema2);
61
3621
  }
62
3622
  }
63
3623
 
@@ -231,8 +3791,8 @@ var SchemaCompatLayer = class {
231
3791
  * @returns The updated description with constraints, or undefined if no constraints
232
3792
  */
233
3793
  mergeParameterDescription(description, constraints) {
234
- if (Object.keys(constraints).length > 0) {
235
- return (description ? description + "\n" : "") + JSON.stringify(constraints);
3794
+ if (constraints.length > 0) {
3795
+ return (description ? description + "\n" : "") + `constraints: ${constraints.join(`, `)}`;
236
3796
  } else {
237
3797
  return description;
238
3798
  }
@@ -262,24 +3822,24 @@ var SchemaCompatLayer = class {
262
3822
  const zodArrayDef = value._def;
263
3823
  const processedType = this.processZodType(zodArrayDef.type);
264
3824
  let result = zod.z.array(processedType);
265
- const constraints = {};
3825
+ const constraints = [];
266
3826
  if (zodArrayDef.minLength?.value !== void 0) {
267
3827
  if (handleChecks.includes("min")) {
268
- constraints.minLength = zodArrayDef.minLength.value;
3828
+ constraints.push(`minimum length ${zodArrayDef.minLength.value}`);
269
3829
  } else {
270
3830
  result = result.min(zodArrayDef.minLength.value);
271
3831
  }
272
3832
  }
273
3833
  if (zodArrayDef.maxLength?.value !== void 0) {
274
3834
  if (handleChecks.includes("max")) {
275
- constraints.maxLength = zodArrayDef.maxLength.value;
3835
+ constraints.push(`maximum length ${zodArrayDef.maxLength.value}`);
276
3836
  } else {
277
3837
  result = result.max(zodArrayDef.maxLength.value);
278
3838
  }
279
3839
  }
280
3840
  if (zodArrayDef.exactLength?.value !== void 0) {
281
3841
  if (handleChecks.includes("length")) {
282
- constraints.exactLength = zodArrayDef.exactLength.value;
3842
+ constraints.push(`exact length ${zodArrayDef.exactLength.value}`);
283
3843
  } else {
284
3844
  result = result.length(zodArrayDef.exactLength.value);
285
3845
  }
@@ -314,7 +3874,7 @@ var SchemaCompatLayer = class {
314
3874
  * @returns The processed Zod string
315
3875
  */
316
3876
  defaultZodStringHandler(value, handleChecks = ALL_STRING_CHECKS) {
317
- const constraints = {};
3877
+ const constraints = [];
318
3878
  const checks = value._def.checks || [];
319
3879
  const newChecks = [];
320
3880
  for (const check of checks) {
@@ -322,38 +3882,20 @@ var SchemaCompatLayer = class {
322
3882
  if (handleChecks.includes(check.kind)) {
323
3883
  switch (check.kind) {
324
3884
  case "regex": {
325
- constraints.regex = {
326
- pattern: check.regex.source,
327
- flags: check.regex.flags
328
- };
329
- break;
330
- }
331
- case "emoji": {
332
- constraints.emoji = true;
333
- break;
334
- }
335
- case "email": {
336
- constraints.email = true;
337
- break;
338
- }
339
- case "url": {
340
- constraints.url = true;
341
- break;
342
- }
343
- case "uuid": {
344
- constraints.uuid = true;
3885
+ constraints.push(`input must match this regex ${check.regex.source}`);
345
3886
  break;
346
3887
  }
3888
+ case "emoji":
3889
+ case "email":
3890
+ case "url":
3891
+ case "uuid":
347
3892
  case "cuid": {
348
- constraints.cuid = true;
349
- break;
350
- }
351
- case "min": {
352
- constraints.minLength = check.value;
3893
+ constraints.push(`a valid ${check.kind}`);
353
3894
  break;
354
3895
  }
3896
+ case "min":
355
3897
  case "max": {
356
- constraints.maxLength = check.value;
3898
+ constraints.push(`${check.kind}imum length ${check.value}`);
357
3899
  break;
358
3900
  }
359
3901
  }
@@ -380,7 +3922,7 @@ var SchemaCompatLayer = class {
380
3922
  * @returns The processed Zod number
381
3923
  */
382
3924
  defaultZodNumberHandler(value, handleChecks = ALL_NUMBER_CHECKS) {
383
- const constraints = {};
3925
+ const constraints = [];
384
3926
  const checks = value._def.checks || [];
385
3927
  const newChecks = [];
386
3928
  for (const check of checks) {
@@ -389,20 +3931,20 @@ var SchemaCompatLayer = class {
389
3931
  switch (check.kind) {
390
3932
  case "min":
391
3933
  if (check.inclusive) {
392
- constraints.gte = check.value;
3934
+ constraints.push(`greater than or equal to ${check.value}`);
393
3935
  } else {
394
- constraints.gt = check.value;
3936
+ constraints.push(`greater than ${check.value}`);
395
3937
  }
396
3938
  break;
397
3939
  case "max":
398
3940
  if (check.inclusive) {
399
- constraints.lte = check.value;
3941
+ constraints.push(`lower than or equal to ${check.value}`);
400
3942
  } else {
401
- constraints.lt = check.value;
3943
+ constraints.push(`lower than ${check.value}`);
402
3944
  }
403
3945
  break;
404
3946
  case "multipleOf": {
405
- constraints.multipleOf = check.value;
3947
+ constraints.push(`multiple of ${check.value}`);
406
3948
  break;
407
3949
  }
408
3950
  }
@@ -437,7 +3979,7 @@ var SchemaCompatLayer = class {
437
3979
  * @returns A Zod string schema representing the date in ISO format
438
3980
  */
439
3981
  defaultZodDateHandler(value) {
440
- const constraints = {};
3982
+ const constraints = [];
441
3983
  const checks = value._def.checks || [];
442
3984
  for (const check of checks) {
443
3985
  if ("kind" in check) {
@@ -445,19 +3987,19 @@ var SchemaCompatLayer = class {
445
3987
  case "min":
446
3988
  const minDate = new Date(check.value);
447
3989
  if (!isNaN(minDate.getTime())) {
448
- constraints.minDate = minDate.toISOString();
3990
+ constraints.push(`Date must be newer than ${minDate.toISOString()} (ISO)`);
449
3991
  }
450
3992
  break;
451
3993
  case "max":
452
3994
  const maxDate = new Date(check.value);
453
3995
  if (!isNaN(maxDate.getTime())) {
454
- constraints.maxDate = maxDate.toISOString();
3996
+ constraints.push(`Date must be older than ${maxDate.toISOString()} (ISO)`);
455
3997
  }
456
3998
  break;
457
3999
  }
458
4000
  }
459
4001
  }
460
- constraints.dateFormat = "date-time";
4002
+ constraints.push(`Date format is date-time`);
461
4003
  let result = zod.z.string().describe("date-time");
462
4004
  const description = this.mergeParameterDescription(value.description, constraints);
463
4005
  if (description) {
@@ -485,8 +4027,8 @@ var SchemaCompatLayer = class {
485
4027
  * @param zodSchema - The Zod object schema to process
486
4028
  * @returns An AI SDK Schema with provider-specific compatibility applied
487
4029
  */
488
- processToAISDKSchema(zodSchema) {
489
- const processedSchema = this.processZodType(zodSchema);
4030
+ processToAISDKSchema(zodSchema2) {
4031
+ const processedSchema = this.processZodType(zodSchema2);
490
4032
  return convertZodSchemaToAISDKSchema(processedSchema, this.getSchemaTarget());
491
4033
  }
492
4034
  /**
@@ -495,8 +4037,8 @@ var SchemaCompatLayer = class {
495
4037
  * @param zodSchema - The Zod object schema to process
496
4038
  * @returns A JSONSchema7 object with provider-specific compatibility applied
497
4039
  */
498
- processToJSONSchema(zodSchema) {
499
- return this.processToAISDKSchema(zodSchema).jsonSchema;
4040
+ processToJSONSchema(zodSchema2) {
4041
+ return this.processToAISDKSchema(zodSchema2).jsonSchema;
500
4042
  }
501
4043
  };
502
4044
  var ALL_STRING_CHECKS2 = [
@@ -665,8 +4207,8 @@ var SchemaCompatLayer2 = class {
665
4207
  * @returns The updated description with constraints, or undefined if no constraints
666
4208
  */
667
4209
  mergeParameterDescription(description, constraints) {
668
- if (Object.keys(constraints).length > 0) {
669
- return (description ? description + "\n" : "") + JSON.stringify(constraints);
4210
+ if (constraints.length > 0) {
4211
+ return (description ? description + "\n" : "") + `constraints: ${constraints.join(`, `)}`;
670
4212
  } else {
671
4213
  return description;
672
4214
  }
@@ -696,26 +4238,26 @@ var SchemaCompatLayer2 = class {
696
4238
  const zodArrayDef = value._zod.def;
697
4239
  const processedType = this.processZodType(zodArrayDef.element);
698
4240
  let result = v4.z.array(processedType);
699
- const constraints = {};
4241
+ const constraints = [];
700
4242
  if (zodArrayDef.checks) {
701
4243
  for (const check of zodArrayDef.checks) {
702
4244
  if (check._zod.def.check === "min_length") {
703
4245
  if (handleChecks.includes("min")) {
704
- constraints.minLength = check._zod.def.minimum;
4246
+ constraints.push(`minimum length ${check._zod.def.minimum}`);
705
4247
  } else {
706
4248
  result = result.min(check._zod.def.minimum);
707
4249
  }
708
4250
  }
709
4251
  if (check._zod.def.check === "max_length") {
710
4252
  if (handleChecks.includes("max")) {
711
- constraints.maxLength = check._zod.def.maximum;
4253
+ constraints.push(`maximum length ${check._zod.def.maximum}`);
712
4254
  } else {
713
4255
  result = result.max(check._zod.def.maximum);
714
4256
  }
715
4257
  }
716
4258
  if (check._zod.def.check === "length_equals") {
717
4259
  if (handleChecks.includes("length")) {
718
- constraints.exactLength = check._zod.def.length;
4260
+ constraints.push(`exact length ${check._zod.def.length}`);
719
4261
  } else {
720
4262
  result = result.length(check._zod.def.length);
721
4263
  }
@@ -754,7 +4296,7 @@ var SchemaCompatLayer2 = class {
754
4296
  * @returns The processed Zod string
755
4297
  */
756
4298
  defaultZodStringHandler(value, handleChecks = ALL_STRING_CHECKS2) {
757
- const constraints = {};
4299
+ const constraints = [];
758
4300
  const checks = value._zod.def.checks || [];
759
4301
  const newChecks = [];
760
4302
  if (checks) {
@@ -762,36 +4304,23 @@ var SchemaCompatLayer2 = class {
762
4304
  if (handleChecks.includes(check._zod.def.check)) {
763
4305
  switch (check._zod.def.check) {
764
4306
  case "min_length":
765
- constraints.minLength = check._zod.def.minimum;
4307
+ constraints.push(`minimum length ${check._zod.def.minimum}`);
766
4308
  break;
767
4309
  case "max_length":
768
- constraints.maxLength = check._zod.def.maximum;
4310
+ constraints.push(`maximum length ${check._zod.def.maximum}`);
769
4311
  break;
770
4312
  case "string_format":
771
4313
  {
772
4314
  switch (check._zod.def.format) {
773
4315
  case "email":
774
- constraints.email = true;
775
- break;
776
4316
  case "url":
777
- constraints.url = true;
778
- break;
779
4317
  case "emoji":
780
- constraints.emoji = true;
781
- break;
782
4318
  case "uuid":
783
- constraints.uuid = true;
784
- break;
785
4319
  case "cuid":
786
- constraints.cuid = true;
4320
+ constraints.push(`a valid ${check._zod.def.format}`);
787
4321
  break;
788
4322
  case "regex":
789
- constraints.regex = {
790
- // @ts-expect-error - fix later
791
- pattern: check._zod.def.pattern,
792
- // @ts-expect-error - fix later
793
- flags: check._zod.def.flags
794
- };
4323
+ constraints.push(`input must match this regex ${check._zod.def.pattern}`);
795
4324
  break;
796
4325
  }
797
4326
  }
@@ -822,7 +4351,7 @@ var SchemaCompatLayer2 = class {
822
4351
  * @returns The processed Zod number
823
4352
  */
824
4353
  defaultZodNumberHandler(value, handleChecks = ALL_NUMBER_CHECKS2) {
825
- const constraints = {};
4354
+ const constraints = [];
826
4355
  const checks = value._zod.def.checks || [];
827
4356
  const newChecks = [];
828
4357
  if (checks) {
@@ -831,20 +4360,20 @@ var SchemaCompatLayer2 = class {
831
4360
  switch (check._zod.def.check) {
832
4361
  case "greater_than":
833
4362
  if (check._zod.def.inclusive) {
834
- constraints.gte = check._zod.def.value;
4363
+ constraints.push(`greater than or equal to ${check._zod.def.value}`);
835
4364
  } else {
836
- constraints.gt = check._zod.def.value;
4365
+ constraints.push(`greater than ${check._zod.def.value}`);
837
4366
  }
838
4367
  break;
839
4368
  case "less_than":
840
4369
  if (check._zod.def.inclusive) {
841
- constraints.lte = check._zod.def.value;
4370
+ constraints.push(`lower than or equal to ${check._zod.def.value}`);
842
4371
  } else {
843
- constraints.lt = check._zod.def.value;
4372
+ constraints.push(`lower than ${check._zod.def.value}`);
844
4373
  }
845
4374
  break;
846
4375
  case "multiple_of": {
847
- constraints.multipleOf = check._zod.def.value;
4376
+ constraints.push(`multiple of ${check._zod.def.value}`);
848
4377
  break;
849
4378
  }
850
4379
  }
@@ -881,7 +4410,7 @@ var SchemaCompatLayer2 = class {
881
4410
  * @returns A Zod string schema representing the date in ISO format
882
4411
  */
883
4412
  defaultZodDateHandler(value) {
884
- const constraints = {};
4413
+ const constraints = [];
885
4414
  const checks = value._zod.def.checks || [];
886
4415
  if (checks) {
887
4416
  for (const check of checks) {
@@ -889,19 +4418,19 @@ var SchemaCompatLayer2 = class {
889
4418
  case "less_than":
890
4419
  const minDate = new Date(check._zod.def.value);
891
4420
  if (!isNaN(minDate.getTime())) {
892
- constraints.minDate = minDate.toISOString();
4421
+ constraints.push(`Date must be newer than ${minDate.toISOString()} (ISO)`);
893
4422
  }
894
4423
  break;
895
4424
  case "greater_than":
896
4425
  const maxDate = new Date(check._zod.def.value);
897
4426
  if (!isNaN(maxDate.getTime())) {
898
- constraints.maxDate = maxDate.toISOString();
4427
+ constraints.push(`Date must be older than ${maxDate.toISOString()} (ISO)`);
899
4428
  }
900
4429
  break;
901
4430
  }
902
4431
  }
903
4432
  }
904
- constraints.dateFormat = "date-time";
4433
+ constraints.push(`Date format is date-time`);
905
4434
  let result = v4.z.string().describe("date-time");
906
4435
  const description = this.mergeParameterDescription(value.description, constraints);
907
4436
  if (description) {
@@ -929,8 +4458,8 @@ var SchemaCompatLayer2 = class {
929
4458
  * @param zodSchema - The Zod object schema to process
930
4459
  * @returns An AI SDK Schema with provider-specific compatibility applied
931
4460
  */
932
- processToAISDKSchema(zodSchema) {
933
- const processedSchema = this.processZodType(zodSchema);
4461
+ processToAISDKSchema(zodSchema2) {
4462
+ const processedSchema = this.processZodType(zodSchema2);
934
4463
  return convertZodSchemaToAISDKSchema(processedSchema, this.getSchemaTarget());
935
4464
  }
936
4465
  /**
@@ -939,8 +4468,8 @@ var SchemaCompatLayer2 = class {
939
4468
  * @param zodSchema - The Zod object schema to process
940
4469
  * @returns A JSONSchema7 object with provider-specific compatibility applied
941
4470
  */
942
- processToJSONSchema(zodSchema) {
943
- return this.processToAISDKSchema(zodSchema).jsonSchema;
4471
+ processToJSONSchema(zodSchema2) {
4472
+ return this.processToAISDKSchema(zodSchema2).jsonSchema;
944
4473
  }
945
4474
  };
946
4475
 
@@ -1127,8 +4656,8 @@ var SchemaCompatLayer3 = class {
1127
4656
  * @param zodSchema - The Zod object schema to process
1128
4657
  * @returns An AI SDK Schema with provider-specific compatibility applied
1129
4658
  */
1130
- processToAISDKSchema(zodSchema) {
1131
- const processedSchema = this.processZodType(zodSchema);
4659
+ processToAISDKSchema(zodSchema2) {
4660
+ const processedSchema = this.processZodType(zodSchema2);
1132
4661
  return convertZodSchemaToAISDKSchema(processedSchema, this.getSchemaTarget());
1133
4662
  }
1134
4663
  /**
@@ -1137,38 +4666,38 @@ var SchemaCompatLayer3 = class {
1137
4666
  * @param zodSchema - The Zod object schema to process
1138
4667
  * @returns A JSONSchema7 object with provider-specific compatibility applied
1139
4668
  */
1140
- processToJSONSchema(zodSchema) {
1141
- return this.processToAISDKSchema(zodSchema).jsonSchema;
4669
+ processToJSONSchema(zodSchema2) {
4670
+ return this.processToAISDKSchema(zodSchema2).jsonSchema;
1142
4671
  }
1143
4672
  };
1144
4673
 
1145
4674
  // src/zodTypes.ts
1146
- function isOptional2(z10) {
1147
- return (v) => v instanceof z10["ZodOptional"];
4675
+ function isOptional2(z11) {
4676
+ return (v) => v instanceof z11["ZodOptional"];
1148
4677
  }
1149
- function isObj2(z10) {
1150
- return (v) => v instanceof z10["ZodObject"];
4678
+ function isObj2(z11) {
4679
+ return (v) => v instanceof z11["ZodObject"];
1151
4680
  }
1152
- function isNull(z10) {
1153
- return (v) => v instanceof z10["ZodNull"];
4681
+ function isNull(z11) {
4682
+ return (v) => v instanceof z11["ZodNull"];
1154
4683
  }
1155
- function isArr2(z10) {
1156
- return (v) => v instanceof z10["ZodArray"];
4684
+ function isArr2(z11) {
4685
+ return (v) => v instanceof z11["ZodArray"];
1157
4686
  }
1158
- function isUnion2(z10) {
1159
- return (v) => v instanceof z10["ZodUnion"];
4687
+ function isUnion2(z11) {
4688
+ return (v) => v instanceof z11["ZodUnion"];
1160
4689
  }
1161
- function isString2(z10) {
1162
- return (v) => v instanceof z10["ZodString"];
4690
+ function isString2(z11) {
4691
+ return (v) => v instanceof z11["ZodString"];
1163
4692
  }
1164
- function isNumber2(z10) {
1165
- return (v) => v instanceof z10["ZodNumber"];
4693
+ function isNumber2(z11) {
4694
+ return (v) => v instanceof z11["ZodNumber"];
1166
4695
  }
1167
- function isDate(z10) {
1168
- return (v) => v instanceof z10["ZodDate"];
4696
+ function isDate(z11) {
4697
+ return (v) => v instanceof z11["ZodDate"];
1169
4698
  }
1170
- function isDefault(z10) {
1171
- return (v) => v instanceof z10["ZodDefault"];
4699
+ function isDefault(z11) {
4700
+ return (v) => v instanceof z11["ZodDefault"];
1172
4701
  }
1173
4702
 
1174
4703
  // src/provider-compats/anthropic.ts
@@ -1369,10 +4898,10 @@ var OpenAIReasoningSchemaCompatLayer = class extends SchemaCompatLayer3 {
1369
4898
  } else if (isDefault(zod.z)(value)) {
1370
4899
  const defaultDef = value._def;
1371
4900
  const innerType = defaultDef.innerType;
1372
- const defaultValue = defaultDef.defaultValue();
1373
- const constraints = {};
4901
+ const defaultValue = typeof defaultDef.defaultValue === "function" ? defaultDef.defaultValue() : defaultDef.defaultValue;
4902
+ const constraints = [];
1374
4903
  if (defaultValue !== void 0) {
1375
- constraints.defaultValue = defaultValue;
4904
+ constraints.push(`the default value is ${defaultValue}`);
1376
4905
  }
1377
4906
  const description = this.mergeParameterDescription(value.description, constraints);
1378
4907
  let result = this.processZodType(innerType);
@@ -1420,5 +4949,6 @@ exports.isObj = isObj;
1420
4949
  exports.isOptional = isOptional;
1421
4950
  exports.isString = isString;
1422
4951
  exports.isUnion = isUnion;
4952
+ exports.jsonSchema = jsonSchema;
1423
4953
  //# sourceMappingURL=index.cjs.map
1424
4954
  //# sourceMappingURL=index.cjs.map