UNPKG

@openrouter/ai-sdk-provider

Version:

The [OpenRouter](https://openrouter.ai/) provider for the [Vercel AI SDK](https://sdk.vercel.ai/docs) gives access to over 300 large language models on the OpenRouter chat and completion APIs.

1,576 lines (1,570 loc) 145 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __objRest = (source, exclude) => { var target = {}; for (var prop in source) if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop]; if (source != null && __getOwnPropSymbols) for (var prop of __getOwnPropSymbols(source)) { if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) target[prop] = source[prop]; } return target; }; var __export = (target, all) => { for (var name15 in all) __defProp(target, name15, { get: all[name15], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { OpenRouter: () => OpenRouter, createOpenRouter: () => createOpenRouter, openrouter: () => openrouter }); module.exports = __toCommonJS(index_exports); // node_modules/.pnpm/@ai-sdk+provider@3.0.0/node_modules/@ai-sdk/provider/dist/index.mjs var marker = "vercel.ai.error"; var symbol = Symbol.for(marker); var _a; var _b; var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name142, message, cause }) { super(message); this[_a] = true; this.name = name142; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error) { return _AISDKError.hasMarker(error, marker); } static hasMarker(error, marker152) { const markerSymbol = Symbol.for(marker152); return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true; } }; var name = "AI_APICallError"; var marker2 = `vercel.ai.error.${name}`; var symbol2 = Symbol.for(marker2); var _a2; var _b2; var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) { constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name, message, cause }); this[_a2] = true; this.url = url; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error) { return AISDKError.hasMarker(error, marker2); } }; var name2 = "AI_EmptyResponseBodyError"; var marker3 = `vercel.ai.error.${name2}`; var symbol3 = Symbol.for(marker3); var _a3; var _b3; var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name2, message }); this[_a3] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker3); } }; function getErrorMessage(error) { if (error == null) { return "unknown error"; } if (typeof error === "string") { return error; } if (error instanceof Error) { return error.message; } return JSON.stringify(error); } var name3 = "AI_InvalidArgumentError"; var marker4 = `vercel.ai.error.${name3}`; var symbol4 = Symbol.for(marker4); var _a4; var _b4; var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) { constructor({ message, cause, argument }) { super({ name: name3, message, cause }); this[_a4] = true; this.argument = argument; } static isInstance(error) { return AISDKError.hasMarker(error, marker4); } }; var name4 = "AI_InvalidPromptError"; var marker5 = `vercel.ai.error.${name4}`; var symbol5 = Symbol.for(marker5); var _a5; var _b5; var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) { constructor({ prompt, message, cause }) { super({ name: name4, message: `Invalid prompt: ${message}`, cause }); this[_a5] = true; this.prompt = prompt; } static isInstance(error) { return AISDKError.hasMarker(error, marker5); } }; var name5 = "AI_InvalidResponseDataError"; var marker6 = `vercel.ai.error.${name5}`; var symbol6 = Symbol.for(marker6); var _a6; var _b6; var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) { constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) { super({ name: name5, message }); this[_a6] = true; this.data = data; } static isInstance(error) { return AISDKError.hasMarker(error, marker6); } }; var name6 = "AI_JSONParseError"; var marker7 = `vercel.ai.error.${name6}`; var symbol7 = Symbol.for(marker7); var _a7; var _b7; var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) { constructor({ text, cause }) { super({ name: name6, message: `JSON parsing failed: Text: ${text}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a7] = true; this.text = text; } static isInstance(error) { return AISDKError.hasMarker(error, marker7); } }; var name7 = "AI_LoadAPIKeyError"; var marker8 = `vercel.ai.error.${name7}`; var symbol8 = Symbol.for(marker8); var _a8; var _b8; var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) { // used in isInstance constructor({ message }) { super({ name: name7, message }); this[_a8] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker8); } }; var name8 = "AI_LoadSettingError"; var marker9 = `vercel.ai.error.${name8}`; var symbol9 = Symbol.for(marker9); var _a9; var _b9; var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) { // used in isInstance constructor({ message }) { super({ name: name8, message }); this[_a9] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker9); } }; var name9 = "AI_NoContentGeneratedError"; var marker10 = `vercel.ai.error.${name9}`; var symbol10 = Symbol.for(marker10); var _a10; var _b10; var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) { // used in isInstance constructor({ message = "No content generated." } = {}) { super({ name: name9, message }); this[_a10] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker10); } }; var name10 = "AI_NoSuchModelError"; var marker11 = `vercel.ai.error.${name10}`; var symbol11 = Symbol.for(marker11); var _a11; var _b11; var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) { constructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) { super({ name: errorName, message }); this[_a11] = true; this.modelId = modelId; this.modelType = modelType; } static isInstance(error) { return AISDKError.hasMarker(error, marker11); } }; var name11 = "AI_TooManyEmbeddingValuesForCallError"; var marker12 = `vercel.ai.error.${name11}`; var symbol12 = Symbol.for(marker12); var _a12; var _b12; var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) { constructor(options) { super({ name: name11, message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.` }); this[_a12] = true; this.provider = options.provider; this.modelId = options.modelId; this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall; this.values = options.values; } static isInstance(error) { return AISDKError.hasMarker(error, marker12); } }; var name12 = "AI_TypeValidationError"; var marker13 = `vercel.ai.error.${name12}`; var symbol13 = Symbol.for(marker13); var _a13; var _b13; var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) { constructor({ value, cause }) { super({ name: name12, message: `Type validation failed: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a13] = true; this.value = value; } static isInstance(error) { return AISDKError.hasMarker(error, marker13); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause }) { return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause }); } }; var name13 = "AI_UnsupportedFunctionalityError"; var marker14 = `vercel.ai.error.${name13}`; var symbol14 = Symbol.for(marker14); var _a14; var _b14; var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) { constructor({ functionality, message = `'${functionality}' functionality not supported.` }) { super({ name: name13, message }); this[_a14] = true; this.functionality = functionality; } static isInstance(error) { return AISDKError.hasMarker(error, marker14); } }; // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs var z4 = __toESM(require("zod/v4"), 1); var import_v3 = require("zod/v3"); var import_v32 = require("zod/v3"); var import_v33 = require("zod/v3"); // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js var ParseError = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; function noop(_arg) { } function createParser(callbacks) { if (typeof callbacks == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; function feed(newChunk) { const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); for (const line of complete) parseLine(line); incompleteLine = incomplete, isFirstChunk = false; } function parseLine(line) { if (line === "") { dispatchEvent(); return; } if (line.startsWith(":")) { onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); return; } const fieldSeparatorIndex = line.indexOf(":"); if (fieldSeparatorIndex !== -1) { const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); processField(field, value, line); return; } processField(line, "", line); } function processField(field, value, line) { switch (field) { case "event": eventType = value; break; case "data": data = `${data}${value} `; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line } ) ); break; } } function dispatchEvent() { data.length > 0 && onEvent({ id, event: eventType || void 0, // If the data buffer's last character is a U+000A LINE FEED (LF) character, // then remove the last character from the data buffer. data: data.endsWith(` `) ? data.slice(0, -1) : data }), id = void 0, data = "", eventType = ""; } function reset(options = {}) { incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = ""; } return { feed, reset }; } function splitLines(chunk) { const lines = []; let incompleteLine = "", searchIndex = 0; for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; 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) { incompleteLine = chunk.slice(searchIndex); break; } else { const line = chunk.slice(searchIndex, lineEnd); lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === ` ` && searchIndex++; } } return [lines, incompleteLine]; } // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js var EventSourceParserStream = class extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser({ onEvent: (event) => { controller.enqueue(event); }, onError(error) { onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs function combineHeaders(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}), {} ); } function extractResponseHeaders(response) { return Object.fromEntries([...response.headers]); } var { btoa, atob } = globalThis; function convertUint8ArrayToBase64(array) { let latin1string = ""; for (let i = 0; i < array.length; i++) { latin1string += String.fromCodePoint(array[i]); } return btoa(latin1string); } var name14 = "AI_DownloadError"; var marker15 = `vercel.ai.error.${name14}`; var symbol15 = Symbol.for(marker15); var _a15; var _b15; var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) { constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) { super({ name: name14, message, cause }); this[_a15] = true; this.url = url; this.statusCode = statusCode; this.statusText = statusText; } static isInstance(error) { return AISDKError.hasMarker(error, marker15); } }; var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i = 0; i < size; i++) { chars[i] = alphabet[Math.random() * alphabetLength | 0]; } return chars.join(""); }; if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return () => `${prefix}${separator}${generator()}`; }; var generateId = createIdGenerator(); function isAbortError(error) { return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js error.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"]; function handleFetchError({ error, url, requestBodyValues }) { if (isAbortError(error)) { return error; } if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) { const cause = error.cause; if (cause != null) { return new APICallError({ message: `Cannot connect to API: ${cause.message}`, cause, url, requestBodyValues, isRetryable: true // retry when network error }); } } return error; } function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) { var _a22, _b22, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a22 = globalThisAny.navigator) == null ? void 0 : _a22.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b22 = globalThisAny.process) == null ? void 0 : _b22.versions) == null ? void 0 : _c.node) { return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; } if (globalThisAny.EdgeRuntime) { return `runtime/vercel-edge`; } return "runtime/unknown"; } function normalizeHeaders(headers) { if (headers == null) { return {}; } const normalized = {}; if (headers instanceof Headers) { headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); } else { if (!Array.isArray(headers)) { headers = Object.entries(headers); } for (const [key, value] of headers) { if (value != null) { normalized[key.toLowerCase()] = value; } } } return normalized; } function withUserAgentSuffix(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION = true ? "4.0.1" : "0.0.0-test"; function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) { if (typeof apiKey === "string") { return apiKey; } if (apiKey != null) { throw new LoadAPIKeyError({ message: `${description} API key must be a string.` }); } if (typeof process === "undefined") { throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.` }); } apiKey = process.env[environmentVariableName]; if (apiKey == null) { throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` }); } if (typeof apiKey !== "string") { throw new LoadAPIKeyError({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` }); } return apiKey; } var suspectProtoRx = /"__proto__"\s*:/; var suspectConstructorRx = /"constructor"\s*:/; function _parse(text) { const obj = JSON.parse(text); if (obj === null || typeof obj !== "object") { return obj; } if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) { return obj; } return filter(obj); } function filter(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) { throw new SyntaxError("Object contains forbidden prototype property"); } if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { throw new SyntaxError("Object contains forbidden prototype property"); } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function secureJsonParse(text) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e) { return _parse(text); } try { return _parse(text); } finally { Error.stackTraceLimit = stackTraceLimit; } } function addAdditionalPropertiesToJsonSchema(jsonSchema2) { if (jsonSchema2.type === "object") { jsonSchema2.additionalProperties = false; const properties = jsonSchema2.properties; if (properties != null) { for (const property in properties) { properties[property] = addAdditionalPropertiesToJsonSchema( properties[property] ); } } } if (jsonSchema2.type === "array" && jsonSchema2.items != null) { if (Array.isArray(jsonSchema2.items)) { jsonSchema2.items = jsonSchema2.items.map( (item) => addAdditionalPropertiesToJsonSchema(item) ); } else { jsonSchema2.items = addAdditionalPropertiesToJsonSchema( jsonSchema2.items ); } } return jsonSchema2; } var ignoreOverride = Symbol( "Let zodToJsonSchema decide on which parser to use" ); var defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions = (options) => typeof options === "string" ? __spreadProps(__spreadValues({}, defaultOptions), { name: options }) : __spreadValues(__spreadValues({}, defaultOptions), options); function parseAnyDef() { return {}; } function parseArrayDef(def, refs) { var _a22, _b22, _c; const res = { type: "array" }; if (((_a22 = def.type) == null ? void 0 : _a22._def) && ((_c = (_b22 = def.type) == null ? void 0 : _b22._def) == null ? void 0 : _c.typeName) !== import_v32.ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef(def.type._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "items"] })); } if (def.minLength) { res.minItems = def.minLength.value; } if (def.maxLength) { res.maxItems = def.maxLength.value; } if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "min": if (check.inclusive) { res.minimum = check.value; } else { res.exclusiveMinimum = check.value; } break; case "max": if (check.inclusive) { res.maximum = check.value; } else { res.exclusiveMaximum = check.value; } break; case "multipleOf": res.multipleOf = check.value; break; } } return res; } function parseBooleanDef() { return { type: "boolean" }; } function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser(def); } } var integerDateParser = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check of def.checks) { switch (check.kind) { case "min": res.minimum = check.value; break; case "max": res.maximum = check.value; break; } } return res; }; function parseDefaultDef(_def, refs) { return __spreadProps(__spreadValues({}, parseDef(_def.innerType._def, refs)), { default: _def.defaultValue() }); } function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(); } function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef(def, refs) { const allOf = [ parseDef(def.left._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })), parseDef(def.right._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "allOf", "1"] })) ].filter((x) => !!x); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const _a16 = schema, { additionalProperties } = _a16, rest = __objRest(_a16, ["additionalProperties"]); nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef(def) { const parsedType = typeof def.value; if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } return { type: parsedType === "bigint" ? "integer" : parsedType, const: def.value }; } var emojiRegex = void 0; var zodPatterns = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (emojiRegex === void 0) { emojiRegex = RegExp( "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u" ); } return emojiRegex; }, /** * Unused */ 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}$/, /** * Unused */ 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])$/, 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])$/, /** * Unused */ 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})))$/, 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])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; function parseStringDef(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check of def.checks) { switch (check.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check.message, refs); break; } break; case "url": addFormat(res, "uri", check.message, refs); break; case "uuid": addFormat(res, "uuid", check.message, refs); break; case "regex": addPattern(res, check.regex, check.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check.message, refs); break; case "startsWith": addPattern( res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs ); break; case "endsWith": addPattern( res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs ); break; case "datetime": addFormat(res, "date-time", check.message, refs); break; case "date": addFormat(res, "date", check.message, refs); break; case "time": addFormat(res, "time", check.message, refs); break; case "duration": addFormat(res, "duration", check.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "includes": { addPattern( res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs ); break; } case "ip": { if (check.version !== "v6") { addFormat(res, "ipv4", check.message, refs); } if (check.version !== "v4") { addFormat(res, "ipv6", check.message, refs); } break; } case "base64url": addPattern(res, zodPatterns.base64url, check.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check.message, refs); break; case "cidr": { if (check.version !== "v6") { addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); } if (check.version !== "v4") { addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji(), check.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check.message, refs); break; } case "contentEncoding:base64": { res.contentEncoding = "base64"; break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check.message, refs); } case "toLowerCase": case "toUpperCase": case "trim": break; default: /* @__PURE__ */ ((_) => { })(check); } } } return res; } function escapeLiteralCheckValue(literal, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; } var ALPHA_NUMERIC = new Set( "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789" ); function escapeNonAlphaNumeric(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat(schema, value, message, refs) { var _a22; if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format }); delete schema.format; } schema.anyOf.push(__spreadValues({ format: value }, message && refs.errorMessages && { errorMessage: { format: message } })); } else { schema.format = value; } } function addPattern(schema, regex, message, refs) { var _a22; if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern }); delete schema.pattern; } schema.allOf.push(__spreadValues({ pattern: stringifyRegExpWithFlags(regex, refs) }, message && refs.errorMessages && { errorMessage: { pattern: message } })); } else { schema.pattern = stringifyRegExpWithFlags(regex, refs); } } function stringifyRegExpWithFlags(regex, refs) { var _a22; if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s") // `.` matches newlines }; const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0; i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } try { new RegExp(pattern); } catch (e) { console.warn( `Could not convert regex pattern at ${refs.currentPath.join( "/" )} to a flag-independent form! Falling back to the flag-ignorant source` ); return regex.source; } return pattern; } function parseRecordDef(def, refs) { var _a22, _b22, _c, _d, _e, _f; const schema = { type: "object", additionalProperties: (_a22 = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) != null ? _a22 : refs.allowedAdditionalProperties }; if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) { const _a16 = parseStringDef(def.keyType._def, refs), { type } = _a16, keyType = __objRest(_a16, ["type"]); return __spreadProps(__spreadValues({}, schema), { propertyNames: keyType }); } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodEnum) { return __spreadProps(__spreadValues({}, schema), { propertyNames: { enum: def.keyType._def.values } }); } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === import_v33.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) { const _b16 = parseBrandedDef( def.keyType._def, refs ), { type } = _b16, keyType = __objRest(_b16, ["type"]); return __spreadProps(__spreadValues({}, schema), { propertyNames: keyType }); } return schema; } function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); } const keys = parseDef(def.keyType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "items", "items", "0"] })) || parseAnyDef(); const values = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "items", "items", "1"] })) || parseAnyDef(); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } function parseNativeEnumDef(def) { const object = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object[object[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object[key]); const parsedTypes = Array.from( new Set(actualValues.map((values) => typeof values)) ); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } function parseNeverDef() { return { not: parseAnyDef() }; } function parseNullDef() { return { type: "null" }; } var primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef(def, refs) { const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every( (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length) )) { const types = options.reduce((types2, x) => { const type = primitiveMappings[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { const types = options.reduce( (acc, x) => { const type = typeof x._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, [] ); if (types.length === options.length) { const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce( (acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, [] ) }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce( (acc, x) => [ ...acc, ...x._def.values.filter((x2) => !acc.includes(x2)) ], [] ) }; } return asAnyOf(def, refs); } var asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map( (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "anyOf", `${i}`] })) ).filter( (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0) ); return anyOf.length ? { anyOf } : void 0; }; function parseNullableDef(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes( def.innerType._def.typeName ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { return { type: [ primitiveMappings[def.innerType._def.typeName], "null" ] }; } const base = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "anyOf", "0"] })); return base && { anyOf: [base, { type: "null" }] }; } function parseNumberDef(def) { const res = { type: "number" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "int": res.type = "integer"; break; case "min": if (check.inclusive) { res.minimum = check.value; } else { res.exclusiveMinimum = check.value; } break; case "max": if (check.inclusive) { res.maximum = check.value; } else { res.exclusiveMaximum = check.value; } break; case "multipleOf": res.multipleOf = check.value; break; } } return res; } function parseObjectDef(def, refs) { const result = { type: "object", properties: {} }; const required = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } const propOptional = safeIsOptional(propDef); const parsedDef = parseDef(propDef._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] })); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required.push(propName); } } if (required.length) { result.required = required; } const additionalProperties = decideAdditionalProperties(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef(def.catchall._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] })); } switch (def.unknownKeys) { case "passthrough": return refs.allowedAdditionalProperties; case "strict": return refs.rejectedAdditionalProperties; case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } } function safeIsOptional(schema) { try { return schema.isOptional(); } catch (e) { return true; } } var parseOptionalDef = (def, refs) => { var _a22; if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) { return parseDef(def.innerType._def, refs); } const innerSchema = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "anyOf", "1"] })); return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef(); }; var parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef(def.out._def, refs); } const a = parseDef(def.in._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })); const b = parseDef(def.out._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] })); return { allOf: [a, b].filter((x) => x !== void 0) }; }; function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } function parseSetDef(def, refs) { const items = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "items"] })); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { schema.minItems = def.minSize.value; } if