freestyle-sandboxes 0.0.94 → 0.0.96

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 (66) hide show
  1. package/dist/ai/inde.d.cts +7 -3
  2. package/dist/ai/inde.d.mts +7 -3
  3. package/dist/ai/index.d.cts +7 -3
  4. package/dist/ai/index.d.mts +7 -3
  5. package/dist/inde.d.cts +8 -7
  6. package/dist/inde.d.mts +8 -7
  7. package/dist/index.cjs +8 -6
  8. package/dist/index.d.cts +8 -7
  9. package/dist/index.d.mts +8 -7
  10. package/dist/index.mjs +8 -6
  11. package/dist/langgraph/inde.d.cts +1 -1
  12. package/dist/langgraph/inde.d.mts +1 -1
  13. package/dist/langgraph/index.d.cts +1 -1
  14. package/dist/langgraph/index.d.mts +1 -1
  15. package/dist/mastra/inde.d.cts +1 -1
  16. package/dist/mastra/inde.d.mts +1 -1
  17. package/dist/mastra/index.d.cts +1 -1
  18. package/dist/mastra/index.d.mts +1 -1
  19. package/dist/{types.gen--Oxc46AH.d.ts → types.gen-CJa21P0C.d.ts} +344 -28
  20. package/dist/{types.gen-CG8tIO9M.d.ts → types.gen-DKjMRuu5.d.ts} +448 -43
  21. package/dist/utils/inde.d.cts +1 -1
  22. package/dist/utils/inde.d.mts +1 -1
  23. package/dist/utils/index.d.cts +1 -1
  24. package/dist/utils/index.d.mts +1 -1
  25. package/openapi/sdk.gen.ts +236 -3
  26. package/openapi/types.gen.ts +391 -29
  27. package/openapi.json +1 -1
  28. package/package.json +1 -1
  29. package/src/index.ts +10 -8
  30. package/dist/index-BBXyg0JQ.cjs +0 -3253
  31. package/dist/index-BQHqnjZK.mjs +0 -3231
  32. package/dist/index-CEEa9WHp.cjs +0 -3238
  33. package/dist/index-D1ulQeJR.mjs +0 -3247
  34. package/dist/index-DCF70Xbq.mjs +0 -3246
  35. package/dist/index-H7UNEAjs.cjs +0 -3254
  36. package/dist/index.d-CXx1AdyW.d.ts +0 -4210
  37. package/dist/types.gen-1sd31qLV.d.ts +0 -172
  38. package/dist/types.gen-627pxroW.d.ts +0 -830
  39. package/dist/types.gen-BCdfx7yt.d.ts +0 -760
  40. package/dist/types.gen-BVXmFV7d.d.ts +0 -1299
  41. package/dist/types.gen-BWwhCgTX.d.ts +0 -1462
  42. package/dist/types.gen-BaMKzqxQ.d.ts +0 -233
  43. package/dist/types.gen-BbekD8Sd.d.ts +0 -1119
  44. package/dist/types.gen-BpWMzgc3.d.ts +0 -1493
  45. package/dist/types.gen-BqN1t03N.d.ts +0 -842
  46. package/dist/types.gen-BtK6PMQy.d.ts +0 -195
  47. package/dist/types.gen-BuhQ5LpB.d.ts +0 -764
  48. package/dist/types.gen-BzRtj_TA.d.ts +0 -725
  49. package/dist/types.gen-C03gaIPq.d.ts +0 -297
  50. package/dist/types.gen-CIf3ciN7.d.ts +0 -807
  51. package/dist/types.gen-CMuCas4r.d.ts +0 -183
  52. package/dist/types.gen-CWa4Mw0J.d.ts +0 -1493
  53. package/dist/types.gen-CZUnqmzP.d.ts +0 -789
  54. package/dist/types.gen-CnEkmbco.d.ts +0 -314
  55. package/dist/types.gen-DDYpuDzZ.d.ts +0 -764
  56. package/dist/types.gen-DHmdEOOa.d.ts +0 -172
  57. package/dist/types.gen-DLYohMJT.d.ts +0 -382
  58. package/dist/types.gen-DbTb_SrD.d.ts +0 -156
  59. package/dist/types.gen-DkFlXKTr.d.ts +0 -1354
  60. package/dist/types.gen-DkQ-Dbs1.d.ts +0 -764
  61. package/dist/types.gen-DyY7Deri.d.ts +0 -138
  62. package/dist/types.gen-MBZCvIhE.d.ts +0 -311
  63. package/dist/types.gen-YhJAHBw8.d.ts +0 -233
  64. package/dist/types.gen-cCnnhnB6.d.ts +0 -182
  65. package/dist/types.gen-mg_JNXrq.d.ts +0 -830
  66. package/dist/types.gen-uDTr6v-7.d.ts +0 -731
@@ -1,3247 +0,0 @@
1
- import { FreestyleSandboxes } from './index.mjs';
2
- import { ZodFirstPartyTypeKind, ZodOptional, z } from 'zod';
3
-
4
- var marker$1 = "vercel.ai.error";
5
- var symbol$1 = Symbol.for(marker$1);
6
- var _a$1;
7
- var _AISDKError$1 = class _AISDKError2 extends Error {
8
- /**
9
- * Creates an AI SDK Error.
10
- *
11
- * @param {Object} params - The parameters for creating the error.
12
- * @param {string} params.name - The name of the error.
13
- * @param {string} params.message - The error message.
14
- * @param {unknown} [params.cause] - The underlying cause of the error.
15
- */
16
- constructor({
17
- name: name14,
18
- message,
19
- cause
20
- }) {
21
- super(message);
22
- this[_a$1] = true;
23
- this.name = name14;
24
- this.cause = cause;
25
- }
26
- /**
27
- * Checks if the given error is an AI SDK Error.
28
- * @param {unknown} error - The error to check.
29
- * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
30
- */
31
- static isInstance(error) {
32
- return _AISDKError2.hasMarker(error, marker$1);
33
- }
34
- static hasMarker(error, marker15) {
35
- const markerSymbol = Symbol.for(marker15);
36
- return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
37
- }
38
- };
39
- _a$1 = symbol$1;
40
- var AISDKError$1 = _AISDKError$1;
41
- function getErrorMessage$1(error) {
42
- if (error == null) {
43
- return "unknown error";
44
- }
45
- if (typeof error === "string") {
46
- return error;
47
- }
48
- if (error instanceof Error) {
49
- return error.message;
50
- }
51
- return JSON.stringify(error);
52
- }
53
- var name3$1 = "AI_InvalidArgumentError";
54
- var marker4$2 = `vercel.ai.error.${name3$1}`;
55
- var symbol4$2 = Symbol.for(marker4$2);
56
- var _a4$2;
57
- var InvalidArgumentError$1 = class InvalidArgumentError extends AISDKError$1 {
58
- constructor({
59
- message,
60
- cause,
61
- argument
62
- }) {
63
- super({ name: name3$1, message, cause });
64
- this[_a4$2] = true;
65
- this.argument = argument;
66
- }
67
- static isInstance(error) {
68
- return AISDKError$1.hasMarker(error, marker4$2);
69
- }
70
- };
71
- _a4$2 = symbol4$2;
72
- var name6$1 = "AI_JSONParseError";
73
- var marker7$1 = `vercel.ai.error.${name6$1}`;
74
- var symbol7$1 = Symbol.for(marker7$1);
75
- var _a7$1;
76
- var JSONParseError$1 = class JSONParseError extends AISDKError$1 {
77
- constructor({ text, cause }) {
78
- super({
79
- name: name6$1,
80
- message: `JSON parsing failed: Text: ${text}.
81
- Error message: ${getErrorMessage$1(cause)}`,
82
- cause
83
- });
84
- this[_a7$1] = true;
85
- this.text = text;
86
- }
87
- static isInstance(error) {
88
- return AISDKError$1.hasMarker(error, marker7$1);
89
- }
90
- };
91
- _a7$1 = symbol7$1;
92
- var name12$1 = "AI_TypeValidationError";
93
- var marker13$1 = `vercel.ai.error.${name12$1}`;
94
- var symbol13$1 = Symbol.for(marker13$1);
95
- var _a13$1;
96
- var _TypeValidationError$1 = class _TypeValidationError2 extends AISDKError$1 {
97
- constructor({ value, cause }) {
98
- super({
99
- name: name12$1,
100
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
101
- Error message: ${getErrorMessage$1(cause)}`,
102
- cause
103
- });
104
- this[_a13$1] = true;
105
- this.value = value;
106
- }
107
- static isInstance(error) {
108
- return AISDKError$1.hasMarker(error, marker13$1);
109
- }
110
- /**
111
- * Wraps an error into a TypeValidationError.
112
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
113
- * Otherwise, it creates a new TypeValidationError.
114
- *
115
- * @param {Object} params - The parameters for wrapping the error.
116
- * @param {unknown} params.value - The value that failed validation.
117
- * @param {unknown} params.cause - The original error or cause of the validation failure.
118
- * @returns {TypeValidationError} A TypeValidationError instance.
119
- */
120
- static wrap({
121
- value,
122
- cause
123
- }) {
124
- return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
125
- }
126
- };
127
- _a13$1 = symbol13$1;
128
- var TypeValidationError$1 = _TypeValidationError$1;
129
-
130
- let customAlphabet = (alphabet, defaultSize = 21) => {
131
- return (size = defaultSize) => {
132
- let id = "";
133
- let i = size | 0;
134
- while (i--) {
135
- id += alphabet[Math.random() * alphabet.length | 0];
136
- }
137
- return id;
138
- };
139
- };
140
-
141
- function getDefaultExportFromCjs (x) {
142
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
143
- }
144
-
145
- var secureJsonParse = {exports: {}};
146
-
147
- var hasRequiredSecureJsonParse;
148
-
149
- function requireSecureJsonParse () {
150
- if (hasRequiredSecureJsonParse) return secureJsonParse.exports;
151
- hasRequiredSecureJsonParse = 1;
152
- const hasBuffer = typeof Buffer !== "undefined";
153
- const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
154
- const 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*:/;
155
- function _parse(text, reviver, options) {
156
- if (options == null) {
157
- if (reviver !== null && typeof reviver === "object") {
158
- options = reviver;
159
- reviver = void 0;
160
- }
161
- }
162
- if (hasBuffer && Buffer.isBuffer(text)) {
163
- text = text.toString();
164
- }
165
- if (text && text.charCodeAt(0) === 65279) {
166
- text = text.slice(1);
167
- }
168
- const obj = JSON.parse(text, reviver);
169
- if (obj === null || typeof obj !== "object") {
170
- return obj;
171
- }
172
- const protoAction = options && options.protoAction || "error";
173
- const constructorAction = options && options.constructorAction || "error";
174
- if (protoAction === "ignore" && constructorAction === "ignore") {
175
- return obj;
176
- }
177
- if (protoAction !== "ignore" && constructorAction !== "ignore") {
178
- if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
179
- return obj;
180
- }
181
- } else if (protoAction !== "ignore" && constructorAction === "ignore") {
182
- if (suspectProtoRx.test(text) === false) {
183
- return obj;
184
- }
185
- } else {
186
- if (suspectConstructorRx.test(text) === false) {
187
- return obj;
188
- }
189
- }
190
- return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
191
- }
192
- function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
193
- let next = [obj];
194
- while (next.length) {
195
- const nodes = next;
196
- next = [];
197
- for (const node of nodes) {
198
- if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
199
- if (safe === true) {
200
- return null;
201
- } else if (protoAction === "error") {
202
- throw new SyntaxError("Object contains forbidden prototype property");
203
- }
204
- delete node.__proto__;
205
- }
206
- if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
207
- if (safe === true) {
208
- return null;
209
- } else if (constructorAction === "error") {
210
- throw new SyntaxError("Object contains forbidden prototype property");
211
- }
212
- delete node.constructor;
213
- }
214
- for (const key in node) {
215
- const value = node[key];
216
- if (value && typeof value === "object") {
217
- next.push(value);
218
- }
219
- }
220
- }
221
- }
222
- return obj;
223
- }
224
- function parse(text, reviver, options) {
225
- const stackTraceLimit = Error.stackTraceLimit;
226
- Error.stackTraceLimit = 0;
227
- try {
228
- return _parse(text, reviver, options);
229
- } finally {
230
- Error.stackTraceLimit = stackTraceLimit;
231
- }
232
- }
233
- function safeParse(text, reviver) {
234
- const stackTraceLimit = Error.stackTraceLimit;
235
- Error.stackTraceLimit = 0;
236
- try {
237
- return _parse(text, reviver, { safe: true });
238
- } catch (_e) {
239
- return null;
240
- } finally {
241
- Error.stackTraceLimit = stackTraceLimit;
242
- }
243
- }
244
- secureJsonParse.exports = parse;
245
- secureJsonParse.exports.default = parse;
246
- secureJsonParse.exports.parse = parse;
247
- secureJsonParse.exports.safeParse = safeParse;
248
- secureJsonParse.exports.scan = filter;
249
- return secureJsonParse.exports;
250
- }
251
-
252
- var secureJsonParseExports = requireSecureJsonParse();
253
- var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
254
-
255
- function convertAsyncIteratorToReadableStream(iterator) {
256
- return new ReadableStream({
257
- /**
258
- * Called when the consumer wants to pull more data from the stream.
259
- *
260
- * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
261
- * @returns {Promise<void>}
262
- */
263
- async pull(controller) {
264
- try {
265
- const { value, done } = await iterator.next();
266
- if (done) {
267
- controller.close();
268
- } else {
269
- controller.enqueue(value);
270
- }
271
- } catch (error) {
272
- controller.error(error);
273
- }
274
- },
275
- /**
276
- * Called when the consumer cancels the stream.
277
- */
278
- cancel() {
279
- }
280
- });
281
- }
282
- var createIdGenerator$1 = ({
283
- prefix,
284
- size: defaultSize = 16,
285
- alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
286
- separator = "-"
287
- } = {}) => {
288
- const generator = customAlphabet(alphabet, defaultSize);
289
- if (prefix == null) {
290
- return generator;
291
- }
292
- if (alphabet.includes(separator)) {
293
- throw new InvalidArgumentError$1({
294
- argument: "separator",
295
- message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
296
- });
297
- }
298
- return (size) => `${prefix}${separator}${generator(size)}`;
299
- };
300
- createIdGenerator$1();
301
- var validatorSymbol$1 = Symbol.for("vercel.ai.validator");
302
- function validator$1(validate) {
303
- return { [validatorSymbol$1]: true, validate };
304
- }
305
- function isValidator$1(value) {
306
- return typeof value === "object" && value !== null && validatorSymbol$1 in value && value[validatorSymbol$1] === true && "validate" in value;
307
- }
308
- function asValidator$1(value) {
309
- return isValidator$1(value) ? value : zodValidator$1(value);
310
- }
311
- function zodValidator$1(zodSchema) {
312
- return validator$1((value) => {
313
- const result = zodSchema.safeParse(value);
314
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
315
- });
316
- }
317
- function safeValidateTypes$1({
318
- value,
319
- schema
320
- }) {
321
- const validator2 = asValidator$1(schema);
322
- try {
323
- if (validator2.validate == null) {
324
- return { success: true, value };
325
- }
326
- const result = validator2.validate(value);
327
- if (result.success) {
328
- return result;
329
- }
330
- return {
331
- success: false,
332
- error: TypeValidationError$1.wrap({ value, cause: result.error })
333
- };
334
- } catch (error) {
335
- return {
336
- success: false,
337
- error: TypeValidationError$1.wrap({ value, cause: error })
338
- };
339
- }
340
- }
341
- function safeParseJSON$1({
342
- text,
343
- schema
344
- }) {
345
- try {
346
- const value = SecureJSON.parse(text);
347
- if (schema == null) {
348
- return { success: true, value, rawValue: value };
349
- }
350
- const validationResult = safeValidateTypes$1({ value, schema });
351
- return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
352
- } catch (error) {
353
- return {
354
- success: false,
355
- error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({ text, cause: error })
356
- };
357
- }
358
- }
359
-
360
- var marker = "vercel.ai.error";
361
- var symbol = Symbol.for(marker);
362
- var _a;
363
- var _AISDKError = class _AISDKError2 extends Error {
364
- /**
365
- * Creates an AI SDK Error.
366
- *
367
- * @param {Object} params - The parameters for creating the error.
368
- * @param {string} params.name - The name of the error.
369
- * @param {string} params.message - The error message.
370
- * @param {unknown} [params.cause] - The underlying cause of the error.
371
- */
372
- constructor({
373
- name: name14,
374
- message,
375
- cause
376
- }) {
377
- super(message);
378
- this[_a] = true;
379
- this.name = name14;
380
- this.cause = cause;
381
- }
382
- /**
383
- * Checks if the given error is an AI SDK Error.
384
- * @param {unknown} error - The error to check.
385
- * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
386
- */
387
- static isInstance(error) {
388
- return _AISDKError2.hasMarker(error, marker);
389
- }
390
- static hasMarker(error, marker15) {
391
- const markerSymbol = Symbol.for(marker15);
392
- return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
393
- }
394
- };
395
- _a = symbol;
396
- var AISDKError = _AISDKError;
397
- function getErrorMessage(error) {
398
- if (error == null) {
399
- return "unknown error";
400
- }
401
- if (typeof error === "string") {
402
- return error;
403
- }
404
- if (error instanceof Error) {
405
- return error.message;
406
- }
407
- return JSON.stringify(error);
408
- }
409
- var name3 = "AI_InvalidArgumentError";
410
- var marker4$1 = `vercel.ai.error.${name3}`;
411
- var symbol4$1 = Symbol.for(marker4$1);
412
- var _a4$1;
413
- var InvalidArgumentError = class extends AISDKError {
414
- constructor({
415
- message,
416
- cause,
417
- argument
418
- }) {
419
- super({ name: name3, message, cause });
420
- this[_a4$1] = true;
421
- this.argument = argument;
422
- }
423
- static isInstance(error) {
424
- return AISDKError.hasMarker(error, marker4$1);
425
- }
426
- };
427
- _a4$1 = symbol4$1;
428
- var name6 = "AI_JSONParseError";
429
- var marker7 = `vercel.ai.error.${name6}`;
430
- var symbol7 = Symbol.for(marker7);
431
- var _a7;
432
- var JSONParseError = class extends AISDKError {
433
- constructor({ text, cause }) {
434
- super({
435
- name: name6,
436
- message: `JSON parsing failed: Text: ${text}.
437
- Error message: ${getErrorMessage(cause)}`,
438
- cause
439
- });
440
- this[_a7] = true;
441
- this.text = text;
442
- }
443
- static isInstance(error) {
444
- return AISDKError.hasMarker(error, marker7);
445
- }
446
- };
447
- _a7 = symbol7;
448
- var name12 = "AI_TypeValidationError";
449
- var marker13 = `vercel.ai.error.${name12}`;
450
- var symbol13 = Symbol.for(marker13);
451
- var _a13;
452
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
453
- constructor({ value, cause }) {
454
- super({
455
- name: name12,
456
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
457
- Error message: ${getErrorMessage(cause)}`,
458
- cause
459
- });
460
- this[_a13] = true;
461
- this.value = value;
462
- }
463
- static isInstance(error) {
464
- return AISDKError.hasMarker(error, marker13);
465
- }
466
- /**
467
- * Wraps an error into a TypeValidationError.
468
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
469
- * Otherwise, it creates a new TypeValidationError.
470
- *
471
- * @param {Object} params - The parameters for wrapping the error.
472
- * @param {unknown} params.value - The value that failed validation.
473
- * @param {unknown} params.cause - The original error or cause of the validation failure.
474
- * @returns {TypeValidationError} A TypeValidationError instance.
475
- */
476
- static wrap({
477
- value,
478
- cause
479
- }) {
480
- return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
481
- }
482
- };
483
- _a13 = symbol13;
484
- var TypeValidationError = _TypeValidationError;
485
-
486
- var createIdGenerator = ({
487
- prefix,
488
- size: defaultSize = 16,
489
- alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
490
- separator = "-"
491
- } = {}) => {
492
- const generator = customAlphabet(alphabet, defaultSize);
493
- if (prefix == null) {
494
- return generator;
495
- }
496
- if (alphabet.includes(separator)) {
497
- throw new InvalidArgumentError({
498
- argument: "separator",
499
- message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
500
- });
501
- }
502
- return (size) => `${prefix}${separator}${generator(size)}`;
503
- };
504
- createIdGenerator();
505
- var validatorSymbol = Symbol.for("vercel.ai.validator");
506
- function validator(validate) {
507
- return { [validatorSymbol]: true, validate };
508
- }
509
- function isValidator(value) {
510
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
511
- }
512
- function asValidator(value) {
513
- return isValidator(value) ? value : zodValidator(value);
514
- }
515
- function zodValidator(zodSchema) {
516
- return validator((value) => {
517
- const result = zodSchema.safeParse(value);
518
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
519
- });
520
- }
521
- function safeValidateTypes({
522
- value,
523
- schema
524
- }) {
525
- const validator2 = asValidator(schema);
526
- try {
527
- if (validator2.validate == null) {
528
- return { success: true, value };
529
- }
530
- const result = validator2.validate(value);
531
- if (result.success) {
532
- return result;
533
- }
534
- return {
535
- success: false,
536
- error: TypeValidationError.wrap({ value, cause: result.error })
537
- };
538
- } catch (error) {
539
- return {
540
- success: false,
541
- error: TypeValidationError.wrap({ value, cause: error })
542
- };
543
- }
544
- }
545
- function safeParseJSON({
546
- text,
547
- schema
548
- }) {
549
- try {
550
- const value = SecureJSON.parse(text);
551
- if (schema == null) {
552
- return { success: true, value, rawValue: value };
553
- }
554
- const validationResult = safeValidateTypes({ value, schema });
555
- return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
556
- } catch (error) {
557
- return {
558
- success: false,
559
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
560
- };
561
- }
562
- }
563
-
564
- const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
565
- const defaultOptions = {
566
- name: void 0,
567
- $refStrategy: "root",
568
- basePath: ["#"],
569
- effectStrategy: "input",
570
- pipeStrategy: "all",
571
- dateStrategy: "format:date-time",
572
- mapStrategy: "entries",
573
- removeAdditionalStrategy: "passthrough",
574
- allowedAdditionalProperties: true,
575
- rejectedAdditionalProperties: false,
576
- definitionPath: "definitions",
577
- target: "jsonSchema7",
578
- strictUnions: false,
579
- definitions: {},
580
- errorMessages: false,
581
- markdownDescription: false,
582
- patternStrategy: "escape",
583
- applyRegexFlags: false,
584
- emailStrategy: "format:email",
585
- base64Strategy: "contentEncoding:base64",
586
- nameStrategy: "ref"
587
- };
588
- const getDefaultOptions = (options) => typeof options === "string" ? {
589
- ...defaultOptions,
590
- name: options
591
- } : {
592
- ...defaultOptions,
593
- ...options
594
- };
595
-
596
- const getRefs = (options) => {
597
- const _options = getDefaultOptions(options);
598
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
599
- return {
600
- ..._options,
601
- currentPath,
602
- propertyPath: void 0,
603
- seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
604
- def._def,
605
- {
606
- def: def._def,
607
- path: [..._options.basePath, _options.definitionPath, name],
608
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
609
- jsonSchema: void 0
610
- }
611
- ]))
612
- };
613
- };
614
-
615
- function addErrorMessage(res, key, errorMessage, refs) {
616
- if (!refs?.errorMessages)
617
- return;
618
- if (errorMessage) {
619
- res.errorMessage = {
620
- ...res.errorMessage,
621
- [key]: errorMessage
622
- };
623
- }
624
- }
625
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
626
- res[key] = value;
627
- addErrorMessage(res, key, errorMessage, refs);
628
- }
629
-
630
- function parseAnyDef() {
631
- return {};
632
- }
633
-
634
- function parseArrayDef(def, refs) {
635
- const res = {
636
- type: "array"
637
- };
638
- if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
639
- res.items = parseDef(def.type._def, {
640
- ...refs,
641
- currentPath: [...refs.currentPath, "items"]
642
- });
643
- }
644
- if (def.minLength) {
645
- setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
646
- }
647
- if (def.maxLength) {
648
- setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
649
- }
650
- if (def.exactLength) {
651
- setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
652
- setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
653
- }
654
- return res;
655
- }
656
-
657
- function parseBigintDef(def, refs) {
658
- const res = {
659
- type: "integer",
660
- format: "int64"
661
- };
662
- if (!def.checks)
663
- return res;
664
- for (const check of def.checks) {
665
- switch (check.kind) {
666
- case "min":
667
- if (refs.target === "jsonSchema7") {
668
- if (check.inclusive) {
669
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
670
- } else {
671
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
672
- }
673
- } else {
674
- if (!check.inclusive) {
675
- res.exclusiveMinimum = true;
676
- }
677
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
678
- }
679
- break;
680
- case "max":
681
- if (refs.target === "jsonSchema7") {
682
- if (check.inclusive) {
683
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
684
- } else {
685
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
686
- }
687
- } else {
688
- if (!check.inclusive) {
689
- res.exclusiveMaximum = true;
690
- }
691
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
692
- }
693
- break;
694
- case "multipleOf":
695
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
696
- break;
697
- }
698
- }
699
- return res;
700
- }
701
-
702
- function parseBooleanDef() {
703
- return {
704
- type: "boolean"
705
- };
706
- }
707
-
708
- function parseBrandedDef(_def, refs) {
709
- return parseDef(_def.type._def, refs);
710
- }
711
-
712
- const parseCatchDef = (def, refs) => {
713
- return parseDef(def.innerType._def, refs);
714
- };
715
-
716
- function parseDateDef(def, refs, overrideDateStrategy) {
717
- const strategy = overrideDateStrategy ?? refs.dateStrategy;
718
- if (Array.isArray(strategy)) {
719
- return {
720
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
721
- };
722
- }
723
- switch (strategy) {
724
- case "string":
725
- case "format:date-time":
726
- return {
727
- type: "string",
728
- format: "date-time"
729
- };
730
- case "format:date":
731
- return {
732
- type: "string",
733
- format: "date"
734
- };
735
- case "integer":
736
- return integerDateParser(def, refs);
737
- }
738
- }
739
- const integerDateParser = (def, refs) => {
740
- const res = {
741
- type: "integer",
742
- format: "unix-time"
743
- };
744
- if (refs.target === "openApi3") {
745
- return res;
746
- }
747
- for (const check of def.checks) {
748
- switch (check.kind) {
749
- case "min":
750
- setResponseValueAndErrors(
751
- res,
752
- "minimum",
753
- check.value,
754
- // This is in milliseconds
755
- check.message,
756
- refs
757
- );
758
- break;
759
- case "max":
760
- setResponseValueAndErrors(
761
- res,
762
- "maximum",
763
- check.value,
764
- // This is in milliseconds
765
- check.message,
766
- refs
767
- );
768
- break;
769
- }
770
- }
771
- return res;
772
- };
773
-
774
- function parseDefaultDef(_def, refs) {
775
- return {
776
- ...parseDef(_def.innerType._def, refs),
777
- default: _def.defaultValue()
778
- };
779
- }
780
-
781
- function parseEffectsDef(_def, refs) {
782
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
783
- }
784
-
785
- function parseEnumDef(def) {
786
- return {
787
- type: "string",
788
- enum: Array.from(def.values)
789
- };
790
- }
791
-
792
- const isJsonSchema7AllOfType = (type) => {
793
- if ("type" in type && type.type === "string")
794
- return false;
795
- return "allOf" in type;
796
- };
797
- function parseIntersectionDef(def, refs) {
798
- const allOf = [
799
- parseDef(def.left._def, {
800
- ...refs,
801
- currentPath: [...refs.currentPath, "allOf", "0"]
802
- }),
803
- parseDef(def.right._def, {
804
- ...refs,
805
- currentPath: [...refs.currentPath, "allOf", "1"]
806
- })
807
- ].filter((x) => !!x);
808
- let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
809
- const mergedAllOf = [];
810
- allOf.forEach((schema) => {
811
- if (isJsonSchema7AllOfType(schema)) {
812
- mergedAllOf.push(...schema.allOf);
813
- if (schema.unevaluatedProperties === void 0) {
814
- unevaluatedProperties = void 0;
815
- }
816
- } else {
817
- let nestedSchema = schema;
818
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
819
- const { additionalProperties, ...rest } = schema;
820
- nestedSchema = rest;
821
- } else {
822
- unevaluatedProperties = void 0;
823
- }
824
- mergedAllOf.push(nestedSchema);
825
- }
826
- });
827
- return mergedAllOf.length ? {
828
- allOf: mergedAllOf,
829
- ...unevaluatedProperties
830
- } : void 0;
831
- }
832
-
833
- function parseLiteralDef(def, refs) {
834
- const parsedType = typeof def.value;
835
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
836
- return {
837
- type: Array.isArray(def.value) ? "array" : "object"
838
- };
839
- }
840
- if (refs.target === "openApi3") {
841
- return {
842
- type: parsedType === "bigint" ? "integer" : parsedType,
843
- enum: [def.value]
844
- };
845
- }
846
- return {
847
- type: parsedType === "bigint" ? "integer" : parsedType,
848
- const: def.value
849
- };
850
- }
851
-
852
- let emojiRegex = void 0;
853
- const zodPatterns = {
854
- /**
855
- * `c` was changed to `[cC]` to replicate /i flag
856
- */
857
- cuid: /^[cC][^\s-]{8,}$/,
858
- cuid2: /^[0-9a-z]+$/,
859
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
860
- /**
861
- * `a-z` was added to replicate /i flag
862
- */
863
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
864
- /**
865
- * Constructed a valid Unicode RegExp
866
- *
867
- * Lazily instantiate since this type of regex isn't supported
868
- * in all envs (e.g. React Native).
869
- *
870
- * See:
871
- * https://github.com/colinhacks/zod/issues/2433
872
- * Fix in Zod:
873
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
874
- */
875
- emoji: () => {
876
- if (emojiRegex === void 0) {
877
- emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
878
- }
879
- return emojiRegex;
880
- },
881
- /**
882
- * Unused
883
- */
884
- 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}$/,
885
- /**
886
- * Unused
887
- */
888
- 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])$/,
889
- 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])$/,
890
- /**
891
- * Unused
892
- */
893
- 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})))$/,
894
- 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])$/,
895
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
896
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
897
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
898
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
899
- };
900
- function parseStringDef(def, refs) {
901
- const res = {
902
- type: "string"
903
- };
904
- if (def.checks) {
905
- for (const check of def.checks) {
906
- switch (check.kind) {
907
- case "min":
908
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
909
- break;
910
- case "max":
911
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
912
- break;
913
- case "email":
914
- switch (refs.emailStrategy) {
915
- case "format:email":
916
- addFormat(res, "email", check.message, refs);
917
- break;
918
- case "format:idn-email":
919
- addFormat(res, "idn-email", check.message, refs);
920
- break;
921
- case "pattern:zod":
922
- addPattern(res, zodPatterns.email, check.message, refs);
923
- break;
924
- }
925
- break;
926
- case "url":
927
- addFormat(res, "uri", check.message, refs);
928
- break;
929
- case "uuid":
930
- addFormat(res, "uuid", check.message, refs);
931
- break;
932
- case "regex":
933
- addPattern(res, check.regex, check.message, refs);
934
- break;
935
- case "cuid":
936
- addPattern(res, zodPatterns.cuid, check.message, refs);
937
- break;
938
- case "cuid2":
939
- addPattern(res, zodPatterns.cuid2, check.message, refs);
940
- break;
941
- case "startsWith":
942
- addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
943
- break;
944
- case "endsWith":
945
- addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
946
- break;
947
- case "datetime":
948
- addFormat(res, "date-time", check.message, refs);
949
- break;
950
- case "date":
951
- addFormat(res, "date", check.message, refs);
952
- break;
953
- case "time":
954
- addFormat(res, "time", check.message, refs);
955
- break;
956
- case "duration":
957
- addFormat(res, "duration", check.message, refs);
958
- break;
959
- case "length":
960
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
961
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
962
- break;
963
- case "includes": {
964
- addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
965
- break;
966
- }
967
- case "ip": {
968
- if (check.version !== "v6") {
969
- addFormat(res, "ipv4", check.message, refs);
970
- }
971
- if (check.version !== "v4") {
972
- addFormat(res, "ipv6", check.message, refs);
973
- }
974
- break;
975
- }
976
- case "base64url":
977
- addPattern(res, zodPatterns.base64url, check.message, refs);
978
- break;
979
- case "jwt":
980
- addPattern(res, zodPatterns.jwt, check.message, refs);
981
- break;
982
- case "cidr": {
983
- if (check.version !== "v6") {
984
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
985
- }
986
- if (check.version !== "v4") {
987
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
988
- }
989
- break;
990
- }
991
- case "emoji":
992
- addPattern(res, zodPatterns.emoji(), check.message, refs);
993
- break;
994
- case "ulid": {
995
- addPattern(res, zodPatterns.ulid, check.message, refs);
996
- break;
997
- }
998
- case "base64": {
999
- switch (refs.base64Strategy) {
1000
- case "format:binary": {
1001
- addFormat(res, "binary", check.message, refs);
1002
- break;
1003
- }
1004
- case "contentEncoding:base64": {
1005
- setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
1006
- break;
1007
- }
1008
- case "pattern:zod": {
1009
- addPattern(res, zodPatterns.base64, check.message, refs);
1010
- break;
1011
- }
1012
- }
1013
- break;
1014
- }
1015
- case "nanoid": {
1016
- addPattern(res, zodPatterns.nanoid, check.message, refs);
1017
- }
1018
- }
1019
- }
1020
- }
1021
- return res;
1022
- }
1023
- function escapeLiteralCheckValue(literal, refs) {
1024
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1025
- }
1026
- const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
1027
- function escapeNonAlphaNumeric(source) {
1028
- let result = "";
1029
- for (let i = 0; i < source.length; i++) {
1030
- if (!ALPHA_NUMERIC.has(source[i])) {
1031
- result += "\\";
1032
- }
1033
- result += source[i];
1034
- }
1035
- return result;
1036
- }
1037
- function addFormat(schema, value, message, refs) {
1038
- if (schema.format || schema.anyOf?.some((x) => x.format)) {
1039
- if (!schema.anyOf) {
1040
- schema.anyOf = [];
1041
- }
1042
- if (schema.format) {
1043
- schema.anyOf.push({
1044
- format: schema.format,
1045
- ...schema.errorMessage && refs.errorMessages && {
1046
- errorMessage: { format: schema.errorMessage.format }
1047
- }
1048
- });
1049
- delete schema.format;
1050
- if (schema.errorMessage) {
1051
- delete schema.errorMessage.format;
1052
- if (Object.keys(schema.errorMessage).length === 0) {
1053
- delete schema.errorMessage;
1054
- }
1055
- }
1056
- }
1057
- schema.anyOf.push({
1058
- format: value,
1059
- ...message && refs.errorMessages && { errorMessage: { format: message } }
1060
- });
1061
- } else {
1062
- setResponseValueAndErrors(schema, "format", value, message, refs);
1063
- }
1064
- }
1065
- function addPattern(schema, regex, message, refs) {
1066
- if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
1067
- if (!schema.allOf) {
1068
- schema.allOf = [];
1069
- }
1070
- if (schema.pattern) {
1071
- schema.allOf.push({
1072
- pattern: schema.pattern,
1073
- ...schema.errorMessage && refs.errorMessages && {
1074
- errorMessage: { pattern: schema.errorMessage.pattern }
1075
- }
1076
- });
1077
- delete schema.pattern;
1078
- if (schema.errorMessage) {
1079
- delete schema.errorMessage.pattern;
1080
- if (Object.keys(schema.errorMessage).length === 0) {
1081
- delete schema.errorMessage;
1082
- }
1083
- }
1084
- }
1085
- schema.allOf.push({
1086
- pattern: stringifyRegExpWithFlags(regex, refs),
1087
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1088
- });
1089
- } else {
1090
- setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
1091
- }
1092
- }
1093
- function stringifyRegExpWithFlags(regex, refs) {
1094
- if (!refs.applyRegexFlags || !regex.flags) {
1095
- return regex.source;
1096
- }
1097
- const flags = {
1098
- i: regex.flags.includes("i"),
1099
- m: regex.flags.includes("m"),
1100
- s: regex.flags.includes("s")
1101
- // `.` matches newlines
1102
- };
1103
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
1104
- let pattern = "";
1105
- let isEscaped = false;
1106
- let inCharGroup = false;
1107
- let inCharRange = false;
1108
- for (let i = 0; i < source.length; i++) {
1109
- if (isEscaped) {
1110
- pattern += source[i];
1111
- isEscaped = false;
1112
- continue;
1113
- }
1114
- if (flags.i) {
1115
- if (inCharGroup) {
1116
- if (source[i].match(/[a-z]/)) {
1117
- if (inCharRange) {
1118
- pattern += source[i];
1119
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1120
- inCharRange = false;
1121
- } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
1122
- pattern += source[i];
1123
- inCharRange = true;
1124
- } else {
1125
- pattern += `${source[i]}${source[i].toUpperCase()}`;
1126
- }
1127
- continue;
1128
- }
1129
- } else if (source[i].match(/[a-z]/)) {
1130
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1131
- continue;
1132
- }
1133
- }
1134
- if (flags.m) {
1135
- if (source[i] === "^") {
1136
- pattern += `(^|(?<=[\r
1137
- ]))`;
1138
- continue;
1139
- } else if (source[i] === "$") {
1140
- pattern += `($|(?=[\r
1141
- ]))`;
1142
- continue;
1143
- }
1144
- }
1145
- if (flags.s && source[i] === ".") {
1146
- pattern += inCharGroup ? `${source[i]}\r
1147
- ` : `[${source[i]}\r
1148
- ]`;
1149
- continue;
1150
- }
1151
- pattern += source[i];
1152
- if (source[i] === "\\") {
1153
- isEscaped = true;
1154
- } else if (inCharGroup && source[i] === "]") {
1155
- inCharGroup = false;
1156
- } else if (!inCharGroup && source[i] === "[") {
1157
- inCharGroup = true;
1158
- }
1159
- }
1160
- try {
1161
- new RegExp(pattern);
1162
- } catch {
1163
- console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
1164
- return regex.source;
1165
- }
1166
- return pattern;
1167
- }
1168
-
1169
- function parseRecordDef(def, refs) {
1170
- if (refs.target === "openAi") {
1171
- console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
1172
- }
1173
- if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
1174
- return {
1175
- type: "object",
1176
- required: def.keyType._def.values,
1177
- properties: def.keyType._def.values.reduce((acc, key) => ({
1178
- ...acc,
1179
- [key]: parseDef(def.valueType._def, {
1180
- ...refs,
1181
- currentPath: [...refs.currentPath, "properties", key]
1182
- }) ?? {}
1183
- }), {}),
1184
- additionalProperties: refs.rejectedAdditionalProperties
1185
- };
1186
- }
1187
- const schema = {
1188
- type: "object",
1189
- additionalProperties: parseDef(def.valueType._def, {
1190
- ...refs,
1191
- currentPath: [...refs.currentPath, "additionalProperties"]
1192
- }) ?? refs.allowedAdditionalProperties
1193
- };
1194
- if (refs.target === "openApi3") {
1195
- return schema;
1196
- }
1197
- if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
1198
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1199
- return {
1200
- ...schema,
1201
- propertyNames: keyType
1202
- };
1203
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
1204
- return {
1205
- ...schema,
1206
- propertyNames: {
1207
- enum: def.keyType._def.values
1208
- }
1209
- };
1210
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
1211
- const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
1212
- return {
1213
- ...schema,
1214
- propertyNames: keyType
1215
- };
1216
- }
1217
- return schema;
1218
- }
1219
-
1220
- function parseMapDef(def, refs) {
1221
- if (refs.mapStrategy === "record") {
1222
- return parseRecordDef(def, refs);
1223
- }
1224
- const keys = parseDef(def.keyType._def, {
1225
- ...refs,
1226
- currentPath: [...refs.currentPath, "items", "items", "0"]
1227
- }) || {};
1228
- const values = parseDef(def.valueType._def, {
1229
- ...refs,
1230
- currentPath: [...refs.currentPath, "items", "items", "1"]
1231
- }) || {};
1232
- return {
1233
- type: "array",
1234
- maxItems: 125,
1235
- items: {
1236
- type: "array",
1237
- items: [keys, values],
1238
- minItems: 2,
1239
- maxItems: 2
1240
- }
1241
- };
1242
- }
1243
-
1244
- function parseNativeEnumDef(def) {
1245
- const object = def.values;
1246
- const actualKeys = Object.keys(def.values).filter((key) => {
1247
- return typeof object[object[key]] !== "number";
1248
- });
1249
- const actualValues = actualKeys.map((key) => object[key]);
1250
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
1251
- return {
1252
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1253
- enum: actualValues
1254
- };
1255
- }
1256
-
1257
- function parseNeverDef() {
1258
- return {
1259
- not: {}
1260
- };
1261
- }
1262
-
1263
- function parseNullDef(refs) {
1264
- return refs.target === "openApi3" ? {
1265
- enum: ["null"],
1266
- nullable: true
1267
- } : {
1268
- type: "null"
1269
- };
1270
- }
1271
-
1272
- const primitiveMappings = {
1273
- ZodString: "string",
1274
- ZodNumber: "number",
1275
- ZodBigInt: "integer",
1276
- ZodBoolean: "boolean",
1277
- ZodNull: "null"
1278
- };
1279
- function parseUnionDef(def, refs) {
1280
- if (refs.target === "openApi3")
1281
- return asAnyOf(def, refs);
1282
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1283
- if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
1284
- const types = options.reduce((types2, x) => {
1285
- const type = primitiveMappings[x._def.typeName];
1286
- return type && !types2.includes(type) ? [...types2, type] : types2;
1287
- }, []);
1288
- return {
1289
- type: types.length > 1 ? types : types[0]
1290
- };
1291
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1292
- const types = options.reduce((acc, x) => {
1293
- const type = typeof x._def.value;
1294
- switch (type) {
1295
- case "string":
1296
- case "number":
1297
- case "boolean":
1298
- return [...acc, type];
1299
- case "bigint":
1300
- return [...acc, "integer"];
1301
- case "object":
1302
- if (x._def.value === null)
1303
- return [...acc, "null"];
1304
- case "symbol":
1305
- case "undefined":
1306
- case "function":
1307
- default:
1308
- return acc;
1309
- }
1310
- }, []);
1311
- if (types.length === options.length) {
1312
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1313
- return {
1314
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1315
- enum: options.reduce((acc, x) => {
1316
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1317
- }, [])
1318
- };
1319
- }
1320
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1321
- return {
1322
- type: "string",
1323
- enum: options.reduce((acc, x) => [
1324
- ...acc,
1325
- ...x._def.values.filter((x2) => !acc.includes(x2))
1326
- ], [])
1327
- };
1328
- }
1329
- return asAnyOf(def, refs);
1330
- }
1331
- const asAnyOf = (def, refs) => {
1332
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
1333
- ...refs,
1334
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
1335
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
1336
- return anyOf.length ? { anyOf } : void 0;
1337
- };
1338
-
1339
- function parseNullableDef(def, refs) {
1340
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1341
- if (refs.target === "openApi3") {
1342
- return {
1343
- type: primitiveMappings[def.innerType._def.typeName],
1344
- nullable: true
1345
- };
1346
- }
1347
- return {
1348
- type: [
1349
- primitiveMappings[def.innerType._def.typeName],
1350
- "null"
1351
- ]
1352
- };
1353
- }
1354
- if (refs.target === "openApi3") {
1355
- const base2 = parseDef(def.innerType._def, {
1356
- ...refs,
1357
- currentPath: [...refs.currentPath]
1358
- });
1359
- if (base2 && "$ref" in base2)
1360
- return { allOf: [base2], nullable: true };
1361
- return base2 && { ...base2, nullable: true };
1362
- }
1363
- const base = parseDef(def.innerType._def, {
1364
- ...refs,
1365
- currentPath: [...refs.currentPath, "anyOf", "0"]
1366
- });
1367
- return base && { anyOf: [base, { type: "null" }] };
1368
- }
1369
-
1370
- function parseNumberDef(def, refs) {
1371
- const res = {
1372
- type: "number"
1373
- };
1374
- if (!def.checks)
1375
- return res;
1376
- for (const check of def.checks) {
1377
- switch (check.kind) {
1378
- case "int":
1379
- res.type = "integer";
1380
- addErrorMessage(res, "type", check.message, refs);
1381
- break;
1382
- case "min":
1383
- if (refs.target === "jsonSchema7") {
1384
- if (check.inclusive) {
1385
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1386
- } else {
1387
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
1388
- }
1389
- } else {
1390
- if (!check.inclusive) {
1391
- res.exclusiveMinimum = true;
1392
- }
1393
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1394
- }
1395
- break;
1396
- case "max":
1397
- if (refs.target === "jsonSchema7") {
1398
- if (check.inclusive) {
1399
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1400
- } else {
1401
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
1402
- }
1403
- } else {
1404
- if (!check.inclusive) {
1405
- res.exclusiveMaximum = true;
1406
- }
1407
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1408
- }
1409
- break;
1410
- case "multipleOf":
1411
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
1412
- break;
1413
- }
1414
- }
1415
- return res;
1416
- }
1417
-
1418
- function parseObjectDef(def, refs) {
1419
- const forceOptionalIntoNullable = refs.target === "openAi";
1420
- const result = {
1421
- type: "object",
1422
- properties: {}
1423
- };
1424
- const required = [];
1425
- const shape = def.shape();
1426
- for (const propName in shape) {
1427
- let propDef = shape[propName];
1428
- if (propDef === void 0 || propDef._def === void 0) {
1429
- continue;
1430
- }
1431
- let propOptional = safeIsOptional(propDef);
1432
- if (propOptional && forceOptionalIntoNullable) {
1433
- if (propDef instanceof ZodOptional) {
1434
- propDef = propDef._def.innerType;
1435
- }
1436
- if (!propDef.isNullable()) {
1437
- propDef = propDef.nullable();
1438
- }
1439
- propOptional = false;
1440
- }
1441
- const parsedDef = parseDef(propDef._def, {
1442
- ...refs,
1443
- currentPath: [...refs.currentPath, "properties", propName],
1444
- propertyPath: [...refs.currentPath, "properties", propName]
1445
- });
1446
- if (parsedDef === void 0) {
1447
- continue;
1448
- }
1449
- result.properties[propName] = parsedDef;
1450
- if (!propOptional) {
1451
- required.push(propName);
1452
- }
1453
- }
1454
- if (required.length) {
1455
- result.required = required;
1456
- }
1457
- const additionalProperties = decideAdditionalProperties(def, refs);
1458
- if (additionalProperties !== void 0) {
1459
- result.additionalProperties = additionalProperties;
1460
- }
1461
- return result;
1462
- }
1463
- function decideAdditionalProperties(def, refs) {
1464
- if (def.catchall._def.typeName !== "ZodNever") {
1465
- return parseDef(def.catchall._def, {
1466
- ...refs,
1467
- currentPath: [...refs.currentPath, "additionalProperties"]
1468
- });
1469
- }
1470
- switch (def.unknownKeys) {
1471
- case "passthrough":
1472
- return refs.allowedAdditionalProperties;
1473
- case "strict":
1474
- return refs.rejectedAdditionalProperties;
1475
- case "strip":
1476
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1477
- }
1478
- }
1479
- function safeIsOptional(schema) {
1480
- try {
1481
- return schema.isOptional();
1482
- } catch {
1483
- return true;
1484
- }
1485
- }
1486
-
1487
- const parseOptionalDef = (def, refs) => {
1488
- if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
1489
- return parseDef(def.innerType._def, refs);
1490
- }
1491
- const innerSchema = parseDef(def.innerType._def, {
1492
- ...refs,
1493
- currentPath: [...refs.currentPath, "anyOf", "1"]
1494
- });
1495
- return innerSchema ? {
1496
- anyOf: [
1497
- {
1498
- not: {}
1499
- },
1500
- innerSchema
1501
- ]
1502
- } : {};
1503
- };
1504
-
1505
- const parsePipelineDef = (def, refs) => {
1506
- if (refs.pipeStrategy === "input") {
1507
- return parseDef(def.in._def, refs);
1508
- } else if (refs.pipeStrategy === "output") {
1509
- return parseDef(def.out._def, refs);
1510
- }
1511
- const a = parseDef(def.in._def, {
1512
- ...refs,
1513
- currentPath: [...refs.currentPath, "allOf", "0"]
1514
- });
1515
- const b = parseDef(def.out._def, {
1516
- ...refs,
1517
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1518
- });
1519
- return {
1520
- allOf: [a, b].filter((x) => x !== void 0)
1521
- };
1522
- };
1523
-
1524
- function parsePromiseDef(def, refs) {
1525
- return parseDef(def.type._def, refs);
1526
- }
1527
-
1528
- function parseSetDef(def, refs) {
1529
- const items = parseDef(def.valueType._def, {
1530
- ...refs,
1531
- currentPath: [...refs.currentPath, "items"]
1532
- });
1533
- const schema = {
1534
- type: "array",
1535
- uniqueItems: true,
1536
- items
1537
- };
1538
- if (def.minSize) {
1539
- setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
1540
- }
1541
- if (def.maxSize) {
1542
- setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
1543
- }
1544
- return schema;
1545
- }
1546
-
1547
- function parseTupleDef(def, refs) {
1548
- if (def.rest) {
1549
- return {
1550
- type: "array",
1551
- minItems: def.items.length,
1552
- items: def.items.map((x, i) => parseDef(x._def, {
1553
- ...refs,
1554
- currentPath: [...refs.currentPath, "items", `${i}`]
1555
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
1556
- additionalItems: parseDef(def.rest._def, {
1557
- ...refs,
1558
- currentPath: [...refs.currentPath, "additionalItems"]
1559
- })
1560
- };
1561
- } else {
1562
- return {
1563
- type: "array",
1564
- minItems: def.items.length,
1565
- maxItems: def.items.length,
1566
- items: def.items.map((x, i) => parseDef(x._def, {
1567
- ...refs,
1568
- currentPath: [...refs.currentPath, "items", `${i}`]
1569
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
1570
- };
1571
- }
1572
- }
1573
-
1574
- function parseUndefinedDef() {
1575
- return {
1576
- not: {}
1577
- };
1578
- }
1579
-
1580
- function parseUnknownDef() {
1581
- return {};
1582
- }
1583
-
1584
- const parseReadonlyDef = (def, refs) => {
1585
- return parseDef(def.innerType._def, refs);
1586
- };
1587
-
1588
- const selectParser = (def, typeName, refs) => {
1589
- switch (typeName) {
1590
- case ZodFirstPartyTypeKind.ZodString:
1591
- return parseStringDef(def, refs);
1592
- case ZodFirstPartyTypeKind.ZodNumber:
1593
- return parseNumberDef(def, refs);
1594
- case ZodFirstPartyTypeKind.ZodObject:
1595
- return parseObjectDef(def, refs);
1596
- case ZodFirstPartyTypeKind.ZodBigInt:
1597
- return parseBigintDef(def, refs);
1598
- case ZodFirstPartyTypeKind.ZodBoolean:
1599
- return parseBooleanDef();
1600
- case ZodFirstPartyTypeKind.ZodDate:
1601
- return parseDateDef(def, refs);
1602
- case ZodFirstPartyTypeKind.ZodUndefined:
1603
- return parseUndefinedDef();
1604
- case ZodFirstPartyTypeKind.ZodNull:
1605
- return parseNullDef(refs);
1606
- case ZodFirstPartyTypeKind.ZodArray:
1607
- return parseArrayDef(def, refs);
1608
- case ZodFirstPartyTypeKind.ZodUnion:
1609
- case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
1610
- return parseUnionDef(def, refs);
1611
- case ZodFirstPartyTypeKind.ZodIntersection:
1612
- return parseIntersectionDef(def, refs);
1613
- case ZodFirstPartyTypeKind.ZodTuple:
1614
- return parseTupleDef(def, refs);
1615
- case ZodFirstPartyTypeKind.ZodRecord:
1616
- return parseRecordDef(def, refs);
1617
- case ZodFirstPartyTypeKind.ZodLiteral:
1618
- return parseLiteralDef(def, refs);
1619
- case ZodFirstPartyTypeKind.ZodEnum:
1620
- return parseEnumDef(def);
1621
- case ZodFirstPartyTypeKind.ZodNativeEnum:
1622
- return parseNativeEnumDef(def);
1623
- case ZodFirstPartyTypeKind.ZodNullable:
1624
- return parseNullableDef(def, refs);
1625
- case ZodFirstPartyTypeKind.ZodOptional:
1626
- return parseOptionalDef(def, refs);
1627
- case ZodFirstPartyTypeKind.ZodMap:
1628
- return parseMapDef(def, refs);
1629
- case ZodFirstPartyTypeKind.ZodSet:
1630
- return parseSetDef(def, refs);
1631
- case ZodFirstPartyTypeKind.ZodLazy:
1632
- return () => def.getter()._def;
1633
- case ZodFirstPartyTypeKind.ZodPromise:
1634
- return parsePromiseDef(def, refs);
1635
- case ZodFirstPartyTypeKind.ZodNaN:
1636
- case ZodFirstPartyTypeKind.ZodNever:
1637
- return parseNeverDef();
1638
- case ZodFirstPartyTypeKind.ZodEffects:
1639
- return parseEffectsDef(def, refs);
1640
- case ZodFirstPartyTypeKind.ZodAny:
1641
- return parseAnyDef();
1642
- case ZodFirstPartyTypeKind.ZodUnknown:
1643
- return parseUnknownDef();
1644
- case ZodFirstPartyTypeKind.ZodDefault:
1645
- return parseDefaultDef(def, refs);
1646
- case ZodFirstPartyTypeKind.ZodBranded:
1647
- return parseBrandedDef(def, refs);
1648
- case ZodFirstPartyTypeKind.ZodReadonly:
1649
- return parseReadonlyDef(def, refs);
1650
- case ZodFirstPartyTypeKind.ZodCatch:
1651
- return parseCatchDef(def, refs);
1652
- case ZodFirstPartyTypeKind.ZodPipeline:
1653
- return parsePipelineDef(def, refs);
1654
- case ZodFirstPartyTypeKind.ZodFunction:
1655
- case ZodFirstPartyTypeKind.ZodVoid:
1656
- case ZodFirstPartyTypeKind.ZodSymbol:
1657
- return void 0;
1658
- default:
1659
- return /* @__PURE__ */ ((_) => void 0)();
1660
- }
1661
- };
1662
-
1663
- function parseDef(def, refs, forceResolution = false) {
1664
- const seenItem = refs.seen.get(def);
1665
- if (refs.override) {
1666
- const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
1667
- if (overrideResult !== ignoreOverride) {
1668
- return overrideResult;
1669
- }
1670
- }
1671
- if (seenItem && !forceResolution) {
1672
- const seenSchema = get$ref(seenItem, refs);
1673
- if (seenSchema !== void 0) {
1674
- return seenSchema;
1675
- }
1676
- }
1677
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1678
- refs.seen.set(def, newItem);
1679
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1680
- const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1681
- if (jsonSchema) {
1682
- addMeta(def, refs, jsonSchema);
1683
- }
1684
- if (refs.postProcess) {
1685
- const postProcessResult = refs.postProcess(jsonSchema, def, refs);
1686
- newItem.jsonSchema = jsonSchema;
1687
- return postProcessResult;
1688
- }
1689
- newItem.jsonSchema = jsonSchema;
1690
- return jsonSchema;
1691
- }
1692
- const get$ref = (item, refs) => {
1693
- switch (refs.$refStrategy) {
1694
- case "root":
1695
- return { $ref: item.path.join("/") };
1696
- case "relative":
1697
- return { $ref: getRelativePath(refs.currentPath, item.path) };
1698
- case "none":
1699
- case "seen": {
1700
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1701
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
1702
- return {};
1703
- }
1704
- return refs.$refStrategy === "seen" ? {} : void 0;
1705
- }
1706
- }
1707
- };
1708
- const getRelativePath = (pathA, pathB) => {
1709
- let i = 0;
1710
- for (; i < pathA.length && i < pathB.length; i++) {
1711
- if (pathA[i] !== pathB[i])
1712
- break;
1713
- }
1714
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1715
- };
1716
- const addMeta = (def, refs, jsonSchema) => {
1717
- if (def.description) {
1718
- jsonSchema.description = def.description;
1719
- if (refs.markdownDescription) {
1720
- jsonSchema.markdownDescription = def.description;
1721
- }
1722
- }
1723
- return jsonSchema;
1724
- };
1725
-
1726
- const zodToJsonSchema = (schema, options) => {
1727
- const refs = getRefs(options);
1728
- const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
1729
- ...acc,
1730
- [name2]: parseDef(schema2._def, {
1731
- ...refs,
1732
- currentPath: [...refs.basePath, refs.definitionPath, name2]
1733
- }, true) ?? {}
1734
- }), {}) : void 0;
1735
- const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
1736
- const main = parseDef(schema._def, name === void 0 ? refs : {
1737
- ...refs,
1738
- currentPath: [...refs.basePath, refs.definitionPath, name]
1739
- }, false) ?? {};
1740
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1741
- if (title !== void 0) {
1742
- main.title = title;
1743
- }
1744
- const combined = name === void 0 ? definitions ? {
1745
- ...main,
1746
- [refs.definitionPath]: definitions
1747
- } : main : {
1748
- $ref: [
1749
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1750
- refs.definitionPath,
1751
- name
1752
- ].join("/"),
1753
- [refs.definitionPath]: {
1754
- ...definitions,
1755
- [name]: main
1756
- }
1757
- };
1758
- if (refs.target === "jsonSchema7") {
1759
- combined.$schema = "http://json-schema.org/draft-07/schema#";
1760
- } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
1761
- combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
1762
- }
1763
- if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
1764
- console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
1765
- }
1766
- return combined;
1767
- };
1768
-
1769
- var textStreamPart = {
1770
- code: "0",
1771
- name: "text",
1772
- parse: (value) => {
1773
- if (typeof value !== "string") {
1774
- throw new Error('"text" parts expect a string value.');
1775
- }
1776
- return { type: "text", value };
1777
- }
1778
- };
1779
- var errorStreamPart = {
1780
- code: "3",
1781
- name: "error",
1782
- parse: (value) => {
1783
- if (typeof value !== "string") {
1784
- throw new Error('"error" parts expect a string value.');
1785
- }
1786
- return { type: "error", value };
1787
- }
1788
- };
1789
- var assistantMessageStreamPart = {
1790
- code: "4",
1791
- name: "assistant_message",
1792
- parse: (value) => {
1793
- if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
1794
- (item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
1795
- )) {
1796
- throw new Error(
1797
- '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
1798
- );
1799
- }
1800
- return {
1801
- type: "assistant_message",
1802
- value
1803
- };
1804
- }
1805
- };
1806
- var assistantControlDataStreamPart = {
1807
- code: "5",
1808
- name: "assistant_control_data",
1809
- parse: (value) => {
1810
- if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
1811
- throw new Error(
1812
- '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
1813
- );
1814
- }
1815
- return {
1816
- type: "assistant_control_data",
1817
- value: {
1818
- threadId: value.threadId,
1819
- messageId: value.messageId
1820
- }
1821
- };
1822
- }
1823
- };
1824
- var dataMessageStreamPart = {
1825
- code: "6",
1826
- name: "data_message",
1827
- parse: (value) => {
1828
- if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
1829
- throw new Error(
1830
- '"data_message" parts expect an object with a "role" and "data" property.'
1831
- );
1832
- }
1833
- return {
1834
- type: "data_message",
1835
- value
1836
- };
1837
- }
1838
- };
1839
- var assistantStreamParts = [
1840
- textStreamPart,
1841
- errorStreamPart,
1842
- assistantMessageStreamPart,
1843
- assistantControlDataStreamPart,
1844
- dataMessageStreamPart
1845
- ];
1846
- ({
1847
- [textStreamPart.code]: textStreamPart,
1848
- [errorStreamPart.code]: errorStreamPart,
1849
- [assistantMessageStreamPart.code]: assistantMessageStreamPart,
1850
- [assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
1851
- [dataMessageStreamPart.code]: dataMessageStreamPart
1852
- });
1853
- ({
1854
- [textStreamPart.name]: textStreamPart.code,
1855
- [errorStreamPart.name]: errorStreamPart.code,
1856
- [assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
1857
- [assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
1858
- [dataMessageStreamPart.name]: dataMessageStreamPart.code
1859
- });
1860
- assistantStreamParts.map((part) => part.code);
1861
- function fixJson(input) {
1862
- const stack = ["ROOT"];
1863
- let lastValidIndex = -1;
1864
- let literalStart = null;
1865
- function processValueStart(char, i, swapState) {
1866
- {
1867
- switch (char) {
1868
- case '"': {
1869
- lastValidIndex = i;
1870
- stack.pop();
1871
- stack.push(swapState);
1872
- stack.push("INSIDE_STRING");
1873
- break;
1874
- }
1875
- case "f":
1876
- case "t":
1877
- case "n": {
1878
- lastValidIndex = i;
1879
- literalStart = i;
1880
- stack.pop();
1881
- stack.push(swapState);
1882
- stack.push("INSIDE_LITERAL");
1883
- break;
1884
- }
1885
- case "-": {
1886
- stack.pop();
1887
- stack.push(swapState);
1888
- stack.push("INSIDE_NUMBER");
1889
- break;
1890
- }
1891
- case "0":
1892
- case "1":
1893
- case "2":
1894
- case "3":
1895
- case "4":
1896
- case "5":
1897
- case "6":
1898
- case "7":
1899
- case "8":
1900
- case "9": {
1901
- lastValidIndex = i;
1902
- stack.pop();
1903
- stack.push(swapState);
1904
- stack.push("INSIDE_NUMBER");
1905
- break;
1906
- }
1907
- case "{": {
1908
- lastValidIndex = i;
1909
- stack.pop();
1910
- stack.push(swapState);
1911
- stack.push("INSIDE_OBJECT_START");
1912
- break;
1913
- }
1914
- case "[": {
1915
- lastValidIndex = i;
1916
- stack.pop();
1917
- stack.push(swapState);
1918
- stack.push("INSIDE_ARRAY_START");
1919
- break;
1920
- }
1921
- }
1922
- }
1923
- }
1924
- function processAfterObjectValue(char, i) {
1925
- switch (char) {
1926
- case ",": {
1927
- stack.pop();
1928
- stack.push("INSIDE_OBJECT_AFTER_COMMA");
1929
- break;
1930
- }
1931
- case "}": {
1932
- lastValidIndex = i;
1933
- stack.pop();
1934
- break;
1935
- }
1936
- }
1937
- }
1938
- function processAfterArrayValue(char, i) {
1939
- switch (char) {
1940
- case ",": {
1941
- stack.pop();
1942
- stack.push("INSIDE_ARRAY_AFTER_COMMA");
1943
- break;
1944
- }
1945
- case "]": {
1946
- lastValidIndex = i;
1947
- stack.pop();
1948
- break;
1949
- }
1950
- }
1951
- }
1952
- for (let i = 0; i < input.length; i++) {
1953
- const char = input[i];
1954
- const currentState = stack[stack.length - 1];
1955
- switch (currentState) {
1956
- case "ROOT":
1957
- processValueStart(char, i, "FINISH");
1958
- break;
1959
- case "INSIDE_OBJECT_START": {
1960
- switch (char) {
1961
- case '"': {
1962
- stack.pop();
1963
- stack.push("INSIDE_OBJECT_KEY");
1964
- break;
1965
- }
1966
- case "}": {
1967
- lastValidIndex = i;
1968
- stack.pop();
1969
- break;
1970
- }
1971
- }
1972
- break;
1973
- }
1974
- case "INSIDE_OBJECT_AFTER_COMMA": {
1975
- switch (char) {
1976
- case '"': {
1977
- stack.pop();
1978
- stack.push("INSIDE_OBJECT_KEY");
1979
- break;
1980
- }
1981
- }
1982
- break;
1983
- }
1984
- case "INSIDE_OBJECT_KEY": {
1985
- switch (char) {
1986
- case '"': {
1987
- stack.pop();
1988
- stack.push("INSIDE_OBJECT_AFTER_KEY");
1989
- break;
1990
- }
1991
- }
1992
- break;
1993
- }
1994
- case "INSIDE_OBJECT_AFTER_KEY": {
1995
- switch (char) {
1996
- case ":": {
1997
- stack.pop();
1998
- stack.push("INSIDE_OBJECT_BEFORE_VALUE");
1999
- break;
2000
- }
2001
- }
2002
- break;
2003
- }
2004
- case "INSIDE_OBJECT_BEFORE_VALUE": {
2005
- processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
2006
- break;
2007
- }
2008
- case "INSIDE_OBJECT_AFTER_VALUE": {
2009
- processAfterObjectValue(char, i);
2010
- break;
2011
- }
2012
- case "INSIDE_STRING": {
2013
- switch (char) {
2014
- case '"': {
2015
- stack.pop();
2016
- lastValidIndex = i;
2017
- break;
2018
- }
2019
- case "\\": {
2020
- stack.push("INSIDE_STRING_ESCAPE");
2021
- break;
2022
- }
2023
- default: {
2024
- lastValidIndex = i;
2025
- }
2026
- }
2027
- break;
2028
- }
2029
- case "INSIDE_ARRAY_START": {
2030
- switch (char) {
2031
- case "]": {
2032
- lastValidIndex = i;
2033
- stack.pop();
2034
- break;
2035
- }
2036
- default: {
2037
- lastValidIndex = i;
2038
- processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
2039
- break;
2040
- }
2041
- }
2042
- break;
2043
- }
2044
- case "INSIDE_ARRAY_AFTER_VALUE": {
2045
- switch (char) {
2046
- case ",": {
2047
- stack.pop();
2048
- stack.push("INSIDE_ARRAY_AFTER_COMMA");
2049
- break;
2050
- }
2051
- case "]": {
2052
- lastValidIndex = i;
2053
- stack.pop();
2054
- break;
2055
- }
2056
- default: {
2057
- lastValidIndex = i;
2058
- break;
2059
- }
2060
- }
2061
- break;
2062
- }
2063
- case "INSIDE_ARRAY_AFTER_COMMA": {
2064
- processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
2065
- break;
2066
- }
2067
- case "INSIDE_STRING_ESCAPE": {
2068
- stack.pop();
2069
- lastValidIndex = i;
2070
- break;
2071
- }
2072
- case "INSIDE_NUMBER": {
2073
- switch (char) {
2074
- case "0":
2075
- case "1":
2076
- case "2":
2077
- case "3":
2078
- case "4":
2079
- case "5":
2080
- case "6":
2081
- case "7":
2082
- case "8":
2083
- case "9": {
2084
- lastValidIndex = i;
2085
- break;
2086
- }
2087
- case "e":
2088
- case "E":
2089
- case "-":
2090
- case ".": {
2091
- break;
2092
- }
2093
- case ",": {
2094
- stack.pop();
2095
- if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2096
- processAfterArrayValue(char, i);
2097
- }
2098
- if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2099
- processAfterObjectValue(char, i);
2100
- }
2101
- break;
2102
- }
2103
- case "}": {
2104
- stack.pop();
2105
- if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2106
- processAfterObjectValue(char, i);
2107
- }
2108
- break;
2109
- }
2110
- case "]": {
2111
- stack.pop();
2112
- if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2113
- processAfterArrayValue(char, i);
2114
- }
2115
- break;
2116
- }
2117
- default: {
2118
- stack.pop();
2119
- break;
2120
- }
2121
- }
2122
- break;
2123
- }
2124
- case "INSIDE_LITERAL": {
2125
- const partialLiteral = input.substring(literalStart, i + 1);
2126
- if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
2127
- stack.pop();
2128
- if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2129
- processAfterObjectValue(char, i);
2130
- } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2131
- processAfterArrayValue(char, i);
2132
- }
2133
- } else {
2134
- lastValidIndex = i;
2135
- }
2136
- break;
2137
- }
2138
- }
2139
- }
2140
- let result = input.slice(0, lastValidIndex + 1);
2141
- for (let i = stack.length - 1; i >= 0; i--) {
2142
- const state = stack[i];
2143
- switch (state) {
2144
- case "INSIDE_STRING": {
2145
- result += '"';
2146
- break;
2147
- }
2148
- case "INSIDE_OBJECT_KEY":
2149
- case "INSIDE_OBJECT_AFTER_KEY":
2150
- case "INSIDE_OBJECT_AFTER_COMMA":
2151
- case "INSIDE_OBJECT_START":
2152
- case "INSIDE_OBJECT_BEFORE_VALUE":
2153
- case "INSIDE_OBJECT_AFTER_VALUE": {
2154
- result += "}";
2155
- break;
2156
- }
2157
- case "INSIDE_ARRAY_START":
2158
- case "INSIDE_ARRAY_AFTER_COMMA":
2159
- case "INSIDE_ARRAY_AFTER_VALUE": {
2160
- result += "]";
2161
- break;
2162
- }
2163
- case "INSIDE_LITERAL": {
2164
- const partialLiteral = input.substring(literalStart, input.length);
2165
- if ("true".startsWith(partialLiteral)) {
2166
- result += "true".slice(partialLiteral.length);
2167
- } else if ("false".startsWith(partialLiteral)) {
2168
- result += "false".slice(partialLiteral.length);
2169
- } else if ("null".startsWith(partialLiteral)) {
2170
- result += "null".slice(partialLiteral.length);
2171
- }
2172
- }
2173
- }
2174
- }
2175
- return result;
2176
- }
2177
- function parsePartialJson(jsonText) {
2178
- if (jsonText === void 0) {
2179
- return { value: void 0, state: "undefined-input" };
2180
- }
2181
- let result = safeParseJSON({ text: jsonText });
2182
- if (result.success) {
2183
- return { value: result.value, state: "successful-parse" };
2184
- }
2185
- result = safeParseJSON({ text: fixJson(jsonText) });
2186
- if (result.success) {
2187
- return { value: result.value, state: "repaired-parse" };
2188
- }
2189
- return { value: void 0, state: "failed-parse" };
2190
- }
2191
- var textStreamPart2 = {
2192
- code: "0",
2193
- name: "text",
2194
- parse: (value) => {
2195
- if (typeof value !== "string") {
2196
- throw new Error('"text" parts expect a string value.');
2197
- }
2198
- return { type: "text", value };
2199
- }
2200
- };
2201
- var dataStreamPart = {
2202
- code: "2",
2203
- name: "data",
2204
- parse: (value) => {
2205
- if (!Array.isArray(value)) {
2206
- throw new Error('"data" parts expect an array value.');
2207
- }
2208
- return { type: "data", value };
2209
- }
2210
- };
2211
- var errorStreamPart2 = {
2212
- code: "3",
2213
- name: "error",
2214
- parse: (value) => {
2215
- if (typeof value !== "string") {
2216
- throw new Error('"error" parts expect a string value.');
2217
- }
2218
- return { type: "error", value };
2219
- }
2220
- };
2221
- var messageAnnotationsStreamPart = {
2222
- code: "8",
2223
- name: "message_annotations",
2224
- parse: (value) => {
2225
- if (!Array.isArray(value)) {
2226
- throw new Error('"message_annotations" parts expect an array value.');
2227
- }
2228
- return { type: "message_annotations", value };
2229
- }
2230
- };
2231
- var toolCallStreamPart = {
2232
- code: "9",
2233
- name: "tool_call",
2234
- parse: (value) => {
2235
- 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") {
2236
- throw new Error(
2237
- '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
2238
- );
2239
- }
2240
- return {
2241
- type: "tool_call",
2242
- value
2243
- };
2244
- }
2245
- };
2246
- var toolResultStreamPart = {
2247
- code: "a",
2248
- name: "tool_result",
2249
- parse: (value) => {
2250
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) {
2251
- throw new Error(
2252
- '"tool_result" parts expect an object with a "toolCallId" and a "result" property.'
2253
- );
2254
- }
2255
- return {
2256
- type: "tool_result",
2257
- value
2258
- };
2259
- }
2260
- };
2261
- var toolCallStreamingStartStreamPart = {
2262
- code: "b",
2263
- name: "tool_call_streaming_start",
2264
- parse: (value) => {
2265
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") {
2266
- throw new Error(
2267
- '"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.'
2268
- );
2269
- }
2270
- return {
2271
- type: "tool_call_streaming_start",
2272
- value
2273
- };
2274
- }
2275
- };
2276
- var toolCallDeltaStreamPart = {
2277
- code: "c",
2278
- name: "tool_call_delta",
2279
- parse: (value) => {
2280
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") {
2281
- throw new Error(
2282
- '"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.'
2283
- );
2284
- }
2285
- return {
2286
- type: "tool_call_delta",
2287
- value
2288
- };
2289
- }
2290
- };
2291
- var finishMessageStreamPart = {
2292
- code: "d",
2293
- name: "finish_message",
2294
- parse: (value) => {
2295
- if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
2296
- throw new Error(
2297
- '"finish_message" parts expect an object with a "finishReason" property.'
2298
- );
2299
- }
2300
- const result = {
2301
- finishReason: value.finishReason
2302
- };
2303
- if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
2304
- result.usage = {
2305
- promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
2306
- completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
2307
- };
2308
- }
2309
- return {
2310
- type: "finish_message",
2311
- value: result
2312
- };
2313
- }
2314
- };
2315
- var finishStepStreamPart = {
2316
- code: "e",
2317
- name: "finish_step",
2318
- parse: (value) => {
2319
- if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
2320
- throw new Error(
2321
- '"finish_step" parts expect an object with a "finishReason" property.'
2322
- );
2323
- }
2324
- const result = {
2325
- finishReason: value.finishReason,
2326
- isContinued: false
2327
- };
2328
- if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
2329
- result.usage = {
2330
- promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
2331
- completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
2332
- };
2333
- }
2334
- if ("isContinued" in value && typeof value.isContinued === "boolean") {
2335
- result.isContinued = value.isContinued;
2336
- }
2337
- return {
2338
- type: "finish_step",
2339
- value: result
2340
- };
2341
- }
2342
- };
2343
- var startStepStreamPart = {
2344
- code: "f",
2345
- name: "start_step",
2346
- parse: (value) => {
2347
- if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") {
2348
- throw new Error(
2349
- '"start_step" parts expect an object with an "id" property.'
2350
- );
2351
- }
2352
- return {
2353
- type: "start_step",
2354
- value: {
2355
- messageId: value.messageId
2356
- }
2357
- };
2358
- }
2359
- };
2360
- var reasoningStreamPart = {
2361
- code: "g",
2362
- name: "reasoning",
2363
- parse: (value) => {
2364
- if (typeof value !== "string") {
2365
- throw new Error('"reasoning" parts expect a string value.');
2366
- }
2367
- return { type: "reasoning", value };
2368
- }
2369
- };
2370
- var sourcePart = {
2371
- code: "h",
2372
- name: "source",
2373
- parse: (value) => {
2374
- if (value == null || typeof value !== "object") {
2375
- throw new Error('"source" parts expect a Source object.');
2376
- }
2377
- return {
2378
- type: "source",
2379
- value
2380
- };
2381
- }
2382
- };
2383
- var redactedReasoningStreamPart = {
2384
- code: "i",
2385
- name: "redacted_reasoning",
2386
- parse: (value) => {
2387
- if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string") {
2388
- throw new Error(
2389
- '"redacted_reasoning" parts expect an object with a "data" property.'
2390
- );
2391
- }
2392
- return { type: "redacted_reasoning", value: { data: value.data } };
2393
- }
2394
- };
2395
- var reasoningSignatureStreamPart = {
2396
- code: "j",
2397
- name: "reasoning_signature",
2398
- parse: (value) => {
2399
- if (value == null || typeof value !== "object" || !("signature" in value) || typeof value.signature !== "string") {
2400
- throw new Error(
2401
- '"reasoning_signature" parts expect an object with a "signature" property.'
2402
- );
2403
- }
2404
- return {
2405
- type: "reasoning_signature",
2406
- value: { signature: value.signature }
2407
- };
2408
- }
2409
- };
2410
- var dataStreamParts = [
2411
- textStreamPart2,
2412
- dataStreamPart,
2413
- errorStreamPart2,
2414
- messageAnnotationsStreamPart,
2415
- toolCallStreamPart,
2416
- toolResultStreamPart,
2417
- toolCallStreamingStartStreamPart,
2418
- toolCallDeltaStreamPart,
2419
- finishMessageStreamPart,
2420
- finishStepStreamPart,
2421
- startStepStreamPart,
2422
- reasoningStreamPart,
2423
- sourcePart,
2424
- redactedReasoningStreamPart,
2425
- reasoningSignatureStreamPart
2426
- ];
2427
- Object.fromEntries(
2428
- dataStreamParts.map((part) => [part.code, part])
2429
- );
2430
- Object.fromEntries(
2431
- dataStreamParts.map((part) => [part.name, part.code])
2432
- );
2433
- dataStreamParts.map((part) => part.code);
2434
- function formatDataStreamPart(type, value) {
2435
- const streamPart = dataStreamParts.find((part) => part.name === type);
2436
- if (!streamPart) {
2437
- throw new Error(`Invalid stream part type: ${type}`);
2438
- }
2439
- return `${streamPart.code}:${JSON.stringify(value)}
2440
- `;
2441
- }
2442
- function zodSchema(zodSchema2, options) {
2443
- var _a;
2444
- const useReferences = (_a = void 0 ) != null ? _a : false;
2445
- return jsonSchema(
2446
- zodToJsonSchema(zodSchema2, {
2447
- $refStrategy: useReferences ? "root" : "none",
2448
- target: "jsonSchema7"
2449
- // note: openai mode breaks various gemini conversions
2450
- }),
2451
- {
2452
- validate: (value) => {
2453
- const result = zodSchema2.safeParse(value);
2454
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2455
- }
2456
- }
2457
- );
2458
- }
2459
- var schemaSymbol = Symbol.for("vercel.ai.schema");
2460
- function jsonSchema(jsonSchema2, {
2461
- validate
2462
- } = {}) {
2463
- return {
2464
- [schemaSymbol]: true,
2465
- _type: void 0,
2466
- // should never be used directly
2467
- [validatorSymbol]: true,
2468
- jsonSchema: jsonSchema2,
2469
- validate
2470
- };
2471
- }
2472
- function isSchema(value) {
2473
- return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2474
- }
2475
- function asSchema(schema) {
2476
- return isSchema(schema) ? schema : zodSchema(schema);
2477
- }
2478
-
2479
- var __defProp = Object.defineProperty;
2480
- var __export = (target, all) => {
2481
- for (var name17 in all)
2482
- __defProp(target, name17, { get: all[name17], enumerable: true });
2483
- };
2484
- function prepareResponseHeaders(headers, {
2485
- contentType,
2486
- dataStreamVersion
2487
- }) {
2488
- const responseHeaders = new Headers(headers != null ? headers : {});
2489
- if (!responseHeaders.has("Content-Type")) {
2490
- responseHeaders.set("Content-Type", contentType);
2491
- }
2492
- {
2493
- responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
2494
- }
2495
- return responseHeaders;
2496
- }
2497
- var name4 = "AI_NoObjectGeneratedError";
2498
- var marker4 = `vercel.ai.error.${name4}`;
2499
- var symbol4 = Symbol.for(marker4);
2500
- var _a4;
2501
- var NoObjectGeneratedError = class extends AISDKError$1 {
2502
- constructor({
2503
- message = "No object generated.",
2504
- cause,
2505
- text: text2,
2506
- response,
2507
- usage
2508
- }) {
2509
- super({ name: name4, message, cause });
2510
- this[_a4] = true;
2511
- this.text = text2;
2512
- this.response = response;
2513
- this.usage = usage;
2514
- }
2515
- static isInstance(error) {
2516
- return AISDKError$1.hasMarker(error, marker4);
2517
- }
2518
- };
2519
- _a4 = symbol4;
2520
- var dataContentSchema = z.union([
2521
- z.string(),
2522
- z.instanceof(Uint8Array),
2523
- z.instanceof(ArrayBuffer),
2524
- z.custom(
2525
- // Buffer might not be available in some environments such as CloudFlare:
2526
- (value) => {
2527
- var _a17, _b;
2528
- return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
2529
- },
2530
- { message: "Must be a Buffer" }
2531
- )
2532
- ]);
2533
- var jsonValueSchema = z.lazy(
2534
- () => z.union([
2535
- z.null(),
2536
- z.string(),
2537
- z.number(),
2538
- z.boolean(),
2539
- z.record(z.string(), jsonValueSchema),
2540
- z.array(jsonValueSchema)
2541
- ])
2542
- );
2543
- var providerMetadataSchema = z.record(
2544
- z.string(),
2545
- z.record(z.string(), jsonValueSchema)
2546
- );
2547
- var toolResultContentSchema = z.array(
2548
- z.union([
2549
- z.object({ type: z.literal("text"), text: z.string() }),
2550
- z.object({
2551
- type: z.literal("image"),
2552
- data: z.string(),
2553
- mimeType: z.string().optional()
2554
- })
2555
- ])
2556
- );
2557
- var textPartSchema = z.object({
2558
- type: z.literal("text"),
2559
- text: z.string(),
2560
- providerOptions: providerMetadataSchema.optional(),
2561
- experimental_providerMetadata: providerMetadataSchema.optional()
2562
- });
2563
- var imagePartSchema = z.object({
2564
- type: z.literal("image"),
2565
- image: z.union([dataContentSchema, z.instanceof(URL)]),
2566
- mimeType: z.string().optional(),
2567
- providerOptions: providerMetadataSchema.optional(),
2568
- experimental_providerMetadata: providerMetadataSchema.optional()
2569
- });
2570
- var filePartSchema = z.object({
2571
- type: z.literal("file"),
2572
- data: z.union([dataContentSchema, z.instanceof(URL)]),
2573
- filename: z.string().optional(),
2574
- mimeType: z.string(),
2575
- providerOptions: providerMetadataSchema.optional(),
2576
- experimental_providerMetadata: providerMetadataSchema.optional()
2577
- });
2578
- var reasoningPartSchema = z.object({
2579
- type: z.literal("reasoning"),
2580
- text: z.string(),
2581
- providerOptions: providerMetadataSchema.optional(),
2582
- experimental_providerMetadata: providerMetadataSchema.optional()
2583
- });
2584
- var redactedReasoningPartSchema = z.object({
2585
- type: z.literal("redacted-reasoning"),
2586
- data: z.string(),
2587
- providerOptions: providerMetadataSchema.optional(),
2588
- experimental_providerMetadata: providerMetadataSchema.optional()
2589
- });
2590
- var toolCallPartSchema = z.object({
2591
- type: z.literal("tool-call"),
2592
- toolCallId: z.string(),
2593
- toolName: z.string(),
2594
- args: z.unknown(),
2595
- providerOptions: providerMetadataSchema.optional(),
2596
- experimental_providerMetadata: providerMetadataSchema.optional()
2597
- });
2598
- var toolResultPartSchema = z.object({
2599
- type: z.literal("tool-result"),
2600
- toolCallId: z.string(),
2601
- toolName: z.string(),
2602
- result: z.unknown(),
2603
- content: toolResultContentSchema.optional(),
2604
- isError: z.boolean().optional(),
2605
- providerOptions: providerMetadataSchema.optional(),
2606
- experimental_providerMetadata: providerMetadataSchema.optional()
2607
- });
2608
- var coreSystemMessageSchema = z.object({
2609
- role: z.literal("system"),
2610
- content: z.string(),
2611
- providerOptions: providerMetadataSchema.optional(),
2612
- experimental_providerMetadata: providerMetadataSchema.optional()
2613
- });
2614
- var coreUserMessageSchema = z.object({
2615
- role: z.literal("user"),
2616
- content: z.union([
2617
- z.string(),
2618
- z.array(z.union([textPartSchema, imagePartSchema, filePartSchema]))
2619
- ]),
2620
- providerOptions: providerMetadataSchema.optional(),
2621
- experimental_providerMetadata: providerMetadataSchema.optional()
2622
- });
2623
- var coreAssistantMessageSchema = z.object({
2624
- role: z.literal("assistant"),
2625
- content: z.union([
2626
- z.string(),
2627
- z.array(
2628
- z.union([
2629
- textPartSchema,
2630
- reasoningPartSchema,
2631
- redactedReasoningPartSchema,
2632
- toolCallPartSchema
2633
- ])
2634
- )
2635
- ]),
2636
- providerOptions: providerMetadataSchema.optional(),
2637
- experimental_providerMetadata: providerMetadataSchema.optional()
2638
- });
2639
- var coreToolMessageSchema = z.object({
2640
- role: z.literal("tool"),
2641
- content: z.array(toolResultPartSchema),
2642
- providerOptions: providerMetadataSchema.optional(),
2643
- experimental_providerMetadata: providerMetadataSchema.optional()
2644
- });
2645
- z.union([
2646
- coreSystemMessageSchema,
2647
- coreUserMessageSchema,
2648
- coreAssistantMessageSchema,
2649
- coreToolMessageSchema
2650
- ]);
2651
- var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
2652
- var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
2653
- var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
2654
- function injectJsonInstruction({
2655
- prompt,
2656
- schema,
2657
- schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,
2658
- schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
2659
- }) {
2660
- return [
2661
- prompt != null && prompt.length > 0 ? prompt : void 0,
2662
- prompt != null && prompt.length > 0 ? "" : void 0,
2663
- // add a newline if prompt is not null
2664
- schemaPrefix,
2665
- schema != null ? JSON.stringify(schema) : void 0,
2666
- schemaSuffix
2667
- ].filter((line) => line != null).join("\n");
2668
- }
2669
- createIdGenerator$1({ prefix: "aiobj", size: 24 });
2670
- createIdGenerator$1({ prefix: "aiobj", size: 24 });
2671
- createIdGenerator$1({
2672
- prefix: "aitxt",
2673
- size: 24
2674
- });
2675
- createIdGenerator$1({
2676
- prefix: "msg",
2677
- size: 24
2678
- });
2679
- var output_exports = {};
2680
- __export(output_exports, {
2681
- object: () => object,
2682
- text: () => text
2683
- });
2684
- var text = () => ({
2685
- type: "text",
2686
- responseFormat: () => ({ type: "text" }),
2687
- injectIntoSystemPrompt({ system }) {
2688
- return system;
2689
- },
2690
- parsePartial({ text: text2 }) {
2691
- return { partial: text2 };
2692
- },
2693
- parseOutput({ text: text2 }) {
2694
- return text2;
2695
- }
2696
- });
2697
- var object = ({
2698
- schema: inputSchema
2699
- }) => {
2700
- const schema = asSchema(inputSchema);
2701
- return {
2702
- type: "object",
2703
- responseFormat: ({ model }) => ({
2704
- type: "json",
2705
- schema: model.supportsStructuredOutputs ? schema.jsonSchema : void 0
2706
- }),
2707
- injectIntoSystemPrompt({ system, model }) {
2708
- return model.supportsStructuredOutputs ? system : injectJsonInstruction({
2709
- prompt: system,
2710
- schema: schema.jsonSchema
2711
- });
2712
- },
2713
- parsePartial({ text: text2 }) {
2714
- const result = parsePartialJson(text2);
2715
- switch (result.state) {
2716
- case "failed-parse":
2717
- case "undefined-input":
2718
- return void 0;
2719
- case "repaired-parse":
2720
- case "successful-parse":
2721
- return {
2722
- // Note: currently no validation of partial results:
2723
- partial: result.value
2724
- };
2725
- default: {
2726
- const _exhaustiveCheck = result.state;
2727
- throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
2728
- }
2729
- }
2730
- },
2731
- parseOutput({ text: text2 }, context) {
2732
- const parseResult = safeParseJSON$1({ text: text2 });
2733
- if (!parseResult.success) {
2734
- throw new NoObjectGeneratedError({
2735
- message: "No object generated: could not parse the response.",
2736
- cause: parseResult.error,
2737
- text: text2,
2738
- response: context.response,
2739
- usage: context.usage
2740
- });
2741
- }
2742
- const validationResult = safeValidateTypes$1({
2743
- value: parseResult.value,
2744
- schema
2745
- });
2746
- if (!validationResult.success) {
2747
- throw new NoObjectGeneratedError({
2748
- message: "No object generated: response did not match schema.",
2749
- cause: validationResult.error,
2750
- text: text2,
2751
- response: context.response,
2752
- usage: context.usage
2753
- });
2754
- }
2755
- return validationResult.value;
2756
- }
2757
- };
2758
- };
2759
- function mergeStreams(stream1, stream2) {
2760
- const reader1 = stream1.getReader();
2761
- const reader2 = stream2.getReader();
2762
- let lastRead1 = void 0;
2763
- let lastRead2 = void 0;
2764
- let stream1Done = false;
2765
- let stream2Done = false;
2766
- async function readStream1(controller) {
2767
- try {
2768
- if (lastRead1 == null) {
2769
- lastRead1 = reader1.read();
2770
- }
2771
- const result = await lastRead1;
2772
- lastRead1 = void 0;
2773
- if (!result.done) {
2774
- controller.enqueue(result.value);
2775
- } else {
2776
- controller.close();
2777
- }
2778
- } catch (error) {
2779
- controller.error(error);
2780
- }
2781
- }
2782
- async function readStream2(controller) {
2783
- try {
2784
- if (lastRead2 == null) {
2785
- lastRead2 = reader2.read();
2786
- }
2787
- const result = await lastRead2;
2788
- lastRead2 = void 0;
2789
- if (!result.done) {
2790
- controller.enqueue(result.value);
2791
- } else {
2792
- controller.close();
2793
- }
2794
- } catch (error) {
2795
- controller.error(error);
2796
- }
2797
- }
2798
- return new ReadableStream({
2799
- async pull(controller) {
2800
- try {
2801
- if (stream1Done) {
2802
- await readStream2(controller);
2803
- return;
2804
- }
2805
- if (stream2Done) {
2806
- await readStream1(controller);
2807
- return;
2808
- }
2809
- if (lastRead1 == null) {
2810
- lastRead1 = reader1.read();
2811
- }
2812
- if (lastRead2 == null) {
2813
- lastRead2 = reader2.read();
2814
- }
2815
- const { result, reader } = await Promise.race([
2816
- lastRead1.then((result2) => ({ result: result2, reader: reader1 })),
2817
- lastRead2.then((result2) => ({ result: result2, reader: reader2 }))
2818
- ]);
2819
- if (!result.done) {
2820
- controller.enqueue(result.value);
2821
- }
2822
- if (reader === reader1) {
2823
- lastRead1 = void 0;
2824
- if (result.done) {
2825
- await readStream2(controller);
2826
- stream1Done = true;
2827
- }
2828
- } else {
2829
- lastRead2 = void 0;
2830
- if (result.done) {
2831
- stream2Done = true;
2832
- await readStream1(controller);
2833
- }
2834
- }
2835
- } catch (error) {
2836
- controller.error(error);
2837
- }
2838
- },
2839
- cancel() {
2840
- reader1.cancel();
2841
- reader2.cancel();
2842
- }
2843
- });
2844
- }
2845
- createIdGenerator$1({
2846
- prefix: "aitxt",
2847
- size: 24
2848
- });
2849
- createIdGenerator$1({
2850
- prefix: "msg",
2851
- size: 24
2852
- });
2853
- function tool(tool2) {
2854
- return tool2;
2855
- }
2856
- var JSONRPC_VERSION = "2.0";
2857
- var ClientOrServerImplementationSchema = z.object({
2858
- name: z.string(),
2859
- version: z.string()
2860
- }).passthrough();
2861
- var BaseParamsSchema = z.object({
2862
- _meta: z.optional(z.object({}).passthrough())
2863
- }).passthrough();
2864
- var RequestSchema = z.object({
2865
- method: z.string(),
2866
- params: z.optional(BaseParamsSchema)
2867
- });
2868
- var ResultSchema = BaseParamsSchema;
2869
- var NotificationSchema = z.object({
2870
- method: z.string(),
2871
- params: z.optional(BaseParamsSchema)
2872
- });
2873
- var RequestIdSchema = z.union([z.string(), z.number().int()]);
2874
- var JSONRPCRequestSchema = z.object({
2875
- jsonrpc: z.literal(JSONRPC_VERSION),
2876
- id: RequestIdSchema
2877
- }).merge(RequestSchema).strict();
2878
- var JSONRPCResponseSchema = z.object({
2879
- jsonrpc: z.literal(JSONRPC_VERSION),
2880
- id: RequestIdSchema,
2881
- result: ResultSchema
2882
- }).strict();
2883
- var JSONRPCErrorSchema = z.object({
2884
- jsonrpc: z.literal(JSONRPC_VERSION),
2885
- id: RequestIdSchema,
2886
- error: z.object({
2887
- code: z.number().int(),
2888
- message: z.string(),
2889
- data: z.optional(z.unknown())
2890
- })
2891
- }).strict();
2892
- var JSONRPCNotificationSchema = z.object({
2893
- jsonrpc: z.literal(JSONRPC_VERSION)
2894
- }).merge(NotificationSchema).strict();
2895
- z.union([
2896
- JSONRPCRequestSchema,
2897
- JSONRPCNotificationSchema,
2898
- JSONRPCResponseSchema,
2899
- JSONRPCErrorSchema
2900
- ]);
2901
- var ServerCapabilitiesSchema = z.object({
2902
- experimental: z.optional(z.object({}).passthrough()),
2903
- logging: z.optional(z.object({}).passthrough()),
2904
- prompts: z.optional(
2905
- z.object({
2906
- listChanged: z.optional(z.boolean())
2907
- }).passthrough()
2908
- ),
2909
- resources: z.optional(
2910
- z.object({
2911
- subscribe: z.optional(z.boolean()),
2912
- listChanged: z.optional(z.boolean())
2913
- }).passthrough()
2914
- ),
2915
- tools: z.optional(
2916
- z.object({
2917
- listChanged: z.optional(z.boolean())
2918
- }).passthrough()
2919
- )
2920
- }).passthrough();
2921
- ResultSchema.extend({
2922
- protocolVersion: z.string(),
2923
- capabilities: ServerCapabilitiesSchema,
2924
- serverInfo: ClientOrServerImplementationSchema,
2925
- instructions: z.optional(z.string())
2926
- });
2927
- var PaginatedResultSchema = ResultSchema.extend({
2928
- nextCursor: z.optional(z.string())
2929
- });
2930
- var ToolSchema = z.object({
2931
- name: z.string(),
2932
- description: z.optional(z.string()),
2933
- inputSchema: z.object({
2934
- type: z.literal("object"),
2935
- properties: z.optional(z.object({}).passthrough())
2936
- }).passthrough()
2937
- }).passthrough();
2938
- PaginatedResultSchema.extend({
2939
- tools: z.array(ToolSchema)
2940
- });
2941
- var TextContentSchema = z.object({
2942
- type: z.literal("text"),
2943
- text: z.string()
2944
- }).passthrough();
2945
- var ImageContentSchema = z.object({
2946
- type: z.literal("image"),
2947
- data: z.string().base64(),
2948
- mimeType: z.string()
2949
- }).passthrough();
2950
- var ResourceContentsSchema = z.object({
2951
- /**
2952
- * The URI of this resource.
2953
- */
2954
- uri: z.string(),
2955
- /**
2956
- * The MIME type of this resource, if known.
2957
- */
2958
- mimeType: z.optional(z.string())
2959
- }).passthrough();
2960
- var TextResourceContentsSchema = ResourceContentsSchema.extend({
2961
- text: z.string()
2962
- });
2963
- var BlobResourceContentsSchema = ResourceContentsSchema.extend({
2964
- blob: z.string().base64()
2965
- });
2966
- var EmbeddedResourceSchema = z.object({
2967
- type: z.literal("resource"),
2968
- resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
2969
- }).passthrough();
2970
- ResultSchema.extend({
2971
- content: z.array(
2972
- z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
2973
- ),
2974
- isError: z.boolean().default(false).optional()
2975
- }).or(
2976
- ResultSchema.extend({
2977
- toolResult: z.unknown()
2978
- })
2979
- );
2980
- var langchain_adapter_exports = {};
2981
- __export(langchain_adapter_exports, {
2982
- mergeIntoDataStream: () => mergeIntoDataStream,
2983
- toDataStream: () => toDataStream,
2984
- toDataStreamResponse: () => toDataStreamResponse
2985
- });
2986
- function createCallbacksTransformer(callbacks = {}) {
2987
- const textEncoder = new TextEncoder();
2988
- let aggregatedResponse = "";
2989
- return new TransformStream({
2990
- async start() {
2991
- if (callbacks.onStart)
2992
- await callbacks.onStart();
2993
- },
2994
- async transform(message, controller) {
2995
- controller.enqueue(textEncoder.encode(message));
2996
- aggregatedResponse += message;
2997
- if (callbacks.onToken)
2998
- await callbacks.onToken(message);
2999
- if (callbacks.onText && typeof message === "string") {
3000
- await callbacks.onText(message);
3001
- }
3002
- },
3003
- async flush() {
3004
- if (callbacks.onCompletion) {
3005
- await callbacks.onCompletion(aggregatedResponse);
3006
- }
3007
- if (callbacks.onFinal) {
3008
- await callbacks.onFinal(aggregatedResponse);
3009
- }
3010
- }
3011
- });
3012
- }
3013
- function toDataStreamInternal(stream, callbacks) {
3014
- return stream.pipeThrough(
3015
- new TransformStream({
3016
- transform: async (value, controller) => {
3017
- var _a17;
3018
- if (typeof value === "string") {
3019
- controller.enqueue(value);
3020
- return;
3021
- }
3022
- if ("event" in value) {
3023
- if (value.event === "on_chat_model_stream") {
3024
- forwardAIMessageChunk(
3025
- (_a17 = value.data) == null ? void 0 : _a17.chunk,
3026
- controller
3027
- );
3028
- }
3029
- return;
3030
- }
3031
- forwardAIMessageChunk(value, controller);
3032
- }
3033
- })
3034
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
3035
- new TransformStream({
3036
- transform: async (chunk, controller) => {
3037
- controller.enqueue(formatDataStreamPart("text", chunk));
3038
- }
3039
- })
3040
- );
3041
- }
3042
- function toDataStream(stream, callbacks) {
3043
- return toDataStreamInternal(stream, callbacks).pipeThrough(
3044
- new TextEncoderStream()
3045
- );
3046
- }
3047
- function toDataStreamResponse(stream, options) {
3048
- var _a17;
3049
- const dataStream = toDataStreamInternal(
3050
- stream,
3051
- options == null ? void 0 : options.callbacks
3052
- ).pipeThrough(new TextEncoderStream());
3053
- const data = options == null ? void 0 : options.data;
3054
- const init = options == null ? void 0 : options.init;
3055
- const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
3056
- return new Response(responseStream, {
3057
- status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
3058
- statusText: init == null ? void 0 : init.statusText,
3059
- headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3060
- contentType: "text/plain; charset=utf-8",
3061
- dataStreamVersion: "v1"
3062
- })
3063
- });
3064
- }
3065
- function mergeIntoDataStream(stream, options) {
3066
- options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
3067
- }
3068
- function forwardAIMessageChunk(chunk, controller) {
3069
- if (typeof chunk.content === "string") {
3070
- controller.enqueue(chunk.content);
3071
- } else {
3072
- const content = chunk.content;
3073
- for (const item of content) {
3074
- if (item.type === "text") {
3075
- controller.enqueue(item.text);
3076
- }
3077
- }
3078
- }
3079
- }
3080
- var llamaindex_adapter_exports = {};
3081
- __export(llamaindex_adapter_exports, {
3082
- mergeIntoDataStream: () => mergeIntoDataStream2,
3083
- toDataStream: () => toDataStream2,
3084
- toDataStreamResponse: () => toDataStreamResponse2
3085
- });
3086
- function toDataStreamInternal2(stream, callbacks) {
3087
- const trimStart = trimStartOfStream();
3088
- return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough(
3089
- new TransformStream({
3090
- async transform(message, controller) {
3091
- controller.enqueue(trimStart(message.delta));
3092
- }
3093
- })
3094
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
3095
- new TransformStream({
3096
- transform: async (chunk, controller) => {
3097
- controller.enqueue(formatDataStreamPart("text", chunk));
3098
- }
3099
- })
3100
- );
3101
- }
3102
- function toDataStream2(stream, callbacks) {
3103
- return toDataStreamInternal2(stream, callbacks).pipeThrough(
3104
- new TextEncoderStream()
3105
- );
3106
- }
3107
- function toDataStreamResponse2(stream, options = {}) {
3108
- var _a17;
3109
- const { init, data, callbacks } = options;
3110
- const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
3111
- new TextEncoderStream()
3112
- );
3113
- const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
3114
- return new Response(responseStream, {
3115
- status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
3116
- statusText: init == null ? void 0 : init.statusText,
3117
- headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3118
- contentType: "text/plain; charset=utf-8",
3119
- dataStreamVersion: "v1"
3120
- })
3121
- });
3122
- }
3123
- function mergeIntoDataStream2(stream, options) {
3124
- options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
3125
- }
3126
- function trimStartOfStream() {
3127
- let isStreamStart = true;
3128
- return (text2) => {
3129
- if (isStreamStart) {
3130
- text2 = text2.trimStart();
3131
- if (text2)
3132
- isStreamStart = false;
3133
- }
3134
- return text2;
3135
- };
3136
- }
3137
-
3138
- const executeCodeSchema = z.object({
3139
- script: z.string().describe(`
3140
- The JavaScript or TypeScript script to execute, must be in the format of:
3141
-
3142
- import { someModule } from "someModule";
3143
- export default () => {
3144
- ... your code here ...
3145
- return output;
3146
- }
3147
-
3148
- or for async functions:
3149
-
3150
- import { someModule } from "someModule";
3151
-
3152
- export default async () => {
3153
- ... your code here ...
3154
- return output;
3155
- }
3156
- `)
3157
- });
3158
- const executeCodeDescription = (envVars, nodeModules) => `Execute a JavaScript or TypeScript script.
3159
- ${envVars.length > 0 ? `You can use the following environment variables: ${envVars}` : ""}
3160
- ${nodeModules.length > 0 ? `You can use the following node modules: ${nodeModules}` : "You cannot use any node modules."}`;
3161
- const executeTool = (config) => {
3162
- const api = new FreestyleSandboxes({
3163
- ...config
3164
- });
3165
- const envVars = Object.keys(config.envVars ?? {}).join(", ");
3166
- const nodeModules = Object.keys(config.nodeModules ?? {}).join(", ");
3167
- return tool({
3168
- description: executeCodeDescription(envVars, nodeModules),
3169
- parameters: executeCodeSchema,
3170
- execute: async ({ script, ...otherParams }, { toolCallId }) => {
3171
- try {
3172
- const res = await api.executeScript(script, config);
3173
- if (config.onResult) {
3174
- await config.onResult({
3175
- toolCallId,
3176
- result: res,
3177
- input: {
3178
- script,
3179
- ...otherParams
3180
- }
3181
- });
3182
- }
3183
- if (config.truncateOutput) {
3184
- if ("output" in res) {
3185
- res.result = JSON.stringify(res.result).slice(0, 1e3);
3186
- res.logs = res.logs.slice(0, 1e3);
3187
- }
3188
- }
3189
- return res;
3190
- } catch (e) {
3191
- console.log("ERROR: ", e.message);
3192
- return {
3193
- message: e.message,
3194
- error: e.error
3195
- };
3196
- }
3197
- }
3198
- });
3199
- };
3200
- const deployWebTool = (config) => {
3201
- const api = new FreestyleSandboxes({
3202
- ...config
3203
- });
3204
- const envVars = Object.keys(config.envVars ?? {}).join(", ");
3205
- const nodeModules = Object.keys(config.nodeModules ?? {}).join(", ");
3206
- return tool({
3207
- description: `Deploy a Web project. ${envVars.length > 0 ? `You can use the following environment variables: ${envVars}` : ""}
3208
- ${nodeModules.length > 0 ? `You can use the following node modules: ${nodeModules}` : "You cannot use any node modules."}`,
3209
- parameters: z.object({
3210
- files: z.record(z.string()).describe(`
3211
- A record of file names and their contents to deploy. For example:
3212
- {
3213
- "index.js": "import http from 'node:http';\\nnconsole.log('starting server');\\n\\nconst server = http.createServer(async(req, res) => {\\n res.writeHead(200, { 'Content-Type': 'text/plain' });\\n res.end('Welcome to New York its been waiting for you');\\n});\\n\\nserver.listen(3000, () => {\\n console.log('Server is running at http://localhost:3000');\\n});",
3214
- }
3215
- `)
3216
- }),
3217
- execute: async ({ files }) => {
3218
- const new_files = Object.keys(files).reduce((acc, key) => {
3219
- acc[key] = { content: files[key] };
3220
- return acc;
3221
- }, {});
3222
- try {
3223
- const res = await api.deployWeb(
3224
- {
3225
- kind: "files",
3226
- files: new_files
3227
- },
3228
- config
3229
- );
3230
- return res;
3231
- } catch (e) {
3232
- console.log("ERROR: ", e.message);
3233
- return `Error deploying web project:
3234
-
3235
- ${JSON.stringify(
3236
- files,
3237
- null,
3238
- 2
3239
- )}
3240
-
3241
- Error: ${e.message}`;
3242
- }
3243
- }
3244
- });
3245
- };
3246
-
3247
- export { executeCodeSchema as a, executeTool as b, deployWebTool as d, executeCodeDescription as e, getDefaultExportFromCjs as g, zodToJsonSchema as z };