@mastra/agent-builder 1.0.0-beta.3 → 1.0.0-beta.5

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,3 +1,4 @@
1
+ import { __commonJS, require_token_error, __toESM } from './chunk-E53QBCQN.js';
1
2
  import { Agent, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '@mastra/core/agent';
2
3
  import { Memory } from '@mastra/memory';
3
4
  import { exec as exec$1, execFile as execFile$1, spawn as spawn$1 } from 'child_process';
@@ -13,9 +14,10 @@ import { ModelRouterLanguageModel } from '@mastra/core/llm';
13
14
  import { tmpdir } from 'os';
14
15
  import { openai } from '@ai-sdk/openai';
15
16
  import { createStep, createWorkflow } from '@mastra/core/workflows';
16
- import { stepCountIs } from 'ai';
17
+ import * as z4 from 'zod/v4';
18
+ import { z as z$1 } from 'zod/v4';
19
+ import { ZodFirstPartyTypeKind } from 'zod/v3';
17
20
 
18
- // src/agent/index.ts
19
21
  var UNIT_KINDS = ["mcp-server", "tool", "workflow", "agent", "integration", "network", "other"];
20
22
  var TemplateUnitSchema = z.object({
21
23
  kind: z.enum(UNIT_KINDS),
@@ -187,7 +189,7 @@ var PackageMergeResultSchema = z.object({
187
189
  error: z.string().optional()
188
190
  });
189
191
  var InstallInputSchema = z.object({
190
- targetPath: z.string().describe("Path to the project to install packages in")
192
+ targetPath: z.string().optional().describe("Path to the project to install packages in")
191
193
  });
192
194
  var InstallResultSchema = z.object({
193
195
  success: z.boolean(),
@@ -247,7 +249,7 @@ function isInWorkspaceSubfolder(cwd) {
247
249
  }
248
250
  }
249
251
  function spawn(command, args, options) {
250
- return new Promise((resolve4, reject) => {
252
+ return new Promise((resolve5, reject) => {
251
253
  const childProcess = spawn$1(command, args, {
252
254
  stdio: "inherit",
253
255
  // Enable proper stdio handling
@@ -258,7 +260,7 @@ function spawn(command, args, options) {
258
260
  });
259
261
  childProcess.on("close", (code) => {
260
262
  if (code === 0) {
261
- resolve4(void 0);
263
+ resolve5(void 0);
262
264
  } else {
263
265
  reject(new Error(`Command failed with exit code ${code}`));
264
266
  }
@@ -1594,7 +1596,7 @@ export const mastra = new Mastra({
1594
1596
  error: stopResult.error || "Unknown stop error"
1595
1597
  };
1596
1598
  }
1597
- await new Promise((resolve4) => setTimeout(resolve4, 500));
1599
+ await new Promise((resolve5) => setTimeout(resolve5, 500));
1598
1600
  const startResult = await _AgentBuilderDefaults.startMastraServer({
1599
1601
  port,
1600
1602
  projectPath
@@ -1814,7 +1816,7 @@ export const mastra = new Mastra({
1814
1816
  stdio: "pipe"
1815
1817
  });
1816
1818
  const stdoutLines = [];
1817
- const serverStarted = new Promise((resolve4, reject) => {
1819
+ const serverStarted = new Promise((resolve5, reject) => {
1818
1820
  const timeout = setTimeout(() => {
1819
1821
  reject(new Error(`Server startup timeout after 30 seconds. Output: ${stdoutLines.join("\n")}`));
1820
1822
  }, 3e4);
@@ -1822,9 +1824,9 @@ export const mastra = new Mastra({
1822
1824
  const output = data.toString();
1823
1825
  const lines = output.split("\n").filter((line) => line.trim());
1824
1826
  stdoutLines.push(...lines);
1825
- if (output.includes("Mastra API running on port")) {
1827
+ if (output.includes("Mastra API running on ")) {
1826
1828
  clearTimeout(timeout);
1827
- resolve4({
1829
+ resolve5({
1828
1830
  success: true,
1829
1831
  status: "running",
1830
1832
  pid: serverProcess.pid,
@@ -1913,7 +1915,7 @@ export const mastra = new Mastra({
1913
1915
  `Killed ${killedPids.length} processes but failed to kill ${failedPids.length} processes: ${failedPids.join(", ")}`
1914
1916
  );
1915
1917
  }
1916
- await new Promise((resolve4) => setTimeout(resolve4, 2e3));
1918
+ await new Promise((resolve5) => setTimeout(resolve5, 2e3));
1917
1919
  try {
1918
1920
  const { stdout: checkStdoutRaw } = await execFile("lsof", ["-ti", String(port)]);
1919
1921
  const checkStdout = checkStdoutRaw.trim() ? checkStdoutRaw : "No process found";
@@ -1928,7 +1930,7 @@ export const mastra = new Mastra({
1928
1930
  }
1929
1931
  }
1930
1932
  }
1931
- await new Promise((resolve4) => setTimeout(resolve4, 1e3));
1933
+ await new Promise((resolve5) => setTimeout(resolve5, 1e3));
1932
1934
  const { stdout: finalCheckRaw } = await execFile("lsof", ["-ti", String(port)]);
1933
1935
  const finalCheck = finalCheckRaw.trim() ? finalCheckRaw : "No process found";
1934
1936
  if (finalCheck && finalCheck !== "No process found") {
@@ -2213,14 +2215,14 @@ export const mastra = new Mastra({
2213
2215
  noEmit: true
2214
2216
  };
2215
2217
  const host = {
2216
- getSourceFile: (name) => name === fileName ? sourceFile : void 0,
2218
+ getSourceFile: (name16) => name16 === fileName ? sourceFile : void 0,
2217
2219
  writeFile: () => {
2218
2220
  },
2219
2221
  getCurrentDirectory: () => "",
2220
2222
  getDirectories: () => [],
2221
- fileExists: (name) => name === fileName,
2222
- readFile: (name) => name === fileName ? fileContent : void 0,
2223
- getCanonicalFileName: (name) => name,
2223
+ fileExists: (name16) => name16 === fileName,
2224
+ readFile: (name16) => name16 === fileName ? fileContent : void 0,
2225
+ getCanonicalFileName: (name16) => name16,
2224
2226
  useCaseSensitiveFileNames: () => true,
2225
2227
  getNewLine: () => "\n",
2226
2228
  getDefaultLibFileName: () => "lib.d.ts"
@@ -3628,25 +3630,25 @@ var packageMergeStep = createStep({
3628
3630
  const tplDevDeps = ensureObj(packageInfo.devDependencies);
3629
3631
  const tplPeerDeps = ensureObj(packageInfo.peerDependencies);
3630
3632
  const tplScripts = ensureObj(packageInfo.scripts);
3631
- const existsAnywhere = (name) => name in targetPkg.dependencies || name in targetPkg.devDependencies || name in targetPkg.peerDependencies;
3632
- for (const [name, ver] of Object.entries(tplDeps)) {
3633
- if (!existsAnywhere(name)) {
3634
- targetPkg.dependencies[name] = String(ver);
3633
+ const existsAnywhere = (name16) => name16 in targetPkg.dependencies || name16 in targetPkg.devDependencies || name16 in targetPkg.peerDependencies;
3634
+ for (const [name16, ver] of Object.entries(tplDeps)) {
3635
+ if (!existsAnywhere(name16)) {
3636
+ targetPkg.dependencies[name16] = String(ver);
3635
3637
  }
3636
3638
  }
3637
- for (const [name, ver] of Object.entries(tplDevDeps)) {
3638
- if (!existsAnywhere(name)) {
3639
- targetPkg.devDependencies[name] = String(ver);
3639
+ for (const [name16, ver] of Object.entries(tplDevDeps)) {
3640
+ if (!existsAnywhere(name16)) {
3641
+ targetPkg.devDependencies[name16] = String(ver);
3640
3642
  }
3641
3643
  }
3642
- for (const [name, ver] of Object.entries(tplPeerDeps)) {
3643
- if (!(name in targetPkg.peerDependencies)) {
3644
- targetPkg.peerDependencies[name] = String(ver);
3644
+ for (const [name16, ver] of Object.entries(tplPeerDeps)) {
3645
+ if (!(name16 in targetPkg.peerDependencies)) {
3646
+ targetPkg.peerDependencies[name16] = String(ver);
3645
3647
  }
3646
3648
  }
3647
3649
  const prefix = `template:${slug}:`;
3648
- for (const [name, cmd] of Object.entries(tplScripts)) {
3649
- const newKey = `${prefix}${name}`;
3650
+ for (const [name16, cmd] of Object.entries(tplScripts)) {
3651
+ const newKey = `${prefix}${name16}`;
3650
3652
  if (!(newKey in targetPkg.scripts)) {
3651
3653
  targetPkg.scripts[newKey] = String(cmd);
3652
3654
  }
@@ -3731,9 +3733,9 @@ var programmaticFileCopyStep = createStep({
3731
3733
  return "unknown";
3732
3734
  }
3733
3735
  };
3734
- const convertNaming = (name, convention) => {
3735
- const baseName = basename(name, extname(name));
3736
- const ext = extname(name);
3736
+ const convertNaming = (name16, convention) => {
3737
+ const baseName = basename(name16, extname(name16));
3738
+ const ext = extname(name16);
3737
3739
  switch (convention) {
3738
3740
  case "camelCase":
3739
3741
  return baseName.replace(/[-_]/g, "").replace(/([A-Z])/g, (match, p1, offset) => offset === 0 ? p1.toLowerCase() : p1) + ext;
@@ -3744,7 +3746,7 @@ var programmaticFileCopyStep = createStep({
3744
3746
  case "PascalCase":
3745
3747
  return baseName.replace(/[-_]/g, "").replace(/^[a-z]/, (match) => match.toUpperCase()) + ext;
3746
3748
  default:
3747
- return name;
3749
+ return name16;
3748
3750
  }
3749
3751
  };
3750
3752
  for (const unit of orderedUnits) {
@@ -4769,6 +4771,4304 @@ var determineConflictStrategy = (_unit, _targetFile) => {
4769
4771
  var shouldAbortWorkflow = (stepResult) => {
4770
4772
  return stepResult?.success === false || stepResult?.error;
4771
4773
  };
4774
+ var marker = "vercel.ai.error";
4775
+ var symbol = Symbol.for(marker);
4776
+ var _a;
4777
+ var _AISDKError = class _AISDKError2 extends Error {
4778
+ /**
4779
+ * Creates an AI SDK Error.
4780
+ *
4781
+ * @param {Object} params - The parameters for creating the error.
4782
+ * @param {string} params.name - The name of the error.
4783
+ * @param {string} params.message - The error message.
4784
+ * @param {unknown} [params.cause] - The underlying cause of the error.
4785
+ */
4786
+ constructor({
4787
+ name: name143,
4788
+ message,
4789
+ cause
4790
+ }) {
4791
+ super(message);
4792
+ this[_a] = true;
4793
+ this.name = name143;
4794
+ this.cause = cause;
4795
+ }
4796
+ /**
4797
+ * Checks if the given error is an AI SDK Error.
4798
+ * @param {unknown} error - The error to check.
4799
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
4800
+ */
4801
+ static isInstance(error) {
4802
+ return _AISDKError2.hasMarker(error, marker);
4803
+ }
4804
+ static hasMarker(error, marker153) {
4805
+ const markerSymbol = Symbol.for(marker153);
4806
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
4807
+ }
4808
+ };
4809
+ _a = symbol;
4810
+ var AISDKError = _AISDKError;
4811
+ var name = "AI_APICallError";
4812
+ var marker2 = `vercel.ai.error.${name}`;
4813
+ var symbol2 = Symbol.for(marker2);
4814
+ var _a2;
4815
+ var APICallError = class extends AISDKError {
4816
+ constructor({
4817
+ message,
4818
+ url,
4819
+ requestBodyValues,
4820
+ statusCode,
4821
+ responseHeaders,
4822
+ responseBody,
4823
+ cause,
4824
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
4825
+ statusCode === 409 || // conflict
4826
+ statusCode === 429 || // too many requests
4827
+ statusCode >= 500),
4828
+ // server error
4829
+ data
4830
+ }) {
4831
+ super({ name, message, cause });
4832
+ this[_a2] = true;
4833
+ this.url = url;
4834
+ this.requestBodyValues = requestBodyValues;
4835
+ this.statusCode = statusCode;
4836
+ this.responseHeaders = responseHeaders;
4837
+ this.responseBody = responseBody;
4838
+ this.isRetryable = isRetryable;
4839
+ this.data = data;
4840
+ }
4841
+ static isInstance(error) {
4842
+ return AISDKError.hasMarker(error, marker2);
4843
+ }
4844
+ };
4845
+ _a2 = symbol2;
4846
+ var name2 = "AI_EmptyResponseBodyError";
4847
+ var marker3 = `vercel.ai.error.${name2}`;
4848
+ var symbol3 = Symbol.for(marker3);
4849
+ var _a3;
4850
+ var EmptyResponseBodyError = class extends AISDKError {
4851
+ // used in isInstance
4852
+ constructor({ message = "Empty response body" } = {}) {
4853
+ super({ name: name2, message });
4854
+ this[_a3] = true;
4855
+ }
4856
+ static isInstance(error) {
4857
+ return AISDKError.hasMarker(error, marker3);
4858
+ }
4859
+ };
4860
+ _a3 = symbol3;
4861
+ function getErrorMessage(error) {
4862
+ if (error == null) {
4863
+ return "unknown error";
4864
+ }
4865
+ if (typeof error === "string") {
4866
+ return error;
4867
+ }
4868
+ if (error instanceof Error) {
4869
+ return error.message;
4870
+ }
4871
+ return JSON.stringify(error);
4872
+ }
4873
+ var name3 = "AI_InvalidArgumentError";
4874
+ var marker4 = `vercel.ai.error.${name3}`;
4875
+ var symbol4 = Symbol.for(marker4);
4876
+ var _a4;
4877
+ var InvalidArgumentError = class extends AISDKError {
4878
+ constructor({
4879
+ message,
4880
+ cause,
4881
+ argument
4882
+ }) {
4883
+ super({ name: name3, message, cause });
4884
+ this[_a4] = true;
4885
+ this.argument = argument;
4886
+ }
4887
+ static isInstance(error) {
4888
+ return AISDKError.hasMarker(error, marker4);
4889
+ }
4890
+ };
4891
+ _a4 = symbol4;
4892
+ var name6 = "AI_JSONParseError";
4893
+ var marker7 = `vercel.ai.error.${name6}`;
4894
+ var symbol7 = Symbol.for(marker7);
4895
+ var _a7;
4896
+ var JSONParseError = class extends AISDKError {
4897
+ constructor({ text: text2, cause }) {
4898
+ super({
4899
+ name: name6,
4900
+ message: `JSON parsing failed: Text: ${text2}.
4901
+ Error message: ${getErrorMessage(cause)}`,
4902
+ cause
4903
+ });
4904
+ this[_a7] = true;
4905
+ this.text = text2;
4906
+ }
4907
+ static isInstance(error) {
4908
+ return AISDKError.hasMarker(error, marker7);
4909
+ }
4910
+ };
4911
+ _a7 = symbol7;
4912
+ var name12 = "AI_TypeValidationError";
4913
+ var marker13 = `vercel.ai.error.${name12}`;
4914
+ var symbol13 = Symbol.for(marker13);
4915
+ var _a13;
4916
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
4917
+ constructor({ value, cause }) {
4918
+ super({
4919
+ name: name12,
4920
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
4921
+ Error message: ${getErrorMessage(cause)}`,
4922
+ cause
4923
+ });
4924
+ this[_a13] = true;
4925
+ this.value = value;
4926
+ }
4927
+ static isInstance(error) {
4928
+ return AISDKError.hasMarker(error, marker13);
4929
+ }
4930
+ /**
4931
+ * Wraps an error into a TypeValidationError.
4932
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
4933
+ * Otherwise, it creates a new TypeValidationError.
4934
+ *
4935
+ * @param {Object} params - The parameters for wrapping the error.
4936
+ * @param {unknown} params.value - The value that failed validation.
4937
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
4938
+ * @returns {TypeValidationError} A TypeValidationError instance.
4939
+ */
4940
+ static wrap({
4941
+ value,
4942
+ cause
4943
+ }) {
4944
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
4945
+ }
4946
+ };
4947
+ _a13 = symbol13;
4948
+ var TypeValidationError = _TypeValidationError;
4949
+ var ParseError = class extends Error {
4950
+ constructor(message, options) {
4951
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
4952
+ }
4953
+ };
4954
+ function noop(_arg) {
4955
+ }
4956
+ function createParser(callbacks) {
4957
+ if (typeof callbacks == "function")
4958
+ throw new TypeError(
4959
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
4960
+ );
4961
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
4962
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
4963
+ function feed(newChunk) {
4964
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
4965
+ for (const line of complete)
4966
+ parseLine(line);
4967
+ incompleteLine = incomplete, isFirstChunk = false;
4968
+ }
4969
+ function parseLine(line) {
4970
+ if (line === "") {
4971
+ dispatchEvent();
4972
+ return;
4973
+ }
4974
+ if (line.startsWith(":")) {
4975
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
4976
+ return;
4977
+ }
4978
+ const fieldSeparatorIndex = line.indexOf(":");
4979
+ if (fieldSeparatorIndex !== -1) {
4980
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
4981
+ processField(field, value, line);
4982
+ return;
4983
+ }
4984
+ processField(line, "", line);
4985
+ }
4986
+ function processField(field, value, line) {
4987
+ switch (field) {
4988
+ case "event":
4989
+ eventType = value;
4990
+ break;
4991
+ case "data":
4992
+ data = `${data}${value}
4993
+ `;
4994
+ break;
4995
+ case "id":
4996
+ id = value.includes("\0") ? void 0 : value;
4997
+ break;
4998
+ case "retry":
4999
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
5000
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
5001
+ type: "invalid-retry",
5002
+ value,
5003
+ line
5004
+ })
5005
+ );
5006
+ break;
5007
+ default:
5008
+ onError(
5009
+ new ParseError(
5010
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
5011
+ { type: "unknown-field", field, value, line }
5012
+ )
5013
+ );
5014
+ break;
5015
+ }
5016
+ }
5017
+ function dispatchEvent() {
5018
+ data.length > 0 && onEvent({
5019
+ id,
5020
+ event: eventType || void 0,
5021
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
5022
+ // then remove the last character from the data buffer.
5023
+ data: data.endsWith(`
5024
+ `) ? data.slice(0, -1) : data
5025
+ }), id = void 0, data = "", eventType = "";
5026
+ }
5027
+ function reset(options = {}) {
5028
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
5029
+ }
5030
+ return { feed, reset };
5031
+ }
5032
+ function splitLines(chunk) {
5033
+ const lines = [];
5034
+ let incompleteLine = "", searchIndex = 0;
5035
+ for (; searchIndex < chunk.length; ) {
5036
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
5037
+ `, searchIndex);
5038
+ let lineEnd = -1;
5039
+ 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) {
5040
+ incompleteLine = chunk.slice(searchIndex);
5041
+ break;
5042
+ } else {
5043
+ const line = chunk.slice(searchIndex, lineEnd);
5044
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
5045
+ ` && searchIndex++;
5046
+ }
5047
+ }
5048
+ return [lines, incompleteLine];
5049
+ }
5050
+ var EventSourceParserStream = class extends TransformStream {
5051
+ constructor({ onError, onRetry, onComment } = {}) {
5052
+ let parser;
5053
+ super({
5054
+ start(controller) {
5055
+ parser = createParser({
5056
+ onEvent: (event) => {
5057
+ controller.enqueue(event);
5058
+ },
5059
+ onError(error) {
5060
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
5061
+ },
5062
+ onRetry,
5063
+ onComment
5064
+ });
5065
+ },
5066
+ transform(chunk) {
5067
+ parser.feed(chunk);
5068
+ }
5069
+ });
5070
+ }
5071
+ };
5072
+ function combineHeaders(...headers) {
5073
+ return headers.reduce(
5074
+ (combinedHeaders, currentHeaders) => ({
5075
+ ...combinedHeaders,
5076
+ ...currentHeaders != null ? currentHeaders : {}
5077
+ }),
5078
+ {}
5079
+ );
5080
+ }
5081
+ function extractResponseHeaders(response) {
5082
+ return Object.fromEntries([...response.headers]);
5083
+ }
5084
+ var createIdGenerator = ({
5085
+ prefix,
5086
+ size = 16,
5087
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
5088
+ separator = "-"
5089
+ } = {}) => {
5090
+ const generator = () => {
5091
+ const alphabetLength = alphabet.length;
5092
+ const chars = new Array(size);
5093
+ for (let i = 0; i < size; i++) {
5094
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
5095
+ }
5096
+ return chars.join("");
5097
+ };
5098
+ if (prefix == null) {
5099
+ return generator;
5100
+ }
5101
+ if (alphabet.includes(separator)) {
5102
+ throw new InvalidArgumentError({
5103
+ argument: "separator",
5104
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
5105
+ });
5106
+ }
5107
+ return () => `${prefix}${separator}${generator()}`;
5108
+ };
5109
+ createIdGenerator();
5110
+ function isAbortError(error) {
5111
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
5112
+ error.name === "TimeoutError");
5113
+ }
5114
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
5115
+ function handleFetchError({
5116
+ error,
5117
+ url,
5118
+ requestBodyValues
5119
+ }) {
5120
+ if (isAbortError(error)) {
5121
+ return error;
5122
+ }
5123
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
5124
+ const cause = error.cause;
5125
+ if (cause != null) {
5126
+ return new APICallError({
5127
+ message: `Cannot connect to API: ${cause.message}`,
5128
+ cause,
5129
+ url,
5130
+ requestBodyValues,
5131
+ isRetryable: true
5132
+ // retry when network error
5133
+ });
5134
+ }
5135
+ }
5136
+ return error;
5137
+ }
5138
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
5139
+ var _a153, _b8, _c;
5140
+ if (globalThisAny.window) {
5141
+ return `runtime/browser`;
5142
+ }
5143
+ if ((_a153 = globalThisAny.navigator) == null ? void 0 : _a153.userAgent) {
5144
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
5145
+ }
5146
+ if ((_c = (_b8 = globalThisAny.process) == null ? void 0 : _b8.versions) == null ? void 0 : _c.node) {
5147
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
5148
+ }
5149
+ if (globalThisAny.EdgeRuntime) {
5150
+ return `runtime/vercel-edge`;
5151
+ }
5152
+ return "runtime/unknown";
5153
+ }
5154
+ function normalizeHeaders(headers) {
5155
+ if (headers == null) {
5156
+ return {};
5157
+ }
5158
+ const normalized = {};
5159
+ if (headers instanceof Headers) {
5160
+ headers.forEach((value, key) => {
5161
+ normalized[key.toLowerCase()] = value;
5162
+ });
5163
+ } else {
5164
+ if (!Array.isArray(headers)) {
5165
+ headers = Object.entries(headers);
5166
+ }
5167
+ for (const [key, value] of headers) {
5168
+ if (value != null) {
5169
+ normalized[key.toLowerCase()] = value;
5170
+ }
5171
+ }
5172
+ }
5173
+ return normalized;
5174
+ }
5175
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
5176
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
5177
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
5178
+ normalizedHeaders.set(
5179
+ "user-agent",
5180
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
5181
+ );
5182
+ return Object.fromEntries(normalizedHeaders.entries());
5183
+ }
5184
+ var VERSION = "3.0.17";
5185
+ var getOriginalFetch = () => globalThis.fetch;
5186
+ var getFromApi = async ({
5187
+ url,
5188
+ headers = {},
5189
+ successfulResponseHandler,
5190
+ failedResponseHandler,
5191
+ abortSignal,
5192
+ fetch: fetch2 = getOriginalFetch()
5193
+ }) => {
5194
+ try {
5195
+ const response = await fetch2(url, {
5196
+ method: "GET",
5197
+ headers: withUserAgentSuffix(
5198
+ headers,
5199
+ `ai-sdk/provider-utils/${VERSION}`,
5200
+ getRuntimeEnvironmentUserAgent()
5201
+ ),
5202
+ signal: abortSignal
5203
+ });
5204
+ const responseHeaders = extractResponseHeaders(response);
5205
+ if (!response.ok) {
5206
+ let errorInformation;
5207
+ try {
5208
+ errorInformation = await failedResponseHandler({
5209
+ response,
5210
+ url,
5211
+ requestBodyValues: {}
5212
+ });
5213
+ } catch (error) {
5214
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5215
+ throw error;
5216
+ }
5217
+ throw new APICallError({
5218
+ message: "Failed to process error response",
5219
+ cause: error,
5220
+ statusCode: response.status,
5221
+ url,
5222
+ responseHeaders,
5223
+ requestBodyValues: {}
5224
+ });
5225
+ }
5226
+ throw errorInformation.value;
5227
+ }
5228
+ try {
5229
+ return await successfulResponseHandler({
5230
+ response,
5231
+ url,
5232
+ requestBodyValues: {}
5233
+ });
5234
+ } catch (error) {
5235
+ if (error instanceof Error) {
5236
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5237
+ throw error;
5238
+ }
5239
+ }
5240
+ throw new APICallError({
5241
+ message: "Failed to process successful response",
5242
+ cause: error,
5243
+ statusCode: response.status,
5244
+ url,
5245
+ responseHeaders,
5246
+ requestBodyValues: {}
5247
+ });
5248
+ }
5249
+ } catch (error) {
5250
+ throw handleFetchError({ error, url, requestBodyValues: {} });
5251
+ }
5252
+ };
5253
+ function loadOptionalSetting({
5254
+ settingValue,
5255
+ environmentVariableName
5256
+ }) {
5257
+ if (typeof settingValue === "string") {
5258
+ return settingValue;
5259
+ }
5260
+ if (settingValue != null || typeof process === "undefined") {
5261
+ return void 0;
5262
+ }
5263
+ settingValue = process.env[environmentVariableName];
5264
+ if (settingValue == null || typeof settingValue !== "string") {
5265
+ return void 0;
5266
+ }
5267
+ return settingValue;
5268
+ }
5269
+ var suspectProtoRx = /"__proto__"\s*:/;
5270
+ var suspectConstructorRx = /"constructor"\s*:/;
5271
+ function _parse(text2) {
5272
+ const obj = JSON.parse(text2);
5273
+ if (obj === null || typeof obj !== "object") {
5274
+ return obj;
5275
+ }
5276
+ if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
5277
+ return obj;
5278
+ }
5279
+ return filter(obj);
5280
+ }
5281
+ function filter(obj) {
5282
+ let next = [obj];
5283
+ while (next.length) {
5284
+ const nodes = next;
5285
+ next = [];
5286
+ for (const node of nodes) {
5287
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
5288
+ throw new SyntaxError("Object contains forbidden prototype property");
5289
+ }
5290
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
5291
+ throw new SyntaxError("Object contains forbidden prototype property");
5292
+ }
5293
+ for (const key in node) {
5294
+ const value = node[key];
5295
+ if (value && typeof value === "object") {
5296
+ next.push(value);
5297
+ }
5298
+ }
5299
+ }
5300
+ }
5301
+ return obj;
5302
+ }
5303
+ function secureJsonParse(text2) {
5304
+ const { stackTraceLimit } = Error;
5305
+ try {
5306
+ Error.stackTraceLimit = 0;
5307
+ } catch (e) {
5308
+ return _parse(text2);
5309
+ }
5310
+ try {
5311
+ return _parse(text2);
5312
+ } finally {
5313
+ Error.stackTraceLimit = stackTraceLimit;
5314
+ }
5315
+ }
5316
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
5317
+ function validator(validate) {
5318
+ return { [validatorSymbol]: true, validate };
5319
+ }
5320
+ function isValidator(value) {
5321
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
5322
+ }
5323
+ function lazyValidator(createValidator) {
5324
+ let validator2;
5325
+ return () => {
5326
+ if (validator2 == null) {
5327
+ validator2 = createValidator();
5328
+ }
5329
+ return validator2;
5330
+ };
5331
+ }
5332
+ function asValidator(value) {
5333
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
5334
+ }
5335
+ function standardSchemaValidator(standardSchema) {
5336
+ return validator(async (value) => {
5337
+ const result = await standardSchema["~standard"].validate(value);
5338
+ return result.issues == null ? { success: true, value: result.value } : {
5339
+ success: false,
5340
+ error: new TypeValidationError({
5341
+ value,
5342
+ cause: result.issues
5343
+ })
5344
+ };
5345
+ });
5346
+ }
5347
+ async function validateTypes({
5348
+ value,
5349
+ schema
5350
+ }) {
5351
+ const result = await safeValidateTypes({ value, schema });
5352
+ if (!result.success) {
5353
+ throw TypeValidationError.wrap({ value, cause: result.error });
5354
+ }
5355
+ return result.value;
5356
+ }
5357
+ async function safeValidateTypes({
5358
+ value,
5359
+ schema
5360
+ }) {
5361
+ const validator2 = asValidator(schema);
5362
+ try {
5363
+ if (validator2.validate == null) {
5364
+ return { success: true, value, rawValue: value };
5365
+ }
5366
+ const result = await validator2.validate(value);
5367
+ if (result.success) {
5368
+ return { success: true, value: result.value, rawValue: value };
5369
+ }
5370
+ return {
5371
+ success: false,
5372
+ error: TypeValidationError.wrap({ value, cause: result.error }),
5373
+ rawValue: value
5374
+ };
5375
+ } catch (error) {
5376
+ return {
5377
+ success: false,
5378
+ error: TypeValidationError.wrap({ value, cause: error }),
5379
+ rawValue: value
5380
+ };
5381
+ }
5382
+ }
5383
+ async function parseJSON({
5384
+ text: text2,
5385
+ schema
5386
+ }) {
5387
+ try {
5388
+ const value = secureJsonParse(text2);
5389
+ if (schema == null) {
5390
+ return value;
5391
+ }
5392
+ return validateTypes({ value, schema });
5393
+ } catch (error) {
5394
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
5395
+ throw error;
5396
+ }
5397
+ throw new JSONParseError({ text: text2, cause: error });
5398
+ }
5399
+ }
5400
+ async function safeParseJSON({
5401
+ text: text2,
5402
+ schema
5403
+ }) {
5404
+ try {
5405
+ const value = secureJsonParse(text2);
5406
+ if (schema == null) {
5407
+ return { success: true, value, rawValue: value };
5408
+ }
5409
+ return await safeValidateTypes({ value, schema });
5410
+ } catch (error) {
5411
+ return {
5412
+ success: false,
5413
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
5414
+ rawValue: void 0
5415
+ };
5416
+ }
5417
+ }
5418
+ function parseJsonEventStream({
5419
+ stream,
5420
+ schema
5421
+ }) {
5422
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
5423
+ new TransformStream({
5424
+ async transform({ data }, controller) {
5425
+ if (data === "[DONE]") {
5426
+ return;
5427
+ }
5428
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
5429
+ }
5430
+ })
5431
+ );
5432
+ }
5433
+ var getOriginalFetch2 = () => globalThis.fetch;
5434
+ var postJsonToApi = async ({
5435
+ url,
5436
+ headers,
5437
+ body,
5438
+ failedResponseHandler,
5439
+ successfulResponseHandler,
5440
+ abortSignal,
5441
+ fetch: fetch2
5442
+ }) => postToApi({
5443
+ url,
5444
+ headers: {
5445
+ "Content-Type": "application/json",
5446
+ ...headers
5447
+ },
5448
+ body: {
5449
+ content: JSON.stringify(body),
5450
+ values: body
5451
+ },
5452
+ failedResponseHandler,
5453
+ successfulResponseHandler,
5454
+ abortSignal,
5455
+ fetch: fetch2
5456
+ });
5457
+ var postToApi = async ({
5458
+ url,
5459
+ headers = {},
5460
+ body,
5461
+ successfulResponseHandler,
5462
+ failedResponseHandler,
5463
+ abortSignal,
5464
+ fetch: fetch2 = getOriginalFetch2()
5465
+ }) => {
5466
+ try {
5467
+ const response = await fetch2(url, {
5468
+ method: "POST",
5469
+ headers: withUserAgentSuffix(
5470
+ headers,
5471
+ `ai-sdk/provider-utils/${VERSION}`,
5472
+ getRuntimeEnvironmentUserAgent()
5473
+ ),
5474
+ body: body.content,
5475
+ signal: abortSignal
5476
+ });
5477
+ const responseHeaders = extractResponseHeaders(response);
5478
+ if (!response.ok) {
5479
+ let errorInformation;
5480
+ try {
5481
+ errorInformation = await failedResponseHandler({
5482
+ response,
5483
+ url,
5484
+ requestBodyValues: body.values
5485
+ });
5486
+ } catch (error) {
5487
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5488
+ throw error;
5489
+ }
5490
+ throw new APICallError({
5491
+ message: "Failed to process error response",
5492
+ cause: error,
5493
+ statusCode: response.status,
5494
+ url,
5495
+ responseHeaders,
5496
+ requestBodyValues: body.values
5497
+ });
5498
+ }
5499
+ throw errorInformation.value;
5500
+ }
5501
+ try {
5502
+ return await successfulResponseHandler({
5503
+ response,
5504
+ url,
5505
+ requestBodyValues: body.values
5506
+ });
5507
+ } catch (error) {
5508
+ if (error instanceof Error) {
5509
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5510
+ throw error;
5511
+ }
5512
+ }
5513
+ throw new APICallError({
5514
+ message: "Failed to process successful response",
5515
+ cause: error,
5516
+ statusCode: response.status,
5517
+ url,
5518
+ responseHeaders,
5519
+ requestBodyValues: body.values
5520
+ });
5521
+ }
5522
+ } catch (error) {
5523
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
5524
+ }
5525
+ };
5526
+ async function resolve4(value) {
5527
+ if (typeof value === "function") {
5528
+ value = value();
5529
+ }
5530
+ return Promise.resolve(value);
5531
+ }
5532
+ var createJsonErrorResponseHandler = ({
5533
+ errorSchema,
5534
+ errorToMessage,
5535
+ isRetryable
5536
+ }) => async ({ response, url, requestBodyValues }) => {
5537
+ const responseBody = await response.text();
5538
+ const responseHeaders = extractResponseHeaders(response);
5539
+ if (responseBody.trim() === "") {
5540
+ return {
5541
+ responseHeaders,
5542
+ value: new APICallError({
5543
+ message: response.statusText,
5544
+ url,
5545
+ requestBodyValues,
5546
+ statusCode: response.status,
5547
+ responseHeaders,
5548
+ responseBody,
5549
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5550
+ })
5551
+ };
5552
+ }
5553
+ try {
5554
+ const parsedError = await parseJSON({
5555
+ text: responseBody,
5556
+ schema: errorSchema
5557
+ });
5558
+ return {
5559
+ responseHeaders,
5560
+ value: new APICallError({
5561
+ message: errorToMessage(parsedError),
5562
+ url,
5563
+ requestBodyValues,
5564
+ statusCode: response.status,
5565
+ responseHeaders,
5566
+ responseBody,
5567
+ data: parsedError,
5568
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
5569
+ })
5570
+ };
5571
+ } catch (parseError) {
5572
+ return {
5573
+ responseHeaders,
5574
+ value: new APICallError({
5575
+ message: response.statusText,
5576
+ url,
5577
+ requestBodyValues,
5578
+ statusCode: response.status,
5579
+ responseHeaders,
5580
+ responseBody,
5581
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5582
+ })
5583
+ };
5584
+ }
5585
+ };
5586
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
5587
+ const responseHeaders = extractResponseHeaders(response);
5588
+ if (response.body == null) {
5589
+ throw new EmptyResponseBodyError({});
5590
+ }
5591
+ return {
5592
+ responseHeaders,
5593
+ value: parseJsonEventStream({
5594
+ stream: response.body,
5595
+ schema: chunkSchema
5596
+ })
5597
+ };
5598
+ };
5599
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
5600
+ const responseBody = await response.text();
5601
+ const parsedResult = await safeParseJSON({
5602
+ text: responseBody,
5603
+ schema: responseSchema
5604
+ });
5605
+ const responseHeaders = extractResponseHeaders(response);
5606
+ if (!parsedResult.success) {
5607
+ throw new APICallError({
5608
+ message: "Invalid JSON response",
5609
+ cause: parsedResult.error,
5610
+ statusCode: response.status,
5611
+ responseHeaders,
5612
+ responseBody,
5613
+ url,
5614
+ requestBodyValues
5615
+ });
5616
+ }
5617
+ return {
5618
+ responseHeaders,
5619
+ value: parsedResult.value,
5620
+ rawValue: parsedResult.rawValue
5621
+ };
5622
+ };
5623
+ var getRelativePath = (pathA, pathB) => {
5624
+ let i = 0;
5625
+ for (; i < pathA.length && i < pathB.length; i++) {
5626
+ if (pathA[i] !== pathB[i]) break;
5627
+ }
5628
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
5629
+ };
5630
+ var ignoreOverride = Symbol(
5631
+ "Let zodToJsonSchema decide on which parser to use"
5632
+ );
5633
+ var defaultOptions = {
5634
+ name: void 0,
5635
+ $refStrategy: "root",
5636
+ basePath: ["#"],
5637
+ effectStrategy: "input",
5638
+ pipeStrategy: "all",
5639
+ dateStrategy: "format:date-time",
5640
+ mapStrategy: "entries",
5641
+ removeAdditionalStrategy: "passthrough",
5642
+ allowedAdditionalProperties: true,
5643
+ rejectedAdditionalProperties: false,
5644
+ definitionPath: "definitions",
5645
+ strictUnions: false,
5646
+ definitions: {},
5647
+ errorMessages: false,
5648
+ patternStrategy: "escape",
5649
+ applyRegexFlags: false,
5650
+ emailStrategy: "format:email",
5651
+ base64Strategy: "contentEncoding:base64",
5652
+ nameStrategy: "ref"
5653
+ };
5654
+ var getDefaultOptions = (options) => typeof options === "string" ? {
5655
+ ...defaultOptions,
5656
+ name: options
5657
+ } : {
5658
+ ...defaultOptions,
5659
+ ...options
5660
+ };
5661
+ function parseAnyDef() {
5662
+ return {};
5663
+ }
5664
+ function parseArrayDef(def, refs) {
5665
+ var _a153, _b8, _c;
5666
+ const res = {
5667
+ type: "array"
5668
+ };
5669
+ if (((_a153 = def.type) == null ? void 0 : _a153._def) && ((_c = (_b8 = def.type) == null ? void 0 : _b8._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
5670
+ res.items = parseDef(def.type._def, {
5671
+ ...refs,
5672
+ currentPath: [...refs.currentPath, "items"]
5673
+ });
5674
+ }
5675
+ if (def.minLength) {
5676
+ res.minItems = def.minLength.value;
5677
+ }
5678
+ if (def.maxLength) {
5679
+ res.maxItems = def.maxLength.value;
5680
+ }
5681
+ if (def.exactLength) {
5682
+ res.minItems = def.exactLength.value;
5683
+ res.maxItems = def.exactLength.value;
5684
+ }
5685
+ return res;
5686
+ }
5687
+ function parseBigintDef(def) {
5688
+ const res = {
5689
+ type: "integer",
5690
+ format: "int64"
5691
+ };
5692
+ if (!def.checks) return res;
5693
+ for (const check of def.checks) {
5694
+ switch (check.kind) {
5695
+ case "min":
5696
+ if (check.inclusive) {
5697
+ res.minimum = check.value;
5698
+ } else {
5699
+ res.exclusiveMinimum = check.value;
5700
+ }
5701
+ break;
5702
+ case "max":
5703
+ if (check.inclusive) {
5704
+ res.maximum = check.value;
5705
+ } else {
5706
+ res.exclusiveMaximum = check.value;
5707
+ }
5708
+ break;
5709
+ case "multipleOf":
5710
+ res.multipleOf = check.value;
5711
+ break;
5712
+ }
5713
+ }
5714
+ return res;
5715
+ }
5716
+ function parseBooleanDef() {
5717
+ return { type: "boolean" };
5718
+ }
5719
+ function parseBrandedDef(_def, refs) {
5720
+ return parseDef(_def.type._def, refs);
5721
+ }
5722
+ var parseCatchDef = (def, refs) => {
5723
+ return parseDef(def.innerType._def, refs);
5724
+ };
5725
+ function parseDateDef(def, refs, overrideDateStrategy) {
5726
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
5727
+ if (Array.isArray(strategy)) {
5728
+ return {
5729
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
5730
+ };
5731
+ }
5732
+ switch (strategy) {
5733
+ case "string":
5734
+ case "format:date-time":
5735
+ return {
5736
+ type: "string",
5737
+ format: "date-time"
5738
+ };
5739
+ case "format:date":
5740
+ return {
5741
+ type: "string",
5742
+ format: "date"
5743
+ };
5744
+ case "integer":
5745
+ return integerDateParser(def);
5746
+ }
5747
+ }
5748
+ var integerDateParser = (def) => {
5749
+ const res = {
5750
+ type: "integer",
5751
+ format: "unix-time"
5752
+ };
5753
+ for (const check of def.checks) {
5754
+ switch (check.kind) {
5755
+ case "min":
5756
+ res.minimum = check.value;
5757
+ break;
5758
+ case "max":
5759
+ res.maximum = check.value;
5760
+ break;
5761
+ }
5762
+ }
5763
+ return res;
5764
+ };
5765
+ function parseDefaultDef(_def, refs) {
5766
+ return {
5767
+ ...parseDef(_def.innerType._def, refs),
5768
+ default: _def.defaultValue()
5769
+ };
5770
+ }
5771
+ function parseEffectsDef(_def, refs) {
5772
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
5773
+ }
5774
+ function parseEnumDef(def) {
5775
+ return {
5776
+ type: "string",
5777
+ enum: Array.from(def.values)
5778
+ };
5779
+ }
5780
+ var isJsonSchema7AllOfType = (type) => {
5781
+ if ("type" in type && type.type === "string") return false;
5782
+ return "allOf" in type;
5783
+ };
5784
+ function parseIntersectionDef(def, refs) {
5785
+ const allOf = [
5786
+ parseDef(def.left._def, {
5787
+ ...refs,
5788
+ currentPath: [...refs.currentPath, "allOf", "0"]
5789
+ }),
5790
+ parseDef(def.right._def, {
5791
+ ...refs,
5792
+ currentPath: [...refs.currentPath, "allOf", "1"]
5793
+ })
5794
+ ].filter((x) => !!x);
5795
+ const mergedAllOf = [];
5796
+ allOf.forEach((schema) => {
5797
+ if (isJsonSchema7AllOfType(schema)) {
5798
+ mergedAllOf.push(...schema.allOf);
5799
+ } else {
5800
+ let nestedSchema = schema;
5801
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
5802
+ const { additionalProperties, ...rest } = schema;
5803
+ nestedSchema = rest;
5804
+ }
5805
+ mergedAllOf.push(nestedSchema);
5806
+ }
5807
+ });
5808
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
5809
+ }
5810
+ function parseLiteralDef(def) {
5811
+ const parsedType = typeof def.value;
5812
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
5813
+ return {
5814
+ type: Array.isArray(def.value) ? "array" : "object"
5815
+ };
5816
+ }
5817
+ return {
5818
+ type: parsedType === "bigint" ? "integer" : parsedType,
5819
+ const: def.value
5820
+ };
5821
+ }
5822
+ var emojiRegex = void 0;
5823
+ var zodPatterns = {
5824
+ /**
5825
+ * `c` was changed to `[cC]` to replicate /i flag
5826
+ */
5827
+ cuid: /^[cC][^\s-]{8,}$/,
5828
+ cuid2: /^[0-9a-z]+$/,
5829
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
5830
+ /**
5831
+ * `a-z` was added to replicate /i flag
5832
+ */
5833
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
5834
+ /**
5835
+ * Constructed a valid Unicode RegExp
5836
+ *
5837
+ * Lazily instantiate since this type of regex isn't supported
5838
+ * in all envs (e.g. React Native).
5839
+ *
5840
+ * See:
5841
+ * https://github.com/colinhacks/zod/issues/2433
5842
+ * Fix in Zod:
5843
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
5844
+ */
5845
+ emoji: () => {
5846
+ if (emojiRegex === void 0) {
5847
+ emojiRegex = RegExp(
5848
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
5849
+ "u"
5850
+ );
5851
+ }
5852
+ return emojiRegex;
5853
+ },
5854
+ /**
5855
+ * Unused
5856
+ */
5857
+ 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}$/,
5858
+ /**
5859
+ * Unused
5860
+ */
5861
+ 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])$/,
5862
+ 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])$/,
5863
+ /**
5864
+ * Unused
5865
+ */
5866
+ 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})))$/,
5867
+ 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])$/,
5868
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
5869
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
5870
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
5871
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
5872
+ };
5873
+ function parseStringDef(def, refs) {
5874
+ const res = {
5875
+ type: "string"
5876
+ };
5877
+ if (def.checks) {
5878
+ for (const check of def.checks) {
5879
+ switch (check.kind) {
5880
+ case "min":
5881
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
5882
+ break;
5883
+ case "max":
5884
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
5885
+ break;
5886
+ case "email":
5887
+ switch (refs.emailStrategy) {
5888
+ case "format:email":
5889
+ addFormat(res, "email", check.message, refs);
5890
+ break;
5891
+ case "format:idn-email":
5892
+ addFormat(res, "idn-email", check.message, refs);
5893
+ break;
5894
+ case "pattern:zod":
5895
+ addPattern(res, zodPatterns.email, check.message, refs);
5896
+ break;
5897
+ }
5898
+ break;
5899
+ case "url":
5900
+ addFormat(res, "uri", check.message, refs);
5901
+ break;
5902
+ case "uuid":
5903
+ addFormat(res, "uuid", check.message, refs);
5904
+ break;
5905
+ case "regex":
5906
+ addPattern(res, check.regex, check.message, refs);
5907
+ break;
5908
+ case "cuid":
5909
+ addPattern(res, zodPatterns.cuid, check.message, refs);
5910
+ break;
5911
+ case "cuid2":
5912
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
5913
+ break;
5914
+ case "startsWith":
5915
+ addPattern(
5916
+ res,
5917
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
5918
+ check.message,
5919
+ refs
5920
+ );
5921
+ break;
5922
+ case "endsWith":
5923
+ addPattern(
5924
+ res,
5925
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
5926
+ check.message,
5927
+ refs
5928
+ );
5929
+ break;
5930
+ case "datetime":
5931
+ addFormat(res, "date-time", check.message, refs);
5932
+ break;
5933
+ case "date":
5934
+ addFormat(res, "date", check.message, refs);
5935
+ break;
5936
+ case "time":
5937
+ addFormat(res, "time", check.message, refs);
5938
+ break;
5939
+ case "duration":
5940
+ addFormat(res, "duration", check.message, refs);
5941
+ break;
5942
+ case "length":
5943
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
5944
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
5945
+ break;
5946
+ case "includes": {
5947
+ addPattern(
5948
+ res,
5949
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
5950
+ check.message,
5951
+ refs
5952
+ );
5953
+ break;
5954
+ }
5955
+ case "ip": {
5956
+ if (check.version !== "v6") {
5957
+ addFormat(res, "ipv4", check.message, refs);
5958
+ }
5959
+ if (check.version !== "v4") {
5960
+ addFormat(res, "ipv6", check.message, refs);
5961
+ }
5962
+ break;
5963
+ }
5964
+ case "base64url":
5965
+ addPattern(res, zodPatterns.base64url, check.message, refs);
5966
+ break;
5967
+ case "jwt":
5968
+ addPattern(res, zodPatterns.jwt, check.message, refs);
5969
+ break;
5970
+ case "cidr": {
5971
+ if (check.version !== "v6") {
5972
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
5973
+ }
5974
+ if (check.version !== "v4") {
5975
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
5976
+ }
5977
+ break;
5978
+ }
5979
+ case "emoji":
5980
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
5981
+ break;
5982
+ case "ulid": {
5983
+ addPattern(res, zodPatterns.ulid, check.message, refs);
5984
+ break;
5985
+ }
5986
+ case "base64": {
5987
+ switch (refs.base64Strategy) {
5988
+ case "format:binary": {
5989
+ addFormat(res, "binary", check.message, refs);
5990
+ break;
5991
+ }
5992
+ case "contentEncoding:base64": {
5993
+ res.contentEncoding = "base64";
5994
+ break;
5995
+ }
5996
+ case "pattern:zod": {
5997
+ addPattern(res, zodPatterns.base64, check.message, refs);
5998
+ break;
5999
+ }
6000
+ }
6001
+ break;
6002
+ }
6003
+ case "nanoid": {
6004
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
6005
+ }
6006
+ }
6007
+ }
6008
+ }
6009
+ return res;
6010
+ }
6011
+ function escapeLiteralCheckValue(literal, refs) {
6012
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
6013
+ }
6014
+ var ALPHA_NUMERIC = new Set(
6015
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
6016
+ );
6017
+ function escapeNonAlphaNumeric(source) {
6018
+ let result = "";
6019
+ for (let i = 0; i < source.length; i++) {
6020
+ if (!ALPHA_NUMERIC.has(source[i])) {
6021
+ result += "\\";
6022
+ }
6023
+ result += source[i];
6024
+ }
6025
+ return result;
6026
+ }
6027
+ function addFormat(schema, value, message, refs) {
6028
+ var _a153;
6029
+ if (schema.format || ((_a153 = schema.anyOf) == null ? void 0 : _a153.some((x) => x.format))) {
6030
+ if (!schema.anyOf) {
6031
+ schema.anyOf = [];
6032
+ }
6033
+ if (schema.format) {
6034
+ schema.anyOf.push({
6035
+ format: schema.format
6036
+ });
6037
+ delete schema.format;
6038
+ }
6039
+ schema.anyOf.push({
6040
+ format: value,
6041
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
6042
+ });
6043
+ } else {
6044
+ schema.format = value;
6045
+ }
6046
+ }
6047
+ function addPattern(schema, regex, message, refs) {
6048
+ var _a153;
6049
+ if (schema.pattern || ((_a153 = schema.allOf) == null ? void 0 : _a153.some((x) => x.pattern))) {
6050
+ if (!schema.allOf) {
6051
+ schema.allOf = [];
6052
+ }
6053
+ if (schema.pattern) {
6054
+ schema.allOf.push({
6055
+ pattern: schema.pattern
6056
+ });
6057
+ delete schema.pattern;
6058
+ }
6059
+ schema.allOf.push({
6060
+ pattern: stringifyRegExpWithFlags(regex, refs),
6061
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
6062
+ });
6063
+ } else {
6064
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
6065
+ }
6066
+ }
6067
+ function stringifyRegExpWithFlags(regex, refs) {
6068
+ var _a153;
6069
+ if (!refs.applyRegexFlags || !regex.flags) {
6070
+ return regex.source;
6071
+ }
6072
+ const flags = {
6073
+ i: regex.flags.includes("i"),
6074
+ // Case-insensitive
6075
+ m: regex.flags.includes("m"),
6076
+ // `^` and `$` matches adjacent to newline characters
6077
+ s: regex.flags.includes("s")
6078
+ // `.` matches newlines
6079
+ };
6080
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
6081
+ let pattern = "";
6082
+ let isEscaped = false;
6083
+ let inCharGroup = false;
6084
+ let inCharRange = false;
6085
+ for (let i = 0; i < source.length; i++) {
6086
+ if (isEscaped) {
6087
+ pattern += source[i];
6088
+ isEscaped = false;
6089
+ continue;
6090
+ }
6091
+ if (flags.i) {
6092
+ if (inCharGroup) {
6093
+ if (source[i].match(/[a-z]/)) {
6094
+ if (inCharRange) {
6095
+ pattern += source[i];
6096
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
6097
+ inCharRange = false;
6098
+ } else if (source[i + 1] === "-" && ((_a153 = source[i + 2]) == null ? void 0 : _a153.match(/[a-z]/))) {
6099
+ pattern += source[i];
6100
+ inCharRange = true;
6101
+ } else {
6102
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
6103
+ }
6104
+ continue;
6105
+ }
6106
+ } else if (source[i].match(/[a-z]/)) {
6107
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
6108
+ continue;
6109
+ }
6110
+ }
6111
+ if (flags.m) {
6112
+ if (source[i] === "^") {
6113
+ pattern += `(^|(?<=[\r
6114
+ ]))`;
6115
+ continue;
6116
+ } else if (source[i] === "$") {
6117
+ pattern += `($|(?=[\r
6118
+ ]))`;
6119
+ continue;
6120
+ }
6121
+ }
6122
+ if (flags.s && source[i] === ".") {
6123
+ pattern += inCharGroup ? `${source[i]}\r
6124
+ ` : `[${source[i]}\r
6125
+ ]`;
6126
+ continue;
6127
+ }
6128
+ pattern += source[i];
6129
+ if (source[i] === "\\") {
6130
+ isEscaped = true;
6131
+ } else if (inCharGroup && source[i] === "]") {
6132
+ inCharGroup = false;
6133
+ } else if (!inCharGroup && source[i] === "[") {
6134
+ inCharGroup = true;
6135
+ }
6136
+ }
6137
+ return pattern;
6138
+ }
6139
+ function parseRecordDef(def, refs) {
6140
+ var _a153, _b8, _c, _d, _e, _f;
6141
+ const schema = {
6142
+ type: "object",
6143
+ additionalProperties: (_a153 = parseDef(def.valueType._def, {
6144
+ ...refs,
6145
+ currentPath: [...refs.currentPath, "additionalProperties"]
6146
+ })) != null ? _a153 : refs.allowedAdditionalProperties
6147
+ };
6148
+ if (((_b8 = def.keyType) == null ? void 0 : _b8._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
6149
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
6150
+ return {
6151
+ ...schema,
6152
+ propertyNames: keyType
6153
+ };
6154
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
6155
+ return {
6156
+ ...schema,
6157
+ propertyNames: {
6158
+ enum: def.keyType._def.values
6159
+ }
6160
+ };
6161
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
6162
+ const { type, ...keyType } = parseBrandedDef(
6163
+ def.keyType._def,
6164
+ refs
6165
+ );
6166
+ return {
6167
+ ...schema,
6168
+ propertyNames: keyType
6169
+ };
6170
+ }
6171
+ return schema;
6172
+ }
6173
+ function parseMapDef(def, refs) {
6174
+ if (refs.mapStrategy === "record") {
6175
+ return parseRecordDef(def, refs);
6176
+ }
6177
+ const keys = parseDef(def.keyType._def, {
6178
+ ...refs,
6179
+ currentPath: [...refs.currentPath, "items", "items", "0"]
6180
+ }) || parseAnyDef();
6181
+ const values = parseDef(def.valueType._def, {
6182
+ ...refs,
6183
+ currentPath: [...refs.currentPath, "items", "items", "1"]
6184
+ }) || parseAnyDef();
6185
+ return {
6186
+ type: "array",
6187
+ maxItems: 125,
6188
+ items: {
6189
+ type: "array",
6190
+ items: [keys, values],
6191
+ minItems: 2,
6192
+ maxItems: 2
6193
+ }
6194
+ };
6195
+ }
6196
+ function parseNativeEnumDef(def) {
6197
+ const object2 = def.values;
6198
+ const actualKeys = Object.keys(def.values).filter((key) => {
6199
+ return typeof object2[object2[key]] !== "number";
6200
+ });
6201
+ const actualValues = actualKeys.map((key) => object2[key]);
6202
+ const parsedTypes = Array.from(
6203
+ new Set(actualValues.map((values) => typeof values))
6204
+ );
6205
+ return {
6206
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
6207
+ enum: actualValues
6208
+ };
6209
+ }
6210
+ function parseNeverDef() {
6211
+ return { not: parseAnyDef() };
6212
+ }
6213
+ function parseNullDef() {
6214
+ return {
6215
+ type: "null"
6216
+ };
6217
+ }
6218
+ var primitiveMappings = {
6219
+ ZodString: "string",
6220
+ ZodNumber: "number",
6221
+ ZodBigInt: "integer",
6222
+ ZodBoolean: "boolean",
6223
+ ZodNull: "null"
6224
+ };
6225
+ function parseUnionDef(def, refs) {
6226
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
6227
+ if (options.every(
6228
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
6229
+ )) {
6230
+ const types = options.reduce((types2, x) => {
6231
+ const type = primitiveMappings[x._def.typeName];
6232
+ return type && !types2.includes(type) ? [...types2, type] : types2;
6233
+ }, []);
6234
+ return {
6235
+ type: types.length > 1 ? types : types[0]
6236
+ };
6237
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
6238
+ const types = options.reduce(
6239
+ (acc, x) => {
6240
+ const type = typeof x._def.value;
6241
+ switch (type) {
6242
+ case "string":
6243
+ case "number":
6244
+ case "boolean":
6245
+ return [...acc, type];
6246
+ case "bigint":
6247
+ return [...acc, "integer"];
6248
+ case "object":
6249
+ if (x._def.value === null) return [...acc, "null"];
6250
+ case "symbol":
6251
+ case "undefined":
6252
+ case "function":
6253
+ default:
6254
+ return acc;
6255
+ }
6256
+ },
6257
+ []
6258
+ );
6259
+ if (types.length === options.length) {
6260
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
6261
+ return {
6262
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
6263
+ enum: options.reduce(
6264
+ (acc, x) => {
6265
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
6266
+ },
6267
+ []
6268
+ )
6269
+ };
6270
+ }
6271
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
6272
+ return {
6273
+ type: "string",
6274
+ enum: options.reduce(
6275
+ (acc, x) => [
6276
+ ...acc,
6277
+ ...x._def.values.filter((x2) => !acc.includes(x2))
6278
+ ],
6279
+ []
6280
+ )
6281
+ };
6282
+ }
6283
+ return asAnyOf(def, refs);
6284
+ }
6285
+ var asAnyOf = (def, refs) => {
6286
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
6287
+ (x, i) => parseDef(x._def, {
6288
+ ...refs,
6289
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
6290
+ })
6291
+ ).filter(
6292
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
6293
+ );
6294
+ return anyOf.length ? { anyOf } : void 0;
6295
+ };
6296
+ function parseNullableDef(def, refs) {
6297
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
6298
+ def.innerType._def.typeName
6299
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
6300
+ return {
6301
+ type: [
6302
+ primitiveMappings[def.innerType._def.typeName],
6303
+ "null"
6304
+ ]
6305
+ };
6306
+ }
6307
+ const base = parseDef(def.innerType._def, {
6308
+ ...refs,
6309
+ currentPath: [...refs.currentPath, "anyOf", "0"]
6310
+ });
6311
+ return base && { anyOf: [base, { type: "null" }] };
6312
+ }
6313
+ function parseNumberDef(def) {
6314
+ const res = {
6315
+ type: "number"
6316
+ };
6317
+ if (!def.checks) return res;
6318
+ for (const check of def.checks) {
6319
+ switch (check.kind) {
6320
+ case "int":
6321
+ res.type = "integer";
6322
+ break;
6323
+ case "min":
6324
+ if (check.inclusive) {
6325
+ res.minimum = check.value;
6326
+ } else {
6327
+ res.exclusiveMinimum = check.value;
6328
+ }
6329
+ break;
6330
+ case "max":
6331
+ if (check.inclusive) {
6332
+ res.maximum = check.value;
6333
+ } else {
6334
+ res.exclusiveMaximum = check.value;
6335
+ }
6336
+ break;
6337
+ case "multipleOf":
6338
+ res.multipleOf = check.value;
6339
+ break;
6340
+ }
6341
+ }
6342
+ return res;
6343
+ }
6344
+ function parseObjectDef(def, refs) {
6345
+ const result = {
6346
+ type: "object",
6347
+ properties: {}
6348
+ };
6349
+ const required = [];
6350
+ const shape = def.shape();
6351
+ for (const propName in shape) {
6352
+ let propDef = shape[propName];
6353
+ if (propDef === void 0 || propDef._def === void 0) {
6354
+ continue;
6355
+ }
6356
+ const propOptional = safeIsOptional(propDef);
6357
+ const parsedDef = parseDef(propDef._def, {
6358
+ ...refs,
6359
+ currentPath: [...refs.currentPath, "properties", propName],
6360
+ propertyPath: [...refs.currentPath, "properties", propName]
6361
+ });
6362
+ if (parsedDef === void 0) {
6363
+ continue;
6364
+ }
6365
+ result.properties[propName] = parsedDef;
6366
+ if (!propOptional) {
6367
+ required.push(propName);
6368
+ }
6369
+ }
6370
+ if (required.length) {
6371
+ result.required = required;
6372
+ }
6373
+ const additionalProperties = decideAdditionalProperties(def, refs);
6374
+ if (additionalProperties !== void 0) {
6375
+ result.additionalProperties = additionalProperties;
6376
+ }
6377
+ return result;
6378
+ }
6379
+ function decideAdditionalProperties(def, refs) {
6380
+ if (def.catchall._def.typeName !== "ZodNever") {
6381
+ return parseDef(def.catchall._def, {
6382
+ ...refs,
6383
+ currentPath: [...refs.currentPath, "additionalProperties"]
6384
+ });
6385
+ }
6386
+ switch (def.unknownKeys) {
6387
+ case "passthrough":
6388
+ return refs.allowedAdditionalProperties;
6389
+ case "strict":
6390
+ return refs.rejectedAdditionalProperties;
6391
+ case "strip":
6392
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
6393
+ }
6394
+ }
6395
+ function safeIsOptional(schema) {
6396
+ try {
6397
+ return schema.isOptional();
6398
+ } catch (e) {
6399
+ return true;
6400
+ }
6401
+ }
6402
+ var parseOptionalDef = (def, refs) => {
6403
+ var _a153;
6404
+ if (refs.currentPath.toString() === ((_a153 = refs.propertyPath) == null ? void 0 : _a153.toString())) {
6405
+ return parseDef(def.innerType._def, refs);
6406
+ }
6407
+ const innerSchema = parseDef(def.innerType._def, {
6408
+ ...refs,
6409
+ currentPath: [...refs.currentPath, "anyOf", "1"]
6410
+ });
6411
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
6412
+ };
6413
+ var parsePipelineDef = (def, refs) => {
6414
+ if (refs.pipeStrategy === "input") {
6415
+ return parseDef(def.in._def, refs);
6416
+ } else if (refs.pipeStrategy === "output") {
6417
+ return parseDef(def.out._def, refs);
6418
+ }
6419
+ const a = parseDef(def.in._def, {
6420
+ ...refs,
6421
+ currentPath: [...refs.currentPath, "allOf", "0"]
6422
+ });
6423
+ const b = parseDef(def.out._def, {
6424
+ ...refs,
6425
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
6426
+ });
6427
+ return {
6428
+ allOf: [a, b].filter((x) => x !== void 0)
6429
+ };
6430
+ };
6431
+ function parsePromiseDef(def, refs) {
6432
+ return parseDef(def.type._def, refs);
6433
+ }
6434
+ function parseSetDef(def, refs) {
6435
+ const items = parseDef(def.valueType._def, {
6436
+ ...refs,
6437
+ currentPath: [...refs.currentPath, "items"]
6438
+ });
6439
+ const schema = {
6440
+ type: "array",
6441
+ uniqueItems: true,
6442
+ items
6443
+ };
6444
+ if (def.minSize) {
6445
+ schema.minItems = def.minSize.value;
6446
+ }
6447
+ if (def.maxSize) {
6448
+ schema.maxItems = def.maxSize.value;
6449
+ }
6450
+ return schema;
6451
+ }
6452
+ function parseTupleDef(def, refs) {
6453
+ if (def.rest) {
6454
+ return {
6455
+ type: "array",
6456
+ minItems: def.items.length,
6457
+ items: def.items.map(
6458
+ (x, i) => parseDef(x._def, {
6459
+ ...refs,
6460
+ currentPath: [...refs.currentPath, "items", `${i}`]
6461
+ })
6462
+ ).reduce(
6463
+ (acc, x) => x === void 0 ? acc : [...acc, x],
6464
+ []
6465
+ ),
6466
+ additionalItems: parseDef(def.rest._def, {
6467
+ ...refs,
6468
+ currentPath: [...refs.currentPath, "additionalItems"]
6469
+ })
6470
+ };
6471
+ } else {
6472
+ return {
6473
+ type: "array",
6474
+ minItems: def.items.length,
6475
+ maxItems: def.items.length,
6476
+ items: def.items.map(
6477
+ (x, i) => parseDef(x._def, {
6478
+ ...refs,
6479
+ currentPath: [...refs.currentPath, "items", `${i}`]
6480
+ })
6481
+ ).reduce(
6482
+ (acc, x) => x === void 0 ? acc : [...acc, x],
6483
+ []
6484
+ )
6485
+ };
6486
+ }
6487
+ }
6488
+ function parseUndefinedDef() {
6489
+ return {
6490
+ not: parseAnyDef()
6491
+ };
6492
+ }
6493
+ function parseUnknownDef() {
6494
+ return parseAnyDef();
6495
+ }
6496
+ var parseReadonlyDef = (def, refs) => {
6497
+ return parseDef(def.innerType._def, refs);
6498
+ };
6499
+ var selectParser = (def, typeName, refs) => {
6500
+ switch (typeName) {
6501
+ case ZodFirstPartyTypeKind.ZodString:
6502
+ return parseStringDef(def, refs);
6503
+ case ZodFirstPartyTypeKind.ZodNumber:
6504
+ return parseNumberDef(def);
6505
+ case ZodFirstPartyTypeKind.ZodObject:
6506
+ return parseObjectDef(def, refs);
6507
+ case ZodFirstPartyTypeKind.ZodBigInt:
6508
+ return parseBigintDef(def);
6509
+ case ZodFirstPartyTypeKind.ZodBoolean:
6510
+ return parseBooleanDef();
6511
+ case ZodFirstPartyTypeKind.ZodDate:
6512
+ return parseDateDef(def, refs);
6513
+ case ZodFirstPartyTypeKind.ZodUndefined:
6514
+ return parseUndefinedDef();
6515
+ case ZodFirstPartyTypeKind.ZodNull:
6516
+ return parseNullDef();
6517
+ case ZodFirstPartyTypeKind.ZodArray:
6518
+ return parseArrayDef(def, refs);
6519
+ case ZodFirstPartyTypeKind.ZodUnion:
6520
+ case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
6521
+ return parseUnionDef(def, refs);
6522
+ case ZodFirstPartyTypeKind.ZodIntersection:
6523
+ return parseIntersectionDef(def, refs);
6524
+ case ZodFirstPartyTypeKind.ZodTuple:
6525
+ return parseTupleDef(def, refs);
6526
+ case ZodFirstPartyTypeKind.ZodRecord:
6527
+ return parseRecordDef(def, refs);
6528
+ case ZodFirstPartyTypeKind.ZodLiteral:
6529
+ return parseLiteralDef(def);
6530
+ case ZodFirstPartyTypeKind.ZodEnum:
6531
+ return parseEnumDef(def);
6532
+ case ZodFirstPartyTypeKind.ZodNativeEnum:
6533
+ return parseNativeEnumDef(def);
6534
+ case ZodFirstPartyTypeKind.ZodNullable:
6535
+ return parseNullableDef(def, refs);
6536
+ case ZodFirstPartyTypeKind.ZodOptional:
6537
+ return parseOptionalDef(def, refs);
6538
+ case ZodFirstPartyTypeKind.ZodMap:
6539
+ return parseMapDef(def, refs);
6540
+ case ZodFirstPartyTypeKind.ZodSet:
6541
+ return parseSetDef(def, refs);
6542
+ case ZodFirstPartyTypeKind.ZodLazy:
6543
+ return () => def.getter()._def;
6544
+ case ZodFirstPartyTypeKind.ZodPromise:
6545
+ return parsePromiseDef(def, refs);
6546
+ case ZodFirstPartyTypeKind.ZodNaN:
6547
+ case ZodFirstPartyTypeKind.ZodNever:
6548
+ return parseNeverDef();
6549
+ case ZodFirstPartyTypeKind.ZodEffects:
6550
+ return parseEffectsDef(def, refs);
6551
+ case ZodFirstPartyTypeKind.ZodAny:
6552
+ return parseAnyDef();
6553
+ case ZodFirstPartyTypeKind.ZodUnknown:
6554
+ return parseUnknownDef();
6555
+ case ZodFirstPartyTypeKind.ZodDefault:
6556
+ return parseDefaultDef(def, refs);
6557
+ case ZodFirstPartyTypeKind.ZodBranded:
6558
+ return parseBrandedDef(def, refs);
6559
+ case ZodFirstPartyTypeKind.ZodReadonly:
6560
+ return parseReadonlyDef(def, refs);
6561
+ case ZodFirstPartyTypeKind.ZodCatch:
6562
+ return parseCatchDef(def, refs);
6563
+ case ZodFirstPartyTypeKind.ZodPipeline:
6564
+ return parsePipelineDef(def, refs);
6565
+ case ZodFirstPartyTypeKind.ZodFunction:
6566
+ case ZodFirstPartyTypeKind.ZodVoid:
6567
+ case ZodFirstPartyTypeKind.ZodSymbol:
6568
+ return void 0;
6569
+ default:
6570
+ return /* @__PURE__ */ ((_) => void 0)();
6571
+ }
6572
+ };
6573
+ function parseDef(def, refs, forceResolution = false) {
6574
+ var _a153;
6575
+ const seenItem = refs.seen.get(def);
6576
+ if (refs.override) {
6577
+ const overrideResult = (_a153 = refs.override) == null ? void 0 : _a153.call(
6578
+ refs,
6579
+ def,
6580
+ refs,
6581
+ seenItem,
6582
+ forceResolution
6583
+ );
6584
+ if (overrideResult !== ignoreOverride) {
6585
+ return overrideResult;
6586
+ }
6587
+ }
6588
+ if (seenItem && !forceResolution) {
6589
+ const seenSchema = get$ref(seenItem, refs);
6590
+ if (seenSchema !== void 0) {
6591
+ return seenSchema;
6592
+ }
6593
+ }
6594
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
6595
+ refs.seen.set(def, newItem);
6596
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
6597
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
6598
+ if (jsonSchema2) {
6599
+ addMeta(def, refs, jsonSchema2);
6600
+ }
6601
+ if (refs.postProcess) {
6602
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
6603
+ newItem.jsonSchema = jsonSchema2;
6604
+ return postProcessResult;
6605
+ }
6606
+ newItem.jsonSchema = jsonSchema2;
6607
+ return jsonSchema2;
6608
+ }
6609
+ var get$ref = (item, refs) => {
6610
+ switch (refs.$refStrategy) {
6611
+ case "root":
6612
+ return { $ref: item.path.join("/") };
6613
+ case "relative":
6614
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
6615
+ case "none":
6616
+ case "seen": {
6617
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
6618
+ console.warn(
6619
+ `Recursive reference detected at ${refs.currentPath.join(
6620
+ "/"
6621
+ )}! Defaulting to any`
6622
+ );
6623
+ return parseAnyDef();
6624
+ }
6625
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
6626
+ }
6627
+ }
6628
+ };
6629
+ var addMeta = (def, refs, jsonSchema2) => {
6630
+ if (def.description) {
6631
+ jsonSchema2.description = def.description;
6632
+ }
6633
+ return jsonSchema2;
6634
+ };
6635
+ var getRefs = (options) => {
6636
+ const _options = getDefaultOptions(options);
6637
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
6638
+ return {
6639
+ ..._options,
6640
+ currentPath,
6641
+ propertyPath: void 0,
6642
+ seen: new Map(
6643
+ Object.entries(_options.definitions).map(([name143, def]) => [
6644
+ def._def,
6645
+ {
6646
+ def: def._def,
6647
+ path: [..._options.basePath, _options.definitionPath, name143],
6648
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
6649
+ jsonSchema: void 0
6650
+ }
6651
+ ])
6652
+ )
6653
+ };
6654
+ };
6655
+ var zodToJsonSchema = (schema, options) => {
6656
+ var _a153;
6657
+ const refs = getRefs(options);
6658
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
6659
+ (acc, [name223, schema2]) => {
6660
+ var _a223;
6661
+ return {
6662
+ ...acc,
6663
+ [name223]: (_a223 = parseDef(
6664
+ schema2._def,
6665
+ {
6666
+ ...refs,
6667
+ currentPath: [...refs.basePath, refs.definitionPath, name223]
6668
+ },
6669
+ true
6670
+ )) != null ? _a223 : parseAnyDef()
6671
+ };
6672
+ },
6673
+ {}
6674
+ ) : void 0;
6675
+ const name143 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
6676
+ const main = (_a153 = parseDef(
6677
+ schema._def,
6678
+ name143 === void 0 ? refs : {
6679
+ ...refs,
6680
+ currentPath: [...refs.basePath, refs.definitionPath, name143]
6681
+ },
6682
+ false
6683
+ )) != null ? _a153 : parseAnyDef();
6684
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
6685
+ if (title !== void 0) {
6686
+ main.title = title;
6687
+ }
6688
+ const combined = name143 === void 0 ? definitions ? {
6689
+ ...main,
6690
+ [refs.definitionPath]: definitions
6691
+ } : main : {
6692
+ $ref: [
6693
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
6694
+ refs.definitionPath,
6695
+ name143
6696
+ ].join("/"),
6697
+ [refs.definitionPath]: {
6698
+ ...definitions,
6699
+ [name143]: main
6700
+ }
6701
+ };
6702
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
6703
+ return combined;
6704
+ };
6705
+ var zod_to_json_schema_default = zodToJsonSchema;
6706
+ function zod3Schema(zodSchema2, options) {
6707
+ var _a153;
6708
+ const useReferences = (_a153 = void 0 ) != null ? _a153 : false;
6709
+ return jsonSchema(
6710
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
6711
+ () => zod_to_json_schema_default(zodSchema2, {
6712
+ $refStrategy: useReferences ? "root" : "none"
6713
+ }),
6714
+ {
6715
+ validate: async (value) => {
6716
+ const result = await zodSchema2.safeParseAsync(value);
6717
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
6718
+ }
6719
+ }
6720
+ );
6721
+ }
6722
+ function zod4Schema(zodSchema2, options) {
6723
+ var _a153;
6724
+ const useReferences = (_a153 = void 0 ) != null ? _a153 : false;
6725
+ return jsonSchema(
6726
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
6727
+ () => z4.toJSONSchema(zodSchema2, {
6728
+ target: "draft-7",
6729
+ io: "output",
6730
+ reused: useReferences ? "ref" : "inline"
6731
+ }),
6732
+ {
6733
+ validate: async (value) => {
6734
+ const result = await z4.safeParseAsync(zodSchema2, value);
6735
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
6736
+ }
6737
+ }
6738
+ );
6739
+ }
6740
+ function isZod4Schema(zodSchema2) {
6741
+ return "_zod" in zodSchema2;
6742
+ }
6743
+ function zodSchema(zodSchema2, options) {
6744
+ if (isZod4Schema(zodSchema2)) {
6745
+ return zod4Schema(zodSchema2);
6746
+ } else {
6747
+ return zod3Schema(zodSchema2);
6748
+ }
6749
+ }
6750
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
6751
+ function jsonSchema(jsonSchema2, {
6752
+ validate
6753
+ } = {}) {
6754
+ return {
6755
+ [schemaSymbol]: true,
6756
+ _type: void 0,
6757
+ // should never be used directly
6758
+ [validatorSymbol]: true,
6759
+ get jsonSchema() {
6760
+ if (typeof jsonSchema2 === "function") {
6761
+ jsonSchema2 = jsonSchema2();
6762
+ }
6763
+ return jsonSchema2;
6764
+ },
6765
+ validate
6766
+ };
6767
+ }
6768
+ function isSchema(value) {
6769
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
6770
+ }
6771
+ function asSchema(schema) {
6772
+ return schema == null ? jsonSchema({
6773
+ properties: {},
6774
+ additionalProperties: false
6775
+ }) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
6776
+ }
6777
+ function withoutTrailingSlash(url) {
6778
+ return url == null ? void 0 : url.replace(/\/$/, "");
6779
+ }
6780
+ var require_get_context = __commonJS({
6781
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-context.js"(exports, module) {
6782
+ var __defProp2 = Object.defineProperty;
6783
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6784
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6785
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6786
+ var __export2 = (target, all) => {
6787
+ for (var name16 in all)
6788
+ __defProp2(target, name16, { get: all[name16], enumerable: true });
6789
+ };
6790
+ var __copyProps = (to, from, except, desc) => {
6791
+ if (from && typeof from === "object" || typeof from === "function") {
6792
+ for (let key of __getOwnPropNames(from))
6793
+ if (!__hasOwnProp.call(to, key) && key !== except)
6794
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
6795
+ }
6796
+ return to;
6797
+ };
6798
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
6799
+ var get_context_exports = {};
6800
+ __export2(get_context_exports, {
6801
+ SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
6802
+ getContext: () => getContext3
6803
+ });
6804
+ module.exports = __toCommonJS(get_context_exports);
6805
+ var SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
6806
+ function getContext3() {
6807
+ const fromSymbol = globalThis;
6808
+ return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
6809
+ }
6810
+ }
6811
+ });
6812
+ var require_get_vercel_oidc_token = __commonJS({
6813
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports, module) {
6814
+ var __defProp2 = Object.defineProperty;
6815
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6816
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6817
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6818
+ var __export2 = (target, all) => {
6819
+ for (var name16 in all)
6820
+ __defProp2(target, name16, { get: all[name16], enumerable: true });
6821
+ };
6822
+ var __copyProps = (to, from, except, desc) => {
6823
+ if (from && typeof from === "object" || typeof from === "function") {
6824
+ for (let key of __getOwnPropNames(from))
6825
+ if (!__hasOwnProp.call(to, key) && key !== except)
6826
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
6827
+ }
6828
+ return to;
6829
+ };
6830
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
6831
+ var get_vercel_oidc_token_exports = {};
6832
+ __export2(get_vercel_oidc_token_exports, {
6833
+ getVercelOidcToken: () => getVercelOidcToken3,
6834
+ getVercelOidcTokenSync: () => getVercelOidcTokenSync2
6835
+ });
6836
+ module.exports = __toCommonJS(get_vercel_oidc_token_exports);
6837
+ var import_get_context = require_get_context();
6838
+ var import_token_error = require_token_error();
6839
+ async function getVercelOidcToken3() {
6840
+ let token = "";
6841
+ let err;
6842
+ try {
6843
+ token = getVercelOidcTokenSync2();
6844
+ } catch (error) {
6845
+ err = error;
6846
+ }
6847
+ try {
6848
+ const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
6849
+ await import('./token-util-NEHG7TUY-DJYRKLRD.js'),
6850
+ await import('./token-6GSAFR2W-KVDFAJ2M.js')
6851
+ ]);
6852
+ if (!token || isExpired(getTokenPayload(token))) {
6853
+ await refreshToken();
6854
+ token = getVercelOidcTokenSync2();
6855
+ }
6856
+ } catch (error) {
6857
+ if (err?.message && error instanceof Error) {
6858
+ error.message = `${err.message}
6859
+ ${error.message}`;
6860
+ }
6861
+ throw new import_token_error.VercelOidcTokenError(`Failed to refresh OIDC token`, error);
6862
+ }
6863
+ return token;
6864
+ }
6865
+ function getVercelOidcTokenSync2() {
6866
+ const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
6867
+ if (!token) {
6868
+ throw new Error(
6869
+ `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
6870
+ );
6871
+ }
6872
+ return token;
6873
+ }
6874
+ }
6875
+ });
6876
+ var require_dist = __commonJS({
6877
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/index.js"(exports, module) {
6878
+ var __defProp2 = Object.defineProperty;
6879
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6880
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6881
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6882
+ var __export2 = (target, all) => {
6883
+ for (var name16 in all)
6884
+ __defProp2(target, name16, { get: all[name16], enumerable: true });
6885
+ };
6886
+ var __copyProps = (to, from, except, desc) => {
6887
+ if (from && typeof from === "object" || typeof from === "function") {
6888
+ for (let key of __getOwnPropNames(from))
6889
+ if (!__hasOwnProp.call(to, key) && key !== except)
6890
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
6891
+ }
6892
+ return to;
6893
+ };
6894
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
6895
+ var src_exports = {};
6896
+ __export2(src_exports, {
6897
+ getContext: () => import_get_context.getContext,
6898
+ getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
6899
+ getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
6900
+ });
6901
+ module.exports = __toCommonJS(src_exports);
6902
+ var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
6903
+ var import_get_context = require_get_context();
6904
+ }
6905
+ });
6906
+ var import_oidc = __toESM(require_dist(), 1);
6907
+ var import_oidc2 = __toESM(require_dist(), 1);
6908
+ var marker15 = "vercel.ai.gateway.error";
6909
+ var symbol15 = Symbol.for(marker15);
6910
+ var _a15;
6911
+ var _b;
6912
+ var GatewayError = class _GatewayError extends (_b = Error, _a15 = symbol15, _b) {
6913
+ constructor({
6914
+ message,
6915
+ statusCode = 500,
6916
+ cause
6917
+ }) {
6918
+ super(message);
6919
+ this[_a15] = true;
6920
+ this.statusCode = statusCode;
6921
+ this.cause = cause;
6922
+ }
6923
+ /**
6924
+ * Checks if the given error is a Gateway Error.
6925
+ * @param {unknown} error - The error to check.
6926
+ * @returns {boolean} True if the error is a Gateway Error, false otherwise.
6927
+ */
6928
+ static isInstance(error) {
6929
+ return _GatewayError.hasMarker(error);
6930
+ }
6931
+ static hasMarker(error) {
6932
+ return typeof error === "object" && error !== null && symbol15 in error && error[symbol15] === true;
6933
+ }
6934
+ };
6935
+ var name14 = "GatewayAuthenticationError";
6936
+ var marker22 = `vercel.ai.gateway.error.${name14}`;
6937
+ var symbol22 = Symbol.for(marker22);
6938
+ var _a22;
6939
+ var _b2;
6940
+ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a22 = symbol22, _b2) {
6941
+ constructor({
6942
+ message = "Authentication failed",
6943
+ statusCode = 401,
6944
+ cause
6945
+ } = {}) {
6946
+ super({ message, statusCode, cause });
6947
+ this[_a22] = true;
6948
+ this.name = name14;
6949
+ this.type = "authentication_error";
6950
+ }
6951
+ static isInstance(error) {
6952
+ return GatewayError.hasMarker(error) && symbol22 in error;
6953
+ }
6954
+ /**
6955
+ * Creates a contextual error message when authentication fails
6956
+ */
6957
+ static createContextualError({
6958
+ apiKeyProvided,
6959
+ oidcTokenProvided,
6960
+ message = "Authentication failed",
6961
+ statusCode = 401,
6962
+ cause
6963
+ }) {
6964
+ let contextualMessage;
6965
+ if (apiKeyProvided) {
6966
+ contextualMessage = `AI Gateway authentication failed: Invalid API key.
6967
+
6968
+ Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
6969
+
6970
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
6971
+ } else if (oidcTokenProvided) {
6972
+ contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.
6973
+
6974
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
6975
+
6976
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;
6977
+ } else {
6978
+ contextualMessage = `AI Gateway authentication failed: No authentication provided.
6979
+
6980
+ Option 1 - API key:
6981
+ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
6982
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
6983
+
6984
+ Option 2 - OIDC token:
6985
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;
6986
+ }
6987
+ return new _GatewayAuthenticationError({
6988
+ message: contextualMessage,
6989
+ statusCode,
6990
+ cause
6991
+ });
6992
+ }
6993
+ };
6994
+ var name22 = "GatewayInvalidRequestError";
6995
+ var marker32 = `vercel.ai.gateway.error.${name22}`;
6996
+ var symbol32 = Symbol.for(marker32);
6997
+ var _a32;
6998
+ var _b3;
6999
+ var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a32 = symbol32, _b3) {
7000
+ constructor({
7001
+ message = "Invalid request",
7002
+ statusCode = 400,
7003
+ cause
7004
+ } = {}) {
7005
+ super({ message, statusCode, cause });
7006
+ this[_a32] = true;
7007
+ this.name = name22;
7008
+ this.type = "invalid_request_error";
7009
+ }
7010
+ static isInstance(error) {
7011
+ return GatewayError.hasMarker(error) && symbol32 in error;
7012
+ }
7013
+ };
7014
+ var name32 = "GatewayRateLimitError";
7015
+ var marker42 = `vercel.ai.gateway.error.${name32}`;
7016
+ var symbol42 = Symbol.for(marker42);
7017
+ var _a42;
7018
+ var _b4;
7019
+ var GatewayRateLimitError = class extends (_b4 = GatewayError, _a42 = symbol42, _b4) {
7020
+ constructor({
7021
+ message = "Rate limit exceeded",
7022
+ statusCode = 429,
7023
+ cause
7024
+ } = {}) {
7025
+ super({ message, statusCode, cause });
7026
+ this[_a42] = true;
7027
+ this.name = name32;
7028
+ this.type = "rate_limit_exceeded";
7029
+ }
7030
+ static isInstance(error) {
7031
+ return GatewayError.hasMarker(error) && symbol42 in error;
7032
+ }
7033
+ };
7034
+ var name42 = "GatewayModelNotFoundError";
7035
+ var marker52 = `vercel.ai.gateway.error.${name42}`;
7036
+ var symbol52 = Symbol.for(marker52);
7037
+ var modelNotFoundParamSchema = lazyValidator(
7038
+ () => zodSchema(
7039
+ z$1.object({
7040
+ modelId: z$1.string()
7041
+ })
7042
+ )
7043
+ );
7044
+ var _a52;
7045
+ var _b5;
7046
+ var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a52 = symbol52, _b5) {
7047
+ constructor({
7048
+ message = "Model not found",
7049
+ statusCode = 404,
7050
+ modelId,
7051
+ cause
7052
+ } = {}) {
7053
+ super({ message, statusCode, cause });
7054
+ this[_a52] = true;
7055
+ this.name = name42;
7056
+ this.type = "model_not_found";
7057
+ this.modelId = modelId;
7058
+ }
7059
+ static isInstance(error) {
7060
+ return GatewayError.hasMarker(error) && symbol52 in error;
7061
+ }
7062
+ };
7063
+ var name52 = "GatewayInternalServerError";
7064
+ var marker62 = `vercel.ai.gateway.error.${name52}`;
7065
+ var symbol62 = Symbol.for(marker62);
7066
+ var _a62;
7067
+ var _b6;
7068
+ var GatewayInternalServerError = class extends (_b6 = GatewayError, _a62 = symbol62, _b6) {
7069
+ constructor({
7070
+ message = "Internal server error",
7071
+ statusCode = 500,
7072
+ cause
7073
+ } = {}) {
7074
+ super({ message, statusCode, cause });
7075
+ this[_a62] = true;
7076
+ this.name = name52;
7077
+ this.type = "internal_server_error";
7078
+ }
7079
+ static isInstance(error) {
7080
+ return GatewayError.hasMarker(error) && symbol62 in error;
7081
+ }
7082
+ };
7083
+ var name62 = "GatewayResponseError";
7084
+ var marker72 = `vercel.ai.gateway.error.${name62}`;
7085
+ var symbol72 = Symbol.for(marker72);
7086
+ var _a72;
7087
+ var _b7;
7088
+ var GatewayResponseError = class extends (_b7 = GatewayError, _a72 = symbol72, _b7) {
7089
+ constructor({
7090
+ message = "Invalid response from Gateway",
7091
+ statusCode = 502,
7092
+ response,
7093
+ validationError,
7094
+ cause
7095
+ } = {}) {
7096
+ super({ message, statusCode, cause });
7097
+ this[_a72] = true;
7098
+ this.name = name62;
7099
+ this.type = "response_error";
7100
+ this.response = response;
7101
+ this.validationError = validationError;
7102
+ }
7103
+ static isInstance(error) {
7104
+ return GatewayError.hasMarker(error) && symbol72 in error;
7105
+ }
7106
+ };
7107
+ async function createGatewayErrorFromResponse({
7108
+ response,
7109
+ statusCode,
7110
+ defaultMessage = "Gateway request failed",
7111
+ cause,
7112
+ authMethod
7113
+ }) {
7114
+ const parseResult = await safeValidateTypes({
7115
+ value: response,
7116
+ schema: gatewayErrorResponseSchema
7117
+ });
7118
+ if (!parseResult.success) {
7119
+ return new GatewayResponseError({
7120
+ message: `Invalid error response format: ${defaultMessage}`,
7121
+ statusCode,
7122
+ response,
7123
+ validationError: parseResult.error,
7124
+ cause
7125
+ });
7126
+ }
7127
+ const validatedResponse = parseResult.value;
7128
+ const errorType = validatedResponse.error.type;
7129
+ const message = validatedResponse.error.message;
7130
+ switch (errorType) {
7131
+ case "authentication_error":
7132
+ return GatewayAuthenticationError.createContextualError({
7133
+ apiKeyProvided: authMethod === "api-key",
7134
+ oidcTokenProvided: authMethod === "oidc",
7135
+ statusCode,
7136
+ cause
7137
+ });
7138
+ case "invalid_request_error":
7139
+ return new GatewayInvalidRequestError({ message, statusCode, cause });
7140
+ case "rate_limit_exceeded":
7141
+ return new GatewayRateLimitError({ message, statusCode, cause });
7142
+ case "model_not_found": {
7143
+ const modelResult = await safeValidateTypes({
7144
+ value: validatedResponse.error.param,
7145
+ schema: modelNotFoundParamSchema
7146
+ });
7147
+ return new GatewayModelNotFoundError({
7148
+ message,
7149
+ statusCode,
7150
+ modelId: modelResult.success ? modelResult.value.modelId : void 0,
7151
+ cause
7152
+ });
7153
+ }
7154
+ case "internal_server_error":
7155
+ return new GatewayInternalServerError({ message, statusCode, cause });
7156
+ default:
7157
+ return new GatewayInternalServerError({ message, statusCode, cause });
7158
+ }
7159
+ }
7160
+ var gatewayErrorResponseSchema = lazyValidator(
7161
+ () => zodSchema(
7162
+ z$1.object({
7163
+ error: z$1.object({
7164
+ message: z$1.string(),
7165
+ type: z$1.string().nullish(),
7166
+ param: z$1.unknown().nullish(),
7167
+ code: z$1.union([z$1.string(), z$1.number()]).nullish()
7168
+ })
7169
+ })
7170
+ )
7171
+ );
7172
+ function asGatewayError(error, authMethod) {
7173
+ var _a83;
7174
+ if (GatewayError.isInstance(error)) {
7175
+ return error;
7176
+ }
7177
+ if (APICallError.isInstance(error)) {
7178
+ return createGatewayErrorFromResponse({
7179
+ response: extractApiCallResponse(error),
7180
+ statusCode: (_a83 = error.statusCode) != null ? _a83 : 500,
7181
+ defaultMessage: "Gateway request failed",
7182
+ cause: error,
7183
+ authMethod
7184
+ });
7185
+ }
7186
+ return createGatewayErrorFromResponse({
7187
+ response: {},
7188
+ statusCode: 500,
7189
+ defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
7190
+ cause: error,
7191
+ authMethod
7192
+ });
7193
+ }
7194
+ function extractApiCallResponse(error) {
7195
+ if (error.data !== void 0) {
7196
+ return error.data;
7197
+ }
7198
+ if (error.responseBody != null) {
7199
+ try {
7200
+ return JSON.parse(error.responseBody);
7201
+ } catch (e) {
7202
+ return error.responseBody;
7203
+ }
7204
+ }
7205
+ return {};
7206
+ }
7207
+ var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
7208
+ async function parseAuthMethod(headers) {
7209
+ const result = await safeValidateTypes({
7210
+ value: headers[GATEWAY_AUTH_METHOD_HEADER],
7211
+ schema: gatewayAuthMethodSchema
7212
+ });
7213
+ return result.success ? result.value : void 0;
7214
+ }
7215
+ var gatewayAuthMethodSchema = lazyValidator(
7216
+ () => zodSchema(z$1.union([z$1.literal("api-key"), z$1.literal("oidc")]))
7217
+ );
7218
+ var GatewayFetchMetadata = class {
7219
+ constructor(config) {
7220
+ this.config = config;
7221
+ }
7222
+ async getAvailableModels() {
7223
+ try {
7224
+ const { value } = await getFromApi({
7225
+ url: `${this.config.baseURL}/config`,
7226
+ headers: await resolve4(this.config.headers()),
7227
+ successfulResponseHandler: createJsonResponseHandler(
7228
+ gatewayAvailableModelsResponseSchema
7229
+ ),
7230
+ failedResponseHandler: createJsonErrorResponseHandler({
7231
+ errorSchema: z$1.any(),
7232
+ errorToMessage: (data) => data
7233
+ }),
7234
+ fetch: this.config.fetch
7235
+ });
7236
+ return value;
7237
+ } catch (error) {
7238
+ throw await asGatewayError(error);
7239
+ }
7240
+ }
7241
+ async getCredits() {
7242
+ try {
7243
+ const baseUrl = new URL(this.config.baseURL);
7244
+ const { value } = await getFromApi({
7245
+ url: `${baseUrl.origin}/v1/credits`,
7246
+ headers: await resolve4(this.config.headers()),
7247
+ successfulResponseHandler: createJsonResponseHandler(
7248
+ gatewayCreditsResponseSchema
7249
+ ),
7250
+ failedResponseHandler: createJsonErrorResponseHandler({
7251
+ errorSchema: z$1.any(),
7252
+ errorToMessage: (data) => data
7253
+ }),
7254
+ fetch: this.config.fetch
7255
+ });
7256
+ return value;
7257
+ } catch (error) {
7258
+ throw await asGatewayError(error);
7259
+ }
7260
+ }
7261
+ };
7262
+ var gatewayAvailableModelsResponseSchema = lazyValidator(
7263
+ () => zodSchema(
7264
+ z$1.object({
7265
+ models: z$1.array(
7266
+ z$1.object({
7267
+ id: z$1.string(),
7268
+ name: z$1.string(),
7269
+ description: z$1.string().nullish(),
7270
+ pricing: z$1.object({
7271
+ input: z$1.string(),
7272
+ output: z$1.string(),
7273
+ input_cache_read: z$1.string().nullish(),
7274
+ input_cache_write: z$1.string().nullish()
7275
+ }).transform(
7276
+ ({ input, output, input_cache_read, input_cache_write }) => ({
7277
+ input,
7278
+ output,
7279
+ ...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
7280
+ ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
7281
+ })
7282
+ ).nullish(),
7283
+ specification: z$1.object({
7284
+ specificationVersion: z$1.literal("v2"),
7285
+ provider: z$1.string(),
7286
+ modelId: z$1.string()
7287
+ }),
7288
+ modelType: z$1.enum(["language", "embedding", "image"]).nullish()
7289
+ })
7290
+ )
7291
+ })
7292
+ )
7293
+ );
7294
+ var gatewayCreditsResponseSchema = lazyValidator(
7295
+ () => zodSchema(
7296
+ z$1.object({
7297
+ balance: z$1.string(),
7298
+ total_used: z$1.string()
7299
+ }).transform(({ balance, total_used }) => ({
7300
+ balance,
7301
+ totalUsed: total_used
7302
+ }))
7303
+ )
7304
+ );
7305
+ var GatewayLanguageModel = class {
7306
+ constructor(modelId, config) {
7307
+ this.modelId = modelId;
7308
+ this.config = config;
7309
+ this.specificationVersion = "v2";
7310
+ this.supportedUrls = { "*/*": [/.*/] };
7311
+ }
7312
+ get provider() {
7313
+ return this.config.provider;
7314
+ }
7315
+ async getArgs(options) {
7316
+ const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
7317
+ return {
7318
+ args: this.maybeEncodeFileParts(optionsWithoutSignal),
7319
+ warnings: []
7320
+ };
7321
+ }
7322
+ async doGenerate(options) {
7323
+ const { args, warnings } = await this.getArgs(options);
7324
+ const { abortSignal } = options;
7325
+ const resolvedHeaders = await resolve4(this.config.headers());
7326
+ try {
7327
+ const {
7328
+ responseHeaders,
7329
+ value: responseBody,
7330
+ rawValue: rawResponse
7331
+ } = await postJsonToApi({
7332
+ url: this.getUrl(),
7333
+ headers: combineHeaders(
7334
+ resolvedHeaders,
7335
+ options.headers,
7336
+ this.getModelConfigHeaders(this.modelId, false),
7337
+ await resolve4(this.config.o11yHeaders)
7338
+ ),
7339
+ body: args,
7340
+ successfulResponseHandler: createJsonResponseHandler(z$1.any()),
7341
+ failedResponseHandler: createJsonErrorResponseHandler({
7342
+ errorSchema: z$1.any(),
7343
+ errorToMessage: (data) => data
7344
+ }),
7345
+ ...abortSignal && { abortSignal },
7346
+ fetch: this.config.fetch
7347
+ });
7348
+ return {
7349
+ ...responseBody,
7350
+ request: { body: args },
7351
+ response: { headers: responseHeaders, body: rawResponse },
7352
+ warnings
7353
+ };
7354
+ } catch (error) {
7355
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7356
+ }
7357
+ }
7358
+ async doStream(options) {
7359
+ const { args, warnings } = await this.getArgs(options);
7360
+ const { abortSignal } = options;
7361
+ const resolvedHeaders = await resolve4(this.config.headers());
7362
+ try {
7363
+ const { value: response, responseHeaders } = await postJsonToApi({
7364
+ url: this.getUrl(),
7365
+ headers: combineHeaders(
7366
+ resolvedHeaders,
7367
+ options.headers,
7368
+ this.getModelConfigHeaders(this.modelId, true),
7369
+ await resolve4(this.config.o11yHeaders)
7370
+ ),
7371
+ body: args,
7372
+ successfulResponseHandler: createEventSourceResponseHandler(z$1.any()),
7373
+ failedResponseHandler: createJsonErrorResponseHandler({
7374
+ errorSchema: z$1.any(),
7375
+ errorToMessage: (data) => data
7376
+ }),
7377
+ ...abortSignal && { abortSignal },
7378
+ fetch: this.config.fetch
7379
+ });
7380
+ return {
7381
+ stream: response.pipeThrough(
7382
+ new TransformStream({
7383
+ start(controller) {
7384
+ if (warnings.length > 0) {
7385
+ controller.enqueue({ type: "stream-start", warnings });
7386
+ }
7387
+ },
7388
+ transform(chunk, controller) {
7389
+ if (chunk.success) {
7390
+ const streamPart = chunk.value;
7391
+ if (streamPart.type === "raw" && !options.includeRawChunks) {
7392
+ return;
7393
+ }
7394
+ if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") {
7395
+ streamPart.timestamp = new Date(streamPart.timestamp);
7396
+ }
7397
+ controller.enqueue(streamPart);
7398
+ } else {
7399
+ controller.error(
7400
+ chunk.error
7401
+ );
7402
+ }
7403
+ }
7404
+ })
7405
+ ),
7406
+ request: { body: args },
7407
+ response: { headers: responseHeaders }
7408
+ };
7409
+ } catch (error) {
7410
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7411
+ }
7412
+ }
7413
+ isFilePart(part) {
7414
+ return part && typeof part === "object" && "type" in part && part.type === "file";
7415
+ }
7416
+ /**
7417
+ * Encodes file parts in the prompt to base64. Mutates the passed options
7418
+ * instance directly to avoid copying the file data.
7419
+ * @param options - The options to encode.
7420
+ * @returns The options with the file parts encoded.
7421
+ */
7422
+ maybeEncodeFileParts(options) {
7423
+ for (const message of options.prompt) {
7424
+ for (const part of message.content) {
7425
+ if (this.isFilePart(part)) {
7426
+ const filePart = part;
7427
+ if (filePart.data instanceof Uint8Array) {
7428
+ const buffer = Uint8Array.from(filePart.data);
7429
+ const base64Data = Buffer.from(buffer).toString("base64");
7430
+ filePart.data = new URL(
7431
+ `data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}`
7432
+ );
7433
+ }
7434
+ }
7435
+ }
7436
+ }
7437
+ return options;
7438
+ }
7439
+ getUrl() {
7440
+ return `${this.config.baseURL}/language-model`;
7441
+ }
7442
+ getModelConfigHeaders(modelId, streaming) {
7443
+ return {
7444
+ "ai-language-model-specification-version": "2",
7445
+ "ai-language-model-id": modelId,
7446
+ "ai-language-model-streaming": String(streaming)
7447
+ };
7448
+ }
7449
+ };
7450
+ var GatewayEmbeddingModel = class {
7451
+ constructor(modelId, config) {
7452
+ this.modelId = modelId;
7453
+ this.config = config;
7454
+ this.specificationVersion = "v2";
7455
+ this.maxEmbeddingsPerCall = 2048;
7456
+ this.supportsParallelCalls = true;
7457
+ }
7458
+ get provider() {
7459
+ return this.config.provider;
7460
+ }
7461
+ async doEmbed({
7462
+ values,
7463
+ headers,
7464
+ abortSignal,
7465
+ providerOptions
7466
+ }) {
7467
+ var _a83;
7468
+ const resolvedHeaders = await resolve4(this.config.headers());
7469
+ try {
7470
+ const {
7471
+ responseHeaders,
7472
+ value: responseBody,
7473
+ rawValue
7474
+ } = await postJsonToApi({
7475
+ url: this.getUrl(),
7476
+ headers: combineHeaders(
7477
+ resolvedHeaders,
7478
+ headers != null ? headers : {},
7479
+ this.getModelConfigHeaders(),
7480
+ await resolve4(this.config.o11yHeaders)
7481
+ ),
7482
+ body: {
7483
+ input: values.length === 1 ? values[0] : values,
7484
+ ...providerOptions ? { providerOptions } : {}
7485
+ },
7486
+ successfulResponseHandler: createJsonResponseHandler(
7487
+ gatewayEmbeddingResponseSchema
7488
+ ),
7489
+ failedResponseHandler: createJsonErrorResponseHandler({
7490
+ errorSchema: z$1.any(),
7491
+ errorToMessage: (data) => data
7492
+ }),
7493
+ ...abortSignal && { abortSignal },
7494
+ fetch: this.config.fetch
7495
+ });
7496
+ return {
7497
+ embeddings: responseBody.embeddings,
7498
+ usage: (_a83 = responseBody.usage) != null ? _a83 : void 0,
7499
+ providerMetadata: responseBody.providerMetadata,
7500
+ response: { headers: responseHeaders, body: rawValue }
7501
+ };
7502
+ } catch (error) {
7503
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7504
+ }
7505
+ }
7506
+ getUrl() {
7507
+ return `${this.config.baseURL}/embedding-model`;
7508
+ }
7509
+ getModelConfigHeaders() {
7510
+ return {
7511
+ "ai-embedding-model-specification-version": "2",
7512
+ "ai-model-id": this.modelId
7513
+ };
7514
+ }
7515
+ };
7516
+ var gatewayEmbeddingResponseSchema = lazyValidator(
7517
+ () => zodSchema(
7518
+ z$1.object({
7519
+ embeddings: z$1.array(z$1.array(z$1.number())),
7520
+ usage: z$1.object({ tokens: z$1.number() }).nullish(),
7521
+ providerMetadata: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown())).optional()
7522
+ })
7523
+ )
7524
+ );
7525
+ var GatewayImageModel = class {
7526
+ constructor(modelId, config) {
7527
+ this.modelId = modelId;
7528
+ this.config = config;
7529
+ this.specificationVersion = "v2";
7530
+ this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
7531
+ }
7532
+ get provider() {
7533
+ return this.config.provider;
7534
+ }
7535
+ async doGenerate({
7536
+ prompt,
7537
+ n,
7538
+ size,
7539
+ aspectRatio,
7540
+ seed,
7541
+ providerOptions,
7542
+ headers,
7543
+ abortSignal
7544
+ }) {
7545
+ var _a83;
7546
+ const resolvedHeaders = await resolve4(this.config.headers());
7547
+ try {
7548
+ const {
7549
+ responseHeaders,
7550
+ value: responseBody
7551
+ } = await postJsonToApi({
7552
+ url: this.getUrl(),
7553
+ headers: combineHeaders(
7554
+ resolvedHeaders,
7555
+ headers != null ? headers : {},
7556
+ this.getModelConfigHeaders(),
7557
+ await resolve4(this.config.o11yHeaders)
7558
+ ),
7559
+ body: {
7560
+ prompt,
7561
+ n,
7562
+ ...size && { size },
7563
+ ...aspectRatio && { aspectRatio },
7564
+ ...seed && { seed },
7565
+ ...providerOptions && { providerOptions }
7566
+ },
7567
+ successfulResponseHandler: createJsonResponseHandler(
7568
+ gatewayImageResponseSchema
7569
+ ),
7570
+ failedResponseHandler: createJsonErrorResponseHandler({
7571
+ errorSchema: z$1.any(),
7572
+ errorToMessage: (data) => data
7573
+ }),
7574
+ ...abortSignal && { abortSignal },
7575
+ fetch: this.config.fetch
7576
+ });
7577
+ return {
7578
+ images: responseBody.images,
7579
+ // Always base64 strings from server
7580
+ warnings: (_a83 = responseBody.warnings) != null ? _a83 : [],
7581
+ providerMetadata: responseBody.providerMetadata,
7582
+ response: {
7583
+ timestamp: /* @__PURE__ */ new Date(),
7584
+ modelId: this.modelId,
7585
+ headers: responseHeaders
7586
+ }
7587
+ };
7588
+ } catch (error) {
7589
+ throw asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7590
+ }
7591
+ }
7592
+ getUrl() {
7593
+ return `${this.config.baseURL}/image-model`;
7594
+ }
7595
+ getModelConfigHeaders() {
7596
+ return {
7597
+ "ai-image-model-specification-version": "2",
7598
+ "ai-model-id": this.modelId
7599
+ };
7600
+ }
7601
+ };
7602
+ var providerMetadataEntrySchema = z$1.object({
7603
+ images: z$1.array(z$1.unknown()).optional()
7604
+ }).catchall(z$1.unknown());
7605
+ var gatewayImageResponseSchema = z$1.object({
7606
+ images: z$1.array(z$1.string()),
7607
+ // Always base64 strings over the wire
7608
+ warnings: z$1.array(
7609
+ z$1.object({
7610
+ type: z$1.literal("other"),
7611
+ message: z$1.string()
7612
+ })
7613
+ ).optional(),
7614
+ providerMetadata: z$1.record(z$1.string(), providerMetadataEntrySchema).optional()
7615
+ });
7616
+ async function getVercelRequestId() {
7617
+ var _a83;
7618
+ return (_a83 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a83["x-vercel-id"];
7619
+ }
7620
+ var VERSION2 = "2.0.15";
7621
+ var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
7622
+ function createGatewayProvider(options = {}) {
7623
+ var _a83, _b8;
7624
+ let pendingMetadata = null;
7625
+ let metadataCache = null;
7626
+ const cacheRefreshMillis = (_a83 = options.metadataCacheRefreshMillis) != null ? _a83 : 1e3 * 60 * 5;
7627
+ let lastFetchTime = 0;
7628
+ const baseURL = (_b8 = withoutTrailingSlash(options.baseURL)) != null ? _b8 : "https://ai-gateway.vercel.sh/v1/ai";
7629
+ const getHeaders = async () => {
7630
+ const auth = await getGatewayAuthToken(options);
7631
+ if (auth) {
7632
+ return withUserAgentSuffix(
7633
+ {
7634
+ Authorization: `Bearer ${auth.token}`,
7635
+ "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
7636
+ [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
7637
+ ...options.headers
7638
+ },
7639
+ `ai-sdk/gateway/${VERSION2}`
7640
+ );
7641
+ }
7642
+ throw GatewayAuthenticationError.createContextualError({
7643
+ apiKeyProvided: false,
7644
+ oidcTokenProvided: false,
7645
+ statusCode: 401
7646
+ });
7647
+ };
7648
+ const createO11yHeaders = () => {
7649
+ const deploymentId = loadOptionalSetting({
7650
+ settingValue: void 0,
7651
+ environmentVariableName: "VERCEL_DEPLOYMENT_ID"
7652
+ });
7653
+ const environment = loadOptionalSetting({
7654
+ settingValue: void 0,
7655
+ environmentVariableName: "VERCEL_ENV"
7656
+ });
7657
+ const region = loadOptionalSetting({
7658
+ settingValue: void 0,
7659
+ environmentVariableName: "VERCEL_REGION"
7660
+ });
7661
+ return async () => {
7662
+ const requestId = await getVercelRequestId();
7663
+ return {
7664
+ ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
7665
+ ...environment && { "ai-o11y-environment": environment },
7666
+ ...region && { "ai-o11y-region": region },
7667
+ ...requestId && { "ai-o11y-request-id": requestId }
7668
+ };
7669
+ };
7670
+ };
7671
+ const createLanguageModel = (modelId) => {
7672
+ return new GatewayLanguageModel(modelId, {
7673
+ provider: "gateway",
7674
+ baseURL,
7675
+ headers: getHeaders,
7676
+ fetch: options.fetch,
7677
+ o11yHeaders: createO11yHeaders()
7678
+ });
7679
+ };
7680
+ const getAvailableModels = async () => {
7681
+ var _a922, _b9, _c;
7682
+ const now2 = (_c = (_b9 = (_a922 = options._internal) == null ? void 0 : _a922.currentDate) == null ? void 0 : _b9.call(_a922).getTime()) != null ? _c : Date.now();
7683
+ if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
7684
+ lastFetchTime = now2;
7685
+ pendingMetadata = new GatewayFetchMetadata({
7686
+ baseURL,
7687
+ headers: getHeaders,
7688
+ fetch: options.fetch
7689
+ }).getAvailableModels().then((metadata) => {
7690
+ metadataCache = metadata;
7691
+ return metadata;
7692
+ }).catch(async (error) => {
7693
+ throw await asGatewayError(
7694
+ error,
7695
+ await parseAuthMethod(await getHeaders())
7696
+ );
7697
+ });
7698
+ }
7699
+ return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
7700
+ };
7701
+ const getCredits = async () => {
7702
+ return new GatewayFetchMetadata({
7703
+ baseURL,
7704
+ headers: getHeaders,
7705
+ fetch: options.fetch
7706
+ }).getCredits().catch(async (error) => {
7707
+ throw await asGatewayError(
7708
+ error,
7709
+ await parseAuthMethod(await getHeaders())
7710
+ );
7711
+ });
7712
+ };
7713
+ const provider = function(modelId) {
7714
+ if (new.target) {
7715
+ throw new Error(
7716
+ "The Gateway Provider model function cannot be called with the new keyword."
7717
+ );
7718
+ }
7719
+ return createLanguageModel(modelId);
7720
+ };
7721
+ provider.getAvailableModels = getAvailableModels;
7722
+ provider.getCredits = getCredits;
7723
+ provider.imageModel = (modelId) => {
7724
+ return new GatewayImageModel(modelId, {
7725
+ provider: "gateway",
7726
+ baseURL,
7727
+ headers: getHeaders,
7728
+ fetch: options.fetch,
7729
+ o11yHeaders: createO11yHeaders()
7730
+ });
7731
+ };
7732
+ provider.languageModel = createLanguageModel;
7733
+ provider.textEmbeddingModel = (modelId) => {
7734
+ return new GatewayEmbeddingModel(modelId, {
7735
+ provider: "gateway",
7736
+ baseURL,
7737
+ headers: getHeaders,
7738
+ fetch: options.fetch,
7739
+ o11yHeaders: createO11yHeaders()
7740
+ });
7741
+ };
7742
+ return provider;
7743
+ }
7744
+ createGatewayProvider();
7745
+ async function getGatewayAuthToken(options) {
7746
+ const apiKey = loadOptionalSetting({
7747
+ settingValue: options.apiKey,
7748
+ environmentVariableName: "AI_GATEWAY_API_KEY"
7749
+ });
7750
+ if (apiKey) {
7751
+ return {
7752
+ token: apiKey,
7753
+ authMethod: "api-key"
7754
+ };
7755
+ }
7756
+ try {
7757
+ const oidcToken = await (0, import_oidc2.getVercelOidcToken)();
7758
+ return {
7759
+ token: oidcToken,
7760
+ authMethod: "oidc"
7761
+ };
7762
+ } catch (e) {
7763
+ return null;
7764
+ }
7765
+ }
7766
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
7767
+ var VERSION22 = "1.9.0";
7768
+ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
7769
+ function _makeCompatibilityCheck(ownVersion) {
7770
+ var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
7771
+ var rejectedVersions = /* @__PURE__ */ new Set();
7772
+ var myVersionMatch = ownVersion.match(re);
7773
+ if (!myVersionMatch) {
7774
+ return function() {
7775
+ return false;
7776
+ };
7777
+ }
7778
+ var ownVersionParsed = {
7779
+ major: +myVersionMatch[1],
7780
+ minor: +myVersionMatch[2],
7781
+ patch: +myVersionMatch[3],
7782
+ prerelease: myVersionMatch[4]
7783
+ };
7784
+ if (ownVersionParsed.prerelease != null) {
7785
+ return function isExactmatch(globalVersion) {
7786
+ return globalVersion === ownVersion;
7787
+ };
7788
+ }
7789
+ function _reject(v) {
7790
+ rejectedVersions.add(v);
7791
+ return false;
7792
+ }
7793
+ function _accept(v) {
7794
+ acceptedVersions.add(v);
7795
+ return true;
7796
+ }
7797
+ return function isCompatible2(globalVersion) {
7798
+ if (acceptedVersions.has(globalVersion)) {
7799
+ return true;
7800
+ }
7801
+ if (rejectedVersions.has(globalVersion)) {
7802
+ return false;
7803
+ }
7804
+ var globalVersionMatch = globalVersion.match(re);
7805
+ if (!globalVersionMatch) {
7806
+ return _reject(globalVersion);
7807
+ }
7808
+ var globalVersionParsed = {
7809
+ major: +globalVersionMatch[1],
7810
+ minor: +globalVersionMatch[2],
7811
+ patch: +globalVersionMatch[3],
7812
+ prerelease: globalVersionMatch[4]
7813
+ };
7814
+ if (globalVersionParsed.prerelease != null) {
7815
+ return _reject(globalVersion);
7816
+ }
7817
+ if (ownVersionParsed.major !== globalVersionParsed.major) {
7818
+ return _reject(globalVersion);
7819
+ }
7820
+ if (ownVersionParsed.major === 0) {
7821
+ if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
7822
+ return _accept(globalVersion);
7823
+ }
7824
+ return _reject(globalVersion);
7825
+ }
7826
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
7827
+ return _accept(globalVersion);
7828
+ }
7829
+ return _reject(globalVersion);
7830
+ };
7831
+ }
7832
+ var isCompatible = _makeCompatibilityCheck(VERSION22);
7833
+ var major = VERSION22.split(".")[0];
7834
+ var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
7835
+ var _global = _globalThis;
7836
+ function registerGlobal(type, instance, diag, allowOverride) {
7837
+ var _a16;
7838
+ if (allowOverride === void 0) {
7839
+ allowOverride = false;
7840
+ }
7841
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a16 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a16 !== void 0 ? _a16 : {
7842
+ version: VERSION22
7843
+ };
7844
+ if (!allowOverride && api[type]) {
7845
+ var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
7846
+ diag.error(err.stack || err.message);
7847
+ return false;
7848
+ }
7849
+ if (api.version !== VERSION22) {
7850
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION22);
7851
+ diag.error(err.stack || err.message);
7852
+ return false;
7853
+ }
7854
+ api[type] = instance;
7855
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION22 + ".");
7856
+ return true;
7857
+ }
7858
+ function getGlobal(type) {
7859
+ var _a16, _b8;
7860
+ var globalVersion = (_a16 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a16 === void 0 ? void 0 : _a16.version;
7861
+ if (!globalVersion || !isCompatible(globalVersion)) {
7862
+ return;
7863
+ }
7864
+ return (_b8 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b8 === void 0 ? void 0 : _b8[type];
7865
+ }
7866
+ function unregisterGlobal(type, diag) {
7867
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION22 + ".");
7868
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
7869
+ if (api) {
7870
+ delete api[type];
7871
+ }
7872
+ }
7873
+ var __read = function(o, n) {
7874
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
7875
+ if (!m) return o;
7876
+ var i = m.call(o), r, ar = [], e;
7877
+ try {
7878
+ while (!(r = i.next()).done) ar.push(r.value);
7879
+ } catch (error) {
7880
+ e = { error };
7881
+ } finally {
7882
+ try {
7883
+ if (r && !r.done && (m = i["return"])) m.call(i);
7884
+ } finally {
7885
+ if (e) throw e.error;
7886
+ }
7887
+ }
7888
+ return ar;
7889
+ };
7890
+ var __spreadArray = function(to, from, pack) {
7891
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
7892
+ if (ar || !(i in from)) {
7893
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
7894
+ ar[i] = from[i];
7895
+ }
7896
+ }
7897
+ return to.concat(ar || Array.prototype.slice.call(from));
7898
+ };
7899
+ var DiagComponentLogger = (
7900
+ /** @class */
7901
+ (function() {
7902
+ function DiagComponentLogger2(props) {
7903
+ this._namespace = props.namespace || "DiagComponentLogger";
7904
+ }
7905
+ DiagComponentLogger2.prototype.debug = function() {
7906
+ var args = [];
7907
+ for (var _i = 0; _i < arguments.length; _i++) {
7908
+ args[_i] = arguments[_i];
7909
+ }
7910
+ return logProxy("debug", this._namespace, args);
7911
+ };
7912
+ DiagComponentLogger2.prototype.error = function() {
7913
+ var args = [];
7914
+ for (var _i = 0; _i < arguments.length; _i++) {
7915
+ args[_i] = arguments[_i];
7916
+ }
7917
+ return logProxy("error", this._namespace, args);
7918
+ };
7919
+ DiagComponentLogger2.prototype.info = function() {
7920
+ var args = [];
7921
+ for (var _i = 0; _i < arguments.length; _i++) {
7922
+ args[_i] = arguments[_i];
7923
+ }
7924
+ return logProxy("info", this._namespace, args);
7925
+ };
7926
+ DiagComponentLogger2.prototype.warn = function() {
7927
+ var args = [];
7928
+ for (var _i = 0; _i < arguments.length; _i++) {
7929
+ args[_i] = arguments[_i];
7930
+ }
7931
+ return logProxy("warn", this._namespace, args);
7932
+ };
7933
+ DiagComponentLogger2.prototype.verbose = function() {
7934
+ var args = [];
7935
+ for (var _i = 0; _i < arguments.length; _i++) {
7936
+ args[_i] = arguments[_i];
7937
+ }
7938
+ return logProxy("verbose", this._namespace, args);
7939
+ };
7940
+ return DiagComponentLogger2;
7941
+ })()
7942
+ );
7943
+ function logProxy(funcName, namespace, args) {
7944
+ var logger = getGlobal("diag");
7945
+ if (!logger) {
7946
+ return;
7947
+ }
7948
+ args.unshift(namespace);
7949
+ return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
7950
+ }
7951
+ var DiagLogLevel;
7952
+ (function(DiagLogLevel2) {
7953
+ DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
7954
+ DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
7955
+ DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
7956
+ DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
7957
+ DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
7958
+ DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
7959
+ DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
7960
+ })(DiagLogLevel || (DiagLogLevel = {}));
7961
+ function createLogLevelDiagLogger(maxLevel, logger) {
7962
+ if (maxLevel < DiagLogLevel.NONE) {
7963
+ maxLevel = DiagLogLevel.NONE;
7964
+ } else if (maxLevel > DiagLogLevel.ALL) {
7965
+ maxLevel = DiagLogLevel.ALL;
7966
+ }
7967
+ logger = logger || {};
7968
+ function _filterFunc(funcName, theLevel) {
7969
+ var theFunc = logger[funcName];
7970
+ if (typeof theFunc === "function" && maxLevel >= theLevel) {
7971
+ return theFunc.bind(logger);
7972
+ }
7973
+ return function() {
7974
+ };
7975
+ }
7976
+ return {
7977
+ error: _filterFunc("error", DiagLogLevel.ERROR),
7978
+ warn: _filterFunc("warn", DiagLogLevel.WARN),
7979
+ info: _filterFunc("info", DiagLogLevel.INFO),
7980
+ debug: _filterFunc("debug", DiagLogLevel.DEBUG),
7981
+ verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
7982
+ };
7983
+ }
7984
+ var __read2 = function(o, n) {
7985
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
7986
+ if (!m) return o;
7987
+ var i = m.call(o), r, ar = [], e;
7988
+ try {
7989
+ while (!(r = i.next()).done) ar.push(r.value);
7990
+ } catch (error) {
7991
+ e = { error };
7992
+ } finally {
7993
+ try {
7994
+ if (r && !r.done && (m = i["return"])) m.call(i);
7995
+ } finally {
7996
+ if (e) throw e.error;
7997
+ }
7998
+ }
7999
+ return ar;
8000
+ };
8001
+ var __spreadArray2 = function(to, from, pack) {
8002
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8003
+ if (ar || !(i in from)) {
8004
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8005
+ ar[i] = from[i];
8006
+ }
8007
+ }
8008
+ return to.concat(ar || Array.prototype.slice.call(from));
8009
+ };
8010
+ var API_NAME = "diag";
8011
+ var DiagAPI = (
8012
+ /** @class */
8013
+ (function() {
8014
+ function DiagAPI2() {
8015
+ function _logProxy(funcName) {
8016
+ return function() {
8017
+ var args = [];
8018
+ for (var _i = 0; _i < arguments.length; _i++) {
8019
+ args[_i] = arguments[_i];
8020
+ }
8021
+ var logger = getGlobal("diag");
8022
+ if (!logger)
8023
+ return;
8024
+ return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
8025
+ };
8026
+ }
8027
+ var self = this;
8028
+ var setLogger = function(logger, optionsOrLogLevel) {
8029
+ var _a16, _b8, _c;
8030
+ if (optionsOrLogLevel === void 0) {
8031
+ optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
8032
+ }
8033
+ if (logger === self) {
8034
+ var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
8035
+ self.error((_a16 = err.stack) !== null && _a16 !== void 0 ? _a16 : err.message);
8036
+ return false;
8037
+ }
8038
+ if (typeof optionsOrLogLevel === "number") {
8039
+ optionsOrLogLevel = {
8040
+ logLevel: optionsOrLogLevel
8041
+ };
8042
+ }
8043
+ var oldLogger = getGlobal("diag");
8044
+ var newLogger = createLogLevelDiagLogger((_b8 = optionsOrLogLevel.logLevel) !== null && _b8 !== void 0 ? _b8 : DiagLogLevel.INFO, logger);
8045
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
8046
+ var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
8047
+ oldLogger.warn("Current logger will be overwritten from " + stack);
8048
+ newLogger.warn("Current logger will overwrite one already registered from " + stack);
8049
+ }
8050
+ return registerGlobal("diag", newLogger, self, true);
8051
+ };
8052
+ self.setLogger = setLogger;
8053
+ self.disable = function() {
8054
+ unregisterGlobal(API_NAME, self);
8055
+ };
8056
+ self.createComponentLogger = function(options) {
8057
+ return new DiagComponentLogger(options);
8058
+ };
8059
+ self.verbose = _logProxy("verbose");
8060
+ self.debug = _logProxy("debug");
8061
+ self.info = _logProxy("info");
8062
+ self.warn = _logProxy("warn");
8063
+ self.error = _logProxy("error");
8064
+ }
8065
+ DiagAPI2.instance = function() {
8066
+ if (!this._instance) {
8067
+ this._instance = new DiagAPI2();
8068
+ }
8069
+ return this._instance;
8070
+ };
8071
+ return DiagAPI2;
8072
+ })()
8073
+ );
8074
+ function createContextKey(description) {
8075
+ return Symbol.for(description);
8076
+ }
8077
+ var BaseContext = (
8078
+ /** @class */
8079
+ /* @__PURE__ */ (function() {
8080
+ function BaseContext2(parentContext) {
8081
+ var self = this;
8082
+ self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
8083
+ self.getValue = function(key) {
8084
+ return self._currentContext.get(key);
8085
+ };
8086
+ self.setValue = function(key, value) {
8087
+ var context = new BaseContext2(self._currentContext);
8088
+ context._currentContext.set(key, value);
8089
+ return context;
8090
+ };
8091
+ self.deleteValue = function(key) {
8092
+ var context = new BaseContext2(self._currentContext);
8093
+ context._currentContext.delete(key);
8094
+ return context;
8095
+ };
8096
+ }
8097
+ return BaseContext2;
8098
+ })()
8099
+ );
8100
+ var ROOT_CONTEXT = new BaseContext();
8101
+ var __read3 = function(o, n) {
8102
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
8103
+ if (!m) return o;
8104
+ var i = m.call(o), r, ar = [], e;
8105
+ try {
8106
+ while (!(r = i.next()).done) ar.push(r.value);
8107
+ } catch (error) {
8108
+ e = { error };
8109
+ } finally {
8110
+ try {
8111
+ if (r && !r.done && (m = i["return"])) m.call(i);
8112
+ } finally {
8113
+ if (e) throw e.error;
8114
+ }
8115
+ }
8116
+ return ar;
8117
+ };
8118
+ var __spreadArray3 = function(to, from, pack) {
8119
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8120
+ if (ar || !(i in from)) {
8121
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8122
+ ar[i] = from[i];
8123
+ }
8124
+ }
8125
+ return to.concat(ar || Array.prototype.slice.call(from));
8126
+ };
8127
+ var NoopContextManager = (
8128
+ /** @class */
8129
+ (function() {
8130
+ function NoopContextManager2() {
8131
+ }
8132
+ NoopContextManager2.prototype.active = function() {
8133
+ return ROOT_CONTEXT;
8134
+ };
8135
+ NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
8136
+ var args = [];
8137
+ for (var _i = 3; _i < arguments.length; _i++) {
8138
+ args[_i - 3] = arguments[_i];
8139
+ }
8140
+ return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
8141
+ };
8142
+ NoopContextManager2.prototype.bind = function(_context, target) {
8143
+ return target;
8144
+ };
8145
+ NoopContextManager2.prototype.enable = function() {
8146
+ return this;
8147
+ };
8148
+ NoopContextManager2.prototype.disable = function() {
8149
+ return this;
8150
+ };
8151
+ return NoopContextManager2;
8152
+ })()
8153
+ );
8154
+ var __read4 = function(o, n) {
8155
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
8156
+ if (!m) return o;
8157
+ var i = m.call(o), r, ar = [], e;
8158
+ try {
8159
+ while (!(r = i.next()).done) ar.push(r.value);
8160
+ } catch (error) {
8161
+ e = { error };
8162
+ } finally {
8163
+ try {
8164
+ if (r && !r.done && (m = i["return"])) m.call(i);
8165
+ } finally {
8166
+ if (e) throw e.error;
8167
+ }
8168
+ }
8169
+ return ar;
8170
+ };
8171
+ var __spreadArray4 = function(to, from, pack) {
8172
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8173
+ if (ar || !(i in from)) {
8174
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8175
+ ar[i] = from[i];
8176
+ }
8177
+ }
8178
+ return to.concat(ar || Array.prototype.slice.call(from));
8179
+ };
8180
+ var API_NAME2 = "context";
8181
+ var NOOP_CONTEXT_MANAGER = new NoopContextManager();
8182
+ var ContextAPI = (
8183
+ /** @class */
8184
+ (function() {
8185
+ function ContextAPI2() {
8186
+ }
8187
+ ContextAPI2.getInstance = function() {
8188
+ if (!this._instance) {
8189
+ this._instance = new ContextAPI2();
8190
+ }
8191
+ return this._instance;
8192
+ };
8193
+ ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
8194
+ return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
8195
+ };
8196
+ ContextAPI2.prototype.active = function() {
8197
+ return this._getContextManager().active();
8198
+ };
8199
+ ContextAPI2.prototype.with = function(context, fn, thisArg) {
8200
+ var _a16;
8201
+ var args = [];
8202
+ for (var _i = 3; _i < arguments.length; _i++) {
8203
+ args[_i - 3] = arguments[_i];
8204
+ }
8205
+ return (_a16 = this._getContextManager()).with.apply(_a16, __spreadArray4([context, fn, thisArg], __read4(args), false));
8206
+ };
8207
+ ContextAPI2.prototype.bind = function(context, target) {
8208
+ return this._getContextManager().bind(context, target);
8209
+ };
8210
+ ContextAPI2.prototype._getContextManager = function() {
8211
+ return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
8212
+ };
8213
+ ContextAPI2.prototype.disable = function() {
8214
+ this._getContextManager().disable();
8215
+ unregisterGlobal(API_NAME2, DiagAPI.instance());
8216
+ };
8217
+ return ContextAPI2;
8218
+ })()
8219
+ );
8220
+ var TraceFlags;
8221
+ (function(TraceFlags2) {
8222
+ TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
8223
+ TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
8224
+ })(TraceFlags || (TraceFlags = {}));
8225
+ var INVALID_SPANID = "0000000000000000";
8226
+ var INVALID_TRACEID = "00000000000000000000000000000000";
8227
+ var INVALID_SPAN_CONTEXT = {
8228
+ traceId: INVALID_TRACEID,
8229
+ spanId: INVALID_SPANID,
8230
+ traceFlags: TraceFlags.NONE
8231
+ };
8232
+ var NonRecordingSpan = (
8233
+ /** @class */
8234
+ (function() {
8235
+ function NonRecordingSpan2(_spanContext) {
8236
+ if (_spanContext === void 0) {
8237
+ _spanContext = INVALID_SPAN_CONTEXT;
8238
+ }
8239
+ this._spanContext = _spanContext;
8240
+ }
8241
+ NonRecordingSpan2.prototype.spanContext = function() {
8242
+ return this._spanContext;
8243
+ };
8244
+ NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
8245
+ return this;
8246
+ };
8247
+ NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
8248
+ return this;
8249
+ };
8250
+ NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
8251
+ return this;
8252
+ };
8253
+ NonRecordingSpan2.prototype.addLink = function(_link) {
8254
+ return this;
8255
+ };
8256
+ NonRecordingSpan2.prototype.addLinks = function(_links) {
8257
+ return this;
8258
+ };
8259
+ NonRecordingSpan2.prototype.setStatus = function(_status) {
8260
+ return this;
8261
+ };
8262
+ NonRecordingSpan2.prototype.updateName = function(_name) {
8263
+ return this;
8264
+ };
8265
+ NonRecordingSpan2.prototype.end = function(_endTime) {
8266
+ };
8267
+ NonRecordingSpan2.prototype.isRecording = function() {
8268
+ return false;
8269
+ };
8270
+ NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
8271
+ };
8272
+ return NonRecordingSpan2;
8273
+ })()
8274
+ );
8275
+ var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
8276
+ function getSpan(context) {
8277
+ return context.getValue(SPAN_KEY) || void 0;
8278
+ }
8279
+ function getActiveSpan() {
8280
+ return getSpan(ContextAPI.getInstance().active());
8281
+ }
8282
+ function setSpan(context, span) {
8283
+ return context.setValue(SPAN_KEY, span);
8284
+ }
8285
+ function deleteSpan(context) {
8286
+ return context.deleteValue(SPAN_KEY);
8287
+ }
8288
+ function setSpanContext(context, spanContext) {
8289
+ return setSpan(context, new NonRecordingSpan(spanContext));
8290
+ }
8291
+ function getSpanContext(context) {
8292
+ var _a16;
8293
+ return (_a16 = getSpan(context)) === null || _a16 === void 0 ? void 0 : _a16.spanContext();
8294
+ }
8295
+ var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
8296
+ var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
8297
+ function isValidTraceId(traceId) {
8298
+ return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
8299
+ }
8300
+ function isValidSpanId(spanId) {
8301
+ return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
8302
+ }
8303
+ function isSpanContextValid(spanContext) {
8304
+ return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
8305
+ }
8306
+ function wrapSpanContext(spanContext) {
8307
+ return new NonRecordingSpan(spanContext);
8308
+ }
8309
+ var contextApi = ContextAPI.getInstance();
8310
+ var NoopTracer = (
8311
+ /** @class */
8312
+ (function() {
8313
+ function NoopTracer2() {
8314
+ }
8315
+ NoopTracer2.prototype.startSpan = function(name16, options, context) {
8316
+ if (context === void 0) {
8317
+ context = contextApi.active();
8318
+ }
8319
+ var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
8320
+ if (root) {
8321
+ return new NonRecordingSpan();
8322
+ }
8323
+ var parentFromContext = context && getSpanContext(context);
8324
+ if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
8325
+ return new NonRecordingSpan(parentFromContext);
8326
+ } else {
8327
+ return new NonRecordingSpan();
8328
+ }
8329
+ };
8330
+ NoopTracer2.prototype.startActiveSpan = function(name16, arg2, arg3, arg4) {
8331
+ var opts;
8332
+ var ctx;
8333
+ var fn;
8334
+ if (arguments.length < 2) {
8335
+ return;
8336
+ } else if (arguments.length === 2) {
8337
+ fn = arg2;
8338
+ } else if (arguments.length === 3) {
8339
+ opts = arg2;
8340
+ fn = arg3;
8341
+ } else {
8342
+ opts = arg2;
8343
+ ctx = arg3;
8344
+ fn = arg4;
8345
+ }
8346
+ var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
8347
+ var span = this.startSpan(name16, opts, parentContext);
8348
+ var contextWithSpanSet = setSpan(parentContext, span);
8349
+ return contextApi.with(contextWithSpanSet, fn, void 0, span);
8350
+ };
8351
+ return NoopTracer2;
8352
+ })()
8353
+ );
8354
+ function isSpanContext(spanContext) {
8355
+ return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
8356
+ }
8357
+ var NOOP_TRACER = new NoopTracer();
8358
+ var ProxyTracer = (
8359
+ /** @class */
8360
+ (function() {
8361
+ function ProxyTracer2(_provider, name16, version, options) {
8362
+ this._provider = _provider;
8363
+ this.name = name16;
8364
+ this.version = version;
8365
+ this.options = options;
8366
+ }
8367
+ ProxyTracer2.prototype.startSpan = function(name16, options, context) {
8368
+ return this._getTracer().startSpan(name16, options, context);
8369
+ };
8370
+ ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
8371
+ var tracer = this._getTracer();
8372
+ return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
8373
+ };
8374
+ ProxyTracer2.prototype._getTracer = function() {
8375
+ if (this._delegate) {
8376
+ return this._delegate;
8377
+ }
8378
+ var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
8379
+ if (!tracer) {
8380
+ return NOOP_TRACER;
8381
+ }
8382
+ this._delegate = tracer;
8383
+ return this._delegate;
8384
+ };
8385
+ return ProxyTracer2;
8386
+ })()
8387
+ );
8388
+ var NoopTracerProvider = (
8389
+ /** @class */
8390
+ (function() {
8391
+ function NoopTracerProvider2() {
8392
+ }
8393
+ NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
8394
+ return new NoopTracer();
8395
+ };
8396
+ return NoopTracerProvider2;
8397
+ })()
8398
+ );
8399
+ var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
8400
+ var ProxyTracerProvider = (
8401
+ /** @class */
8402
+ (function() {
8403
+ function ProxyTracerProvider2() {
8404
+ }
8405
+ ProxyTracerProvider2.prototype.getTracer = function(name16, version, options) {
8406
+ var _a16;
8407
+ return (_a16 = this.getDelegateTracer(name16, version, options)) !== null && _a16 !== void 0 ? _a16 : new ProxyTracer(this, name16, version, options);
8408
+ };
8409
+ ProxyTracerProvider2.prototype.getDelegate = function() {
8410
+ var _a16;
8411
+ return (_a16 = this._delegate) !== null && _a16 !== void 0 ? _a16 : NOOP_TRACER_PROVIDER;
8412
+ };
8413
+ ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
8414
+ this._delegate = delegate;
8415
+ };
8416
+ ProxyTracerProvider2.prototype.getDelegateTracer = function(name16, version, options) {
8417
+ var _a16;
8418
+ return (_a16 = this._delegate) === null || _a16 === void 0 ? void 0 : _a16.getTracer(name16, version, options);
8419
+ };
8420
+ return ProxyTracerProvider2;
8421
+ })()
8422
+ );
8423
+ var SpanStatusCode;
8424
+ (function(SpanStatusCode2) {
8425
+ SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
8426
+ SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
8427
+ SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
8428
+ })(SpanStatusCode || (SpanStatusCode = {}));
8429
+ var API_NAME3 = "trace";
8430
+ var TraceAPI = (
8431
+ /** @class */
8432
+ (function() {
8433
+ function TraceAPI2() {
8434
+ this._proxyTracerProvider = new ProxyTracerProvider();
8435
+ this.wrapSpanContext = wrapSpanContext;
8436
+ this.isSpanContextValid = isSpanContextValid;
8437
+ this.deleteSpan = deleteSpan;
8438
+ this.getSpan = getSpan;
8439
+ this.getActiveSpan = getActiveSpan;
8440
+ this.getSpanContext = getSpanContext;
8441
+ this.setSpan = setSpan;
8442
+ this.setSpanContext = setSpanContext;
8443
+ }
8444
+ TraceAPI2.getInstance = function() {
8445
+ if (!this._instance) {
8446
+ this._instance = new TraceAPI2();
8447
+ }
8448
+ return this._instance;
8449
+ };
8450
+ TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
8451
+ var success = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance());
8452
+ if (success) {
8453
+ this._proxyTracerProvider.setDelegate(provider);
8454
+ }
8455
+ return success;
8456
+ };
8457
+ TraceAPI2.prototype.getTracerProvider = function() {
8458
+ return getGlobal(API_NAME3) || this._proxyTracerProvider;
8459
+ };
8460
+ TraceAPI2.prototype.getTracer = function(name16, version) {
8461
+ return this.getTracerProvider().getTracer(name16, version);
8462
+ };
8463
+ TraceAPI2.prototype.disable = function() {
8464
+ unregisterGlobal(API_NAME3, DiagAPI.instance());
8465
+ this._proxyTracerProvider = new ProxyTracerProvider();
8466
+ };
8467
+ return TraceAPI2;
8468
+ })()
8469
+ );
8470
+ TraceAPI.getInstance();
8471
+ var __defProp = Object.defineProperty;
8472
+ var __export = (target, all) => {
8473
+ for (var name16 in all)
8474
+ __defProp(target, name16, { get: all[name16], enumerable: true });
8475
+ };
8476
+ var name622 = "AI_NoObjectGeneratedError";
8477
+ var marker622 = `vercel.ai.error.${name622}`;
8478
+ var symbol622 = Symbol.for(marker622);
8479
+ var _a622;
8480
+ var NoObjectGeneratedError = class extends AISDKError {
8481
+ constructor({
8482
+ message = "No object generated.",
8483
+ cause,
8484
+ text: text2,
8485
+ response,
8486
+ usage,
8487
+ finishReason
8488
+ }) {
8489
+ super({ name: name622, message, cause });
8490
+ this[_a622] = true;
8491
+ this.text = text2;
8492
+ this.response = response;
8493
+ this.usage = usage;
8494
+ this.finishReason = finishReason;
8495
+ }
8496
+ static isInstance(error) {
8497
+ return AISDKError.hasMarker(error, marker622);
8498
+ }
8499
+ };
8500
+ _a622 = symbol622;
8501
+ var dataContentSchema = z$1.union([
8502
+ z$1.string(),
8503
+ z$1.instanceof(Uint8Array),
8504
+ z$1.instanceof(ArrayBuffer),
8505
+ z$1.custom(
8506
+ // Buffer might not be available in some environments such as CloudFlare:
8507
+ (value) => {
8508
+ var _a16, _b8;
8509
+ return (_b8 = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b8 : false;
8510
+ },
8511
+ { message: "Must be a Buffer" }
8512
+ )
8513
+ ]);
8514
+ var jsonValueSchema = z$1.lazy(
8515
+ () => z$1.union([
8516
+ z$1.null(),
8517
+ z$1.string(),
8518
+ z$1.number(),
8519
+ z$1.boolean(),
8520
+ z$1.record(z$1.string(), jsonValueSchema),
8521
+ z$1.array(jsonValueSchema)
8522
+ ])
8523
+ );
8524
+ var providerMetadataSchema = z$1.record(
8525
+ z$1.string(),
8526
+ z$1.record(z$1.string(), jsonValueSchema)
8527
+ );
8528
+ var textPartSchema = z$1.object({
8529
+ type: z$1.literal("text"),
8530
+ text: z$1.string(),
8531
+ providerOptions: providerMetadataSchema.optional()
8532
+ });
8533
+ var imagePartSchema = z$1.object({
8534
+ type: z$1.literal("image"),
8535
+ image: z$1.union([dataContentSchema, z$1.instanceof(URL)]),
8536
+ mediaType: z$1.string().optional(),
8537
+ providerOptions: providerMetadataSchema.optional()
8538
+ });
8539
+ var filePartSchema = z$1.object({
8540
+ type: z$1.literal("file"),
8541
+ data: z$1.union([dataContentSchema, z$1.instanceof(URL)]),
8542
+ filename: z$1.string().optional(),
8543
+ mediaType: z$1.string(),
8544
+ providerOptions: providerMetadataSchema.optional()
8545
+ });
8546
+ var reasoningPartSchema = z$1.object({
8547
+ type: z$1.literal("reasoning"),
8548
+ text: z$1.string(),
8549
+ providerOptions: providerMetadataSchema.optional()
8550
+ });
8551
+ var toolCallPartSchema = z$1.object({
8552
+ type: z$1.literal("tool-call"),
8553
+ toolCallId: z$1.string(),
8554
+ toolName: z$1.string(),
8555
+ input: z$1.unknown(),
8556
+ providerOptions: providerMetadataSchema.optional(),
8557
+ providerExecuted: z$1.boolean().optional()
8558
+ });
8559
+ var outputSchema = z$1.discriminatedUnion("type", [
8560
+ z$1.object({
8561
+ type: z$1.literal("text"),
8562
+ value: z$1.string()
8563
+ }),
8564
+ z$1.object({
8565
+ type: z$1.literal("json"),
8566
+ value: jsonValueSchema
8567
+ }),
8568
+ z$1.object({
8569
+ type: z$1.literal("error-text"),
8570
+ value: z$1.string()
8571
+ }),
8572
+ z$1.object({
8573
+ type: z$1.literal("error-json"),
8574
+ value: jsonValueSchema
8575
+ }),
8576
+ z$1.object({
8577
+ type: z$1.literal("content"),
8578
+ value: z$1.array(
8579
+ z$1.union([
8580
+ z$1.object({
8581
+ type: z$1.literal("text"),
8582
+ text: z$1.string()
8583
+ }),
8584
+ z$1.object({
8585
+ type: z$1.literal("media"),
8586
+ data: z$1.string(),
8587
+ mediaType: z$1.string()
8588
+ })
8589
+ ])
8590
+ )
8591
+ })
8592
+ ]);
8593
+ var toolResultPartSchema = z$1.object({
8594
+ type: z$1.literal("tool-result"),
8595
+ toolCallId: z$1.string(),
8596
+ toolName: z$1.string(),
8597
+ output: outputSchema,
8598
+ providerOptions: providerMetadataSchema.optional()
8599
+ });
8600
+ var systemModelMessageSchema = z$1.object(
8601
+ {
8602
+ role: z$1.literal("system"),
8603
+ content: z$1.string(),
8604
+ providerOptions: providerMetadataSchema.optional()
8605
+ }
8606
+ );
8607
+ var userModelMessageSchema = z$1.object({
8608
+ role: z$1.literal("user"),
8609
+ content: z$1.union([
8610
+ z$1.string(),
8611
+ z$1.array(z$1.union([textPartSchema, imagePartSchema, filePartSchema]))
8612
+ ]),
8613
+ providerOptions: providerMetadataSchema.optional()
8614
+ });
8615
+ var assistantModelMessageSchema = z$1.object({
8616
+ role: z$1.literal("assistant"),
8617
+ content: z$1.union([
8618
+ z$1.string(),
8619
+ z$1.array(
8620
+ z$1.union([
8621
+ textPartSchema,
8622
+ filePartSchema,
8623
+ reasoningPartSchema,
8624
+ toolCallPartSchema,
8625
+ toolResultPartSchema
8626
+ ])
8627
+ )
8628
+ ]),
8629
+ providerOptions: providerMetadataSchema.optional()
8630
+ });
8631
+ var toolModelMessageSchema = z$1.object({
8632
+ role: z$1.literal("tool"),
8633
+ content: z$1.array(toolResultPartSchema),
8634
+ providerOptions: providerMetadataSchema.optional()
8635
+ });
8636
+ z$1.union([
8637
+ systemModelMessageSchema,
8638
+ userModelMessageSchema,
8639
+ assistantModelMessageSchema,
8640
+ toolModelMessageSchema
8641
+ ]);
8642
+ function stepCountIs(stepCount) {
8643
+ return ({ steps }) => steps.length === stepCount;
8644
+ }
8645
+ createIdGenerator({
8646
+ prefix: "aitxt",
8647
+ size: 24
8648
+ });
8649
+ (class extends TransformStream {
8650
+ constructor() {
8651
+ super({
8652
+ transform(part, controller) {
8653
+ controller.enqueue(`data: ${JSON.stringify(part)}
8654
+
8655
+ `);
8656
+ },
8657
+ flush(controller) {
8658
+ controller.enqueue("data: [DONE]\n\n");
8659
+ }
8660
+ });
8661
+ }
8662
+ });
8663
+ function fixJson(input) {
8664
+ const stack = ["ROOT"];
8665
+ let lastValidIndex = -1;
8666
+ let literalStart = null;
8667
+ function processValueStart(char, i, swapState) {
8668
+ {
8669
+ switch (char) {
8670
+ case '"': {
8671
+ lastValidIndex = i;
8672
+ stack.pop();
8673
+ stack.push(swapState);
8674
+ stack.push("INSIDE_STRING");
8675
+ break;
8676
+ }
8677
+ case "f":
8678
+ case "t":
8679
+ case "n": {
8680
+ lastValidIndex = i;
8681
+ literalStart = i;
8682
+ stack.pop();
8683
+ stack.push(swapState);
8684
+ stack.push("INSIDE_LITERAL");
8685
+ break;
8686
+ }
8687
+ case "-": {
8688
+ stack.pop();
8689
+ stack.push(swapState);
8690
+ stack.push("INSIDE_NUMBER");
8691
+ break;
8692
+ }
8693
+ case "0":
8694
+ case "1":
8695
+ case "2":
8696
+ case "3":
8697
+ case "4":
8698
+ case "5":
8699
+ case "6":
8700
+ case "7":
8701
+ case "8":
8702
+ case "9": {
8703
+ lastValidIndex = i;
8704
+ stack.pop();
8705
+ stack.push(swapState);
8706
+ stack.push("INSIDE_NUMBER");
8707
+ break;
8708
+ }
8709
+ case "{": {
8710
+ lastValidIndex = i;
8711
+ stack.pop();
8712
+ stack.push(swapState);
8713
+ stack.push("INSIDE_OBJECT_START");
8714
+ break;
8715
+ }
8716
+ case "[": {
8717
+ lastValidIndex = i;
8718
+ stack.pop();
8719
+ stack.push(swapState);
8720
+ stack.push("INSIDE_ARRAY_START");
8721
+ break;
8722
+ }
8723
+ }
8724
+ }
8725
+ }
8726
+ function processAfterObjectValue(char, i) {
8727
+ switch (char) {
8728
+ case ",": {
8729
+ stack.pop();
8730
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
8731
+ break;
8732
+ }
8733
+ case "}": {
8734
+ lastValidIndex = i;
8735
+ stack.pop();
8736
+ break;
8737
+ }
8738
+ }
8739
+ }
8740
+ function processAfterArrayValue(char, i) {
8741
+ switch (char) {
8742
+ case ",": {
8743
+ stack.pop();
8744
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
8745
+ break;
8746
+ }
8747
+ case "]": {
8748
+ lastValidIndex = i;
8749
+ stack.pop();
8750
+ break;
8751
+ }
8752
+ }
8753
+ }
8754
+ for (let i = 0; i < input.length; i++) {
8755
+ const char = input[i];
8756
+ const currentState = stack[stack.length - 1];
8757
+ switch (currentState) {
8758
+ case "ROOT":
8759
+ processValueStart(char, i, "FINISH");
8760
+ break;
8761
+ case "INSIDE_OBJECT_START": {
8762
+ switch (char) {
8763
+ case '"': {
8764
+ stack.pop();
8765
+ stack.push("INSIDE_OBJECT_KEY");
8766
+ break;
8767
+ }
8768
+ case "}": {
8769
+ lastValidIndex = i;
8770
+ stack.pop();
8771
+ break;
8772
+ }
8773
+ }
8774
+ break;
8775
+ }
8776
+ case "INSIDE_OBJECT_AFTER_COMMA": {
8777
+ switch (char) {
8778
+ case '"': {
8779
+ stack.pop();
8780
+ stack.push("INSIDE_OBJECT_KEY");
8781
+ break;
8782
+ }
8783
+ }
8784
+ break;
8785
+ }
8786
+ case "INSIDE_OBJECT_KEY": {
8787
+ switch (char) {
8788
+ case '"': {
8789
+ stack.pop();
8790
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
8791
+ break;
8792
+ }
8793
+ }
8794
+ break;
8795
+ }
8796
+ case "INSIDE_OBJECT_AFTER_KEY": {
8797
+ switch (char) {
8798
+ case ":": {
8799
+ stack.pop();
8800
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
8801
+ break;
8802
+ }
8803
+ }
8804
+ break;
8805
+ }
8806
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
8807
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
8808
+ break;
8809
+ }
8810
+ case "INSIDE_OBJECT_AFTER_VALUE": {
8811
+ processAfterObjectValue(char, i);
8812
+ break;
8813
+ }
8814
+ case "INSIDE_STRING": {
8815
+ switch (char) {
8816
+ case '"': {
8817
+ stack.pop();
8818
+ lastValidIndex = i;
8819
+ break;
8820
+ }
8821
+ case "\\": {
8822
+ stack.push("INSIDE_STRING_ESCAPE");
8823
+ break;
8824
+ }
8825
+ default: {
8826
+ lastValidIndex = i;
8827
+ }
8828
+ }
8829
+ break;
8830
+ }
8831
+ case "INSIDE_ARRAY_START": {
8832
+ switch (char) {
8833
+ case "]": {
8834
+ lastValidIndex = i;
8835
+ stack.pop();
8836
+ break;
8837
+ }
8838
+ default: {
8839
+ lastValidIndex = i;
8840
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
8841
+ break;
8842
+ }
8843
+ }
8844
+ break;
8845
+ }
8846
+ case "INSIDE_ARRAY_AFTER_VALUE": {
8847
+ switch (char) {
8848
+ case ",": {
8849
+ stack.pop();
8850
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
8851
+ break;
8852
+ }
8853
+ case "]": {
8854
+ lastValidIndex = i;
8855
+ stack.pop();
8856
+ break;
8857
+ }
8858
+ default: {
8859
+ lastValidIndex = i;
8860
+ break;
8861
+ }
8862
+ }
8863
+ break;
8864
+ }
8865
+ case "INSIDE_ARRAY_AFTER_COMMA": {
8866
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
8867
+ break;
8868
+ }
8869
+ case "INSIDE_STRING_ESCAPE": {
8870
+ stack.pop();
8871
+ lastValidIndex = i;
8872
+ break;
8873
+ }
8874
+ case "INSIDE_NUMBER": {
8875
+ switch (char) {
8876
+ case "0":
8877
+ case "1":
8878
+ case "2":
8879
+ case "3":
8880
+ case "4":
8881
+ case "5":
8882
+ case "6":
8883
+ case "7":
8884
+ case "8":
8885
+ case "9": {
8886
+ lastValidIndex = i;
8887
+ break;
8888
+ }
8889
+ case "e":
8890
+ case "E":
8891
+ case "-":
8892
+ case ".": {
8893
+ break;
8894
+ }
8895
+ case ",": {
8896
+ stack.pop();
8897
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
8898
+ processAfterArrayValue(char, i);
8899
+ }
8900
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
8901
+ processAfterObjectValue(char, i);
8902
+ }
8903
+ break;
8904
+ }
8905
+ case "}": {
8906
+ stack.pop();
8907
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
8908
+ processAfterObjectValue(char, i);
8909
+ }
8910
+ break;
8911
+ }
8912
+ case "]": {
8913
+ stack.pop();
8914
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
8915
+ processAfterArrayValue(char, i);
8916
+ }
8917
+ break;
8918
+ }
8919
+ default: {
8920
+ stack.pop();
8921
+ break;
8922
+ }
8923
+ }
8924
+ break;
8925
+ }
8926
+ case "INSIDE_LITERAL": {
8927
+ const partialLiteral = input.substring(literalStart, i + 1);
8928
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
8929
+ stack.pop();
8930
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
8931
+ processAfterObjectValue(char, i);
8932
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
8933
+ processAfterArrayValue(char, i);
8934
+ }
8935
+ } else {
8936
+ lastValidIndex = i;
8937
+ }
8938
+ break;
8939
+ }
8940
+ }
8941
+ }
8942
+ let result = input.slice(0, lastValidIndex + 1);
8943
+ for (let i = stack.length - 1; i >= 0; i--) {
8944
+ const state = stack[i];
8945
+ switch (state) {
8946
+ case "INSIDE_STRING": {
8947
+ result += '"';
8948
+ break;
8949
+ }
8950
+ case "INSIDE_OBJECT_KEY":
8951
+ case "INSIDE_OBJECT_AFTER_KEY":
8952
+ case "INSIDE_OBJECT_AFTER_COMMA":
8953
+ case "INSIDE_OBJECT_START":
8954
+ case "INSIDE_OBJECT_BEFORE_VALUE":
8955
+ case "INSIDE_OBJECT_AFTER_VALUE": {
8956
+ result += "}";
8957
+ break;
8958
+ }
8959
+ case "INSIDE_ARRAY_START":
8960
+ case "INSIDE_ARRAY_AFTER_COMMA":
8961
+ case "INSIDE_ARRAY_AFTER_VALUE": {
8962
+ result += "]";
8963
+ break;
8964
+ }
8965
+ case "INSIDE_LITERAL": {
8966
+ const partialLiteral = input.substring(literalStart, input.length);
8967
+ if ("true".startsWith(partialLiteral)) {
8968
+ result += "true".slice(partialLiteral.length);
8969
+ } else if ("false".startsWith(partialLiteral)) {
8970
+ result += "false".slice(partialLiteral.length);
8971
+ } else if ("null".startsWith(partialLiteral)) {
8972
+ result += "null".slice(partialLiteral.length);
8973
+ }
8974
+ }
8975
+ }
8976
+ }
8977
+ return result;
8978
+ }
8979
+ async function parsePartialJson(jsonText) {
8980
+ if (jsonText === void 0) {
8981
+ return { value: void 0, state: "undefined-input" };
8982
+ }
8983
+ let result = await safeParseJSON({ text: jsonText });
8984
+ if (result.success) {
8985
+ return { value: result.value, state: "successful-parse" };
8986
+ }
8987
+ result = await safeParseJSON({ text: fixJson(jsonText) });
8988
+ if (result.success) {
8989
+ return { value: result.value, state: "repaired-parse" };
8990
+ }
8991
+ return { value: void 0, state: "failed-parse" };
8992
+ }
8993
+ createIdGenerator({
8994
+ prefix: "aitxt",
8995
+ size: 24
8996
+ });
8997
+ createIdGenerator({ prefix: "aiobj", size: 24 });
8998
+ createIdGenerator({ prefix: "aiobj", size: 24 });
8999
+ var output_exports = {};
9000
+ __export(output_exports, {
9001
+ object: () => object,
9002
+ text: () => text
9003
+ });
9004
+ var text = () => ({
9005
+ type: "text",
9006
+ responseFormat: { type: "text" },
9007
+ async parsePartial({ text: text2 }) {
9008
+ return { partial: text2 };
9009
+ },
9010
+ async parseOutput({ text: text2 }) {
9011
+ return text2;
9012
+ }
9013
+ });
9014
+ var object = ({
9015
+ schema: inputSchema
9016
+ }) => {
9017
+ const schema = asSchema(inputSchema);
9018
+ return {
9019
+ type: "object",
9020
+ responseFormat: {
9021
+ type: "json",
9022
+ schema: schema.jsonSchema
9023
+ },
9024
+ async parsePartial({ text: text2 }) {
9025
+ const result = await parsePartialJson(text2);
9026
+ switch (result.state) {
9027
+ case "failed-parse":
9028
+ case "undefined-input":
9029
+ return void 0;
9030
+ case "repaired-parse":
9031
+ case "successful-parse":
9032
+ return {
9033
+ // Note: currently no validation of partial results:
9034
+ partial: result.value
9035
+ };
9036
+ default: {
9037
+ const _exhaustiveCheck = result.state;
9038
+ throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
9039
+ }
9040
+ }
9041
+ },
9042
+ async parseOutput({ text: text2 }, context) {
9043
+ const parseResult = await safeParseJSON({ text: text2 });
9044
+ if (!parseResult.success) {
9045
+ throw new NoObjectGeneratedError({
9046
+ message: "No object generated: could not parse the response.",
9047
+ cause: parseResult.error,
9048
+ text: text2,
9049
+ response: context.response,
9050
+ usage: context.usage,
9051
+ finishReason: context.finishReason
9052
+ });
9053
+ }
9054
+ const validationResult = await safeValidateTypes({
9055
+ value: parseResult.value,
9056
+ schema
9057
+ });
9058
+ if (!validationResult.success) {
9059
+ throw new NoObjectGeneratedError({
9060
+ message: "No object generated: response did not match schema.",
9061
+ cause: validationResult.error,
9062
+ text: text2,
9063
+ response: context.response,
9064
+ usage: context.usage,
9065
+ finishReason: context.finishReason
9066
+ });
9067
+ }
9068
+ return validationResult.value;
9069
+ }
9070
+ };
9071
+ };
4772
9072
  var TaskSchema = z.array(
4773
9073
  z.object({
4774
9074
  id: z.string().describe("Unique task ID using kebab-case"),