@ai-sdk/provider-utils 0.0.0-64aae7dd-20260114144918

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 (174) hide show
  1. package/CHANGELOG.md +1471 -0
  2. package/README.md +1 -0
  3. package/dist/index.d.mts +1368 -0
  4. package/dist/index.d.ts +1368 -0
  5. package/dist/index.js +2637 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.mjs +2551 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/dist/test/index.d.mts +17 -0
  10. package/dist/test/index.d.ts +17 -0
  11. package/dist/test/index.js +110 -0
  12. package/dist/test/index.js.map +1 -0
  13. package/dist/test/index.mjs +77 -0
  14. package/dist/test/index.mjs.map +1 -0
  15. package/package.json +77 -0
  16. package/src/__snapshots__/schema.test.ts.snap +346 -0
  17. package/src/add-additional-properties-to-json-schema.test.ts +289 -0
  18. package/src/add-additional-properties-to-json-schema.ts +53 -0
  19. package/src/combine-headers.ts +11 -0
  20. package/src/convert-async-iterator-to-readable-stream.test.ts +78 -0
  21. package/src/convert-async-iterator-to-readable-stream.ts +47 -0
  22. package/src/convert-image-model-file-to-data-uri.test.ts +85 -0
  23. package/src/convert-image-model-file-to-data-uri.ts +19 -0
  24. package/src/convert-to-form-data.test.ts +167 -0
  25. package/src/convert-to-form-data.ts +61 -0
  26. package/src/create-tool-name-mapping.test.ts +163 -0
  27. package/src/create-tool-name-mapping.ts +66 -0
  28. package/src/delay.test.ts +212 -0
  29. package/src/delay.ts +47 -0
  30. package/src/delayed-promise.test.ts +132 -0
  31. package/src/delayed-promise.ts +61 -0
  32. package/src/download-blob.test.ts +145 -0
  33. package/src/download-blob.ts +31 -0
  34. package/src/download-error.ts +39 -0
  35. package/src/extract-response-headers.ts +9 -0
  36. package/src/fetch-function.ts +4 -0
  37. package/src/generate-id.test.ts +31 -0
  38. package/src/generate-id.ts +57 -0
  39. package/src/get-error-message.ts +15 -0
  40. package/src/get-from-api.test.ts +199 -0
  41. package/src/get-from-api.ts +97 -0
  42. package/src/get-runtime-environment-user-agent.test.ts +47 -0
  43. package/src/get-runtime-environment-user-agent.ts +24 -0
  44. package/src/handle-fetch-error.ts +39 -0
  45. package/src/index.ts +67 -0
  46. package/src/inject-json-instruction.test.ts +404 -0
  47. package/src/inject-json-instruction.ts +63 -0
  48. package/src/is-abort-error.ts +8 -0
  49. package/src/is-async-iterable.ts +3 -0
  50. package/src/is-non-nullable.ts +12 -0
  51. package/src/is-url-supported.test.ts +282 -0
  52. package/src/is-url-supported.ts +40 -0
  53. package/src/load-api-key.ts +45 -0
  54. package/src/load-optional-setting.ts +30 -0
  55. package/src/load-setting.ts +62 -0
  56. package/src/maybe-promise-like.ts +3 -0
  57. package/src/media-type-to-extension.test.ts +26 -0
  58. package/src/media-type-to-extension.ts +22 -0
  59. package/src/normalize-headers.test.ts +64 -0
  60. package/src/normalize-headers.ts +38 -0
  61. package/src/parse-json-event-stream.ts +33 -0
  62. package/src/parse-json.test.ts +191 -0
  63. package/src/parse-json.ts +122 -0
  64. package/src/parse-provider-options.ts +32 -0
  65. package/src/post-to-api.ts +166 -0
  66. package/src/provider-tool-factory.ts +125 -0
  67. package/src/remove-undefined-entries.test.ts +57 -0
  68. package/src/remove-undefined-entries.ts +12 -0
  69. package/src/resolve.test.ts +125 -0
  70. package/src/resolve.ts +17 -0
  71. package/src/response-handler.test.ts +89 -0
  72. package/src/response-handler.ts +187 -0
  73. package/src/schema.test-d.ts +11 -0
  74. package/src/schema.test.ts +502 -0
  75. package/src/schema.ts +267 -0
  76. package/src/secure-json-parse.test.ts +59 -0
  77. package/src/secure-json-parse.ts +92 -0
  78. package/src/test/convert-array-to-async-iterable.ts +9 -0
  79. package/src/test/convert-array-to-readable-stream.ts +15 -0
  80. package/src/test/convert-async-iterable-to-array.ts +9 -0
  81. package/src/test/convert-readable-stream-to-array.ts +14 -0
  82. package/src/test/convert-response-stream-to-array.ts +9 -0
  83. package/src/test/index.ts +7 -0
  84. package/src/test/is-node-version.ts +4 -0
  85. package/src/test/mock-id.ts +8 -0
  86. package/src/to-json-schema/zod3-to-json-schema/LICENSE +16 -0
  87. package/src/to-json-schema/zod3-to-json-schema/README.md +24 -0
  88. package/src/to-json-schema/zod3-to-json-schema/get-relative-path.ts +7 -0
  89. package/src/to-json-schema/zod3-to-json-schema/index.ts +1 -0
  90. package/src/to-json-schema/zod3-to-json-schema/options.ts +98 -0
  91. package/src/to-json-schema/zod3-to-json-schema/parse-def.test.ts +224 -0
  92. package/src/to-json-schema/zod3-to-json-schema/parse-def.ts +109 -0
  93. package/src/to-json-schema/zod3-to-json-schema/parse-types.ts +57 -0
  94. package/src/to-json-schema/zod3-to-json-schema/parsers/any.ts +5 -0
  95. package/src/to-json-schema/zod3-to-json-schema/parsers/array.test.ts +98 -0
  96. package/src/to-json-schema/zod3-to-json-schema/parsers/array.ts +38 -0
  97. package/src/to-json-schema/zod3-to-json-schema/parsers/bigint.test.ts +51 -0
  98. package/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts +44 -0
  99. package/src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts +7 -0
  100. package/src/to-json-schema/zod3-to-json-schema/parsers/branded.test.ts +16 -0
  101. package/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts +7 -0
  102. package/src/to-json-schema/zod3-to-json-schema/parsers/catch.test.ts +15 -0
  103. package/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts +7 -0
  104. package/src/to-json-schema/zod3-to-json-schema/parsers/date.test.ts +97 -0
  105. package/src/to-json-schema/zod3-to-json-schema/parsers/date.ts +64 -0
  106. package/src/to-json-schema/zod3-to-json-schema/parsers/default.test.ts +54 -0
  107. package/src/to-json-schema/zod3-to-json-schema/parsers/default.ts +14 -0
  108. package/src/to-json-schema/zod3-to-json-schema/parsers/effects.test.ts +41 -0
  109. package/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts +14 -0
  110. package/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts +13 -0
  111. package/src/to-json-schema/zod3-to-json-schema/parsers/intersection.test.ts +92 -0
  112. package/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts +52 -0
  113. package/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts +29 -0
  114. package/src/to-json-schema/zod3-to-json-schema/parsers/map.test.ts +48 -0
  115. package/src/to-json-schema/zod3-to-json-schema/parsers/map.ts +47 -0
  116. package/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.test.ts +102 -0
  117. package/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts +31 -0
  118. package/src/to-json-schema/zod3-to-json-schema/parsers/never.ts +9 -0
  119. package/src/to-json-schema/zod3-to-json-schema/parsers/null.ts +9 -0
  120. package/src/to-json-schema/zod3-to-json-schema/parsers/nullable.test.ts +67 -0
  121. package/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts +42 -0
  122. package/src/to-json-schema/zod3-to-json-schema/parsers/number.test.ts +65 -0
  123. package/src/to-json-schema/zod3-to-json-schema/parsers/number.ts +44 -0
  124. package/src/to-json-schema/zod3-to-json-schema/parsers/object.test.ts +149 -0
  125. package/src/to-json-schema/zod3-to-json-schema/parsers/object.ts +88 -0
  126. package/src/to-json-schema/zod3-to-json-schema/parsers/optional.test.ts +147 -0
  127. package/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts +23 -0
  128. package/src/to-json-schema/zod3-to-json-schema/parsers/pipe.test.ts +35 -0
  129. package/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts +29 -0
  130. package/src/to-json-schema/zod3-to-json-schema/parsers/promise.test.ts +15 -0
  131. package/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts +11 -0
  132. package/src/to-json-schema/zod3-to-json-schema/parsers/readonly.test.ts +20 -0
  133. package/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts +7 -0
  134. package/src/to-json-schema/zod3-to-json-schema/parsers/record.test.ts +108 -0
  135. package/src/to-json-schema/zod3-to-json-schema/parsers/record.ts +71 -0
  136. package/src/to-json-schema/zod3-to-json-schema/parsers/set.test.ts +20 -0
  137. package/src/to-json-schema/zod3-to-json-schema/parsers/set.ts +35 -0
  138. package/src/to-json-schema/zod3-to-json-schema/parsers/string.test.ts +438 -0
  139. package/src/to-json-schema/zod3-to-json-schema/parsers/string.ts +426 -0
  140. package/src/to-json-schema/zod3-to-json-schema/parsers/tuple.test.ts +33 -0
  141. package/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts +61 -0
  142. package/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts +11 -0
  143. package/src/to-json-schema/zod3-to-json-schema/parsers/union.test.ts +226 -0
  144. package/src/to-json-schema/zod3-to-json-schema/parsers/union.ts +144 -0
  145. package/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts +7 -0
  146. package/src/to-json-schema/zod3-to-json-schema/refs.test.ts +919 -0
  147. package/src/to-json-schema/zod3-to-json-schema/refs.ts +39 -0
  148. package/src/to-json-schema/zod3-to-json-schema/select-parser.ts +115 -0
  149. package/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.test.ts +862 -0
  150. package/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts +93 -0
  151. package/src/types/assistant-model-message.ts +39 -0
  152. package/src/types/content-part.ts +379 -0
  153. package/src/types/data-content.ts +4 -0
  154. package/src/types/execute-tool.ts +27 -0
  155. package/src/types/index.ts +40 -0
  156. package/src/types/model-message.ts +14 -0
  157. package/src/types/provider-options.ts +9 -0
  158. package/src/types/system-model-message.ts +20 -0
  159. package/src/types/tool-approval-request.ts +16 -0
  160. package/src/types/tool-approval-response.ts +27 -0
  161. package/src/types/tool-call.ts +31 -0
  162. package/src/types/tool-model-message.ts +23 -0
  163. package/src/types/tool-result.ts +35 -0
  164. package/src/types/tool.test-d.ts +193 -0
  165. package/src/types/tool.ts +324 -0
  166. package/src/types/user-model-message.ts +22 -0
  167. package/src/uint8-utils.ts +26 -0
  168. package/src/validate-types.test.ts +105 -0
  169. package/src/validate-types.ts +81 -0
  170. package/src/version.ts +6 -0
  171. package/src/with-user-agent-suffix.test.ts +84 -0
  172. package/src/with-user-agent-suffix.ts +27 -0
  173. package/src/without-trailing-slash.ts +3 -0
  174. package/test.d.ts +1 -0
package/dist/index.js ADDED
@@ -0,0 +1,2637 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name2 in all)
10
+ __defProp(target, name2, { get: all[name2], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ DelayedPromise: () => DelayedPromise,
35
+ DownloadError: () => DownloadError,
36
+ EventSourceParserStream: () => import_stream2.EventSourceParserStream,
37
+ VERSION: () => VERSION,
38
+ asSchema: () => asSchema,
39
+ combineHeaders: () => combineHeaders,
40
+ convertAsyncIteratorToReadableStream: () => convertAsyncIteratorToReadableStream,
41
+ convertBase64ToUint8Array: () => convertBase64ToUint8Array,
42
+ convertImageModelFileToDataUri: () => convertImageModelFileToDataUri,
43
+ convertToBase64: () => convertToBase64,
44
+ convertToFormData: () => convertToFormData,
45
+ convertUint8ArrayToBase64: () => convertUint8ArrayToBase64,
46
+ createBinaryResponseHandler: () => createBinaryResponseHandler,
47
+ createEventSourceResponseHandler: () => createEventSourceResponseHandler,
48
+ createIdGenerator: () => createIdGenerator,
49
+ createJsonErrorResponseHandler: () => createJsonErrorResponseHandler,
50
+ createJsonResponseHandler: () => createJsonResponseHandler,
51
+ createProviderToolFactory: () => createProviderToolFactory,
52
+ createProviderToolFactoryWithOutputSchema: () => createProviderToolFactoryWithOutputSchema,
53
+ createStatusCodeErrorResponseHandler: () => createStatusCodeErrorResponseHandler,
54
+ createToolNameMapping: () => createToolNameMapping,
55
+ delay: () => delay,
56
+ downloadBlob: () => downloadBlob,
57
+ dynamicTool: () => dynamicTool,
58
+ executeTool: () => executeTool,
59
+ extractResponseHeaders: () => extractResponseHeaders,
60
+ generateId: () => generateId,
61
+ getErrorMessage: () => getErrorMessage,
62
+ getFromApi: () => getFromApi,
63
+ getRuntimeEnvironmentUserAgent: () => getRuntimeEnvironmentUserAgent,
64
+ injectJsonInstructionIntoMessages: () => injectJsonInstructionIntoMessages,
65
+ isAbortError: () => isAbortError,
66
+ isNonNullable: () => isNonNullable,
67
+ isParsableJson: () => isParsableJson,
68
+ isUrlSupported: () => isUrlSupported,
69
+ jsonSchema: () => jsonSchema,
70
+ lazySchema: () => lazySchema,
71
+ loadApiKey: () => loadApiKey,
72
+ loadOptionalSetting: () => loadOptionalSetting,
73
+ loadSetting: () => loadSetting,
74
+ mediaTypeToExtension: () => mediaTypeToExtension,
75
+ normalizeHeaders: () => normalizeHeaders,
76
+ parseJSON: () => parseJSON,
77
+ parseJsonEventStream: () => parseJsonEventStream,
78
+ parseProviderOptions: () => parseProviderOptions,
79
+ postFormDataToApi: () => postFormDataToApi,
80
+ postJsonToApi: () => postJsonToApi,
81
+ postToApi: () => postToApi,
82
+ removeUndefinedEntries: () => removeUndefinedEntries,
83
+ resolve: () => resolve,
84
+ safeParseJSON: () => safeParseJSON,
85
+ safeValidateTypes: () => safeValidateTypes,
86
+ tool: () => tool,
87
+ validateTypes: () => validateTypes,
88
+ withUserAgentSuffix: () => withUserAgentSuffix,
89
+ withoutTrailingSlash: () => withoutTrailingSlash,
90
+ zodSchema: () => zodSchema
91
+ });
92
+ module.exports = __toCommonJS(src_exports);
93
+
94
+ // src/combine-headers.ts
95
+ function combineHeaders(...headers) {
96
+ return headers.reduce(
97
+ (combinedHeaders, currentHeaders) => ({
98
+ ...combinedHeaders,
99
+ ...currentHeaders != null ? currentHeaders : {}
100
+ }),
101
+ {}
102
+ );
103
+ }
104
+
105
+ // src/convert-async-iterator-to-readable-stream.ts
106
+ function convertAsyncIteratorToReadableStream(iterator) {
107
+ let cancelled = false;
108
+ return new ReadableStream({
109
+ /**
110
+ * Called when the consumer wants to pull more data from the stream.
111
+ *
112
+ * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
113
+ * @returns {Promise<void>}
114
+ */
115
+ async pull(controller) {
116
+ if (cancelled) return;
117
+ try {
118
+ const { value, done } = await iterator.next();
119
+ if (done) {
120
+ controller.close();
121
+ } else {
122
+ controller.enqueue(value);
123
+ }
124
+ } catch (error) {
125
+ controller.error(error);
126
+ }
127
+ },
128
+ /**
129
+ * Called when the consumer cancels the stream.
130
+ */
131
+ async cancel(reason) {
132
+ cancelled = true;
133
+ if (iterator.return) {
134
+ try {
135
+ await iterator.return(reason);
136
+ } catch (e) {
137
+ }
138
+ }
139
+ }
140
+ });
141
+ }
142
+
143
+ // src/create-tool-name-mapping.ts
144
+ function createToolNameMapping({
145
+ tools = [],
146
+ providerToolNames
147
+ }) {
148
+ const customToolNameToProviderToolName = {};
149
+ const providerToolNameToCustomToolName = {};
150
+ for (const tool2 of tools) {
151
+ if (tool2.type === "provider" && tool2.id in providerToolNames) {
152
+ const providerToolName = providerToolNames[tool2.id];
153
+ customToolNameToProviderToolName[tool2.name] = providerToolName;
154
+ providerToolNameToCustomToolName[providerToolName] = tool2.name;
155
+ }
156
+ }
157
+ return {
158
+ toProviderToolName: (customToolName) => {
159
+ var _a2;
160
+ return (_a2 = customToolNameToProviderToolName[customToolName]) != null ? _a2 : customToolName;
161
+ },
162
+ toCustomToolName: (providerToolName) => {
163
+ var _a2;
164
+ return (_a2 = providerToolNameToCustomToolName[providerToolName]) != null ? _a2 : providerToolName;
165
+ }
166
+ };
167
+ }
168
+
169
+ // src/delay.ts
170
+ async function delay(delayInMs, options) {
171
+ if (delayInMs == null) {
172
+ return Promise.resolve();
173
+ }
174
+ const signal = options == null ? void 0 : options.abortSignal;
175
+ return new Promise((resolve2, reject) => {
176
+ if (signal == null ? void 0 : signal.aborted) {
177
+ reject(createAbortError());
178
+ return;
179
+ }
180
+ const timeoutId = setTimeout(() => {
181
+ cleanup();
182
+ resolve2();
183
+ }, delayInMs);
184
+ const cleanup = () => {
185
+ clearTimeout(timeoutId);
186
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
187
+ };
188
+ const onAbort = () => {
189
+ cleanup();
190
+ reject(createAbortError());
191
+ };
192
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort);
193
+ });
194
+ }
195
+ function createAbortError() {
196
+ return new DOMException("Delay was aborted", "AbortError");
197
+ }
198
+
199
+ // src/delayed-promise.ts
200
+ var DelayedPromise = class {
201
+ constructor() {
202
+ this.status = { type: "pending" };
203
+ this._resolve = void 0;
204
+ this._reject = void 0;
205
+ }
206
+ get promise() {
207
+ if (this._promise) {
208
+ return this._promise;
209
+ }
210
+ this._promise = new Promise((resolve2, reject) => {
211
+ if (this.status.type === "resolved") {
212
+ resolve2(this.status.value);
213
+ } else if (this.status.type === "rejected") {
214
+ reject(this.status.error);
215
+ }
216
+ this._resolve = resolve2;
217
+ this._reject = reject;
218
+ });
219
+ return this._promise;
220
+ }
221
+ resolve(value) {
222
+ var _a2;
223
+ this.status = { type: "resolved", value };
224
+ if (this._promise) {
225
+ (_a2 = this._resolve) == null ? void 0 : _a2.call(this, value);
226
+ }
227
+ }
228
+ reject(error) {
229
+ var _a2;
230
+ this.status = { type: "rejected", error };
231
+ if (this._promise) {
232
+ (_a2 = this._reject) == null ? void 0 : _a2.call(this, error);
233
+ }
234
+ }
235
+ isResolved() {
236
+ return this.status.type === "resolved";
237
+ }
238
+ isRejected() {
239
+ return this.status.type === "rejected";
240
+ }
241
+ isPending() {
242
+ return this.status.type === "pending";
243
+ }
244
+ };
245
+
246
+ // src/extract-response-headers.ts
247
+ function extractResponseHeaders(response) {
248
+ return Object.fromEntries([...response.headers]);
249
+ }
250
+
251
+ // src/uint8-utils.ts
252
+ var { btoa, atob } = globalThis;
253
+ function convertBase64ToUint8Array(base64String) {
254
+ const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
255
+ const latin1string = atob(base64Url);
256
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
257
+ }
258
+ function convertUint8ArrayToBase64(array) {
259
+ let latin1string = "";
260
+ for (let i = 0; i < array.length; i++) {
261
+ latin1string += String.fromCodePoint(array[i]);
262
+ }
263
+ return btoa(latin1string);
264
+ }
265
+ function convertToBase64(value) {
266
+ return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
267
+ }
268
+
269
+ // src/convert-image-model-file-to-data-uri.ts
270
+ function convertImageModelFileToDataUri(file) {
271
+ if (file.type === "url") return file.url;
272
+ return `data:${file.mediaType};base64,${typeof file.data === "string" ? file.data : convertUint8ArrayToBase64(file.data)}`;
273
+ }
274
+
275
+ // src/convert-to-form-data.ts
276
+ function convertToFormData(input, options = {}) {
277
+ const { useArrayBrackets = true } = options;
278
+ const formData = new FormData();
279
+ for (const [key, value] of Object.entries(input)) {
280
+ if (value == null) {
281
+ continue;
282
+ }
283
+ if (Array.isArray(value)) {
284
+ if (value.length === 1) {
285
+ formData.append(key, value[0]);
286
+ continue;
287
+ }
288
+ const arrayKey = useArrayBrackets ? `${key}[]` : key;
289
+ for (const item of value) {
290
+ formData.append(arrayKey, item);
291
+ }
292
+ continue;
293
+ }
294
+ formData.append(key, value);
295
+ }
296
+ return formData;
297
+ }
298
+
299
+ // src/download-error.ts
300
+ var import_provider = require("@ai-sdk/provider");
301
+ var name = "AI_DownloadError";
302
+ var marker = `vercel.ai.error.${name}`;
303
+ var symbol = Symbol.for(marker);
304
+ var _a, _b;
305
+ var DownloadError = class extends (_b = import_provider.AISDKError, _a = symbol, _b) {
306
+ constructor({
307
+ url,
308
+ statusCode,
309
+ statusText,
310
+ cause,
311
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
312
+ }) {
313
+ super({ name, message, cause });
314
+ this[_a] = true;
315
+ this.url = url;
316
+ this.statusCode = statusCode;
317
+ this.statusText = statusText;
318
+ }
319
+ static isInstance(error) {
320
+ return import_provider.AISDKError.hasMarker(error, marker);
321
+ }
322
+ };
323
+
324
+ // src/download-blob.ts
325
+ async function downloadBlob(url) {
326
+ try {
327
+ const response = await fetch(url);
328
+ if (!response.ok) {
329
+ throw new DownloadError({
330
+ url,
331
+ statusCode: response.status,
332
+ statusText: response.statusText
333
+ });
334
+ }
335
+ return await response.blob();
336
+ } catch (error) {
337
+ if (DownloadError.isInstance(error)) {
338
+ throw error;
339
+ }
340
+ throw new DownloadError({ url, cause: error });
341
+ }
342
+ }
343
+
344
+ // src/generate-id.ts
345
+ var import_provider2 = require("@ai-sdk/provider");
346
+ var createIdGenerator = ({
347
+ prefix,
348
+ size = 16,
349
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
350
+ separator = "-"
351
+ } = {}) => {
352
+ const generator = () => {
353
+ const alphabetLength = alphabet.length;
354
+ const chars = new Array(size);
355
+ for (let i = 0; i < size; i++) {
356
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
357
+ }
358
+ return chars.join("");
359
+ };
360
+ if (prefix == null) {
361
+ return generator;
362
+ }
363
+ if (alphabet.includes(separator)) {
364
+ throw new import_provider2.InvalidArgumentError({
365
+ argument: "separator",
366
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
367
+ });
368
+ }
369
+ return () => `${prefix}${separator}${generator()}`;
370
+ };
371
+ var generateId = createIdGenerator();
372
+
373
+ // src/get-error-message.ts
374
+ function getErrorMessage(error) {
375
+ if (error == null) {
376
+ return "unknown error";
377
+ }
378
+ if (typeof error === "string") {
379
+ return error;
380
+ }
381
+ if (error instanceof Error) {
382
+ return error.message;
383
+ }
384
+ return JSON.stringify(error);
385
+ }
386
+
387
+ // src/get-from-api.ts
388
+ var import_provider4 = require("@ai-sdk/provider");
389
+
390
+ // src/handle-fetch-error.ts
391
+ var import_provider3 = require("@ai-sdk/provider");
392
+
393
+ // src/is-abort-error.ts
394
+ function isAbortError(error) {
395
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
396
+ error.name === "TimeoutError");
397
+ }
398
+
399
+ // src/handle-fetch-error.ts
400
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
401
+ function handleFetchError({
402
+ error,
403
+ url,
404
+ requestBodyValues
405
+ }) {
406
+ if (isAbortError(error)) {
407
+ return error;
408
+ }
409
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
410
+ const cause = error.cause;
411
+ if (cause != null) {
412
+ return new import_provider3.APICallError({
413
+ message: `Cannot connect to API: ${cause.message}`,
414
+ cause,
415
+ url,
416
+ requestBodyValues,
417
+ isRetryable: true
418
+ // retry when network error
419
+ });
420
+ }
421
+ }
422
+ return error;
423
+ }
424
+
425
+ // src/get-runtime-environment-user-agent.ts
426
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
427
+ var _a2, _b2, _c;
428
+ if (globalThisAny.window) {
429
+ return `runtime/browser`;
430
+ }
431
+ if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) {
432
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
433
+ }
434
+ if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) {
435
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
436
+ }
437
+ if (globalThisAny.EdgeRuntime) {
438
+ return `runtime/vercel-edge`;
439
+ }
440
+ return "runtime/unknown";
441
+ }
442
+
443
+ // src/normalize-headers.ts
444
+ function normalizeHeaders(headers) {
445
+ if (headers == null) {
446
+ return {};
447
+ }
448
+ const normalized = {};
449
+ if (headers instanceof Headers) {
450
+ headers.forEach((value, key) => {
451
+ normalized[key.toLowerCase()] = value;
452
+ });
453
+ } else {
454
+ if (!Array.isArray(headers)) {
455
+ headers = Object.entries(headers);
456
+ }
457
+ for (const [key, value] of headers) {
458
+ if (value != null) {
459
+ normalized[key.toLowerCase()] = value;
460
+ }
461
+ }
462
+ }
463
+ return normalized;
464
+ }
465
+
466
+ // src/with-user-agent-suffix.ts
467
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
468
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
469
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
470
+ normalizedHeaders.set(
471
+ "user-agent",
472
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
473
+ );
474
+ return Object.fromEntries(normalizedHeaders.entries());
475
+ }
476
+
477
+ // src/version.ts
478
+ var VERSION = true ? "0.0.0-64aae7dd-20260114144918" : "0.0.0-test";
479
+
480
+ // src/get-from-api.ts
481
+ var getOriginalFetch = () => globalThis.fetch;
482
+ var getFromApi = async ({
483
+ url,
484
+ headers = {},
485
+ successfulResponseHandler,
486
+ failedResponseHandler,
487
+ abortSignal,
488
+ fetch: fetch2 = getOriginalFetch()
489
+ }) => {
490
+ try {
491
+ const response = await fetch2(url, {
492
+ method: "GET",
493
+ headers: withUserAgentSuffix(
494
+ headers,
495
+ `ai-sdk/provider-utils/${VERSION}`,
496
+ getRuntimeEnvironmentUserAgent()
497
+ ),
498
+ signal: abortSignal
499
+ });
500
+ const responseHeaders = extractResponseHeaders(response);
501
+ if (!response.ok) {
502
+ let errorInformation;
503
+ try {
504
+ errorInformation = await failedResponseHandler({
505
+ response,
506
+ url,
507
+ requestBodyValues: {}
508
+ });
509
+ } catch (error) {
510
+ if (isAbortError(error) || import_provider4.APICallError.isInstance(error)) {
511
+ throw error;
512
+ }
513
+ throw new import_provider4.APICallError({
514
+ message: "Failed to process error response",
515
+ cause: error,
516
+ statusCode: response.status,
517
+ url,
518
+ responseHeaders,
519
+ requestBodyValues: {}
520
+ });
521
+ }
522
+ throw errorInformation.value;
523
+ }
524
+ try {
525
+ return await successfulResponseHandler({
526
+ response,
527
+ url,
528
+ requestBodyValues: {}
529
+ });
530
+ } catch (error) {
531
+ if (error instanceof Error) {
532
+ if (isAbortError(error) || import_provider4.APICallError.isInstance(error)) {
533
+ throw error;
534
+ }
535
+ }
536
+ throw new import_provider4.APICallError({
537
+ message: "Failed to process successful response",
538
+ cause: error,
539
+ statusCode: response.status,
540
+ url,
541
+ responseHeaders,
542
+ requestBodyValues: {}
543
+ });
544
+ }
545
+ } catch (error) {
546
+ throw handleFetchError({ error, url, requestBodyValues: {} });
547
+ }
548
+ };
549
+
550
+ // src/inject-json-instruction.ts
551
+ var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
552
+ var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
553
+ var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
554
+ function injectJsonInstruction({
555
+ prompt,
556
+ schema,
557
+ schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,
558
+ schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
559
+ }) {
560
+ return [
561
+ prompt != null && prompt.length > 0 ? prompt : void 0,
562
+ prompt != null && prompt.length > 0 ? "" : void 0,
563
+ // add a newline if prompt is not null
564
+ schemaPrefix,
565
+ schema != null ? JSON.stringify(schema) : void 0,
566
+ schemaSuffix
567
+ ].filter((line) => line != null).join("\n");
568
+ }
569
+ function injectJsonInstructionIntoMessages({
570
+ messages,
571
+ schema,
572
+ schemaPrefix,
573
+ schemaSuffix
574
+ }) {
575
+ var _a2, _b2;
576
+ const systemMessage = ((_a2 = messages[0]) == null ? void 0 : _a2.role) === "system" ? { ...messages[0] } : { role: "system", content: "" };
577
+ systemMessage.content = injectJsonInstruction({
578
+ prompt: systemMessage.content,
579
+ schema,
580
+ schemaPrefix,
581
+ schemaSuffix
582
+ });
583
+ return [
584
+ systemMessage,
585
+ ...((_b2 = messages[0]) == null ? void 0 : _b2.role) === "system" ? messages.slice(1) : messages
586
+ ];
587
+ }
588
+
589
+ // src/is-non-nullable.ts
590
+ function isNonNullable(value) {
591
+ return value != null;
592
+ }
593
+
594
+ // src/is-url-supported.ts
595
+ function isUrlSupported({
596
+ mediaType,
597
+ url,
598
+ supportedUrls
599
+ }) {
600
+ url = url.toLowerCase();
601
+ mediaType = mediaType.toLowerCase();
602
+ return Object.entries(supportedUrls).map(([key, value]) => {
603
+ const mediaType2 = key.toLowerCase();
604
+ return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value };
605
+ }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
606
+ }
607
+
608
+ // src/load-api-key.ts
609
+ var import_provider5 = require("@ai-sdk/provider");
610
+ function loadApiKey({
611
+ apiKey,
612
+ environmentVariableName,
613
+ apiKeyParameterName = "apiKey",
614
+ description
615
+ }) {
616
+ if (typeof apiKey === "string") {
617
+ return apiKey;
618
+ }
619
+ if (apiKey != null) {
620
+ throw new import_provider5.LoadAPIKeyError({
621
+ message: `${description} API key must be a string.`
622
+ });
623
+ }
624
+ if (typeof process === "undefined") {
625
+ throw new import_provider5.LoadAPIKeyError({
626
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
627
+ });
628
+ }
629
+ apiKey = process.env[environmentVariableName];
630
+ if (apiKey == null) {
631
+ throw new import_provider5.LoadAPIKeyError({
632
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
633
+ });
634
+ }
635
+ if (typeof apiKey !== "string") {
636
+ throw new import_provider5.LoadAPIKeyError({
637
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
638
+ });
639
+ }
640
+ return apiKey;
641
+ }
642
+
643
+ // src/load-optional-setting.ts
644
+ function loadOptionalSetting({
645
+ settingValue,
646
+ environmentVariableName
647
+ }) {
648
+ if (typeof settingValue === "string") {
649
+ return settingValue;
650
+ }
651
+ if (settingValue != null || typeof process === "undefined") {
652
+ return void 0;
653
+ }
654
+ settingValue = process.env[environmentVariableName];
655
+ if (settingValue == null || typeof settingValue !== "string") {
656
+ return void 0;
657
+ }
658
+ return settingValue;
659
+ }
660
+
661
+ // src/load-setting.ts
662
+ var import_provider6 = require("@ai-sdk/provider");
663
+ function loadSetting({
664
+ settingValue,
665
+ environmentVariableName,
666
+ settingName,
667
+ description
668
+ }) {
669
+ if (typeof settingValue === "string") {
670
+ return settingValue;
671
+ }
672
+ if (settingValue != null) {
673
+ throw new import_provider6.LoadSettingError({
674
+ message: `${description} setting must be a string.`
675
+ });
676
+ }
677
+ if (typeof process === "undefined") {
678
+ throw new import_provider6.LoadSettingError({
679
+ message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`
680
+ });
681
+ }
682
+ settingValue = process.env[environmentVariableName];
683
+ if (settingValue == null) {
684
+ throw new import_provider6.LoadSettingError({
685
+ message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`
686
+ });
687
+ }
688
+ if (typeof settingValue !== "string") {
689
+ throw new import_provider6.LoadSettingError({
690
+ message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
691
+ });
692
+ }
693
+ return settingValue;
694
+ }
695
+
696
+ // src/media-type-to-extension.ts
697
+ function mediaTypeToExtension(mediaType) {
698
+ var _a2;
699
+ const [_type, subtype = ""] = mediaType.toLowerCase().split("/");
700
+ return (_a2 = {
701
+ mpeg: "mp3",
702
+ "x-wav": "wav",
703
+ opus: "ogg",
704
+ mp4: "m4a",
705
+ "x-m4a": "m4a"
706
+ }[subtype]) != null ? _a2 : subtype;
707
+ }
708
+
709
+ // src/parse-json.ts
710
+ var import_provider9 = require("@ai-sdk/provider");
711
+
712
+ // src/secure-json-parse.ts
713
+ var suspectProtoRx = /"__proto__"\s*:/;
714
+ var suspectConstructorRx = /"constructor"\s*:/;
715
+ function _parse(text) {
716
+ const obj = JSON.parse(text);
717
+ if (obj === null || typeof obj !== "object") {
718
+ return obj;
719
+ }
720
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
721
+ return obj;
722
+ }
723
+ return filter(obj);
724
+ }
725
+ function filter(obj) {
726
+ let next = [obj];
727
+ while (next.length) {
728
+ const nodes = next;
729
+ next = [];
730
+ for (const node of nodes) {
731
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
732
+ throw new SyntaxError("Object contains forbidden prototype property");
733
+ }
734
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
735
+ throw new SyntaxError("Object contains forbidden prototype property");
736
+ }
737
+ for (const key in node) {
738
+ const value = node[key];
739
+ if (value && typeof value === "object") {
740
+ next.push(value);
741
+ }
742
+ }
743
+ }
744
+ }
745
+ return obj;
746
+ }
747
+ function secureJsonParse(text) {
748
+ const { stackTraceLimit } = Error;
749
+ try {
750
+ Error.stackTraceLimit = 0;
751
+ } catch (e) {
752
+ return _parse(text);
753
+ }
754
+ try {
755
+ return _parse(text);
756
+ } finally {
757
+ Error.stackTraceLimit = stackTraceLimit;
758
+ }
759
+ }
760
+
761
+ // src/validate-types.ts
762
+ var import_provider8 = require("@ai-sdk/provider");
763
+
764
+ // src/schema.ts
765
+ var import_provider7 = require("@ai-sdk/provider");
766
+ var z4 = __toESM(require("zod/v4"));
767
+
768
+ // src/add-additional-properties-to-json-schema.ts
769
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
770
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
771
+ jsonSchema2.additionalProperties = false;
772
+ const { properties } = jsonSchema2;
773
+ if (properties != null) {
774
+ for (const key of Object.keys(properties)) {
775
+ properties[key] = visit(properties[key]);
776
+ }
777
+ }
778
+ }
779
+ if (jsonSchema2.items != null) {
780
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
781
+ }
782
+ if (jsonSchema2.anyOf != null) {
783
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
784
+ }
785
+ if (jsonSchema2.allOf != null) {
786
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
787
+ }
788
+ if (jsonSchema2.oneOf != null) {
789
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
790
+ }
791
+ const { definitions } = jsonSchema2;
792
+ if (definitions != null) {
793
+ for (const key of Object.keys(definitions)) {
794
+ definitions[key] = visit(definitions[key]);
795
+ }
796
+ }
797
+ return jsonSchema2;
798
+ }
799
+ function visit(def) {
800
+ if (typeof def === "boolean") return def;
801
+ return addAdditionalPropertiesToJsonSchema(def);
802
+ }
803
+
804
+ // src/to-json-schema/zod3-to-json-schema/options.ts
805
+ var ignoreOverride = Symbol(
806
+ "Let zodToJsonSchema decide on which parser to use"
807
+ );
808
+ var defaultOptions = {
809
+ name: void 0,
810
+ $refStrategy: "root",
811
+ basePath: ["#"],
812
+ effectStrategy: "input",
813
+ pipeStrategy: "all",
814
+ dateStrategy: "format:date-time",
815
+ mapStrategy: "entries",
816
+ removeAdditionalStrategy: "passthrough",
817
+ allowedAdditionalProperties: true,
818
+ rejectedAdditionalProperties: false,
819
+ definitionPath: "definitions",
820
+ strictUnions: false,
821
+ definitions: {},
822
+ errorMessages: false,
823
+ patternStrategy: "escape",
824
+ applyRegexFlags: false,
825
+ emailStrategy: "format:email",
826
+ base64Strategy: "contentEncoding:base64",
827
+ nameStrategy: "ref"
828
+ };
829
+ var getDefaultOptions = (options) => typeof options === "string" ? {
830
+ ...defaultOptions,
831
+ name: options
832
+ } : {
833
+ ...defaultOptions,
834
+ ...options
835
+ };
836
+
837
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
838
+ var import_v33 = require("zod/v3");
839
+
840
+ // src/to-json-schema/zod3-to-json-schema/parsers/any.ts
841
+ function parseAnyDef() {
842
+ return {};
843
+ }
844
+
845
+ // src/to-json-schema/zod3-to-json-schema/parsers/array.ts
846
+ var import_v3 = require("zod/v3");
847
+ function parseArrayDef(def, refs) {
848
+ var _a2, _b2, _c;
849
+ const res = {
850
+ type: "array"
851
+ };
852
+ if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== import_v3.ZodFirstPartyTypeKind.ZodAny) {
853
+ res.items = parseDef(def.type._def, {
854
+ ...refs,
855
+ currentPath: [...refs.currentPath, "items"]
856
+ });
857
+ }
858
+ if (def.minLength) {
859
+ res.minItems = def.minLength.value;
860
+ }
861
+ if (def.maxLength) {
862
+ res.maxItems = def.maxLength.value;
863
+ }
864
+ if (def.exactLength) {
865
+ res.minItems = def.exactLength.value;
866
+ res.maxItems = def.exactLength.value;
867
+ }
868
+ return res;
869
+ }
870
+
871
+ // src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts
872
+ function parseBigintDef(def) {
873
+ const res = {
874
+ type: "integer",
875
+ format: "int64"
876
+ };
877
+ if (!def.checks) return res;
878
+ for (const check of def.checks) {
879
+ switch (check.kind) {
880
+ case "min":
881
+ if (check.inclusive) {
882
+ res.minimum = check.value;
883
+ } else {
884
+ res.exclusiveMinimum = check.value;
885
+ }
886
+ break;
887
+ case "max":
888
+ if (check.inclusive) {
889
+ res.maximum = check.value;
890
+ } else {
891
+ res.exclusiveMaximum = check.value;
892
+ }
893
+ break;
894
+ case "multipleOf":
895
+ res.multipleOf = check.value;
896
+ break;
897
+ }
898
+ }
899
+ return res;
900
+ }
901
+
902
+ // src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts
903
+ function parseBooleanDef() {
904
+ return { type: "boolean" };
905
+ }
906
+
907
+ // src/to-json-schema/zod3-to-json-schema/parsers/branded.ts
908
+ function parseBrandedDef(_def, refs) {
909
+ return parseDef(_def.type._def, refs);
910
+ }
911
+
912
+ // src/to-json-schema/zod3-to-json-schema/parsers/catch.ts
913
+ var parseCatchDef = (def, refs) => {
914
+ return parseDef(def.innerType._def, refs);
915
+ };
916
+
917
+ // src/to-json-schema/zod3-to-json-schema/parsers/date.ts
918
+ function parseDateDef(def, refs, overrideDateStrategy) {
919
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
920
+ if (Array.isArray(strategy)) {
921
+ return {
922
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
923
+ };
924
+ }
925
+ switch (strategy) {
926
+ case "string":
927
+ case "format:date-time":
928
+ return {
929
+ type: "string",
930
+ format: "date-time"
931
+ };
932
+ case "format:date":
933
+ return {
934
+ type: "string",
935
+ format: "date"
936
+ };
937
+ case "integer":
938
+ return integerDateParser(def);
939
+ }
940
+ }
941
+ var integerDateParser = (def) => {
942
+ const res = {
943
+ type: "integer",
944
+ format: "unix-time"
945
+ };
946
+ for (const check of def.checks) {
947
+ switch (check.kind) {
948
+ case "min":
949
+ res.minimum = check.value;
950
+ break;
951
+ case "max":
952
+ res.maximum = check.value;
953
+ break;
954
+ }
955
+ }
956
+ return res;
957
+ };
958
+
959
+ // src/to-json-schema/zod3-to-json-schema/parsers/default.ts
960
+ function parseDefaultDef(_def, refs) {
961
+ return {
962
+ ...parseDef(_def.innerType._def, refs),
963
+ default: _def.defaultValue()
964
+ };
965
+ }
966
+
967
+ // src/to-json-schema/zod3-to-json-schema/parsers/effects.ts
968
+ function parseEffectsDef(_def, refs) {
969
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
970
+ }
971
+
972
+ // src/to-json-schema/zod3-to-json-schema/parsers/enum.ts
973
+ function parseEnumDef(def) {
974
+ return {
975
+ type: "string",
976
+ enum: Array.from(def.values)
977
+ };
978
+ }
979
+
980
+ // src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts
981
+ var isJsonSchema7AllOfType = (type) => {
982
+ if ("type" in type && type.type === "string") return false;
983
+ return "allOf" in type;
984
+ };
985
+ function parseIntersectionDef(def, refs) {
986
+ const allOf = [
987
+ parseDef(def.left._def, {
988
+ ...refs,
989
+ currentPath: [...refs.currentPath, "allOf", "0"]
990
+ }),
991
+ parseDef(def.right._def, {
992
+ ...refs,
993
+ currentPath: [...refs.currentPath, "allOf", "1"]
994
+ })
995
+ ].filter((x) => !!x);
996
+ const mergedAllOf = [];
997
+ allOf.forEach((schema) => {
998
+ if (isJsonSchema7AllOfType(schema)) {
999
+ mergedAllOf.push(...schema.allOf);
1000
+ } else {
1001
+ let nestedSchema = schema;
1002
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
1003
+ const { additionalProperties, ...rest } = schema;
1004
+ nestedSchema = rest;
1005
+ }
1006
+ mergedAllOf.push(nestedSchema);
1007
+ }
1008
+ });
1009
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
1010
+ }
1011
+
1012
+ // src/to-json-schema/zod3-to-json-schema/parsers/literal.ts
1013
+ function parseLiteralDef(def) {
1014
+ const parsedType = typeof def.value;
1015
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1016
+ return {
1017
+ type: Array.isArray(def.value) ? "array" : "object"
1018
+ };
1019
+ }
1020
+ return {
1021
+ type: parsedType === "bigint" ? "integer" : parsedType,
1022
+ const: def.value
1023
+ };
1024
+ }
1025
+
1026
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
1027
+ var import_v32 = require("zod/v3");
1028
+
1029
+ // src/to-json-schema/zod3-to-json-schema/parsers/string.ts
1030
+ var emojiRegex = void 0;
1031
+ var zodPatterns = {
1032
+ /**
1033
+ * `c` was changed to `[cC]` to replicate /i flag
1034
+ */
1035
+ cuid: /^[cC][^\s-]{8,}$/,
1036
+ cuid2: /^[0-9a-z]+$/,
1037
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1038
+ /**
1039
+ * `a-z` was added to replicate /i flag
1040
+ */
1041
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1042
+ /**
1043
+ * Constructed a valid Unicode RegExp
1044
+ *
1045
+ * Lazily instantiate since this type of regex isn't supported
1046
+ * in all envs (e.g. React Native).
1047
+ *
1048
+ * See:
1049
+ * https://github.com/colinhacks/zod/issues/2433
1050
+ * Fix in Zod:
1051
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1052
+ */
1053
+ emoji: () => {
1054
+ if (emojiRegex === void 0) {
1055
+ emojiRegex = RegExp(
1056
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
1057
+ "u"
1058
+ );
1059
+ }
1060
+ return emojiRegex;
1061
+ },
1062
+ /**
1063
+ * Unused
1064
+ */
1065
+ 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}$/,
1066
+ /**
1067
+ * Unused
1068
+ */
1069
+ 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])$/,
1070
+ 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])$/,
1071
+ /**
1072
+ * Unused
1073
+ */
1074
+ 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})))$/,
1075
+ 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])$/,
1076
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1077
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1078
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1079
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1080
+ };
1081
+ function parseStringDef(def, refs) {
1082
+ const res = {
1083
+ type: "string"
1084
+ };
1085
+ if (def.checks) {
1086
+ for (const check of def.checks) {
1087
+ switch (check.kind) {
1088
+ case "min":
1089
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1090
+ break;
1091
+ case "max":
1092
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1093
+ break;
1094
+ case "email":
1095
+ switch (refs.emailStrategy) {
1096
+ case "format:email":
1097
+ addFormat(res, "email", check.message, refs);
1098
+ break;
1099
+ case "format:idn-email":
1100
+ addFormat(res, "idn-email", check.message, refs);
1101
+ break;
1102
+ case "pattern:zod":
1103
+ addPattern(res, zodPatterns.email, check.message, refs);
1104
+ break;
1105
+ }
1106
+ break;
1107
+ case "url":
1108
+ addFormat(res, "uri", check.message, refs);
1109
+ break;
1110
+ case "uuid":
1111
+ addFormat(res, "uuid", check.message, refs);
1112
+ break;
1113
+ case "regex":
1114
+ addPattern(res, check.regex, check.message, refs);
1115
+ break;
1116
+ case "cuid":
1117
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1118
+ break;
1119
+ case "cuid2":
1120
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1121
+ break;
1122
+ case "startsWith":
1123
+ addPattern(
1124
+ res,
1125
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1126
+ check.message,
1127
+ refs
1128
+ );
1129
+ break;
1130
+ case "endsWith":
1131
+ addPattern(
1132
+ res,
1133
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1134
+ check.message,
1135
+ refs
1136
+ );
1137
+ break;
1138
+ case "datetime":
1139
+ addFormat(res, "date-time", check.message, refs);
1140
+ break;
1141
+ case "date":
1142
+ addFormat(res, "date", check.message, refs);
1143
+ break;
1144
+ case "time":
1145
+ addFormat(res, "time", check.message, refs);
1146
+ break;
1147
+ case "duration":
1148
+ addFormat(res, "duration", check.message, refs);
1149
+ break;
1150
+ case "length":
1151
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1152
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1153
+ break;
1154
+ case "includes": {
1155
+ addPattern(
1156
+ res,
1157
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1158
+ check.message,
1159
+ refs
1160
+ );
1161
+ break;
1162
+ }
1163
+ case "ip": {
1164
+ if (check.version !== "v6") {
1165
+ addFormat(res, "ipv4", check.message, refs);
1166
+ }
1167
+ if (check.version !== "v4") {
1168
+ addFormat(res, "ipv6", check.message, refs);
1169
+ }
1170
+ break;
1171
+ }
1172
+ case "base64url":
1173
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1174
+ break;
1175
+ case "jwt":
1176
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1177
+ break;
1178
+ case "cidr": {
1179
+ if (check.version !== "v6") {
1180
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1181
+ }
1182
+ if (check.version !== "v4") {
1183
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1184
+ }
1185
+ break;
1186
+ }
1187
+ case "emoji":
1188
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1189
+ break;
1190
+ case "ulid": {
1191
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1192
+ break;
1193
+ }
1194
+ case "base64": {
1195
+ switch (refs.base64Strategy) {
1196
+ case "format:binary": {
1197
+ addFormat(res, "binary", check.message, refs);
1198
+ break;
1199
+ }
1200
+ case "contentEncoding:base64": {
1201
+ res.contentEncoding = "base64";
1202
+ break;
1203
+ }
1204
+ case "pattern:zod": {
1205
+ addPattern(res, zodPatterns.base64, check.message, refs);
1206
+ break;
1207
+ }
1208
+ }
1209
+ break;
1210
+ }
1211
+ case "nanoid": {
1212
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1213
+ }
1214
+ case "toLowerCase":
1215
+ case "toUpperCase":
1216
+ case "trim":
1217
+ break;
1218
+ default:
1219
+ /* @__PURE__ */ ((_) => {
1220
+ })(check);
1221
+ }
1222
+ }
1223
+ }
1224
+ return res;
1225
+ }
1226
+ function escapeLiteralCheckValue(literal, refs) {
1227
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1228
+ }
1229
+ var ALPHA_NUMERIC = new Set(
1230
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1231
+ );
1232
+ function escapeNonAlphaNumeric(source) {
1233
+ let result = "";
1234
+ for (let i = 0; i < source.length; i++) {
1235
+ if (!ALPHA_NUMERIC.has(source[i])) {
1236
+ result += "\\";
1237
+ }
1238
+ result += source[i];
1239
+ }
1240
+ return result;
1241
+ }
1242
+ function addFormat(schema, value, message, refs) {
1243
+ var _a2;
1244
+ if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {
1245
+ if (!schema.anyOf) {
1246
+ schema.anyOf = [];
1247
+ }
1248
+ if (schema.format) {
1249
+ schema.anyOf.push({
1250
+ format: schema.format
1251
+ });
1252
+ delete schema.format;
1253
+ }
1254
+ schema.anyOf.push({
1255
+ format: value,
1256
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
1257
+ });
1258
+ } else {
1259
+ schema.format = value;
1260
+ }
1261
+ }
1262
+ function addPattern(schema, regex, message, refs) {
1263
+ var _a2;
1264
+ if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {
1265
+ if (!schema.allOf) {
1266
+ schema.allOf = [];
1267
+ }
1268
+ if (schema.pattern) {
1269
+ schema.allOf.push({
1270
+ pattern: schema.pattern
1271
+ });
1272
+ delete schema.pattern;
1273
+ }
1274
+ schema.allOf.push({
1275
+ pattern: stringifyRegExpWithFlags(regex, refs),
1276
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1277
+ });
1278
+ } else {
1279
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1280
+ }
1281
+ }
1282
+ function stringifyRegExpWithFlags(regex, refs) {
1283
+ var _a2;
1284
+ if (!refs.applyRegexFlags || !regex.flags) {
1285
+ return regex.source;
1286
+ }
1287
+ const flags = {
1288
+ i: regex.flags.includes("i"),
1289
+ // Case-insensitive
1290
+ m: regex.flags.includes("m"),
1291
+ // `^` and `$` matches adjacent to newline characters
1292
+ s: regex.flags.includes("s")
1293
+ // `.` matches newlines
1294
+ };
1295
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1296
+ let pattern = "";
1297
+ let isEscaped = false;
1298
+ let inCharGroup = false;
1299
+ let inCharRange = false;
1300
+ for (let i = 0; i < source.length; i++) {
1301
+ if (isEscaped) {
1302
+ pattern += source[i];
1303
+ isEscaped = false;
1304
+ continue;
1305
+ }
1306
+ if (flags.i) {
1307
+ if (inCharGroup) {
1308
+ if (source[i].match(/[a-z]/)) {
1309
+ if (inCharRange) {
1310
+ pattern += source[i];
1311
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1312
+ inCharRange = false;
1313
+ } else if (source[i + 1] === "-" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {
1314
+ pattern += source[i];
1315
+ inCharRange = true;
1316
+ } else {
1317
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1318
+ }
1319
+ continue;
1320
+ }
1321
+ } else if (source[i].match(/[a-z]/)) {
1322
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1323
+ continue;
1324
+ }
1325
+ }
1326
+ if (flags.m) {
1327
+ if (source[i] === "^") {
1328
+ pattern += `(^|(?<=[\r
1329
+ ]))`;
1330
+ continue;
1331
+ } else if (source[i] === "$") {
1332
+ pattern += `($|(?=[\r
1333
+ ]))`;
1334
+ continue;
1335
+ }
1336
+ }
1337
+ if (flags.s && source[i] === ".") {
1338
+ pattern += inCharGroup ? `${source[i]}\r
1339
+ ` : `[${source[i]}\r
1340
+ ]`;
1341
+ continue;
1342
+ }
1343
+ pattern += source[i];
1344
+ if (source[i] === "\\") {
1345
+ isEscaped = true;
1346
+ } else if (inCharGroup && source[i] === "]") {
1347
+ inCharGroup = false;
1348
+ } else if (!inCharGroup && source[i] === "[") {
1349
+ inCharGroup = true;
1350
+ }
1351
+ }
1352
+ try {
1353
+ new RegExp(pattern);
1354
+ } catch (e) {
1355
+ console.warn(
1356
+ `Could not convert regex pattern at ${refs.currentPath.join(
1357
+ "/"
1358
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1359
+ );
1360
+ return regex.source;
1361
+ }
1362
+ return pattern;
1363
+ }
1364
+
1365
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
1366
+ function parseRecordDef(def, refs) {
1367
+ var _a2, _b2, _c, _d, _e, _f;
1368
+ const schema = {
1369
+ type: "object",
1370
+ additionalProperties: (_a2 = parseDef(def.valueType._def, {
1371
+ ...refs,
1372
+ currentPath: [...refs.currentPath, "additionalProperties"]
1373
+ })) != null ? _a2 : refs.allowedAdditionalProperties
1374
+ };
1375
+ if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === import_v32.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1376
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1377
+ return {
1378
+ ...schema,
1379
+ propertyNames: keyType
1380
+ };
1381
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === import_v32.ZodFirstPartyTypeKind.ZodEnum) {
1382
+ return {
1383
+ ...schema,
1384
+ propertyNames: {
1385
+ enum: def.keyType._def.values
1386
+ }
1387
+ };
1388
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === import_v32.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === import_v32.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1389
+ const { type, ...keyType } = parseBrandedDef(
1390
+ def.keyType._def,
1391
+ refs
1392
+ );
1393
+ return {
1394
+ ...schema,
1395
+ propertyNames: keyType
1396
+ };
1397
+ }
1398
+ return schema;
1399
+ }
1400
+
1401
+ // src/to-json-schema/zod3-to-json-schema/parsers/map.ts
1402
+ function parseMapDef(def, refs) {
1403
+ if (refs.mapStrategy === "record") {
1404
+ return parseRecordDef(def, refs);
1405
+ }
1406
+ const keys = parseDef(def.keyType._def, {
1407
+ ...refs,
1408
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1409
+ }) || parseAnyDef();
1410
+ const values = parseDef(def.valueType._def, {
1411
+ ...refs,
1412
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1413
+ }) || parseAnyDef();
1414
+ return {
1415
+ type: "array",
1416
+ maxItems: 125,
1417
+ items: {
1418
+ type: "array",
1419
+ items: [keys, values],
1420
+ minItems: 2,
1421
+ maxItems: 2
1422
+ }
1423
+ };
1424
+ }
1425
+
1426
+ // src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts
1427
+ function parseNativeEnumDef(def) {
1428
+ const object = def.values;
1429
+ const actualKeys = Object.keys(def.values).filter((key) => {
1430
+ return typeof object[object[key]] !== "number";
1431
+ });
1432
+ const actualValues = actualKeys.map((key) => object[key]);
1433
+ const parsedTypes = Array.from(
1434
+ new Set(actualValues.map((values) => typeof values))
1435
+ );
1436
+ return {
1437
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1438
+ enum: actualValues
1439
+ };
1440
+ }
1441
+
1442
+ // src/to-json-schema/zod3-to-json-schema/parsers/never.ts
1443
+ function parseNeverDef() {
1444
+ return { not: parseAnyDef() };
1445
+ }
1446
+
1447
+ // src/to-json-schema/zod3-to-json-schema/parsers/null.ts
1448
+ function parseNullDef() {
1449
+ return {
1450
+ type: "null"
1451
+ };
1452
+ }
1453
+
1454
+ // src/to-json-schema/zod3-to-json-schema/parsers/union.ts
1455
+ var primitiveMappings = {
1456
+ ZodString: "string",
1457
+ ZodNumber: "number",
1458
+ ZodBigInt: "integer",
1459
+ ZodBoolean: "boolean",
1460
+ ZodNull: "null"
1461
+ };
1462
+ function parseUnionDef(def, refs) {
1463
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1464
+ if (options.every(
1465
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1466
+ )) {
1467
+ const types = options.reduce((types2, x) => {
1468
+ const type = primitiveMappings[x._def.typeName];
1469
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1470
+ }, []);
1471
+ return {
1472
+ type: types.length > 1 ? types : types[0]
1473
+ };
1474
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1475
+ const types = options.reduce(
1476
+ (acc, x) => {
1477
+ const type = typeof x._def.value;
1478
+ switch (type) {
1479
+ case "string":
1480
+ case "number":
1481
+ case "boolean":
1482
+ return [...acc, type];
1483
+ case "bigint":
1484
+ return [...acc, "integer"];
1485
+ case "object":
1486
+ if (x._def.value === null) return [...acc, "null"];
1487
+ case "symbol":
1488
+ case "undefined":
1489
+ case "function":
1490
+ default:
1491
+ return acc;
1492
+ }
1493
+ },
1494
+ []
1495
+ );
1496
+ if (types.length === options.length) {
1497
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1498
+ return {
1499
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1500
+ enum: options.reduce(
1501
+ (acc, x) => {
1502
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1503
+ },
1504
+ []
1505
+ )
1506
+ };
1507
+ }
1508
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1509
+ return {
1510
+ type: "string",
1511
+ enum: options.reduce(
1512
+ (acc, x) => [
1513
+ ...acc,
1514
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1515
+ ],
1516
+ []
1517
+ )
1518
+ };
1519
+ }
1520
+ return asAnyOf(def, refs);
1521
+ }
1522
+ var asAnyOf = (def, refs) => {
1523
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1524
+ (x, i) => parseDef(x._def, {
1525
+ ...refs,
1526
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1527
+ })
1528
+ ).filter(
1529
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1530
+ );
1531
+ return anyOf.length ? { anyOf } : void 0;
1532
+ };
1533
+
1534
+ // src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts
1535
+ function parseNullableDef(def, refs) {
1536
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1537
+ def.innerType._def.typeName
1538
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1539
+ return {
1540
+ type: [
1541
+ primitiveMappings[def.innerType._def.typeName],
1542
+ "null"
1543
+ ]
1544
+ };
1545
+ }
1546
+ const base = parseDef(def.innerType._def, {
1547
+ ...refs,
1548
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1549
+ });
1550
+ return base && { anyOf: [base, { type: "null" }] };
1551
+ }
1552
+
1553
+ // src/to-json-schema/zod3-to-json-schema/parsers/number.ts
1554
+ function parseNumberDef(def) {
1555
+ const res = {
1556
+ type: "number"
1557
+ };
1558
+ if (!def.checks) return res;
1559
+ for (const check of def.checks) {
1560
+ switch (check.kind) {
1561
+ case "int":
1562
+ res.type = "integer";
1563
+ break;
1564
+ case "min":
1565
+ if (check.inclusive) {
1566
+ res.minimum = check.value;
1567
+ } else {
1568
+ res.exclusiveMinimum = check.value;
1569
+ }
1570
+ break;
1571
+ case "max":
1572
+ if (check.inclusive) {
1573
+ res.maximum = check.value;
1574
+ } else {
1575
+ res.exclusiveMaximum = check.value;
1576
+ }
1577
+ break;
1578
+ case "multipleOf":
1579
+ res.multipleOf = check.value;
1580
+ break;
1581
+ }
1582
+ }
1583
+ return res;
1584
+ }
1585
+
1586
+ // src/to-json-schema/zod3-to-json-schema/parsers/object.ts
1587
+ function parseObjectDef(def, refs) {
1588
+ const result = {
1589
+ type: "object",
1590
+ properties: {}
1591
+ };
1592
+ const required = [];
1593
+ const shape = def.shape();
1594
+ for (const propName in shape) {
1595
+ let propDef = shape[propName];
1596
+ if (propDef === void 0 || propDef._def === void 0) {
1597
+ continue;
1598
+ }
1599
+ const propOptional = safeIsOptional(propDef);
1600
+ const parsedDef = parseDef(propDef._def, {
1601
+ ...refs,
1602
+ currentPath: [...refs.currentPath, "properties", propName],
1603
+ propertyPath: [...refs.currentPath, "properties", propName]
1604
+ });
1605
+ if (parsedDef === void 0) {
1606
+ continue;
1607
+ }
1608
+ result.properties[propName] = parsedDef;
1609
+ if (!propOptional) {
1610
+ required.push(propName);
1611
+ }
1612
+ }
1613
+ if (required.length) {
1614
+ result.required = required;
1615
+ }
1616
+ const additionalProperties = decideAdditionalProperties(def, refs);
1617
+ if (additionalProperties !== void 0) {
1618
+ result.additionalProperties = additionalProperties;
1619
+ }
1620
+ return result;
1621
+ }
1622
+ function decideAdditionalProperties(def, refs) {
1623
+ if (def.catchall._def.typeName !== "ZodNever") {
1624
+ return parseDef(def.catchall._def, {
1625
+ ...refs,
1626
+ currentPath: [...refs.currentPath, "additionalProperties"]
1627
+ });
1628
+ }
1629
+ switch (def.unknownKeys) {
1630
+ case "passthrough":
1631
+ return refs.allowedAdditionalProperties;
1632
+ case "strict":
1633
+ return refs.rejectedAdditionalProperties;
1634
+ case "strip":
1635
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1636
+ }
1637
+ }
1638
+ function safeIsOptional(schema) {
1639
+ try {
1640
+ return schema.isOptional();
1641
+ } catch (e) {
1642
+ return true;
1643
+ }
1644
+ }
1645
+
1646
+ // src/to-json-schema/zod3-to-json-schema/parsers/optional.ts
1647
+ var parseOptionalDef = (def, refs) => {
1648
+ var _a2;
1649
+ if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) {
1650
+ return parseDef(def.innerType._def, refs);
1651
+ }
1652
+ const innerSchema = parseDef(def.innerType._def, {
1653
+ ...refs,
1654
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1655
+ });
1656
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1657
+ };
1658
+
1659
+ // src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts
1660
+ var parsePipelineDef = (def, refs) => {
1661
+ if (refs.pipeStrategy === "input") {
1662
+ return parseDef(def.in._def, refs);
1663
+ } else if (refs.pipeStrategy === "output") {
1664
+ return parseDef(def.out._def, refs);
1665
+ }
1666
+ const a = parseDef(def.in._def, {
1667
+ ...refs,
1668
+ currentPath: [...refs.currentPath, "allOf", "0"]
1669
+ });
1670
+ const b = parseDef(def.out._def, {
1671
+ ...refs,
1672
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1673
+ });
1674
+ return {
1675
+ allOf: [a, b].filter((x) => x !== void 0)
1676
+ };
1677
+ };
1678
+
1679
+ // src/to-json-schema/zod3-to-json-schema/parsers/promise.ts
1680
+ function parsePromiseDef(def, refs) {
1681
+ return parseDef(def.type._def, refs);
1682
+ }
1683
+
1684
+ // src/to-json-schema/zod3-to-json-schema/parsers/set.ts
1685
+ function parseSetDef(def, refs) {
1686
+ const items = parseDef(def.valueType._def, {
1687
+ ...refs,
1688
+ currentPath: [...refs.currentPath, "items"]
1689
+ });
1690
+ const schema = {
1691
+ type: "array",
1692
+ uniqueItems: true,
1693
+ items
1694
+ };
1695
+ if (def.minSize) {
1696
+ schema.minItems = def.minSize.value;
1697
+ }
1698
+ if (def.maxSize) {
1699
+ schema.maxItems = def.maxSize.value;
1700
+ }
1701
+ return schema;
1702
+ }
1703
+
1704
+ // src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts
1705
+ function parseTupleDef(def, refs) {
1706
+ if (def.rest) {
1707
+ return {
1708
+ type: "array",
1709
+ minItems: def.items.length,
1710
+ items: def.items.map(
1711
+ (x, i) => parseDef(x._def, {
1712
+ ...refs,
1713
+ currentPath: [...refs.currentPath, "items", `${i}`]
1714
+ })
1715
+ ).reduce(
1716
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1717
+ []
1718
+ ),
1719
+ additionalItems: parseDef(def.rest._def, {
1720
+ ...refs,
1721
+ currentPath: [...refs.currentPath, "additionalItems"]
1722
+ })
1723
+ };
1724
+ } else {
1725
+ return {
1726
+ type: "array",
1727
+ minItems: def.items.length,
1728
+ maxItems: def.items.length,
1729
+ items: def.items.map(
1730
+ (x, i) => parseDef(x._def, {
1731
+ ...refs,
1732
+ currentPath: [...refs.currentPath, "items", `${i}`]
1733
+ })
1734
+ ).reduce(
1735
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1736
+ []
1737
+ )
1738
+ };
1739
+ }
1740
+ }
1741
+
1742
+ // src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts
1743
+ function parseUndefinedDef() {
1744
+ return {
1745
+ not: parseAnyDef()
1746
+ };
1747
+ }
1748
+
1749
+ // src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts
1750
+ function parseUnknownDef() {
1751
+ return parseAnyDef();
1752
+ }
1753
+
1754
+ // src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts
1755
+ var parseReadonlyDef = (def, refs) => {
1756
+ return parseDef(def.innerType._def, refs);
1757
+ };
1758
+
1759
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
1760
+ var selectParser = (def, typeName, refs) => {
1761
+ switch (typeName) {
1762
+ case import_v33.ZodFirstPartyTypeKind.ZodString:
1763
+ return parseStringDef(def, refs);
1764
+ case import_v33.ZodFirstPartyTypeKind.ZodNumber:
1765
+ return parseNumberDef(def);
1766
+ case import_v33.ZodFirstPartyTypeKind.ZodObject:
1767
+ return parseObjectDef(def, refs);
1768
+ case import_v33.ZodFirstPartyTypeKind.ZodBigInt:
1769
+ return parseBigintDef(def);
1770
+ case import_v33.ZodFirstPartyTypeKind.ZodBoolean:
1771
+ return parseBooleanDef();
1772
+ case import_v33.ZodFirstPartyTypeKind.ZodDate:
1773
+ return parseDateDef(def, refs);
1774
+ case import_v33.ZodFirstPartyTypeKind.ZodUndefined:
1775
+ return parseUndefinedDef();
1776
+ case import_v33.ZodFirstPartyTypeKind.ZodNull:
1777
+ return parseNullDef();
1778
+ case import_v33.ZodFirstPartyTypeKind.ZodArray:
1779
+ return parseArrayDef(def, refs);
1780
+ case import_v33.ZodFirstPartyTypeKind.ZodUnion:
1781
+ case import_v33.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
1782
+ return parseUnionDef(def, refs);
1783
+ case import_v33.ZodFirstPartyTypeKind.ZodIntersection:
1784
+ return parseIntersectionDef(def, refs);
1785
+ case import_v33.ZodFirstPartyTypeKind.ZodTuple:
1786
+ return parseTupleDef(def, refs);
1787
+ case import_v33.ZodFirstPartyTypeKind.ZodRecord:
1788
+ return parseRecordDef(def, refs);
1789
+ case import_v33.ZodFirstPartyTypeKind.ZodLiteral:
1790
+ return parseLiteralDef(def);
1791
+ case import_v33.ZodFirstPartyTypeKind.ZodEnum:
1792
+ return parseEnumDef(def);
1793
+ case import_v33.ZodFirstPartyTypeKind.ZodNativeEnum:
1794
+ return parseNativeEnumDef(def);
1795
+ case import_v33.ZodFirstPartyTypeKind.ZodNullable:
1796
+ return parseNullableDef(def, refs);
1797
+ case import_v33.ZodFirstPartyTypeKind.ZodOptional:
1798
+ return parseOptionalDef(def, refs);
1799
+ case import_v33.ZodFirstPartyTypeKind.ZodMap:
1800
+ return parseMapDef(def, refs);
1801
+ case import_v33.ZodFirstPartyTypeKind.ZodSet:
1802
+ return parseSetDef(def, refs);
1803
+ case import_v33.ZodFirstPartyTypeKind.ZodLazy:
1804
+ return () => def.getter()._def;
1805
+ case import_v33.ZodFirstPartyTypeKind.ZodPromise:
1806
+ return parsePromiseDef(def, refs);
1807
+ case import_v33.ZodFirstPartyTypeKind.ZodNaN:
1808
+ case import_v33.ZodFirstPartyTypeKind.ZodNever:
1809
+ return parseNeverDef();
1810
+ case import_v33.ZodFirstPartyTypeKind.ZodEffects:
1811
+ return parseEffectsDef(def, refs);
1812
+ case import_v33.ZodFirstPartyTypeKind.ZodAny:
1813
+ return parseAnyDef();
1814
+ case import_v33.ZodFirstPartyTypeKind.ZodUnknown:
1815
+ return parseUnknownDef();
1816
+ case import_v33.ZodFirstPartyTypeKind.ZodDefault:
1817
+ return parseDefaultDef(def, refs);
1818
+ case import_v33.ZodFirstPartyTypeKind.ZodBranded:
1819
+ return parseBrandedDef(def, refs);
1820
+ case import_v33.ZodFirstPartyTypeKind.ZodReadonly:
1821
+ return parseReadonlyDef(def, refs);
1822
+ case import_v33.ZodFirstPartyTypeKind.ZodCatch:
1823
+ return parseCatchDef(def, refs);
1824
+ case import_v33.ZodFirstPartyTypeKind.ZodPipeline:
1825
+ return parsePipelineDef(def, refs);
1826
+ case import_v33.ZodFirstPartyTypeKind.ZodFunction:
1827
+ case import_v33.ZodFirstPartyTypeKind.ZodVoid:
1828
+ case import_v33.ZodFirstPartyTypeKind.ZodSymbol:
1829
+ return void 0;
1830
+ default:
1831
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1832
+ }
1833
+ };
1834
+
1835
+ // src/to-json-schema/zod3-to-json-schema/get-relative-path.ts
1836
+ var getRelativePath = (pathA, pathB) => {
1837
+ let i = 0;
1838
+ for (; i < pathA.length && i < pathB.length; i++) {
1839
+ if (pathA[i] !== pathB[i]) break;
1840
+ }
1841
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1842
+ };
1843
+
1844
+ // src/to-json-schema/zod3-to-json-schema/parse-def.ts
1845
+ function parseDef(def, refs, forceResolution = false) {
1846
+ var _a2;
1847
+ const seenItem = refs.seen.get(def);
1848
+ if (refs.override) {
1849
+ const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(
1850
+ refs,
1851
+ def,
1852
+ refs,
1853
+ seenItem,
1854
+ forceResolution
1855
+ );
1856
+ if (overrideResult !== ignoreOverride) {
1857
+ return overrideResult;
1858
+ }
1859
+ }
1860
+ if (seenItem && !forceResolution) {
1861
+ const seenSchema = get$ref(seenItem, refs);
1862
+ if (seenSchema !== void 0) {
1863
+ return seenSchema;
1864
+ }
1865
+ }
1866
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1867
+ refs.seen.set(def, newItem);
1868
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1869
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1870
+ if (jsonSchema2) {
1871
+ addMeta(def, refs, jsonSchema2);
1872
+ }
1873
+ if (refs.postProcess) {
1874
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1875
+ newItem.jsonSchema = jsonSchema2;
1876
+ return postProcessResult;
1877
+ }
1878
+ newItem.jsonSchema = jsonSchema2;
1879
+ return jsonSchema2;
1880
+ }
1881
+ var get$ref = (item, refs) => {
1882
+ switch (refs.$refStrategy) {
1883
+ case "root":
1884
+ return { $ref: item.path.join("/") };
1885
+ case "relative":
1886
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1887
+ case "none":
1888
+ case "seen": {
1889
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1890
+ console.warn(
1891
+ `Recursive reference detected at ${refs.currentPath.join(
1892
+ "/"
1893
+ )}! Defaulting to any`
1894
+ );
1895
+ return parseAnyDef();
1896
+ }
1897
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1898
+ }
1899
+ }
1900
+ };
1901
+ var addMeta = (def, refs, jsonSchema2) => {
1902
+ if (def.description) {
1903
+ jsonSchema2.description = def.description;
1904
+ }
1905
+ return jsonSchema2;
1906
+ };
1907
+
1908
+ // src/to-json-schema/zod3-to-json-schema/refs.ts
1909
+ var getRefs = (options) => {
1910
+ const _options = getDefaultOptions(options);
1911
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1912
+ return {
1913
+ ..._options,
1914
+ currentPath,
1915
+ propertyPath: void 0,
1916
+ seen: new Map(
1917
+ Object.entries(_options.definitions).map(([name2, def]) => [
1918
+ def._def,
1919
+ {
1920
+ def: def._def,
1921
+ path: [..._options.basePath, _options.definitionPath, name2],
1922
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1923
+ jsonSchema: void 0
1924
+ }
1925
+ ])
1926
+ )
1927
+ };
1928
+ };
1929
+
1930
+ // src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts
1931
+ var zod3ToJsonSchema = (schema, options) => {
1932
+ var _a2;
1933
+ const refs = getRefs(options);
1934
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1935
+ (acc, [name3, schema2]) => {
1936
+ var _a3;
1937
+ return {
1938
+ ...acc,
1939
+ [name3]: (_a3 = parseDef(
1940
+ schema2._def,
1941
+ {
1942
+ ...refs,
1943
+ currentPath: [...refs.basePath, refs.definitionPath, name3]
1944
+ },
1945
+ true
1946
+ )) != null ? _a3 : parseAnyDef()
1947
+ };
1948
+ },
1949
+ {}
1950
+ ) : void 0;
1951
+ const name2 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1952
+ const main = (_a2 = parseDef(
1953
+ schema._def,
1954
+ name2 === void 0 ? refs : {
1955
+ ...refs,
1956
+ currentPath: [...refs.basePath, refs.definitionPath, name2]
1957
+ },
1958
+ false
1959
+ )) != null ? _a2 : parseAnyDef();
1960
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1961
+ if (title !== void 0) {
1962
+ main.title = title;
1963
+ }
1964
+ const combined = name2 === void 0 ? definitions ? {
1965
+ ...main,
1966
+ [refs.definitionPath]: definitions
1967
+ } : main : {
1968
+ $ref: [
1969
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1970
+ refs.definitionPath,
1971
+ name2
1972
+ ].join("/"),
1973
+ [refs.definitionPath]: {
1974
+ ...definitions,
1975
+ [name2]: main
1976
+ }
1977
+ };
1978
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1979
+ return combined;
1980
+ };
1981
+
1982
+ // src/schema.ts
1983
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1984
+ function lazySchema(createSchema) {
1985
+ let schema;
1986
+ return () => {
1987
+ if (schema == null) {
1988
+ schema = createSchema();
1989
+ }
1990
+ return schema;
1991
+ };
1992
+ }
1993
+ function jsonSchema(jsonSchema2, {
1994
+ validate
1995
+ } = {}) {
1996
+ return {
1997
+ [schemaSymbol]: true,
1998
+ _type: void 0,
1999
+ // should never be used directly
2000
+ get jsonSchema() {
2001
+ if (typeof jsonSchema2 === "function") {
2002
+ jsonSchema2 = jsonSchema2();
2003
+ }
2004
+ return jsonSchema2;
2005
+ },
2006
+ validate
2007
+ };
2008
+ }
2009
+ function isSchema(value) {
2010
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2011
+ }
2012
+ function asSchema(schema) {
2013
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
2014
+ }
2015
+ function standardSchema(standardSchema2) {
2016
+ return jsonSchema(
2017
+ () => addAdditionalPropertiesToJsonSchema(
2018
+ standardSchema2["~standard"].jsonSchema.input({
2019
+ target: "draft-07"
2020
+ })
2021
+ ),
2022
+ {
2023
+ validate: async (value) => {
2024
+ const result = await standardSchema2["~standard"].validate(value);
2025
+ return "value" in result ? { success: true, value: result.value } : {
2026
+ success: false,
2027
+ error: new import_provider7.TypeValidationError({
2028
+ value,
2029
+ cause: result.issues
2030
+ })
2031
+ };
2032
+ }
2033
+ }
2034
+ );
2035
+ }
2036
+ function zod3Schema(zodSchema2, options) {
2037
+ var _a2;
2038
+ const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
2039
+ return jsonSchema(
2040
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2041
+ () => zod3ToJsonSchema(zodSchema2, {
2042
+ $refStrategy: useReferences ? "root" : "none"
2043
+ }),
2044
+ {
2045
+ validate: async (value) => {
2046
+ const result = await zodSchema2.safeParseAsync(value);
2047
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2048
+ }
2049
+ }
2050
+ );
2051
+ }
2052
+ function zod4Schema(zodSchema2, options) {
2053
+ var _a2;
2054
+ const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
2055
+ return jsonSchema(
2056
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2057
+ () => addAdditionalPropertiesToJsonSchema(
2058
+ z4.toJSONSchema(zodSchema2, {
2059
+ target: "draft-7",
2060
+ io: "input",
2061
+ reused: useReferences ? "ref" : "inline"
2062
+ })
2063
+ ),
2064
+ {
2065
+ validate: async (value) => {
2066
+ const result = await z4.safeParseAsync(zodSchema2, value);
2067
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2068
+ }
2069
+ }
2070
+ );
2071
+ }
2072
+ function isZod4Schema(zodSchema2) {
2073
+ return "_zod" in zodSchema2;
2074
+ }
2075
+ function zodSchema(zodSchema2, options) {
2076
+ if (isZod4Schema(zodSchema2)) {
2077
+ return zod4Schema(zodSchema2, options);
2078
+ } else {
2079
+ return zod3Schema(zodSchema2, options);
2080
+ }
2081
+ }
2082
+
2083
+ // src/validate-types.ts
2084
+ async function validateTypes({
2085
+ value,
2086
+ schema
2087
+ }) {
2088
+ const result = await safeValidateTypes({ value, schema });
2089
+ if (!result.success) {
2090
+ throw import_provider8.TypeValidationError.wrap({ value, cause: result.error });
2091
+ }
2092
+ return result.value;
2093
+ }
2094
+ async function safeValidateTypes({
2095
+ value,
2096
+ schema
2097
+ }) {
2098
+ const actualSchema = asSchema(schema);
2099
+ try {
2100
+ if (actualSchema.validate == null) {
2101
+ return { success: true, value, rawValue: value };
2102
+ }
2103
+ const result = await actualSchema.validate(value);
2104
+ if (result.success) {
2105
+ return { success: true, value: result.value, rawValue: value };
2106
+ }
2107
+ return {
2108
+ success: false,
2109
+ error: import_provider8.TypeValidationError.wrap({ value, cause: result.error }),
2110
+ rawValue: value
2111
+ };
2112
+ } catch (error) {
2113
+ return {
2114
+ success: false,
2115
+ error: import_provider8.TypeValidationError.wrap({ value, cause: error }),
2116
+ rawValue: value
2117
+ };
2118
+ }
2119
+ }
2120
+
2121
+ // src/parse-json.ts
2122
+ async function parseJSON({
2123
+ text,
2124
+ schema
2125
+ }) {
2126
+ try {
2127
+ const value = secureJsonParse(text);
2128
+ if (schema == null) {
2129
+ return value;
2130
+ }
2131
+ return validateTypes({ value, schema });
2132
+ } catch (error) {
2133
+ if (import_provider9.JSONParseError.isInstance(error) || import_provider9.TypeValidationError.isInstance(error)) {
2134
+ throw error;
2135
+ }
2136
+ throw new import_provider9.JSONParseError({ text, cause: error });
2137
+ }
2138
+ }
2139
+ async function safeParseJSON({
2140
+ text,
2141
+ schema
2142
+ }) {
2143
+ try {
2144
+ const value = secureJsonParse(text);
2145
+ if (schema == null) {
2146
+ return { success: true, value, rawValue: value };
2147
+ }
2148
+ return await safeValidateTypes({ value, schema });
2149
+ } catch (error) {
2150
+ return {
2151
+ success: false,
2152
+ error: import_provider9.JSONParseError.isInstance(error) ? error : new import_provider9.JSONParseError({ text, cause: error }),
2153
+ rawValue: void 0
2154
+ };
2155
+ }
2156
+ }
2157
+ function isParsableJson(input) {
2158
+ try {
2159
+ secureJsonParse(input);
2160
+ return true;
2161
+ } catch (e) {
2162
+ return false;
2163
+ }
2164
+ }
2165
+
2166
+ // src/parse-json-event-stream.ts
2167
+ var import_stream = require("eventsource-parser/stream");
2168
+ function parseJsonEventStream({
2169
+ stream,
2170
+ schema
2171
+ }) {
2172
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new import_stream.EventSourceParserStream()).pipeThrough(
2173
+ new TransformStream({
2174
+ async transform({ data }, controller) {
2175
+ if (data === "[DONE]") {
2176
+ return;
2177
+ }
2178
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
2179
+ }
2180
+ })
2181
+ );
2182
+ }
2183
+
2184
+ // src/parse-provider-options.ts
2185
+ var import_provider10 = require("@ai-sdk/provider");
2186
+ async function parseProviderOptions({
2187
+ provider,
2188
+ providerOptions,
2189
+ schema
2190
+ }) {
2191
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
2192
+ return void 0;
2193
+ }
2194
+ const parsedProviderOptions = await safeValidateTypes({
2195
+ value: providerOptions[provider],
2196
+ schema
2197
+ });
2198
+ if (!parsedProviderOptions.success) {
2199
+ throw new import_provider10.InvalidArgumentError({
2200
+ argument: "providerOptions",
2201
+ message: `invalid ${provider} provider options`,
2202
+ cause: parsedProviderOptions.error
2203
+ });
2204
+ }
2205
+ return parsedProviderOptions.value;
2206
+ }
2207
+
2208
+ // src/post-to-api.ts
2209
+ var import_provider11 = require("@ai-sdk/provider");
2210
+ var getOriginalFetch2 = () => globalThis.fetch;
2211
+ var postJsonToApi = async ({
2212
+ url,
2213
+ headers,
2214
+ body,
2215
+ failedResponseHandler,
2216
+ successfulResponseHandler,
2217
+ abortSignal,
2218
+ fetch: fetch2
2219
+ }) => postToApi({
2220
+ url,
2221
+ headers: {
2222
+ "Content-Type": "application/json",
2223
+ ...headers
2224
+ },
2225
+ body: {
2226
+ content: JSON.stringify(body),
2227
+ values: body
2228
+ },
2229
+ failedResponseHandler,
2230
+ successfulResponseHandler,
2231
+ abortSignal,
2232
+ fetch: fetch2
2233
+ });
2234
+ var postFormDataToApi = async ({
2235
+ url,
2236
+ headers,
2237
+ formData,
2238
+ failedResponseHandler,
2239
+ successfulResponseHandler,
2240
+ abortSignal,
2241
+ fetch: fetch2
2242
+ }) => postToApi({
2243
+ url,
2244
+ headers,
2245
+ body: {
2246
+ content: formData,
2247
+ values: Object.fromEntries(formData.entries())
2248
+ },
2249
+ failedResponseHandler,
2250
+ successfulResponseHandler,
2251
+ abortSignal,
2252
+ fetch: fetch2
2253
+ });
2254
+ var postToApi = async ({
2255
+ url,
2256
+ headers = {},
2257
+ body,
2258
+ successfulResponseHandler,
2259
+ failedResponseHandler,
2260
+ abortSignal,
2261
+ fetch: fetch2 = getOriginalFetch2()
2262
+ }) => {
2263
+ try {
2264
+ const response = await fetch2(url, {
2265
+ method: "POST",
2266
+ headers: withUserAgentSuffix(
2267
+ headers,
2268
+ `ai-sdk/provider-utils/${VERSION}`,
2269
+ getRuntimeEnvironmentUserAgent()
2270
+ ),
2271
+ body: body.content,
2272
+ signal: abortSignal
2273
+ });
2274
+ const responseHeaders = extractResponseHeaders(response);
2275
+ if (!response.ok) {
2276
+ let errorInformation;
2277
+ try {
2278
+ errorInformation = await failedResponseHandler({
2279
+ response,
2280
+ url,
2281
+ requestBodyValues: body.values
2282
+ });
2283
+ } catch (error) {
2284
+ if (isAbortError(error) || import_provider11.APICallError.isInstance(error)) {
2285
+ throw error;
2286
+ }
2287
+ throw new import_provider11.APICallError({
2288
+ message: "Failed to process error response",
2289
+ cause: error,
2290
+ statusCode: response.status,
2291
+ url,
2292
+ responseHeaders,
2293
+ requestBodyValues: body.values
2294
+ });
2295
+ }
2296
+ throw errorInformation.value;
2297
+ }
2298
+ try {
2299
+ return await successfulResponseHandler({
2300
+ response,
2301
+ url,
2302
+ requestBodyValues: body.values
2303
+ });
2304
+ } catch (error) {
2305
+ if (error instanceof Error) {
2306
+ if (isAbortError(error) || import_provider11.APICallError.isInstance(error)) {
2307
+ throw error;
2308
+ }
2309
+ }
2310
+ throw new import_provider11.APICallError({
2311
+ message: "Failed to process successful response",
2312
+ cause: error,
2313
+ statusCode: response.status,
2314
+ url,
2315
+ responseHeaders,
2316
+ requestBodyValues: body.values
2317
+ });
2318
+ }
2319
+ } catch (error) {
2320
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
2321
+ }
2322
+ };
2323
+
2324
+ // src/types/tool.ts
2325
+ function tool(tool2) {
2326
+ return tool2;
2327
+ }
2328
+ function dynamicTool(tool2) {
2329
+ return { ...tool2, type: "dynamic" };
2330
+ }
2331
+
2332
+ // src/provider-tool-factory.ts
2333
+ function createProviderToolFactory({
2334
+ id,
2335
+ inputSchema
2336
+ }) {
2337
+ return ({
2338
+ execute,
2339
+ outputSchema,
2340
+ needsApproval,
2341
+ toModelOutput,
2342
+ onInputStart,
2343
+ onInputDelta,
2344
+ onInputAvailable,
2345
+ ...args
2346
+ }) => tool({
2347
+ type: "provider",
2348
+ id,
2349
+ args,
2350
+ inputSchema,
2351
+ outputSchema,
2352
+ execute,
2353
+ needsApproval,
2354
+ toModelOutput,
2355
+ onInputStart,
2356
+ onInputDelta,
2357
+ onInputAvailable
2358
+ });
2359
+ }
2360
+ function createProviderToolFactoryWithOutputSchema({
2361
+ id,
2362
+ inputSchema,
2363
+ outputSchema,
2364
+ supportsDeferredResults
2365
+ }) {
2366
+ return ({
2367
+ execute,
2368
+ needsApproval,
2369
+ toModelOutput,
2370
+ onInputStart,
2371
+ onInputDelta,
2372
+ onInputAvailable,
2373
+ ...args
2374
+ }) => tool({
2375
+ type: "provider",
2376
+ id,
2377
+ args,
2378
+ inputSchema,
2379
+ outputSchema,
2380
+ execute,
2381
+ needsApproval,
2382
+ toModelOutput,
2383
+ onInputStart,
2384
+ onInputDelta,
2385
+ onInputAvailable,
2386
+ supportsDeferredResults
2387
+ });
2388
+ }
2389
+
2390
+ // src/remove-undefined-entries.ts
2391
+ function removeUndefinedEntries(record) {
2392
+ return Object.fromEntries(
2393
+ Object.entries(record).filter(([_key, value]) => value != null)
2394
+ );
2395
+ }
2396
+
2397
+ // src/resolve.ts
2398
+ async function resolve(value) {
2399
+ if (typeof value === "function") {
2400
+ value = value();
2401
+ }
2402
+ return Promise.resolve(value);
2403
+ }
2404
+
2405
+ // src/response-handler.ts
2406
+ var import_provider12 = require("@ai-sdk/provider");
2407
+ var createJsonErrorResponseHandler = ({
2408
+ errorSchema,
2409
+ errorToMessage,
2410
+ isRetryable
2411
+ }) => async ({ response, url, requestBodyValues }) => {
2412
+ const responseBody = await response.text();
2413
+ const responseHeaders = extractResponseHeaders(response);
2414
+ if (responseBody.trim() === "") {
2415
+ return {
2416
+ responseHeaders,
2417
+ value: new import_provider12.APICallError({
2418
+ message: response.statusText,
2419
+ url,
2420
+ requestBodyValues,
2421
+ statusCode: response.status,
2422
+ responseHeaders,
2423
+ responseBody,
2424
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2425
+ })
2426
+ };
2427
+ }
2428
+ try {
2429
+ const parsedError = await parseJSON({
2430
+ text: responseBody,
2431
+ schema: errorSchema
2432
+ });
2433
+ return {
2434
+ responseHeaders,
2435
+ value: new import_provider12.APICallError({
2436
+ message: errorToMessage(parsedError),
2437
+ url,
2438
+ requestBodyValues,
2439
+ statusCode: response.status,
2440
+ responseHeaders,
2441
+ responseBody,
2442
+ data: parsedError,
2443
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
2444
+ })
2445
+ };
2446
+ } catch (parseError) {
2447
+ return {
2448
+ responseHeaders,
2449
+ value: new import_provider12.APICallError({
2450
+ message: response.statusText,
2451
+ url,
2452
+ requestBodyValues,
2453
+ statusCode: response.status,
2454
+ responseHeaders,
2455
+ responseBody,
2456
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2457
+ })
2458
+ };
2459
+ }
2460
+ };
2461
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
2462
+ const responseHeaders = extractResponseHeaders(response);
2463
+ if (response.body == null) {
2464
+ throw new import_provider12.EmptyResponseBodyError({});
2465
+ }
2466
+ return {
2467
+ responseHeaders,
2468
+ value: parseJsonEventStream({
2469
+ stream: response.body,
2470
+ schema: chunkSchema
2471
+ })
2472
+ };
2473
+ };
2474
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
2475
+ const responseBody = await response.text();
2476
+ const parsedResult = await safeParseJSON({
2477
+ text: responseBody,
2478
+ schema: responseSchema
2479
+ });
2480
+ const responseHeaders = extractResponseHeaders(response);
2481
+ if (!parsedResult.success) {
2482
+ throw new import_provider12.APICallError({
2483
+ message: "Invalid JSON response",
2484
+ cause: parsedResult.error,
2485
+ statusCode: response.status,
2486
+ responseHeaders,
2487
+ responseBody,
2488
+ url,
2489
+ requestBodyValues
2490
+ });
2491
+ }
2492
+ return {
2493
+ responseHeaders,
2494
+ value: parsedResult.value,
2495
+ rawValue: parsedResult.rawValue
2496
+ };
2497
+ };
2498
+ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2499
+ const responseHeaders = extractResponseHeaders(response);
2500
+ if (!response.body) {
2501
+ throw new import_provider12.APICallError({
2502
+ message: "Response body is empty",
2503
+ url,
2504
+ requestBodyValues,
2505
+ statusCode: response.status,
2506
+ responseHeaders,
2507
+ responseBody: void 0
2508
+ });
2509
+ }
2510
+ try {
2511
+ const buffer = await response.arrayBuffer();
2512
+ return {
2513
+ responseHeaders,
2514
+ value: new Uint8Array(buffer)
2515
+ };
2516
+ } catch (error) {
2517
+ throw new import_provider12.APICallError({
2518
+ message: "Failed to read response as array buffer",
2519
+ url,
2520
+ requestBodyValues,
2521
+ statusCode: response.status,
2522
+ responseHeaders,
2523
+ responseBody: void 0,
2524
+ cause: error
2525
+ });
2526
+ }
2527
+ };
2528
+ var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2529
+ const responseHeaders = extractResponseHeaders(response);
2530
+ const responseBody = await response.text();
2531
+ return {
2532
+ responseHeaders,
2533
+ value: new import_provider12.APICallError({
2534
+ message: response.statusText,
2535
+ url,
2536
+ requestBodyValues,
2537
+ statusCode: response.status,
2538
+ responseHeaders,
2539
+ responseBody
2540
+ })
2541
+ };
2542
+ };
2543
+
2544
+ // src/without-trailing-slash.ts
2545
+ function withoutTrailingSlash(url) {
2546
+ return url == null ? void 0 : url.replace(/\/$/, "");
2547
+ }
2548
+
2549
+ // src/is-async-iterable.ts
2550
+ function isAsyncIterable(obj) {
2551
+ return obj != null && typeof obj[Symbol.asyncIterator] === "function";
2552
+ }
2553
+
2554
+ // src/types/execute-tool.ts
2555
+ async function* executeTool({
2556
+ execute,
2557
+ input,
2558
+ options
2559
+ }) {
2560
+ const result = execute(input, options);
2561
+ if (isAsyncIterable(result)) {
2562
+ let lastOutput;
2563
+ for await (const output of result) {
2564
+ lastOutput = output;
2565
+ yield { type: "preliminary", output };
2566
+ }
2567
+ yield { type: "final", output: lastOutput };
2568
+ } else {
2569
+ yield { type: "final", output: await result };
2570
+ }
2571
+ }
2572
+
2573
+ // src/index.ts
2574
+ __reExport(src_exports, require("@standard-schema/spec"), module.exports);
2575
+ var import_stream2 = require("eventsource-parser/stream");
2576
+ // Annotate the CommonJS export names for ESM import in node:
2577
+ 0 && (module.exports = {
2578
+ DelayedPromise,
2579
+ DownloadError,
2580
+ EventSourceParserStream,
2581
+ VERSION,
2582
+ asSchema,
2583
+ combineHeaders,
2584
+ convertAsyncIteratorToReadableStream,
2585
+ convertBase64ToUint8Array,
2586
+ convertImageModelFileToDataUri,
2587
+ convertToBase64,
2588
+ convertToFormData,
2589
+ convertUint8ArrayToBase64,
2590
+ createBinaryResponseHandler,
2591
+ createEventSourceResponseHandler,
2592
+ createIdGenerator,
2593
+ createJsonErrorResponseHandler,
2594
+ createJsonResponseHandler,
2595
+ createProviderToolFactory,
2596
+ createProviderToolFactoryWithOutputSchema,
2597
+ createStatusCodeErrorResponseHandler,
2598
+ createToolNameMapping,
2599
+ delay,
2600
+ downloadBlob,
2601
+ dynamicTool,
2602
+ executeTool,
2603
+ extractResponseHeaders,
2604
+ generateId,
2605
+ getErrorMessage,
2606
+ getFromApi,
2607
+ getRuntimeEnvironmentUserAgent,
2608
+ injectJsonInstructionIntoMessages,
2609
+ isAbortError,
2610
+ isNonNullable,
2611
+ isParsableJson,
2612
+ isUrlSupported,
2613
+ jsonSchema,
2614
+ lazySchema,
2615
+ loadApiKey,
2616
+ loadOptionalSetting,
2617
+ loadSetting,
2618
+ mediaTypeToExtension,
2619
+ normalizeHeaders,
2620
+ parseJSON,
2621
+ parseJsonEventStream,
2622
+ parseProviderOptions,
2623
+ postFormDataToApi,
2624
+ postJsonToApi,
2625
+ postToApi,
2626
+ removeUndefinedEntries,
2627
+ resolve,
2628
+ safeParseJSON,
2629
+ safeValidateTypes,
2630
+ tool,
2631
+ validateTypes,
2632
+ withUserAgentSuffix,
2633
+ withoutTrailingSlash,
2634
+ zodSchema,
2635
+ ...require("@standard-schema/spec")
2636
+ });
2637
+ //# sourceMappingURL=index.js.map