@apertis/ai-sdk-provider 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,16 +1,2163 @@
1
- // src/apertis-provider.ts
2
- import { loadApiKey, withoutTrailingSlash } from "@ai-sdk/provider-utils";
1
+ // node_modules/.pnpm/@ai-sdk+provider@3.0.4/node_modules/@ai-sdk/provider/dist/index.mjs
2
+ var marker = "vercel.ai.error";
3
+ var symbol = Symbol.for(marker);
4
+ var _a;
5
+ var _b;
6
+ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
7
+ /**
8
+ * Creates an AI SDK Error.
9
+ *
10
+ * @param {Object} params - The parameters for creating the error.
11
+ * @param {string} params.name - The name of the error.
12
+ * @param {string} params.message - The error message.
13
+ * @param {unknown} [params.cause] - The underlying cause of the error.
14
+ */
15
+ constructor({
16
+ name: name142,
17
+ message,
18
+ cause
19
+ }) {
20
+ super(message);
21
+ this[_a] = true;
22
+ this.name = name142;
23
+ this.cause = cause;
24
+ }
25
+ /**
26
+ * Checks if the given error is an AI SDK Error.
27
+ * @param {unknown} error - The error to check.
28
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
29
+ */
30
+ static isInstance(error) {
31
+ return _AISDKError.hasMarker(error, marker);
32
+ }
33
+ static hasMarker(error, marker152) {
34
+ const markerSymbol = Symbol.for(marker152);
35
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
36
+ }
37
+ };
38
+ var name = "AI_APICallError";
39
+ var marker2 = `vercel.ai.error.${name}`;
40
+ var symbol2 = Symbol.for(marker2);
41
+ var _a2;
42
+ var _b2;
43
+ var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
44
+ constructor({
45
+ message,
46
+ url,
47
+ requestBodyValues,
48
+ statusCode,
49
+ responseHeaders,
50
+ responseBody,
51
+ cause,
52
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
53
+ statusCode === 409 || // conflict
54
+ statusCode === 429 || // too many requests
55
+ statusCode >= 500),
56
+ // server error
57
+ data
58
+ }) {
59
+ super({ name, message, cause });
60
+ this[_a2] = true;
61
+ this.url = url;
62
+ this.requestBodyValues = requestBodyValues;
63
+ this.statusCode = statusCode;
64
+ this.responseHeaders = responseHeaders;
65
+ this.responseBody = responseBody;
66
+ this.isRetryable = isRetryable;
67
+ this.data = data;
68
+ }
69
+ static isInstance(error) {
70
+ return AISDKError.hasMarker(error, marker2);
71
+ }
72
+ };
73
+ var name2 = "AI_EmptyResponseBodyError";
74
+ var marker3 = `vercel.ai.error.${name2}`;
75
+ var symbol3 = Symbol.for(marker3);
76
+ var _a3;
77
+ var _b3;
78
+ var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
79
+ // used in isInstance
80
+ constructor({ message = "Empty response body" } = {}) {
81
+ super({ name: name2, message });
82
+ this[_a3] = true;
83
+ }
84
+ static isInstance(error) {
85
+ return AISDKError.hasMarker(error, marker3);
86
+ }
87
+ };
88
+ function getErrorMessage(error) {
89
+ if (error == null) {
90
+ return "unknown error";
91
+ }
92
+ if (typeof error === "string") {
93
+ return error;
94
+ }
95
+ if (error instanceof Error) {
96
+ return error.message;
97
+ }
98
+ return JSON.stringify(error);
99
+ }
100
+ var name3 = "AI_InvalidArgumentError";
101
+ var marker4 = `vercel.ai.error.${name3}`;
102
+ var symbol4 = Symbol.for(marker4);
103
+ var _a4;
104
+ var _b4;
105
+ var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
106
+ constructor({
107
+ message,
108
+ cause,
109
+ argument
110
+ }) {
111
+ super({ name: name3, message, cause });
112
+ this[_a4] = true;
113
+ this.argument = argument;
114
+ }
115
+ static isInstance(error) {
116
+ return AISDKError.hasMarker(error, marker4);
117
+ }
118
+ };
119
+ var name4 = "AI_InvalidPromptError";
120
+ var marker5 = `vercel.ai.error.${name4}`;
121
+ var symbol5 = Symbol.for(marker5);
122
+ var _a5;
123
+ var _b5;
124
+ var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {
125
+ constructor({
126
+ prompt,
127
+ message,
128
+ cause
129
+ }) {
130
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
131
+ this[_a5] = true;
132
+ this.prompt = prompt;
133
+ }
134
+ static isInstance(error) {
135
+ return AISDKError.hasMarker(error, marker5);
136
+ }
137
+ };
138
+ var name5 = "AI_InvalidResponseDataError";
139
+ var marker6 = `vercel.ai.error.${name5}`;
140
+ var symbol6 = Symbol.for(marker6);
141
+ var _a6;
142
+ var _b6;
143
+ var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {
144
+ constructor({
145
+ data,
146
+ message = `Invalid response data: ${JSON.stringify(data)}.`
147
+ }) {
148
+ super({ name: name5, message });
149
+ this[_a6] = true;
150
+ this.data = data;
151
+ }
152
+ static isInstance(error) {
153
+ return AISDKError.hasMarker(error, marker6);
154
+ }
155
+ };
156
+ var name6 = "AI_JSONParseError";
157
+ var marker7 = `vercel.ai.error.${name6}`;
158
+ var symbol7 = Symbol.for(marker7);
159
+ var _a7;
160
+ var _b7;
161
+ var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
162
+ constructor({ text, cause }) {
163
+ super({
164
+ name: name6,
165
+ message: `JSON parsing failed: Text: ${text}.
166
+ Error message: ${getErrorMessage(cause)}`,
167
+ cause
168
+ });
169
+ this[_a7] = true;
170
+ this.text = text;
171
+ }
172
+ static isInstance(error) {
173
+ return AISDKError.hasMarker(error, marker7);
174
+ }
175
+ };
176
+ var name7 = "AI_LoadAPIKeyError";
177
+ var marker8 = `vercel.ai.error.${name7}`;
178
+ var symbol8 = Symbol.for(marker8);
179
+ var _a8;
180
+ var _b8;
181
+ var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {
182
+ // used in isInstance
183
+ constructor({ message }) {
184
+ super({ name: name7, message });
185
+ this[_a8] = true;
186
+ }
187
+ static isInstance(error) {
188
+ return AISDKError.hasMarker(error, marker8);
189
+ }
190
+ };
191
+ var name8 = "AI_LoadSettingError";
192
+ var marker9 = `vercel.ai.error.${name8}`;
193
+ var symbol9 = Symbol.for(marker9);
194
+ var _a9;
195
+ var _b9;
196
+ var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {
197
+ // used in isInstance
198
+ constructor({ message }) {
199
+ super({ name: name8, message });
200
+ this[_a9] = true;
201
+ }
202
+ static isInstance(error) {
203
+ return AISDKError.hasMarker(error, marker9);
204
+ }
205
+ };
206
+ var name9 = "AI_NoContentGeneratedError";
207
+ var marker10 = `vercel.ai.error.${name9}`;
208
+ var symbol10 = Symbol.for(marker10);
209
+ var _a10;
210
+ var _b10;
211
+ var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {
212
+ // used in isInstance
213
+ constructor({
214
+ message = "No content generated."
215
+ } = {}) {
216
+ super({ name: name9, message });
217
+ this[_a10] = true;
218
+ }
219
+ static isInstance(error) {
220
+ return AISDKError.hasMarker(error, marker10);
221
+ }
222
+ };
223
+ var name10 = "AI_NoSuchModelError";
224
+ var marker11 = `vercel.ai.error.${name10}`;
225
+ var symbol11 = Symbol.for(marker11);
226
+ var _a11;
227
+ var _b11;
228
+ var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
229
+ constructor({
230
+ errorName = name10,
231
+ modelId,
232
+ modelType,
233
+ message = `No such ${modelType}: ${modelId}`
234
+ }) {
235
+ super({ name: errorName, message });
236
+ this[_a11] = true;
237
+ this.modelId = modelId;
238
+ this.modelType = modelType;
239
+ }
240
+ static isInstance(error) {
241
+ return AISDKError.hasMarker(error, marker11);
242
+ }
243
+ };
244
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
245
+ var marker12 = `vercel.ai.error.${name11}`;
246
+ var symbol12 = Symbol.for(marker12);
247
+ var _a12;
248
+ var _b12;
249
+ var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {
250
+ constructor(options) {
251
+ super({
252
+ name: name11,
253
+ message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
254
+ });
255
+ this[_a12] = true;
256
+ this.provider = options.provider;
257
+ this.modelId = options.modelId;
258
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
259
+ this.values = options.values;
260
+ }
261
+ static isInstance(error) {
262
+ return AISDKError.hasMarker(error, marker12);
263
+ }
264
+ };
265
+ var name12 = "AI_TypeValidationError";
266
+ var marker13 = `vercel.ai.error.${name12}`;
267
+ var symbol13 = Symbol.for(marker13);
268
+ var _a13;
269
+ var _b13;
270
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
271
+ constructor({ value, cause }) {
272
+ super({
273
+ name: name12,
274
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
275
+ Error message: ${getErrorMessage(cause)}`,
276
+ cause
277
+ });
278
+ this[_a13] = true;
279
+ this.value = value;
280
+ }
281
+ static isInstance(error) {
282
+ return AISDKError.hasMarker(error, marker13);
283
+ }
284
+ /**
285
+ * Wraps an error into a TypeValidationError.
286
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
287
+ * Otherwise, it creates a new TypeValidationError.
288
+ *
289
+ * @param {Object} params - The parameters for wrapping the error.
290
+ * @param {unknown} params.value - The value that failed validation.
291
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
292
+ * @returns {TypeValidationError} A TypeValidationError instance.
293
+ */
294
+ static wrap({
295
+ value,
296
+ cause
297
+ }) {
298
+ return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
299
+ }
300
+ };
301
+ var name13 = "AI_UnsupportedFunctionalityError";
302
+ var marker14 = `vercel.ai.error.${name13}`;
303
+ var symbol14 = Symbol.for(marker14);
304
+ var _a14;
305
+ var _b14;
306
+ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
307
+ constructor({
308
+ functionality,
309
+ message = `'${functionality}' functionality not supported.`
310
+ }) {
311
+ super({ name: name13, message });
312
+ this[_a14] = true;
313
+ this.functionality = functionality;
314
+ }
315
+ static isInstance(error) {
316
+ return AISDKError.hasMarker(error, marker14);
317
+ }
318
+ };
3
319
 
4
- // src/apertis-chat-language-model.ts
320
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.8_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
321
+ import * as z4 from "zod/v4";
322
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
323
+ import { ZodFirstPartyTypeKind } from "zod/v3";
5
324
  import {
6
- createEventSourceResponseHandler,
7
- createJsonResponseHandler,
8
- generateId,
9
- postJsonToApi
10
- } from "@ai-sdk/provider-utils";
325
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
326
+ } from "zod/v3";
327
+
328
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
329
+ var ParseError = class extends Error {
330
+ constructor(message, options) {
331
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
332
+ }
333
+ };
334
+ function noop(_arg) {
335
+ }
336
+ function createParser(callbacks) {
337
+ if (typeof callbacks == "function")
338
+ throw new TypeError(
339
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
340
+ );
341
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
342
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
343
+ function feed(newChunk) {
344
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
345
+ for (const line of complete)
346
+ parseLine(line);
347
+ incompleteLine = incomplete, isFirstChunk = false;
348
+ }
349
+ function parseLine(line) {
350
+ if (line === "") {
351
+ dispatchEvent();
352
+ return;
353
+ }
354
+ if (line.startsWith(":")) {
355
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
356
+ return;
357
+ }
358
+ const fieldSeparatorIndex = line.indexOf(":");
359
+ if (fieldSeparatorIndex !== -1) {
360
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
361
+ processField(field, value, line);
362
+ return;
363
+ }
364
+ processField(line, "", line);
365
+ }
366
+ function processField(field, value, line) {
367
+ switch (field) {
368
+ case "event":
369
+ eventType = value;
370
+ break;
371
+ case "data":
372
+ data = `${data}${value}
373
+ `;
374
+ break;
375
+ case "id":
376
+ id = value.includes("\0") ? void 0 : value;
377
+ break;
378
+ case "retry":
379
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
380
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
381
+ type: "invalid-retry",
382
+ value,
383
+ line
384
+ })
385
+ );
386
+ break;
387
+ default:
388
+ onError(
389
+ new ParseError(
390
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
391
+ { type: "unknown-field", field, value, line }
392
+ )
393
+ );
394
+ break;
395
+ }
396
+ }
397
+ function dispatchEvent() {
398
+ data.length > 0 && onEvent({
399
+ id,
400
+ event: eventType || void 0,
401
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
402
+ // then remove the last character from the data buffer.
403
+ data: data.endsWith(`
404
+ `) ? data.slice(0, -1) : data
405
+ }), id = void 0, data = "", eventType = "";
406
+ }
407
+ function reset(options = {}) {
408
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
409
+ }
410
+ return { feed, reset };
411
+ }
412
+ function splitLines(chunk) {
413
+ const lines = [];
414
+ let incompleteLine = "", searchIndex = 0;
415
+ for (; searchIndex < chunk.length; ) {
416
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
417
+ `, searchIndex);
418
+ let lineEnd = -1;
419
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
420
+ incompleteLine = chunk.slice(searchIndex);
421
+ break;
422
+ } else {
423
+ const line = chunk.slice(searchIndex, lineEnd);
424
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
425
+ ` && searchIndex++;
426
+ }
427
+ }
428
+ return [lines, incompleteLine];
429
+ }
430
+
431
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
432
+ var EventSourceParserStream = class extends TransformStream {
433
+ constructor({ onError, onRetry, onComment } = {}) {
434
+ let parser;
435
+ super({
436
+ start(controller) {
437
+ parser = createParser({
438
+ onEvent: (event) => {
439
+ controller.enqueue(event);
440
+ },
441
+ onError(error) {
442
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
443
+ },
444
+ onRetry,
445
+ onComment
446
+ });
447
+ },
448
+ transform(chunk) {
449
+ parser.feed(chunk);
450
+ }
451
+ });
452
+ }
453
+ };
454
+
455
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.8_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
456
+ function extractResponseHeaders(response) {
457
+ return Object.fromEntries([...response.headers]);
458
+ }
459
+ var { btoa, atob } = globalThis;
460
+ var name14 = "AI_DownloadError";
461
+ var marker15 = `vercel.ai.error.${name14}`;
462
+ var symbol15 = Symbol.for(marker15);
463
+ var _a15;
464
+ var _b15;
465
+ var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
466
+ constructor({
467
+ url,
468
+ statusCode,
469
+ statusText,
470
+ cause,
471
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
472
+ }) {
473
+ super({ name: name14, message, cause });
474
+ this[_a15] = true;
475
+ this.url = url;
476
+ this.statusCode = statusCode;
477
+ this.statusText = statusText;
478
+ }
479
+ static isInstance(error) {
480
+ return AISDKError.hasMarker(error, marker15);
481
+ }
482
+ };
483
+ var createIdGenerator = ({
484
+ prefix,
485
+ size = 16,
486
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
487
+ separator = "-"
488
+ } = {}) => {
489
+ const generator = () => {
490
+ const alphabetLength = alphabet.length;
491
+ const chars = new Array(size);
492
+ for (let i = 0; i < size; i++) {
493
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
494
+ }
495
+ return chars.join("");
496
+ };
497
+ if (prefix == null) {
498
+ return generator;
499
+ }
500
+ if (alphabet.includes(separator)) {
501
+ throw new InvalidArgumentError({
502
+ argument: "separator",
503
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
504
+ });
505
+ }
506
+ return () => `${prefix}${separator}${generator()}`;
507
+ };
508
+ var generateId = createIdGenerator();
509
+ function isAbortError(error) {
510
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
511
+ error.name === "TimeoutError");
512
+ }
513
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
514
+ function handleFetchError({
515
+ error,
516
+ url,
517
+ requestBodyValues
518
+ }) {
519
+ if (isAbortError(error)) {
520
+ return error;
521
+ }
522
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
523
+ const cause = error.cause;
524
+ if (cause != null) {
525
+ return new APICallError({
526
+ message: `Cannot connect to API: ${cause.message}`,
527
+ cause,
528
+ url,
529
+ requestBodyValues,
530
+ isRetryable: true
531
+ // retry when network error
532
+ });
533
+ }
534
+ }
535
+ return error;
536
+ }
537
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
538
+ var _a22, _b22, _c;
539
+ if (globalThisAny.window) {
540
+ return `runtime/browser`;
541
+ }
542
+ if ((_a22 = globalThisAny.navigator) == null ? void 0 : _a22.userAgent) {
543
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
544
+ }
545
+ if ((_c = (_b22 = globalThisAny.process) == null ? void 0 : _b22.versions) == null ? void 0 : _c.node) {
546
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
547
+ }
548
+ if (globalThisAny.EdgeRuntime) {
549
+ return `runtime/vercel-edge`;
550
+ }
551
+ return "runtime/unknown";
552
+ }
553
+ function normalizeHeaders(headers) {
554
+ if (headers == null) {
555
+ return {};
556
+ }
557
+ const normalized = {};
558
+ if (headers instanceof Headers) {
559
+ headers.forEach((value, key) => {
560
+ normalized[key.toLowerCase()] = value;
561
+ });
562
+ } else {
563
+ if (!Array.isArray(headers)) {
564
+ headers = Object.entries(headers);
565
+ }
566
+ for (const [key, value] of headers) {
567
+ if (value != null) {
568
+ normalized[key.toLowerCase()] = value;
569
+ }
570
+ }
571
+ }
572
+ return normalized;
573
+ }
574
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
575
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
576
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
577
+ normalizedHeaders.set(
578
+ "user-agent",
579
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
580
+ );
581
+ return Object.fromEntries(normalizedHeaders.entries());
582
+ }
583
+ var VERSION = true ? "4.0.8" : "0.0.0-test";
584
+ function loadApiKey({
585
+ apiKey,
586
+ environmentVariableName,
587
+ apiKeyParameterName = "apiKey",
588
+ description
589
+ }) {
590
+ if (typeof apiKey === "string") {
591
+ return apiKey;
592
+ }
593
+ if (apiKey != null) {
594
+ throw new LoadAPIKeyError({
595
+ message: `${description} API key must be a string.`
596
+ });
597
+ }
598
+ if (typeof process === "undefined") {
599
+ throw new LoadAPIKeyError({
600
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
601
+ });
602
+ }
603
+ apiKey = process.env[environmentVariableName];
604
+ if (apiKey == null) {
605
+ throw new LoadAPIKeyError({
606
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
607
+ });
608
+ }
609
+ if (typeof apiKey !== "string") {
610
+ throw new LoadAPIKeyError({
611
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
612
+ });
613
+ }
614
+ return apiKey;
615
+ }
616
+ var suspectProtoRx = /"__proto__"\s*:/;
617
+ var suspectConstructorRx = /"constructor"\s*:/;
618
+ function _parse(text) {
619
+ const obj = JSON.parse(text);
620
+ if (obj === null || typeof obj !== "object") {
621
+ return obj;
622
+ }
623
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
624
+ return obj;
625
+ }
626
+ return filter(obj);
627
+ }
628
+ function filter(obj) {
629
+ let next = [obj];
630
+ while (next.length) {
631
+ const nodes = next;
632
+ next = [];
633
+ for (const node of nodes) {
634
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
635
+ throw new SyntaxError("Object contains forbidden prototype property");
636
+ }
637
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
638
+ throw new SyntaxError("Object contains forbidden prototype property");
639
+ }
640
+ for (const key in node) {
641
+ const value = node[key];
642
+ if (value && typeof value === "object") {
643
+ next.push(value);
644
+ }
645
+ }
646
+ }
647
+ }
648
+ return obj;
649
+ }
650
+ function secureJsonParse(text) {
651
+ const { stackTraceLimit } = Error;
652
+ try {
653
+ Error.stackTraceLimit = 0;
654
+ } catch (e) {
655
+ return _parse(text);
656
+ }
657
+ try {
658
+ return _parse(text);
659
+ } finally {
660
+ Error.stackTraceLimit = stackTraceLimit;
661
+ }
662
+ }
663
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
664
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
665
+ jsonSchema2.additionalProperties = false;
666
+ const { properties } = jsonSchema2;
667
+ if (properties != null) {
668
+ for (const key of Object.keys(properties)) {
669
+ properties[key] = visit(properties[key]);
670
+ }
671
+ }
672
+ }
673
+ if (jsonSchema2.items != null) {
674
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
675
+ }
676
+ if (jsonSchema2.anyOf != null) {
677
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
678
+ }
679
+ if (jsonSchema2.allOf != null) {
680
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
681
+ }
682
+ if (jsonSchema2.oneOf != null) {
683
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
684
+ }
685
+ const { definitions } = jsonSchema2;
686
+ if (definitions != null) {
687
+ for (const key of Object.keys(definitions)) {
688
+ definitions[key] = visit(definitions[key]);
689
+ }
690
+ }
691
+ return jsonSchema2;
692
+ }
693
+ function visit(def) {
694
+ if (typeof def === "boolean") return def;
695
+ return addAdditionalPropertiesToJsonSchema(def);
696
+ }
697
+ var ignoreOverride = /* @__PURE__ */ Symbol(
698
+ "Let zodToJsonSchema decide on which parser to use"
699
+ );
700
+ var defaultOptions = {
701
+ name: void 0,
702
+ $refStrategy: "root",
703
+ basePath: ["#"],
704
+ effectStrategy: "input",
705
+ pipeStrategy: "all",
706
+ dateStrategy: "format:date-time",
707
+ mapStrategy: "entries",
708
+ removeAdditionalStrategy: "passthrough",
709
+ allowedAdditionalProperties: true,
710
+ rejectedAdditionalProperties: false,
711
+ definitionPath: "definitions",
712
+ strictUnions: false,
713
+ definitions: {},
714
+ errorMessages: false,
715
+ patternStrategy: "escape",
716
+ applyRegexFlags: false,
717
+ emailStrategy: "format:email",
718
+ base64Strategy: "contentEncoding:base64",
719
+ nameStrategy: "ref"
720
+ };
721
+ var getDefaultOptions = (options) => typeof options === "string" ? {
722
+ ...defaultOptions,
723
+ name: options
724
+ } : {
725
+ ...defaultOptions,
726
+ ...options
727
+ };
728
+ function parseAnyDef() {
729
+ return {};
730
+ }
731
+ function parseArrayDef(def, refs) {
732
+ var _a22, _b22, _c;
733
+ const res = {
734
+ type: "array"
735
+ };
736
+ if (((_a22 = def.type) == null ? void 0 : _a22._def) && ((_c = (_b22 = def.type) == null ? void 0 : _b22._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
737
+ res.items = parseDef(def.type._def, {
738
+ ...refs,
739
+ currentPath: [...refs.currentPath, "items"]
740
+ });
741
+ }
742
+ if (def.minLength) {
743
+ res.minItems = def.minLength.value;
744
+ }
745
+ if (def.maxLength) {
746
+ res.maxItems = def.maxLength.value;
747
+ }
748
+ if (def.exactLength) {
749
+ res.minItems = def.exactLength.value;
750
+ res.maxItems = def.exactLength.value;
751
+ }
752
+ return res;
753
+ }
754
+ function parseBigintDef(def) {
755
+ const res = {
756
+ type: "integer",
757
+ format: "int64"
758
+ };
759
+ if (!def.checks) return res;
760
+ for (const check of def.checks) {
761
+ switch (check.kind) {
762
+ case "min":
763
+ if (check.inclusive) {
764
+ res.minimum = check.value;
765
+ } else {
766
+ res.exclusiveMinimum = check.value;
767
+ }
768
+ break;
769
+ case "max":
770
+ if (check.inclusive) {
771
+ res.maximum = check.value;
772
+ } else {
773
+ res.exclusiveMaximum = check.value;
774
+ }
775
+ break;
776
+ case "multipleOf":
777
+ res.multipleOf = check.value;
778
+ break;
779
+ }
780
+ }
781
+ return res;
782
+ }
783
+ function parseBooleanDef() {
784
+ return { type: "boolean" };
785
+ }
786
+ function parseBrandedDef(_def, refs) {
787
+ return parseDef(_def.type._def, refs);
788
+ }
789
+ var parseCatchDef = (def, refs) => {
790
+ return parseDef(def.innerType._def, refs);
791
+ };
792
+ function parseDateDef(def, refs, overrideDateStrategy) {
793
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
794
+ if (Array.isArray(strategy)) {
795
+ return {
796
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
797
+ };
798
+ }
799
+ switch (strategy) {
800
+ case "string":
801
+ case "format:date-time":
802
+ return {
803
+ type: "string",
804
+ format: "date-time"
805
+ };
806
+ case "format:date":
807
+ return {
808
+ type: "string",
809
+ format: "date"
810
+ };
811
+ case "integer":
812
+ return integerDateParser(def);
813
+ }
814
+ }
815
+ var integerDateParser = (def) => {
816
+ const res = {
817
+ type: "integer",
818
+ format: "unix-time"
819
+ };
820
+ for (const check of def.checks) {
821
+ switch (check.kind) {
822
+ case "min":
823
+ res.minimum = check.value;
824
+ break;
825
+ case "max":
826
+ res.maximum = check.value;
827
+ break;
828
+ }
829
+ }
830
+ return res;
831
+ };
832
+ function parseDefaultDef(_def, refs) {
833
+ return {
834
+ ...parseDef(_def.innerType._def, refs),
835
+ default: _def.defaultValue()
836
+ };
837
+ }
838
+ function parseEffectsDef(_def, refs) {
839
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
840
+ }
841
+ function parseEnumDef(def) {
842
+ return {
843
+ type: "string",
844
+ enum: Array.from(def.values)
845
+ };
846
+ }
847
+ var isJsonSchema7AllOfType = (type) => {
848
+ if ("type" in type && type.type === "string") return false;
849
+ return "allOf" in type;
850
+ };
851
+ function parseIntersectionDef(def, refs) {
852
+ const allOf = [
853
+ parseDef(def.left._def, {
854
+ ...refs,
855
+ currentPath: [...refs.currentPath, "allOf", "0"]
856
+ }),
857
+ parseDef(def.right._def, {
858
+ ...refs,
859
+ currentPath: [...refs.currentPath, "allOf", "1"]
860
+ })
861
+ ].filter((x) => !!x);
862
+ const mergedAllOf = [];
863
+ allOf.forEach((schema) => {
864
+ if (isJsonSchema7AllOfType(schema)) {
865
+ mergedAllOf.push(...schema.allOf);
866
+ } else {
867
+ let nestedSchema = schema;
868
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
869
+ const { additionalProperties, ...rest } = schema;
870
+ nestedSchema = rest;
871
+ }
872
+ mergedAllOf.push(nestedSchema);
873
+ }
874
+ });
875
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
876
+ }
877
+ function parseLiteralDef(def) {
878
+ const parsedType = typeof def.value;
879
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
880
+ return {
881
+ type: Array.isArray(def.value) ? "array" : "object"
882
+ };
883
+ }
884
+ return {
885
+ type: parsedType === "bigint" ? "integer" : parsedType,
886
+ const: def.value
887
+ };
888
+ }
889
+ var emojiRegex = void 0;
890
+ var zodPatterns = {
891
+ /**
892
+ * `c` was changed to `[cC]` to replicate /i flag
893
+ */
894
+ cuid: /^[cC][^\s-]{8,}$/,
895
+ cuid2: /^[0-9a-z]+$/,
896
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
897
+ /**
898
+ * `a-z` was added to replicate /i flag
899
+ */
900
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
901
+ /**
902
+ * Constructed a valid Unicode RegExp
903
+ *
904
+ * Lazily instantiate since this type of regex isn't supported
905
+ * in all envs (e.g. React Native).
906
+ *
907
+ * See:
908
+ * https://github.com/colinhacks/zod/issues/2433
909
+ * Fix in Zod:
910
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
911
+ */
912
+ emoji: () => {
913
+ if (emojiRegex === void 0) {
914
+ emojiRegex = RegExp(
915
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
916
+ "u"
917
+ );
918
+ }
919
+ return emojiRegex;
920
+ },
921
+ /**
922
+ * Unused
923
+ */
924
+ 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}$/,
925
+ /**
926
+ * Unused
927
+ */
928
+ 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])$/,
929
+ 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])$/,
930
+ /**
931
+ * Unused
932
+ */
933
+ 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})))$/,
934
+ 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])$/,
935
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
936
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
937
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
938
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
939
+ };
940
+ function parseStringDef(def, refs) {
941
+ const res = {
942
+ type: "string"
943
+ };
944
+ if (def.checks) {
945
+ for (const check of def.checks) {
946
+ switch (check.kind) {
947
+ case "min":
948
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
949
+ break;
950
+ case "max":
951
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
952
+ break;
953
+ case "email":
954
+ switch (refs.emailStrategy) {
955
+ case "format:email":
956
+ addFormat(res, "email", check.message, refs);
957
+ break;
958
+ case "format:idn-email":
959
+ addFormat(res, "idn-email", check.message, refs);
960
+ break;
961
+ case "pattern:zod":
962
+ addPattern(res, zodPatterns.email, check.message, refs);
963
+ break;
964
+ }
965
+ break;
966
+ case "url":
967
+ addFormat(res, "uri", check.message, refs);
968
+ break;
969
+ case "uuid":
970
+ addFormat(res, "uuid", check.message, refs);
971
+ break;
972
+ case "regex":
973
+ addPattern(res, check.regex, check.message, refs);
974
+ break;
975
+ case "cuid":
976
+ addPattern(res, zodPatterns.cuid, check.message, refs);
977
+ break;
978
+ case "cuid2":
979
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
980
+ break;
981
+ case "startsWith":
982
+ addPattern(
983
+ res,
984
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
985
+ check.message,
986
+ refs
987
+ );
988
+ break;
989
+ case "endsWith":
990
+ addPattern(
991
+ res,
992
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
993
+ check.message,
994
+ refs
995
+ );
996
+ break;
997
+ case "datetime":
998
+ addFormat(res, "date-time", check.message, refs);
999
+ break;
1000
+ case "date":
1001
+ addFormat(res, "date", check.message, refs);
1002
+ break;
1003
+ case "time":
1004
+ addFormat(res, "time", check.message, refs);
1005
+ break;
1006
+ case "duration":
1007
+ addFormat(res, "duration", check.message, refs);
1008
+ break;
1009
+ case "length":
1010
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1011
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1012
+ break;
1013
+ case "includes": {
1014
+ addPattern(
1015
+ res,
1016
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1017
+ check.message,
1018
+ refs
1019
+ );
1020
+ break;
1021
+ }
1022
+ case "ip": {
1023
+ if (check.version !== "v6") {
1024
+ addFormat(res, "ipv4", check.message, refs);
1025
+ }
1026
+ if (check.version !== "v4") {
1027
+ addFormat(res, "ipv6", check.message, refs);
1028
+ }
1029
+ break;
1030
+ }
1031
+ case "base64url":
1032
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1033
+ break;
1034
+ case "jwt":
1035
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1036
+ break;
1037
+ case "cidr": {
1038
+ if (check.version !== "v6") {
1039
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1040
+ }
1041
+ if (check.version !== "v4") {
1042
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1043
+ }
1044
+ break;
1045
+ }
1046
+ case "emoji":
1047
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1048
+ break;
1049
+ case "ulid": {
1050
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1051
+ break;
1052
+ }
1053
+ case "base64": {
1054
+ switch (refs.base64Strategy) {
1055
+ case "format:binary": {
1056
+ addFormat(res, "binary", check.message, refs);
1057
+ break;
1058
+ }
1059
+ case "contentEncoding:base64": {
1060
+ res.contentEncoding = "base64";
1061
+ break;
1062
+ }
1063
+ case "pattern:zod": {
1064
+ addPattern(res, zodPatterns.base64, check.message, refs);
1065
+ break;
1066
+ }
1067
+ }
1068
+ break;
1069
+ }
1070
+ case "nanoid": {
1071
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1072
+ }
1073
+ case "toLowerCase":
1074
+ case "toUpperCase":
1075
+ case "trim":
1076
+ break;
1077
+ default:
1078
+ /* @__PURE__ */ ((_) => {
1079
+ })(check);
1080
+ }
1081
+ }
1082
+ }
1083
+ return res;
1084
+ }
1085
+ function escapeLiteralCheckValue(literal, refs) {
1086
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1087
+ }
1088
+ var ALPHA_NUMERIC = new Set(
1089
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1090
+ );
1091
+ function escapeNonAlphaNumeric(source) {
1092
+ let result = "";
1093
+ for (let i = 0; i < source.length; i++) {
1094
+ if (!ALPHA_NUMERIC.has(source[i])) {
1095
+ result += "\\";
1096
+ }
1097
+ result += source[i];
1098
+ }
1099
+ return result;
1100
+ }
1101
+ function addFormat(schema, value, message, refs) {
1102
+ var _a22;
1103
+ if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) {
1104
+ if (!schema.anyOf) {
1105
+ schema.anyOf = [];
1106
+ }
1107
+ if (schema.format) {
1108
+ schema.anyOf.push({
1109
+ format: schema.format
1110
+ });
1111
+ delete schema.format;
1112
+ }
1113
+ schema.anyOf.push({
1114
+ format: value,
1115
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
1116
+ });
1117
+ } else {
1118
+ schema.format = value;
1119
+ }
1120
+ }
1121
+ function addPattern(schema, regex, message, refs) {
1122
+ var _a22;
1123
+ if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) {
1124
+ if (!schema.allOf) {
1125
+ schema.allOf = [];
1126
+ }
1127
+ if (schema.pattern) {
1128
+ schema.allOf.push({
1129
+ pattern: schema.pattern
1130
+ });
1131
+ delete schema.pattern;
1132
+ }
1133
+ schema.allOf.push({
1134
+ pattern: stringifyRegExpWithFlags(regex, refs),
1135
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1136
+ });
1137
+ } else {
1138
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1139
+ }
1140
+ }
1141
+ function stringifyRegExpWithFlags(regex, refs) {
1142
+ var _a22;
1143
+ if (!refs.applyRegexFlags || !regex.flags) {
1144
+ return regex.source;
1145
+ }
1146
+ const flags = {
1147
+ i: regex.flags.includes("i"),
1148
+ // Case-insensitive
1149
+ m: regex.flags.includes("m"),
1150
+ // `^` and `$` matches adjacent to newline characters
1151
+ s: regex.flags.includes("s")
1152
+ // `.` matches newlines
1153
+ };
1154
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1155
+ let pattern = "";
1156
+ let isEscaped = false;
1157
+ let inCharGroup = false;
1158
+ let inCharRange = false;
1159
+ for (let i = 0; i < source.length; i++) {
1160
+ if (isEscaped) {
1161
+ pattern += source[i];
1162
+ isEscaped = false;
1163
+ continue;
1164
+ }
1165
+ if (flags.i) {
1166
+ if (inCharGroup) {
1167
+ if (source[i].match(/[a-z]/)) {
1168
+ if (inCharRange) {
1169
+ pattern += source[i];
1170
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1171
+ inCharRange = false;
1172
+ } else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) {
1173
+ pattern += source[i];
1174
+ inCharRange = true;
1175
+ } else {
1176
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1177
+ }
1178
+ continue;
1179
+ }
1180
+ } else if (source[i].match(/[a-z]/)) {
1181
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1182
+ continue;
1183
+ }
1184
+ }
1185
+ if (flags.m) {
1186
+ if (source[i] === "^") {
1187
+ pattern += `(^|(?<=[\r
1188
+ ]))`;
1189
+ continue;
1190
+ } else if (source[i] === "$") {
1191
+ pattern += `($|(?=[\r
1192
+ ]))`;
1193
+ continue;
1194
+ }
1195
+ }
1196
+ if (flags.s && source[i] === ".") {
1197
+ pattern += inCharGroup ? `${source[i]}\r
1198
+ ` : `[${source[i]}\r
1199
+ ]`;
1200
+ continue;
1201
+ }
1202
+ pattern += source[i];
1203
+ if (source[i] === "\\") {
1204
+ isEscaped = true;
1205
+ } else if (inCharGroup && source[i] === "]") {
1206
+ inCharGroup = false;
1207
+ } else if (!inCharGroup && source[i] === "[") {
1208
+ inCharGroup = true;
1209
+ }
1210
+ }
1211
+ try {
1212
+ new RegExp(pattern);
1213
+ } catch (e) {
1214
+ console.warn(
1215
+ `Could not convert regex pattern at ${refs.currentPath.join(
1216
+ "/"
1217
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1218
+ );
1219
+ return regex.source;
1220
+ }
1221
+ return pattern;
1222
+ }
1223
+ function parseRecordDef(def, refs) {
1224
+ var _a22, _b22, _c, _d, _e, _f;
1225
+ const schema = {
1226
+ type: "object",
1227
+ additionalProperties: (_a22 = parseDef(def.valueType._def, {
1228
+ ...refs,
1229
+ currentPath: [...refs.currentPath, "additionalProperties"]
1230
+ })) != null ? _a22 : refs.allowedAdditionalProperties
1231
+ };
1232
+ if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1233
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1234
+ return {
1235
+ ...schema,
1236
+ propertyNames: keyType
1237
+ };
1238
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1239
+ return {
1240
+ ...schema,
1241
+ propertyNames: {
1242
+ enum: def.keyType._def.values
1243
+ }
1244
+ };
1245
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1246
+ const { type, ...keyType } = parseBrandedDef(
1247
+ def.keyType._def,
1248
+ refs
1249
+ );
1250
+ return {
1251
+ ...schema,
1252
+ propertyNames: keyType
1253
+ };
1254
+ }
1255
+ return schema;
1256
+ }
1257
+ function parseMapDef(def, refs) {
1258
+ if (refs.mapStrategy === "record") {
1259
+ return parseRecordDef(def, refs);
1260
+ }
1261
+ const keys = parseDef(def.keyType._def, {
1262
+ ...refs,
1263
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1264
+ }) || parseAnyDef();
1265
+ const values = parseDef(def.valueType._def, {
1266
+ ...refs,
1267
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1268
+ }) || parseAnyDef();
1269
+ return {
1270
+ type: "array",
1271
+ maxItems: 125,
1272
+ items: {
1273
+ type: "array",
1274
+ items: [keys, values],
1275
+ minItems: 2,
1276
+ maxItems: 2
1277
+ }
1278
+ };
1279
+ }
1280
+ function parseNativeEnumDef(def) {
1281
+ const object = def.values;
1282
+ const actualKeys = Object.keys(def.values).filter((key) => {
1283
+ return typeof object[object[key]] !== "number";
1284
+ });
1285
+ const actualValues = actualKeys.map((key) => object[key]);
1286
+ const parsedTypes = Array.from(
1287
+ new Set(actualValues.map((values) => typeof values))
1288
+ );
1289
+ return {
1290
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1291
+ enum: actualValues
1292
+ };
1293
+ }
1294
+ function parseNeverDef() {
1295
+ return { not: parseAnyDef() };
1296
+ }
1297
+ function parseNullDef() {
1298
+ return {
1299
+ type: "null"
1300
+ };
1301
+ }
1302
+ var primitiveMappings = {
1303
+ ZodString: "string",
1304
+ ZodNumber: "number",
1305
+ ZodBigInt: "integer",
1306
+ ZodBoolean: "boolean",
1307
+ ZodNull: "null"
1308
+ };
1309
+ function parseUnionDef(def, refs) {
1310
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1311
+ if (options.every(
1312
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1313
+ )) {
1314
+ const types = options.reduce((types2, x) => {
1315
+ const type = primitiveMappings[x._def.typeName];
1316
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1317
+ }, []);
1318
+ return {
1319
+ type: types.length > 1 ? types : types[0]
1320
+ };
1321
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1322
+ const types = options.reduce(
1323
+ (acc, x) => {
1324
+ const type = typeof x._def.value;
1325
+ switch (type) {
1326
+ case "string":
1327
+ case "number":
1328
+ case "boolean":
1329
+ return [...acc, type];
1330
+ case "bigint":
1331
+ return [...acc, "integer"];
1332
+ case "object":
1333
+ if (x._def.value === null) return [...acc, "null"];
1334
+ case "symbol":
1335
+ case "undefined":
1336
+ case "function":
1337
+ default:
1338
+ return acc;
1339
+ }
1340
+ },
1341
+ []
1342
+ );
1343
+ if (types.length === options.length) {
1344
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1345
+ return {
1346
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1347
+ enum: options.reduce(
1348
+ (acc, x) => {
1349
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1350
+ },
1351
+ []
1352
+ )
1353
+ };
1354
+ }
1355
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1356
+ return {
1357
+ type: "string",
1358
+ enum: options.reduce(
1359
+ (acc, x) => [
1360
+ ...acc,
1361
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1362
+ ],
1363
+ []
1364
+ )
1365
+ };
1366
+ }
1367
+ return asAnyOf(def, refs);
1368
+ }
1369
+ var asAnyOf = (def, refs) => {
1370
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1371
+ (x, i) => parseDef(x._def, {
1372
+ ...refs,
1373
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1374
+ })
1375
+ ).filter(
1376
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1377
+ );
1378
+ return anyOf.length ? { anyOf } : void 0;
1379
+ };
1380
+ function parseNullableDef(def, refs) {
1381
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1382
+ def.innerType._def.typeName
1383
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1384
+ return {
1385
+ type: [
1386
+ primitiveMappings[def.innerType._def.typeName],
1387
+ "null"
1388
+ ]
1389
+ };
1390
+ }
1391
+ const base = parseDef(def.innerType._def, {
1392
+ ...refs,
1393
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1394
+ });
1395
+ return base && { anyOf: [base, { type: "null" }] };
1396
+ }
1397
+ function parseNumberDef(def) {
1398
+ const res = {
1399
+ type: "number"
1400
+ };
1401
+ if (!def.checks) return res;
1402
+ for (const check of def.checks) {
1403
+ switch (check.kind) {
1404
+ case "int":
1405
+ res.type = "integer";
1406
+ break;
1407
+ case "min":
1408
+ if (check.inclusive) {
1409
+ res.minimum = check.value;
1410
+ } else {
1411
+ res.exclusiveMinimum = check.value;
1412
+ }
1413
+ break;
1414
+ case "max":
1415
+ if (check.inclusive) {
1416
+ res.maximum = check.value;
1417
+ } else {
1418
+ res.exclusiveMaximum = check.value;
1419
+ }
1420
+ break;
1421
+ case "multipleOf":
1422
+ res.multipleOf = check.value;
1423
+ break;
1424
+ }
1425
+ }
1426
+ return res;
1427
+ }
1428
+ function parseObjectDef(def, refs) {
1429
+ const result = {
1430
+ type: "object",
1431
+ properties: {}
1432
+ };
1433
+ const required = [];
1434
+ const shape = def.shape();
1435
+ for (const propName in shape) {
1436
+ let propDef = shape[propName];
1437
+ if (propDef === void 0 || propDef._def === void 0) {
1438
+ continue;
1439
+ }
1440
+ const propOptional = safeIsOptional(propDef);
1441
+ const parsedDef = parseDef(propDef._def, {
1442
+ ...refs,
1443
+ currentPath: [...refs.currentPath, "properties", propName],
1444
+ propertyPath: [...refs.currentPath, "properties", propName]
1445
+ });
1446
+ if (parsedDef === void 0) {
1447
+ continue;
1448
+ }
1449
+ result.properties[propName] = parsedDef;
1450
+ if (!propOptional) {
1451
+ required.push(propName);
1452
+ }
1453
+ }
1454
+ if (required.length) {
1455
+ result.required = required;
1456
+ }
1457
+ const additionalProperties = decideAdditionalProperties(def, refs);
1458
+ if (additionalProperties !== void 0) {
1459
+ result.additionalProperties = additionalProperties;
1460
+ }
1461
+ return result;
1462
+ }
1463
+ function decideAdditionalProperties(def, refs) {
1464
+ if (def.catchall._def.typeName !== "ZodNever") {
1465
+ return parseDef(def.catchall._def, {
1466
+ ...refs,
1467
+ currentPath: [...refs.currentPath, "additionalProperties"]
1468
+ });
1469
+ }
1470
+ switch (def.unknownKeys) {
1471
+ case "passthrough":
1472
+ return refs.allowedAdditionalProperties;
1473
+ case "strict":
1474
+ return refs.rejectedAdditionalProperties;
1475
+ case "strip":
1476
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1477
+ }
1478
+ }
1479
+ function safeIsOptional(schema) {
1480
+ try {
1481
+ return schema.isOptional();
1482
+ } catch (e) {
1483
+ return true;
1484
+ }
1485
+ }
1486
+ var parseOptionalDef = (def, refs) => {
1487
+ var _a22;
1488
+ if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) {
1489
+ return parseDef(def.innerType._def, refs);
1490
+ }
1491
+ const innerSchema = parseDef(def.innerType._def, {
1492
+ ...refs,
1493
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1494
+ });
1495
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1496
+ };
1497
+ var parsePipelineDef = (def, refs) => {
1498
+ if (refs.pipeStrategy === "input") {
1499
+ return parseDef(def.in._def, refs);
1500
+ } else if (refs.pipeStrategy === "output") {
1501
+ return parseDef(def.out._def, refs);
1502
+ }
1503
+ const a = parseDef(def.in._def, {
1504
+ ...refs,
1505
+ currentPath: [...refs.currentPath, "allOf", "0"]
1506
+ });
1507
+ const b = parseDef(def.out._def, {
1508
+ ...refs,
1509
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1510
+ });
1511
+ return {
1512
+ allOf: [a, b].filter((x) => x !== void 0)
1513
+ };
1514
+ };
1515
+ function parsePromiseDef(def, refs) {
1516
+ return parseDef(def.type._def, refs);
1517
+ }
1518
+ function parseSetDef(def, refs) {
1519
+ const items = parseDef(def.valueType._def, {
1520
+ ...refs,
1521
+ currentPath: [...refs.currentPath, "items"]
1522
+ });
1523
+ const schema = {
1524
+ type: "array",
1525
+ uniqueItems: true,
1526
+ items
1527
+ };
1528
+ if (def.minSize) {
1529
+ schema.minItems = def.minSize.value;
1530
+ }
1531
+ if (def.maxSize) {
1532
+ schema.maxItems = def.maxSize.value;
1533
+ }
1534
+ return schema;
1535
+ }
1536
+ function parseTupleDef(def, refs) {
1537
+ if (def.rest) {
1538
+ return {
1539
+ type: "array",
1540
+ minItems: def.items.length,
1541
+ items: def.items.map(
1542
+ (x, i) => parseDef(x._def, {
1543
+ ...refs,
1544
+ currentPath: [...refs.currentPath, "items", `${i}`]
1545
+ })
1546
+ ).reduce(
1547
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1548
+ []
1549
+ ),
1550
+ additionalItems: parseDef(def.rest._def, {
1551
+ ...refs,
1552
+ currentPath: [...refs.currentPath, "additionalItems"]
1553
+ })
1554
+ };
1555
+ } else {
1556
+ return {
1557
+ type: "array",
1558
+ minItems: def.items.length,
1559
+ maxItems: def.items.length,
1560
+ items: def.items.map(
1561
+ (x, i) => parseDef(x._def, {
1562
+ ...refs,
1563
+ currentPath: [...refs.currentPath, "items", `${i}`]
1564
+ })
1565
+ ).reduce(
1566
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1567
+ []
1568
+ )
1569
+ };
1570
+ }
1571
+ }
1572
+ function parseUndefinedDef() {
1573
+ return {
1574
+ not: parseAnyDef()
1575
+ };
1576
+ }
1577
+ function parseUnknownDef() {
1578
+ return parseAnyDef();
1579
+ }
1580
+ var parseReadonlyDef = (def, refs) => {
1581
+ return parseDef(def.innerType._def, refs);
1582
+ };
1583
+ var selectParser = (def, typeName, refs) => {
1584
+ switch (typeName) {
1585
+ case ZodFirstPartyTypeKind3.ZodString:
1586
+ return parseStringDef(def, refs);
1587
+ case ZodFirstPartyTypeKind3.ZodNumber:
1588
+ return parseNumberDef(def);
1589
+ case ZodFirstPartyTypeKind3.ZodObject:
1590
+ return parseObjectDef(def, refs);
1591
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1592
+ return parseBigintDef(def);
1593
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1594
+ return parseBooleanDef();
1595
+ case ZodFirstPartyTypeKind3.ZodDate:
1596
+ return parseDateDef(def, refs);
1597
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1598
+ return parseUndefinedDef();
1599
+ case ZodFirstPartyTypeKind3.ZodNull:
1600
+ return parseNullDef();
1601
+ case ZodFirstPartyTypeKind3.ZodArray:
1602
+ return parseArrayDef(def, refs);
1603
+ case ZodFirstPartyTypeKind3.ZodUnion:
1604
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1605
+ return parseUnionDef(def, refs);
1606
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1607
+ return parseIntersectionDef(def, refs);
1608
+ case ZodFirstPartyTypeKind3.ZodTuple:
1609
+ return parseTupleDef(def, refs);
1610
+ case ZodFirstPartyTypeKind3.ZodRecord:
1611
+ return parseRecordDef(def, refs);
1612
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1613
+ return parseLiteralDef(def);
1614
+ case ZodFirstPartyTypeKind3.ZodEnum:
1615
+ return parseEnumDef(def);
1616
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1617
+ return parseNativeEnumDef(def);
1618
+ case ZodFirstPartyTypeKind3.ZodNullable:
1619
+ return parseNullableDef(def, refs);
1620
+ case ZodFirstPartyTypeKind3.ZodOptional:
1621
+ return parseOptionalDef(def, refs);
1622
+ case ZodFirstPartyTypeKind3.ZodMap:
1623
+ return parseMapDef(def, refs);
1624
+ case ZodFirstPartyTypeKind3.ZodSet:
1625
+ return parseSetDef(def, refs);
1626
+ case ZodFirstPartyTypeKind3.ZodLazy:
1627
+ return () => def.getter()._def;
1628
+ case ZodFirstPartyTypeKind3.ZodPromise:
1629
+ return parsePromiseDef(def, refs);
1630
+ case ZodFirstPartyTypeKind3.ZodNaN:
1631
+ case ZodFirstPartyTypeKind3.ZodNever:
1632
+ return parseNeverDef();
1633
+ case ZodFirstPartyTypeKind3.ZodEffects:
1634
+ return parseEffectsDef(def, refs);
1635
+ case ZodFirstPartyTypeKind3.ZodAny:
1636
+ return parseAnyDef();
1637
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1638
+ return parseUnknownDef();
1639
+ case ZodFirstPartyTypeKind3.ZodDefault:
1640
+ return parseDefaultDef(def, refs);
1641
+ case ZodFirstPartyTypeKind3.ZodBranded:
1642
+ return parseBrandedDef(def, refs);
1643
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1644
+ return parseReadonlyDef(def, refs);
1645
+ case ZodFirstPartyTypeKind3.ZodCatch:
1646
+ return parseCatchDef(def, refs);
1647
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1648
+ return parsePipelineDef(def, refs);
1649
+ case ZodFirstPartyTypeKind3.ZodFunction:
1650
+ case ZodFirstPartyTypeKind3.ZodVoid:
1651
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1652
+ return void 0;
1653
+ default:
1654
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1655
+ }
1656
+ };
1657
+ var getRelativePath = (pathA, pathB) => {
1658
+ let i = 0;
1659
+ for (; i < pathA.length && i < pathB.length; i++) {
1660
+ if (pathA[i] !== pathB[i]) break;
1661
+ }
1662
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1663
+ };
1664
+ function parseDef(def, refs, forceResolution = false) {
1665
+ var _a22;
1666
+ const seenItem = refs.seen.get(def);
1667
+ if (refs.override) {
1668
+ const overrideResult = (_a22 = refs.override) == null ? void 0 : _a22.call(
1669
+ refs,
1670
+ def,
1671
+ refs,
1672
+ seenItem,
1673
+ forceResolution
1674
+ );
1675
+ if (overrideResult !== ignoreOverride) {
1676
+ return overrideResult;
1677
+ }
1678
+ }
1679
+ if (seenItem && !forceResolution) {
1680
+ const seenSchema = get$ref(seenItem, refs);
1681
+ if (seenSchema !== void 0) {
1682
+ return seenSchema;
1683
+ }
1684
+ }
1685
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1686
+ refs.seen.set(def, newItem);
1687
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1688
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1689
+ if (jsonSchema2) {
1690
+ addMeta(def, refs, jsonSchema2);
1691
+ }
1692
+ if (refs.postProcess) {
1693
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1694
+ newItem.jsonSchema = jsonSchema2;
1695
+ return postProcessResult;
1696
+ }
1697
+ newItem.jsonSchema = jsonSchema2;
1698
+ return jsonSchema2;
1699
+ }
1700
+ var get$ref = (item, refs) => {
1701
+ switch (refs.$refStrategy) {
1702
+ case "root":
1703
+ return { $ref: item.path.join("/") };
1704
+ case "relative":
1705
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1706
+ case "none":
1707
+ case "seen": {
1708
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1709
+ console.warn(
1710
+ `Recursive reference detected at ${refs.currentPath.join(
1711
+ "/"
1712
+ )}! Defaulting to any`
1713
+ );
1714
+ return parseAnyDef();
1715
+ }
1716
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1717
+ }
1718
+ }
1719
+ };
1720
+ var addMeta = (def, refs, jsonSchema2) => {
1721
+ if (def.description) {
1722
+ jsonSchema2.description = def.description;
1723
+ }
1724
+ return jsonSchema2;
1725
+ };
1726
+ var getRefs = (options) => {
1727
+ const _options = getDefaultOptions(options);
1728
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1729
+ return {
1730
+ ..._options,
1731
+ currentPath,
1732
+ propertyPath: void 0,
1733
+ seen: new Map(
1734
+ Object.entries(_options.definitions).map(([name22, def]) => [
1735
+ def._def,
1736
+ {
1737
+ def: def._def,
1738
+ path: [..._options.basePath, _options.definitionPath, name22],
1739
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1740
+ jsonSchema: void 0
1741
+ }
1742
+ ])
1743
+ )
1744
+ };
1745
+ };
1746
+ var zod3ToJsonSchema = (schema, options) => {
1747
+ var _a22;
1748
+ const refs = getRefs(options);
1749
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1750
+ (acc, [name32, schema2]) => {
1751
+ var _a32;
1752
+ return {
1753
+ ...acc,
1754
+ [name32]: (_a32 = parseDef(
1755
+ schema2._def,
1756
+ {
1757
+ ...refs,
1758
+ currentPath: [...refs.basePath, refs.definitionPath, name32]
1759
+ },
1760
+ true
1761
+ )) != null ? _a32 : parseAnyDef()
1762
+ };
1763
+ },
1764
+ {}
1765
+ ) : void 0;
1766
+ const name22 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1767
+ const main = (_a22 = parseDef(
1768
+ schema._def,
1769
+ name22 === void 0 ? refs : {
1770
+ ...refs,
1771
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
1772
+ },
1773
+ false
1774
+ )) != null ? _a22 : parseAnyDef();
1775
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1776
+ if (title !== void 0) {
1777
+ main.title = title;
1778
+ }
1779
+ const combined = name22 === void 0 ? definitions ? {
1780
+ ...main,
1781
+ [refs.definitionPath]: definitions
1782
+ } : main : {
1783
+ $ref: [
1784
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1785
+ refs.definitionPath,
1786
+ name22
1787
+ ].join("/"),
1788
+ [refs.definitionPath]: {
1789
+ ...definitions,
1790
+ [name22]: main
1791
+ }
1792
+ };
1793
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1794
+ return combined;
1795
+ };
1796
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1797
+ function jsonSchema(jsonSchema2, {
1798
+ validate
1799
+ } = {}) {
1800
+ return {
1801
+ [schemaSymbol]: true,
1802
+ _type: void 0,
1803
+ // should never be used directly
1804
+ get jsonSchema() {
1805
+ if (typeof jsonSchema2 === "function") {
1806
+ jsonSchema2 = jsonSchema2();
1807
+ }
1808
+ return jsonSchema2;
1809
+ },
1810
+ validate
1811
+ };
1812
+ }
1813
+ function isSchema(value) {
1814
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1815
+ }
1816
+ function asSchema(schema) {
1817
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
1818
+ }
1819
+ function standardSchema(standardSchema2) {
1820
+ return jsonSchema(
1821
+ () => addAdditionalPropertiesToJsonSchema(
1822
+ standardSchema2["~standard"].jsonSchema.input({
1823
+ target: "draft-07"
1824
+ })
1825
+ ),
1826
+ {
1827
+ validate: async (value) => {
1828
+ const result = await standardSchema2["~standard"].validate(value);
1829
+ return "value" in result ? { success: true, value: result.value } : {
1830
+ success: false,
1831
+ error: new TypeValidationError({
1832
+ value,
1833
+ cause: result.issues
1834
+ })
1835
+ };
1836
+ }
1837
+ }
1838
+ );
1839
+ }
1840
+ function zod3Schema(zodSchema2, options) {
1841
+ var _a22;
1842
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1843
+ return jsonSchema(
1844
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1845
+ () => zod3ToJsonSchema(zodSchema2, {
1846
+ $refStrategy: useReferences ? "root" : "none"
1847
+ }),
1848
+ {
1849
+ validate: async (value) => {
1850
+ const result = await zodSchema2.safeParseAsync(value);
1851
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1852
+ }
1853
+ }
1854
+ );
1855
+ }
1856
+ function zod4Schema(zodSchema2, options) {
1857
+ var _a22;
1858
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1859
+ return jsonSchema(
1860
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1861
+ () => addAdditionalPropertiesToJsonSchema(
1862
+ z4.toJSONSchema(zodSchema2, {
1863
+ target: "draft-7",
1864
+ io: "input",
1865
+ reused: useReferences ? "ref" : "inline"
1866
+ })
1867
+ ),
1868
+ {
1869
+ validate: async (value) => {
1870
+ const result = await z4.safeParseAsync(zodSchema2, value);
1871
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1872
+ }
1873
+ }
1874
+ );
1875
+ }
1876
+ function isZod4Schema(zodSchema2) {
1877
+ return "_zod" in zodSchema2;
1878
+ }
1879
+ function zodSchema(zodSchema2, options) {
1880
+ if (isZod4Schema(zodSchema2)) {
1881
+ return zod4Schema(zodSchema2, options);
1882
+ } else {
1883
+ return zod3Schema(zodSchema2, options);
1884
+ }
1885
+ }
1886
+ async function validateTypes({
1887
+ value,
1888
+ schema
1889
+ }) {
1890
+ const result = await safeValidateTypes({ value, schema });
1891
+ if (!result.success) {
1892
+ throw TypeValidationError.wrap({ value, cause: result.error });
1893
+ }
1894
+ return result.value;
1895
+ }
1896
+ async function safeValidateTypes({
1897
+ value,
1898
+ schema
1899
+ }) {
1900
+ const actualSchema = asSchema(schema);
1901
+ try {
1902
+ if (actualSchema.validate == null) {
1903
+ return { success: true, value, rawValue: value };
1904
+ }
1905
+ const result = await actualSchema.validate(value);
1906
+ if (result.success) {
1907
+ return { success: true, value: result.value, rawValue: value };
1908
+ }
1909
+ return {
1910
+ success: false,
1911
+ error: TypeValidationError.wrap({ value, cause: result.error }),
1912
+ rawValue: value
1913
+ };
1914
+ } catch (error) {
1915
+ return {
1916
+ success: false,
1917
+ error: TypeValidationError.wrap({ value, cause: error }),
1918
+ rawValue: value
1919
+ };
1920
+ }
1921
+ }
1922
+ async function parseJSON({
1923
+ text,
1924
+ schema
1925
+ }) {
1926
+ try {
1927
+ const value = secureJsonParse(text);
1928
+ if (schema == null) {
1929
+ return value;
1930
+ }
1931
+ return validateTypes({ value, schema });
1932
+ } catch (error) {
1933
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
1934
+ throw error;
1935
+ }
1936
+ throw new JSONParseError({ text, cause: error });
1937
+ }
1938
+ }
1939
+ async function safeParseJSON({
1940
+ text,
1941
+ schema
1942
+ }) {
1943
+ try {
1944
+ const value = secureJsonParse(text);
1945
+ if (schema == null) {
1946
+ return { success: true, value, rawValue: value };
1947
+ }
1948
+ return await safeValidateTypes({ value, schema });
1949
+ } catch (error) {
1950
+ return {
1951
+ success: false,
1952
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
1953
+ rawValue: void 0
1954
+ };
1955
+ }
1956
+ }
1957
+ function parseJsonEventStream({
1958
+ stream,
1959
+ schema
1960
+ }) {
1961
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
1962
+ new TransformStream({
1963
+ async transform({ data }, controller) {
1964
+ if (data === "[DONE]") {
1965
+ return;
1966
+ }
1967
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
1968
+ }
1969
+ })
1970
+ );
1971
+ }
1972
+ var getOriginalFetch2 = () => globalThis.fetch;
1973
+ var postJsonToApi = async ({
1974
+ url,
1975
+ headers,
1976
+ body,
1977
+ failedResponseHandler,
1978
+ successfulResponseHandler,
1979
+ abortSignal,
1980
+ fetch: fetch2
1981
+ }) => postToApi({
1982
+ url,
1983
+ headers: {
1984
+ "Content-Type": "application/json",
1985
+ ...headers
1986
+ },
1987
+ body: {
1988
+ content: JSON.stringify(body),
1989
+ values: body
1990
+ },
1991
+ failedResponseHandler,
1992
+ successfulResponseHandler,
1993
+ abortSignal,
1994
+ fetch: fetch2
1995
+ });
1996
+ var postToApi = async ({
1997
+ url,
1998
+ headers = {},
1999
+ body,
2000
+ successfulResponseHandler,
2001
+ failedResponseHandler,
2002
+ abortSignal,
2003
+ fetch: fetch2 = getOriginalFetch2()
2004
+ }) => {
2005
+ try {
2006
+ const response = await fetch2(url, {
2007
+ method: "POST",
2008
+ headers: withUserAgentSuffix(
2009
+ headers,
2010
+ `ai-sdk/provider-utils/${VERSION}`,
2011
+ getRuntimeEnvironmentUserAgent()
2012
+ ),
2013
+ body: body.content,
2014
+ signal: abortSignal
2015
+ });
2016
+ const responseHeaders = extractResponseHeaders(response);
2017
+ if (!response.ok) {
2018
+ let errorInformation;
2019
+ try {
2020
+ errorInformation = await failedResponseHandler({
2021
+ response,
2022
+ url,
2023
+ requestBodyValues: body.values
2024
+ });
2025
+ } catch (error) {
2026
+ if (isAbortError(error) || APICallError.isInstance(error)) {
2027
+ throw error;
2028
+ }
2029
+ throw new APICallError({
2030
+ message: "Failed to process error response",
2031
+ cause: error,
2032
+ statusCode: response.status,
2033
+ url,
2034
+ responseHeaders,
2035
+ requestBodyValues: body.values
2036
+ });
2037
+ }
2038
+ throw errorInformation.value;
2039
+ }
2040
+ try {
2041
+ return await successfulResponseHandler({
2042
+ response,
2043
+ url,
2044
+ requestBodyValues: body.values
2045
+ });
2046
+ } catch (error) {
2047
+ if (error instanceof Error) {
2048
+ if (isAbortError(error) || APICallError.isInstance(error)) {
2049
+ throw error;
2050
+ }
2051
+ }
2052
+ throw new APICallError({
2053
+ message: "Failed to process successful response",
2054
+ cause: error,
2055
+ statusCode: response.status,
2056
+ url,
2057
+ responseHeaders,
2058
+ requestBodyValues: body.values
2059
+ });
2060
+ }
2061
+ } catch (error) {
2062
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
2063
+ }
2064
+ };
2065
+ var createJsonErrorResponseHandler = ({
2066
+ errorSchema,
2067
+ errorToMessage,
2068
+ isRetryable
2069
+ }) => async ({ response, url, requestBodyValues }) => {
2070
+ const responseBody = await response.text();
2071
+ const responseHeaders = extractResponseHeaders(response);
2072
+ if (responseBody.trim() === "") {
2073
+ return {
2074
+ responseHeaders,
2075
+ value: new APICallError({
2076
+ message: response.statusText,
2077
+ url,
2078
+ requestBodyValues,
2079
+ statusCode: response.status,
2080
+ responseHeaders,
2081
+ responseBody,
2082
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2083
+ })
2084
+ };
2085
+ }
2086
+ try {
2087
+ const parsedError = await parseJSON({
2088
+ text: responseBody,
2089
+ schema: errorSchema
2090
+ });
2091
+ return {
2092
+ responseHeaders,
2093
+ value: new APICallError({
2094
+ message: errorToMessage(parsedError),
2095
+ url,
2096
+ requestBodyValues,
2097
+ statusCode: response.status,
2098
+ responseHeaders,
2099
+ responseBody,
2100
+ data: parsedError,
2101
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
2102
+ })
2103
+ };
2104
+ } catch (parseError) {
2105
+ return {
2106
+ responseHeaders,
2107
+ value: new APICallError({
2108
+ message: response.statusText,
2109
+ url,
2110
+ requestBodyValues,
2111
+ statusCode: response.status,
2112
+ responseHeaders,
2113
+ responseBody,
2114
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2115
+ })
2116
+ };
2117
+ }
2118
+ };
2119
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
2120
+ const responseHeaders = extractResponseHeaders(response);
2121
+ if (response.body == null) {
2122
+ throw new EmptyResponseBodyError({});
2123
+ }
2124
+ return {
2125
+ responseHeaders,
2126
+ value: parseJsonEventStream({
2127
+ stream: response.body,
2128
+ schema: chunkSchema
2129
+ })
2130
+ };
2131
+ };
2132
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
2133
+ const responseBody = await response.text();
2134
+ const parsedResult = await safeParseJSON({
2135
+ text: responseBody,
2136
+ schema: responseSchema
2137
+ });
2138
+ const responseHeaders = extractResponseHeaders(response);
2139
+ if (!parsedResult.success) {
2140
+ throw new APICallError({
2141
+ message: "Invalid JSON response",
2142
+ cause: parsedResult.error,
2143
+ statusCode: response.status,
2144
+ responseHeaders,
2145
+ responseBody,
2146
+ url,
2147
+ requestBodyValues
2148
+ });
2149
+ }
2150
+ return {
2151
+ responseHeaders,
2152
+ value: parsedResult.value,
2153
+ rawValue: parsedResult.rawValue
2154
+ };
2155
+ };
2156
+ function withoutTrailingSlash(url) {
2157
+ return url == null ? void 0 : url.replace(/\/$/, "");
2158
+ }
11
2159
 
12
2160
  // src/apertis-error.ts
13
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
14
2161
  import { z } from "zod";
15
2162
  var apertisErrorSchema = z.object({
16
2163
  error: z.object({
@@ -92,21 +2239,29 @@ var openAIChatChunkSchema = z2.object({
92
2239
  });
93
2240
 
94
2241
  // src/utils/map-finish-reason.ts
95
- function mapApertisFinishReason(finishReason) {
96
- const raw = finishReason ?? void 0;
2242
+ function normalizeFinishReason(finishReason) {
97
2243
  switch (finishReason) {
98
2244
  case "stop":
99
- return { unified: "stop", raw };
2245
+ return "stop";
100
2246
  case "length":
101
- return { unified: "length", raw };
2247
+ return "length";
102
2248
  case "tool_calls":
103
- return { unified: "tool-calls", raw };
2249
+ return "tool-calls";
104
2250
  case "content_filter":
105
- return { unified: "content-filter", raw };
2251
+ return "content-filter";
106
2252
  default:
107
- return { unified: "other", raw };
2253
+ return "other";
108
2254
  }
109
2255
  }
2256
+ function mapApertisFinishReason(finishReason) {
2257
+ return {
2258
+ unified: normalizeFinishReason(finishReason),
2259
+ raw: finishReason ?? void 0
2260
+ };
2261
+ }
2262
+ function mapApertisFinishReasonV2(finishReason) {
2263
+ return normalizeFinishReason(finishReason);
2264
+ }
110
2265
 
111
2266
  // src/utils/convert-to-openai-messages.ts
112
2267
  function convertToOpenAIMessages(prompt) {
@@ -193,62 +2348,279 @@ function convertToOpenAIMessages(prompt) {
193
2348
  content = "{}";
194
2349
  }
195
2350
  }
196
- messages.push({
197
- role: "tool",
198
- tool_call_id: result.toolCallId,
199
- content
2351
+ messages.push({
2352
+ role: "tool",
2353
+ tool_call_id: result.toolCallId,
2354
+ content
2355
+ });
2356
+ }
2357
+ break;
2358
+ }
2359
+ }
2360
+ return messages;
2361
+ }
2362
+
2363
+ // src/utils/convert-to-openai-tools.ts
2364
+ function convertToOpenAITools(tools) {
2365
+ if (!tools || tools.length === 0) return void 0;
2366
+ return tools.map((tool) => ({
2367
+ type: "function",
2368
+ function: {
2369
+ name: tool.name,
2370
+ description: tool.description,
2371
+ parameters: tool.inputSchema
2372
+ }
2373
+ }));
2374
+ }
2375
+ function convertToOpenAIToolChoice(toolChoice) {
2376
+ if (!toolChoice) return void 0;
2377
+ switch (toolChoice.type) {
2378
+ case "none":
2379
+ return "none";
2380
+ case "auto":
2381
+ return "auto";
2382
+ case "required":
2383
+ return "required";
2384
+ case "tool":
2385
+ if (!toolChoice.toolName) return void 0;
2386
+ return {
2387
+ type: "function",
2388
+ function: { name: toolChoice.toolName }
2389
+ };
2390
+ default:
2391
+ return void 0;
2392
+ }
2393
+ }
2394
+
2395
+ // src/apertis-chat-language-model.ts
2396
+ var ApertisChatLanguageModel = class {
2397
+ constructor(modelId, settings, config) {
2398
+ this.modelId = modelId;
2399
+ this.settings = settings;
2400
+ this.config = config;
2401
+ }
2402
+ specificationVersion = "v3";
2403
+ /**
2404
+ * Supported URL patterns for different media types.
2405
+ * Supports HTTP(S) image URLs for direct URL passing.
2406
+ */
2407
+ supportedUrls = {
2408
+ "image/*": [/^https?:\/\/.+$/]
2409
+ };
2410
+ get provider() {
2411
+ return this.config.provider;
2412
+ }
2413
+ async doGenerate(options) {
2414
+ const body = this.buildRequestBody(options, false);
2415
+ const { value: response } = await postJsonToApi({
2416
+ url: `${this.config.baseURL}/chat/completions`,
2417
+ headers: this.config.headers(),
2418
+ body,
2419
+ failedResponseHandler: apertisFailedResponseHandler,
2420
+ successfulResponseHandler: createJsonResponseHandler(
2421
+ openAIChatResponseSchema
2422
+ ),
2423
+ fetch: this.config.fetch,
2424
+ abortSignal: options.abortSignal
2425
+ });
2426
+ const choice = response.choices[0];
2427
+ const content = [];
2428
+ if (choice.message.content) {
2429
+ content.push({
2430
+ type: "text",
2431
+ text: choice.message.content
2432
+ });
2433
+ }
2434
+ if (choice.message.tool_calls) {
2435
+ for (const tc of choice.message.tool_calls) {
2436
+ content.push({
2437
+ type: "tool-call",
2438
+ toolCallId: tc.id,
2439
+ toolName: tc.function.name,
2440
+ input: tc.function.arguments
2441
+ });
2442
+ }
2443
+ }
2444
+ return {
2445
+ content,
2446
+ finishReason: mapApertisFinishReason(choice.finish_reason),
2447
+ usage: {
2448
+ inputTokens: {
2449
+ total: response.usage?.prompt_tokens ?? 0,
2450
+ noCache: void 0,
2451
+ cacheRead: void 0,
2452
+ cacheWrite: void 0
2453
+ },
2454
+ outputTokens: {
2455
+ total: response.usage?.completion_tokens ?? 0,
2456
+ text: void 0,
2457
+ reasoning: void 0
2458
+ }
2459
+ },
2460
+ warnings: [],
2461
+ request: { body }
2462
+ };
2463
+ }
2464
+ async doStream(options) {
2465
+ const body = this.buildRequestBody(options, true);
2466
+ const { value: response } = await postJsonToApi({
2467
+ url: `${this.config.baseURL}/chat/completions`,
2468
+ headers: this.config.headers(),
2469
+ body,
2470
+ failedResponseHandler: apertisFailedResponseHandler,
2471
+ successfulResponseHandler: createEventSourceResponseHandler(
2472
+ openAIChatChunkSchema
2473
+ ),
2474
+ fetch: this.config.fetch,
2475
+ abortSignal: options.abortSignal
2476
+ });
2477
+ const toolCallBuffers = /* @__PURE__ */ new Map();
2478
+ let textId = null;
2479
+ const transformStream = new TransformStream({
2480
+ transform(parseResult, controller) {
2481
+ if (!parseResult.success) {
2482
+ return;
2483
+ }
2484
+ const chunk = parseResult.value;
2485
+ const choice = chunk.choices[0];
2486
+ if (!choice) return;
2487
+ if (choice.delta.content) {
2488
+ if (!textId) {
2489
+ textId = generateId();
2490
+ controller.enqueue({
2491
+ type: "text-start",
2492
+ id: textId
2493
+ });
2494
+ }
2495
+ controller.enqueue({
2496
+ type: "text-delta",
2497
+ id: textId,
2498
+ delta: choice.delta.content
2499
+ });
2500
+ }
2501
+ if (choice.delta.tool_calls) {
2502
+ for (const tc of choice.delta.tool_calls) {
2503
+ let buffer = toolCallBuffers.get(tc.index);
2504
+ if (!buffer) {
2505
+ buffer = { id: tc.id ?? generateId(), name: "", arguments: "" };
2506
+ toolCallBuffers.set(tc.index, buffer);
2507
+ }
2508
+ if (tc.id) buffer.id = tc.id;
2509
+ if (tc.function?.name) buffer.name += tc.function.name;
2510
+ if (tc.function?.arguments)
2511
+ buffer.arguments += tc.function.arguments;
2512
+ }
2513
+ }
2514
+ if (choice.finish_reason) {
2515
+ if (textId) {
2516
+ controller.enqueue({
2517
+ type: "text-end",
2518
+ id: textId
2519
+ });
2520
+ }
2521
+ for (const [, buffer] of toolCallBuffers) {
2522
+ if (buffer.name) {
2523
+ controller.enqueue({
2524
+ type: "tool-call",
2525
+ toolCallId: buffer.id,
2526
+ toolName: buffer.name,
2527
+ input: buffer.arguments
2528
+ });
2529
+ }
2530
+ }
2531
+ toolCallBuffers.clear();
2532
+ controller.enqueue({
2533
+ type: "finish",
2534
+ finishReason: mapApertisFinishReason(choice.finish_reason),
2535
+ usage: {
2536
+ inputTokens: {
2537
+ total: chunk.usage?.prompt_tokens ?? 0,
2538
+ noCache: void 0,
2539
+ cacheRead: void 0,
2540
+ cacheWrite: void 0
2541
+ },
2542
+ outputTokens: {
2543
+ total: chunk.usage?.completion_tokens ?? 0,
2544
+ text: void 0,
2545
+ reasoning: void 0
2546
+ }
2547
+ }
200
2548
  });
201
2549
  }
202
- break;
203
- }
2550
+ },
2551
+ flush(controller) {
2552
+ if (textId) {
2553
+ controller.enqueue({
2554
+ type: "text-end",
2555
+ id: textId
2556
+ });
2557
+ }
2558
+ for (const [, buffer] of toolCallBuffers) {
2559
+ if (buffer.name) {
2560
+ controller.enqueue({
2561
+ type: "tool-call",
2562
+ toolCallId: buffer.id,
2563
+ toolName: buffer.name,
2564
+ input: buffer.arguments
2565
+ });
2566
+ }
2567
+ }
2568
+ }
2569
+ });
2570
+ return {
2571
+ stream: response.pipeThrough(transformStream),
2572
+ request: { body }
2573
+ };
204
2574
  }
205
- return messages;
206
- }
207
-
208
- // src/utils/convert-to-openai-tools.ts
209
- function convertToOpenAITools(tools) {
210
- if (!tools || tools.length === 0) return void 0;
211
- return tools.map((tool) => ({
212
- type: "function",
213
- function: {
214
- name: tool.name,
215
- description: tool.description,
216
- parameters: tool.inputSchema
217
- }
218
- }));
219
- }
220
- function convertToOpenAIToolChoice(toolChoice) {
221
- if (!toolChoice) return void 0;
222
- switch (toolChoice.type) {
223
- case "none":
224
- return "none";
225
- case "auto":
226
- return "auto";
227
- case "required":
228
- return "required";
229
- case "tool":
230
- if (!toolChoice.toolName) return void 0;
231
- return {
232
- type: "function",
233
- function: { name: toolChoice.toolName }
234
- };
235
- default:
236
- return void 0;
2575
+ buildRequestBody(options, stream) {
2576
+ const tools = this.filterFunctionTools(options.tools);
2577
+ const responseFormat = options.responseFormat?.type === "json" ? { type: "json_object" } : void 0;
2578
+ const body = {
2579
+ model: this.modelId,
2580
+ messages: convertToOpenAIMessages(options.prompt),
2581
+ stream
2582
+ };
2583
+ if (stream) body.stream_options = { include_usage: true };
2584
+ if (options.temperature !== void 0)
2585
+ body.temperature = options.temperature;
2586
+ if (options.maxOutputTokens !== void 0)
2587
+ body.max_tokens = options.maxOutputTokens;
2588
+ if (options.topP !== void 0) body.top_p = options.topP;
2589
+ if (options.frequencyPenalty !== void 0)
2590
+ body.frequency_penalty = options.frequencyPenalty;
2591
+ if (options.presencePenalty !== void 0)
2592
+ body.presence_penalty = options.presencePenalty;
2593
+ if (options.stopSequences !== void 0) body.stop = options.stopSequences;
2594
+ if (options.seed !== void 0) body.seed = options.seed;
2595
+ const convertedTools = convertToOpenAITools(tools);
2596
+ if (convertedTools !== void 0) body.tools = convertedTools;
2597
+ const convertedToolChoice = convertToOpenAIToolChoice(options.toolChoice);
2598
+ if (convertedToolChoice !== void 0)
2599
+ body.tool_choice = convertedToolChoice;
2600
+ if (responseFormat !== void 0) body.response_format = responseFormat;
2601
+ if (this.settings.user !== void 0) body.user = this.settings.user;
2602
+ if (this.settings.logprobs !== void 0)
2603
+ body.logprobs = this.settings.logprobs;
2604
+ if (this.settings.topLogprobs !== void 0)
2605
+ body.top_logprobs = this.settings.topLogprobs;
2606
+ return body;
237
2607
  }
238
- }
2608
+ filterFunctionTools(tools) {
2609
+ if (!tools) return void 0;
2610
+ return tools.filter(
2611
+ (tool) => tool.type === "function"
2612
+ );
2613
+ }
2614
+ };
239
2615
 
240
- // src/apertis-chat-language-model.ts
241
- var ApertisChatLanguageModel = class {
2616
+ // src/apertis-chat-language-model-v2.ts
2617
+ var ApertisChatLanguageModelV2 = class {
242
2618
  constructor(modelId, settings, config) {
243
2619
  this.modelId = modelId;
244
2620
  this.settings = settings;
245
2621
  this.config = config;
246
2622
  }
247
- specificationVersion = "v3";
248
- /**
249
- * Supported URL patterns for different media types.
250
- * Supports HTTP(S) image URLs for direct URL passing.
251
- */
2623
+ specificationVersion = "v2";
252
2624
  supportedUrls = {
253
2625
  "image/*": [/^https?:\/\/.+$/]
254
2626
  };
@@ -288,19 +2660,11 @@ var ApertisChatLanguageModel = class {
288
2660
  }
289
2661
  return {
290
2662
  content,
291
- finishReason: mapApertisFinishReason(choice.finish_reason),
2663
+ finishReason: mapApertisFinishReasonV2(choice.finish_reason),
292
2664
  usage: {
293
- inputTokens: {
294
- total: response.usage?.prompt_tokens ?? 0,
295
- noCache: void 0,
296
- cacheRead: void 0,
297
- cacheWrite: void 0
298
- },
299
- outputTokens: {
300
- total: response.usage?.completion_tokens ?? 0,
301
- text: void 0,
302
- reasoning: void 0
303
- }
2665
+ inputTokens: response.usage?.prompt_tokens ?? 0,
2666
+ outputTokens: response.usage?.completion_tokens ?? 0,
2667
+ totalTokens: response.usage?.total_tokens ?? void 0
304
2668
  },
305
2669
  warnings: [],
306
2670
  request: { body }
@@ -347,7 +2711,11 @@ var ApertisChatLanguageModel = class {
347
2711
  for (const tc of choice.delta.tool_calls) {
348
2712
  let buffer = toolCallBuffers.get(tc.index);
349
2713
  if (!buffer) {
350
- buffer = { id: tc.id ?? generateId(), name: "", arguments: "" };
2714
+ buffer = {
2715
+ id: tc.id ?? generateId(),
2716
+ name: "",
2717
+ arguments: ""
2718
+ };
351
2719
  toolCallBuffers.set(tc.index, buffer);
352
2720
  }
353
2721
  if (tc.id) buffer.id = tc.id;
@@ -376,19 +2744,11 @@ var ApertisChatLanguageModel = class {
376
2744
  toolCallBuffers.clear();
377
2745
  controller.enqueue({
378
2746
  type: "finish",
379
- finishReason: mapApertisFinishReason(choice.finish_reason),
2747
+ finishReason: mapApertisFinishReasonV2(choice.finish_reason),
380
2748
  usage: {
381
- inputTokens: {
382
- total: chunk.usage?.prompt_tokens ?? 0,
383
- noCache: void 0,
384
- cacheRead: void 0,
385
- cacheWrite: void 0
386
- },
387
- outputTokens: {
388
- total: chunk.usage?.completion_tokens ?? 0,
389
- text: void 0,
390
- reasoning: void 0
391
- }
2749
+ inputTokens: chunk.usage?.prompt_tokens ?? 0,
2750
+ outputTokens: chunk.usage?.completion_tokens ?? 0,
2751
+ totalTokens: void 0
392
2752
  }
393
2753
  });
394
2754
  }
@@ -458,12 +2818,6 @@ var ApertisChatLanguageModel = class {
458
2818
  }
459
2819
  };
460
2820
 
461
- // src/apertis-embedding-model.ts
462
- import {
463
- createJsonResponseHandler as createJsonResponseHandler2,
464
- postJsonToApi as postJsonToApi2
465
- } from "@ai-sdk/provider-utils";
466
-
467
2821
  // src/schemas/embedding-response.ts
468
2822
  import { z as z3 } from "zod";
469
2823
  var openAIEmbeddingResponseSchema = z3.object({
@@ -509,12 +2863,12 @@ var ApertisEmbeddingModel = class {
509
2863
  if (this.settings.user !== void 0) {
510
2864
  body.user = this.settings.user;
511
2865
  }
512
- const { value: response } = await postJsonToApi2({
2866
+ const { value: response } = await postJsonToApi({
513
2867
  url: `${this.config.baseURL}/embeddings`,
514
2868
  headers: this.config.headers(),
515
2869
  body,
516
2870
  failedResponseHandler: apertisFailedResponseHandler,
517
- successfulResponseHandler: createJsonResponseHandler2(
2871
+ successfulResponseHandler: createJsonResponseHandler(
518
2872
  openAIEmbeddingResponseSchema
519
2873
  ),
520
2874
  fetch: this.config.fetch,
@@ -528,8 +2882,53 @@ var ApertisEmbeddingModel = class {
528
2882
  }
529
2883
  };
530
2884
 
2885
+ // src/apertis-embedding-model-v2.ts
2886
+ var ApertisEmbeddingModelV2 = class {
2887
+ constructor(modelId, settings, config) {
2888
+ this.modelId = modelId;
2889
+ this.settings = settings;
2890
+ this.config = config;
2891
+ this.maxEmbeddingsPerCall = settings.maxEmbeddingsPerCall ?? 2048;
2892
+ this.supportsParallelCalls = settings.supportsParallelCalls ?? true;
2893
+ }
2894
+ specificationVersion = "v2";
2895
+ maxEmbeddingsPerCall;
2896
+ supportsParallelCalls;
2897
+ get provider() {
2898
+ return this.config.provider;
2899
+ }
2900
+ async doEmbed(options) {
2901
+ const body = {
2902
+ model: this.modelId,
2903
+ input: options.values,
2904
+ encoding_format: "float"
2905
+ };
2906
+ if (this.settings.dimensions !== void 0) {
2907
+ body.dimensions = this.settings.dimensions;
2908
+ }
2909
+ if (this.settings.user !== void 0) {
2910
+ body.user = this.settings.user;
2911
+ }
2912
+ const { value: response } = await postJsonToApi({
2913
+ url: `${this.config.baseURL}/embeddings`,
2914
+ headers: this.config.headers(),
2915
+ body,
2916
+ failedResponseHandler: apertisFailedResponseHandler,
2917
+ successfulResponseHandler: createJsonResponseHandler(
2918
+ openAIEmbeddingResponseSchema
2919
+ ),
2920
+ fetch: this.config.fetch,
2921
+ abortSignal: options.abortSignal
2922
+ });
2923
+ return {
2924
+ embeddings: response.data.map((item) => item.embedding),
2925
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0
2926
+ };
2927
+ }
2928
+ };
2929
+
531
2930
  // src/apertis-provider.ts
532
- function createApertis(options = {}) {
2931
+ function initializeProvider(options = {}) {
533
2932
  const baseURL = withoutTrailingSlash(options.baseURL) ?? "https://api.apertis.ai/v1";
534
2933
  const getHeaders = () => ({
535
2934
  ...options.headers,
@@ -540,17 +2939,49 @@ function createApertis(options = {}) {
540
2939
  })}`,
541
2940
  "Content-Type": "application/json"
542
2941
  });
2942
+ return { baseURL, getHeaders, fetch: options.fetch };
2943
+ }
2944
+ function createApertis(options = {}) {
2945
+ const { baseURL, getHeaders, fetch: fetchImpl } = initializeProvider(options);
2946
+ const createChatModel = (modelId, settings = {}) => new ApertisChatLanguageModelV2(modelId, settings, {
2947
+ provider: "apertis.chat",
2948
+ baseURL,
2949
+ headers: getHeaders,
2950
+ fetch: fetchImpl
2951
+ });
2952
+ const createEmbeddingModel = (modelId, settings = {}) => new ApertisEmbeddingModelV2(modelId, settings, {
2953
+ provider: "apertis.embedding",
2954
+ baseURL,
2955
+ headers: getHeaders,
2956
+ fetch: fetchImpl
2957
+ });
2958
+ const provider = Object.assign(
2959
+ (modelId, settings) => createChatModel(modelId, settings),
2960
+ {
2961
+ specificationVersion: "v2",
2962
+ chat: createChatModel,
2963
+ languageModel: (modelId) => createChatModel(modelId),
2964
+ textEmbeddingModel: createEmbeddingModel,
2965
+ imageModel: () => {
2966
+ throw new Error("Image models are not supported by Apertis");
2967
+ }
2968
+ }
2969
+ );
2970
+ return provider;
2971
+ }
2972
+ function createApertisV3(options = {}) {
2973
+ const { baseURL, getHeaders, fetch: fetchImpl } = initializeProvider(options);
543
2974
  const createChatModel = (modelId, settings = {}) => new ApertisChatLanguageModel(modelId, settings, {
544
2975
  provider: "apertis.chat",
545
2976
  baseURL,
546
2977
  headers: getHeaders,
547
- fetch: options.fetch
2978
+ fetch: fetchImpl
548
2979
  });
549
2980
  const createEmbeddingModel = (modelId, settings = {}) => new ApertisEmbeddingModel(modelId, settings, {
550
2981
  provider: "apertis.embedding",
551
2982
  baseURL,
552
2983
  headers: getHeaders,
553
- fetch: options.fetch
2984
+ fetch: fetchImpl
554
2985
  });
555
2986
  const provider = Object.assign(
556
2987
  (modelId, settings) => createChatModel(modelId, settings),
@@ -570,6 +3001,7 @@ function createApertis(options = {}) {
570
3001
  var apertis = createApertis();
571
3002
  export {
572
3003
  apertis,
573
- createApertis
3004
+ createApertis,
3005
+ createApertisV3
574
3006
  };
575
3007
  //# sourceMappingURL=index.js.map