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