v0-mcp-ts
Version:
A powerful Model Context Protocol (MCP) server that integrates v0.dev AI capabilities for modern web development. Powered by Bun for 25x faster performance.
15,419 lines • 506 kB
JavaScript
import { createRequire } from "node:module";
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __toESM = (mod, isNodeMode, target) => {
target = mod != null ? __create(__getProtoOf(mod)) : {};
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
for (let key of __getOwnPropNames(mod))
if (!__hasOwnProp.call(to, key))
__defProp(to, key, {
get: () => mod[key],
enumerable: true
});
return to;
};
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, {
get: all[name],
enumerable: true,
configurable: true,
set: (newValue) => all[name] = () => newValue
});
};
var __require = /* @__PURE__ */ createRequire(import.meta.url);
// node_modules/secure-json-parse/index.js
var require_secure_json_parse = __commonJS((exports, module) => {
var hasBuffer = typeof Buffer !== "undefined";
var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
function _parse(text, reviver, options) {
if (options == null) {
if (reviver !== null && typeof reviver === "object") {
options = reviver;
reviver = undefined;
}
}
if (hasBuffer && Buffer.isBuffer(text)) {
text = text.toString();
}
if (text && text.charCodeAt(0) === 65279) {
text = text.slice(1);
}
const obj = JSON.parse(text, reviver);
if (obj === null || typeof obj !== "object") {
return obj;
}
const protoAction = options && options.protoAction || "error";
const constructorAction = options && options.constructorAction || "error";
if (protoAction === "ignore" && constructorAction === "ignore") {
return obj;
}
if (protoAction !== "ignore" && constructorAction !== "ignore") {
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
return obj;
}
} else if (protoAction !== "ignore" && constructorAction === "ignore") {
if (suspectProtoRx.test(text) === false) {
return obj;
}
} else {
if (suspectConstructorRx.test(text) === false) {
return obj;
}
}
return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
}
function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
let next = [obj];
while (next.length) {
const nodes = next;
next = [];
for (const node of nodes) {
if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
if (safe === true) {
return null;
} else if (protoAction === "error") {
throw new SyntaxError("Object contains forbidden prototype property");
}
delete node.__proto__;
}
if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
if (safe === true) {
return null;
} else if (constructorAction === "error") {
throw new SyntaxError("Object contains forbidden prototype property");
}
delete node.constructor;
}
for (const key in node) {
const value = node[key];
if (value && typeof value === "object") {
next.push(value);
}
}
}
}
return obj;
}
function parse(text, reviver, options) {
const stackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
try {
return _parse(text, reviver, options);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
function safeParse(text, reviver) {
const stackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
try {
return _parse(text, reviver, { safe: true });
} catch (_e) {
return null;
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
module.exports = parse;
module.exports.default = parse;
module.exports.parse = parse;
module.exports.safeParse = safeParse;
module.exports.scan = filter;
});
// node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js
var require_globalThis = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports._globalThis = undefined;
exports._globalThis = typeof globalThis === "object" ? globalThis : global;
});
// node_modules/@opentelemetry/api/build/src/platform/node/index.js
var require_node = __commonJS((exports) => {
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined)
k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
__createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require_globalThis(), exports);
});
// node_modules/@opentelemetry/api/build/src/platform/index.js
var require_platform = __commonJS((exports) => {
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined)
k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
__createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require_node(), exports);
});
// node_modules/@opentelemetry/api/build/src/version.js
var require_version = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.VERSION = undefined;
exports.VERSION = "1.9.0";
});
// node_modules/@opentelemetry/api/build/src/internal/semver.js
var require_semver = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCompatible = exports._makeCompatibilityCheck = undefined;
var version_1 = require_version();
var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
function _makeCompatibilityCheck(ownVersion) {
const acceptedVersions = new Set([ownVersion]);
const rejectedVersions = new Set;
const myVersionMatch = ownVersion.match(re);
if (!myVersionMatch) {
return () => false;
}
const ownVersionParsed = {
major: +myVersionMatch[1],
minor: +myVersionMatch[2],
patch: +myVersionMatch[3],
prerelease: myVersionMatch[4]
};
if (ownVersionParsed.prerelease != null) {
return function isExactmatch(globalVersion) {
return globalVersion === ownVersion;
};
}
function _reject(v) {
rejectedVersions.add(v);
return false;
}
function _accept(v) {
acceptedVersions.add(v);
return true;
}
return function isCompatible(globalVersion) {
if (acceptedVersions.has(globalVersion)) {
return true;
}
if (rejectedVersions.has(globalVersion)) {
return false;
}
const globalVersionMatch = globalVersion.match(re);
if (!globalVersionMatch) {
return _reject(globalVersion);
}
const globalVersionParsed = {
major: +globalVersionMatch[1],
minor: +globalVersionMatch[2],
patch: +globalVersionMatch[3],
prerelease: globalVersionMatch[4]
};
if (globalVersionParsed.prerelease != null) {
return _reject(globalVersion);
}
if (ownVersionParsed.major !== globalVersionParsed.major) {
return _reject(globalVersion);
}
if (ownVersionParsed.major === 0) {
if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
return _accept(globalVersion);
}
return _reject(globalVersion);
}
if (ownVersionParsed.minor <= globalVersionParsed.minor) {
return _accept(globalVersion);
}
return _reject(globalVersion);
};
}
exports._makeCompatibilityCheck = _makeCompatibilityCheck;
exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION);
});
// node_modules/@opentelemetry/api/build/src/internal/global-utils.js
var require_global_utils = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = undefined;
var platform_1 = require_platform();
var version_1 = require_version();
var semver_1 = require_semver();
var major = version_1.VERSION.split(".")[0];
var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
var _global = platform_1._globalThis;
function registerGlobal(type, instance, diag, allowOverride = false) {
var _a15;
const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a15 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a15 !== undefined ? _a15 : {
version: version_1.VERSION
};
if (!allowOverride && api[type]) {
const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
diag.error(err.stack || err.message);
return false;
}
if (api.version !== version_1.VERSION) {
const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
diag.error(err.stack || err.message);
return false;
}
api[type] = instance;
diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
return true;
}
exports.registerGlobal = registerGlobal;
function getGlobal(type) {
var _a15, _b;
const globalVersion = (_a15 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a15 === undefined ? undefined : _a15.version;
if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
return;
}
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === undefined ? undefined : _b[type];
}
exports.getGlobal = getGlobal;
function unregisterGlobal(type, diag) {
diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
if (api) {
delete api[type];
}
}
exports.unregisterGlobal = unregisterGlobal;
});
// node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js
var require_ComponentLogger = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagComponentLogger = undefined;
var global_utils_1 = require_global_utils();
class DiagComponentLogger {
constructor(props) {
this._namespace = props.namespace || "DiagComponentLogger";
}
debug(...args) {
return logProxy("debug", this._namespace, args);
}
error(...args) {
return logProxy("error", this._namespace, args);
}
info(...args) {
return logProxy("info", this._namespace, args);
}
warn(...args) {
return logProxy("warn", this._namespace, args);
}
verbose(...args) {
return logProxy("verbose", this._namespace, args);
}
}
exports.DiagComponentLogger = DiagComponentLogger;
function logProxy(funcName, namespace, args) {
const logger = (0, global_utils_1.getGlobal)("diag");
if (!logger) {
return;
}
args.unshift(namespace);
return logger[funcName](...args);
}
});
// node_modules/@opentelemetry/api/build/src/diag/types.js
var require_types = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagLogLevel = undefined;
var DiagLogLevel;
(function(DiagLogLevel2) {
DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {}));
});
// node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js
var require_logLevelLogger = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLogLevelDiagLogger = undefined;
var types_1 = require_types();
function createLogLevelDiagLogger(maxLevel, logger) {
if (maxLevel < types_1.DiagLogLevel.NONE) {
maxLevel = types_1.DiagLogLevel.NONE;
} else if (maxLevel > types_1.DiagLogLevel.ALL) {
maxLevel = types_1.DiagLogLevel.ALL;
}
logger = logger || {};
function _filterFunc(funcName, theLevel) {
const theFunc = logger[funcName];
if (typeof theFunc === "function" && maxLevel >= theLevel) {
return theFunc.bind(logger);
}
return function() {};
}
return {
error: _filterFunc("error", types_1.DiagLogLevel.ERROR),
warn: _filterFunc("warn", types_1.DiagLogLevel.WARN),
info: _filterFunc("info", types_1.DiagLogLevel.INFO),
debug: _filterFunc("debug", types_1.DiagLogLevel.DEBUG),
verbose: _filterFunc("verbose", types_1.DiagLogLevel.VERBOSE)
};
}
exports.createLogLevelDiagLogger = createLogLevelDiagLogger;
});
// node_modules/@opentelemetry/api/build/src/api/diag.js
var require_diag = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagAPI = undefined;
var ComponentLogger_1 = require_ComponentLogger();
var logLevelLogger_1 = require_logLevelLogger();
var types_1 = require_types();
var global_utils_1 = require_global_utils();
var API_NAME = "diag";
class DiagAPI {
constructor() {
function _logProxy(funcName) {
return function(...args) {
const logger = (0, global_utils_1.getGlobal)("diag");
if (!logger)
return;
return logger[funcName](...args);
};
}
const self = this;
const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => {
var _a15, _b, _c;
if (logger === self) {
const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
self.error((_a15 = err.stack) !== null && _a15 !== undefined ? _a15 : err.message);
return false;
}
if (typeof optionsOrLogLevel === "number") {
optionsOrLogLevel = {
logLevel: optionsOrLogLevel
};
}
const oldLogger = (0, global_utils_1.getGlobal)("diag");
const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== undefined ? _b : types_1.DiagLogLevel.INFO, logger);
if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
const stack = (_c = new Error().stack) !== null && _c !== undefined ? _c : "<failed to generate stacktrace>";
oldLogger.warn(`Current logger will be overwritten from ${stack}`);
newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
}
return (0, global_utils_1.registerGlobal)("diag", newLogger, self, true);
};
self.setLogger = setLogger;
self.disable = () => {
(0, global_utils_1.unregisterGlobal)(API_NAME, self);
};
self.createComponentLogger = (options) => {
return new ComponentLogger_1.DiagComponentLogger(options);
};
self.verbose = _logProxy("verbose");
self.debug = _logProxy("debug");
self.info = _logProxy("info");
self.warn = _logProxy("warn");
self.error = _logProxy("error");
}
static instance() {
if (!this._instance) {
this._instance = new DiagAPI;
}
return this._instance;
}
}
exports.DiagAPI = DiagAPI;
});
// node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js
var require_baggage_impl = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaggageImpl = undefined;
class BaggageImpl {
constructor(entries) {
this._entries = entries ? new Map(entries) : new Map;
}
getEntry(key) {
const entry = this._entries.get(key);
if (!entry) {
return;
}
return Object.assign({}, entry);
}
getAllEntries() {
return Array.from(this._entries.entries()).map(([k, v]) => [k, v]);
}
setEntry(key, entry) {
const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.set(key, entry);
return newBaggage;
}
removeEntry(key) {
const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.delete(key);
return newBaggage;
}
removeEntries(...keys) {
const newBaggage = new BaggageImpl(this._entries);
for (const key of keys) {
newBaggage._entries.delete(key);
}
return newBaggage;
}
clear() {
return new BaggageImpl;
}
}
exports.BaggageImpl = BaggageImpl;
});
// node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js
var require_symbol = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.baggageEntryMetadataSymbol = undefined;
exports.baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata");
});
// node_modules/@opentelemetry/api/build/src/baggage/utils.js
var require_utils = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.baggageEntryMetadataFromString = exports.createBaggage = undefined;
var diag_1 = require_diag();
var baggage_impl_1 = require_baggage_impl();
var symbol_1 = require_symbol();
var diag = diag_1.DiagAPI.instance();
function createBaggage(entries = {}) {
return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries)));
}
exports.createBaggage = createBaggage;
function baggageEntryMetadataFromString(str) {
if (typeof str !== "string") {
diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
str = "";
}
return {
__TYPE__: symbol_1.baggageEntryMetadataSymbol,
toString() {
return str;
}
};
}
exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString;
});
// node_modules/@opentelemetry/api/build/src/context/context.js
var require_context = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ROOT_CONTEXT = exports.createContextKey = undefined;
function createContextKey(description) {
return Symbol.for(description);
}
exports.createContextKey = createContextKey;
class BaseContext {
constructor(parentContext) {
const self = this;
self._currentContext = parentContext ? new Map(parentContext) : new Map;
self.getValue = (key) => self._currentContext.get(key);
self.setValue = (key, value) => {
const context = new BaseContext(self._currentContext);
context._currentContext.set(key, value);
return context;
};
self.deleteValue = (key) => {
const context = new BaseContext(self._currentContext);
context._currentContext.delete(key);
return context;
};
}
}
exports.ROOT_CONTEXT = new BaseContext;
});
// node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js
var require_consoleLogger = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagConsoleLogger = undefined;
var consoleMap = [
{ n: "error", c: "error" },
{ n: "warn", c: "warn" },
{ n: "info", c: "info" },
{ n: "debug", c: "debug" },
{ n: "verbose", c: "trace" }
];
class DiagConsoleLogger {
constructor() {
function _consoleFunc(funcName) {
return function(...args) {
if (console) {
let theFunc = console[funcName];
if (typeof theFunc !== "function") {
theFunc = console.log;
}
if (typeof theFunc === "function") {
return theFunc.apply(console, args);
}
}
};
}
for (let i = 0;i < consoleMap.length; i++) {
this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);
}
}
}
exports.DiagConsoleLogger = DiagConsoleLogger;
});
// node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js
var require_NoopMeter = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = undefined;
class NoopMeter {
constructor() {}
createGauge(_name, _options) {
return exports.NOOP_GAUGE_METRIC;
}
createHistogram(_name, _options) {
return exports.NOOP_HISTOGRAM_METRIC;
}
createCounter(_name, _options) {
return exports.NOOP_COUNTER_METRIC;
}
createUpDownCounter(_name, _options) {
return exports.NOOP_UP_DOWN_COUNTER_METRIC;
}
createObservableGauge(_name, _options) {
return exports.NOOP_OBSERVABLE_GAUGE_METRIC;
}
createObservableCounter(_name, _options) {
return exports.NOOP_OBSERVABLE_COUNTER_METRIC;
}
createObservableUpDownCounter(_name, _options) {
return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
}
addBatchObservableCallback(_callback, _observables) {}
removeBatchObservableCallback(_callback) {}
}
exports.NoopMeter = NoopMeter;
class NoopMetric {
}
exports.NoopMetric = NoopMetric;
class NoopCounterMetric extends NoopMetric {
add(_value, _attributes) {}
}
exports.NoopCounterMetric = NoopCounterMetric;
class NoopUpDownCounterMetric extends NoopMetric {
add(_value, _attributes) {}
}
exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric;
class NoopGaugeMetric extends NoopMetric {
record(_value, _attributes) {}
}
exports.NoopGaugeMetric = NoopGaugeMetric;
class NoopHistogramMetric extends NoopMetric {
record(_value, _attributes) {}
}
exports.NoopHistogramMetric = NoopHistogramMetric;
class NoopObservableMetric {
addCallback(_callback) {}
removeCallback(_callback) {}
}
exports.NoopObservableMetric = NoopObservableMetric;
class NoopObservableCounterMetric extends NoopObservableMetric {
}
exports.NoopObservableCounterMetric = NoopObservableCounterMetric;
class NoopObservableGaugeMetric extends NoopObservableMetric {
}
exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric;
class NoopObservableUpDownCounterMetric extends NoopObservableMetric {
}
exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric;
exports.NOOP_METER = new NoopMeter;
exports.NOOP_COUNTER_METRIC = new NoopCounterMetric;
exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric;
exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric;
exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric;
exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric;
exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric;
exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric;
function createNoopMeter() {
return exports.NOOP_METER;
}
exports.createNoopMeter = createNoopMeter;
});
// node_modules/@opentelemetry/api/build/src/metrics/Metric.js
var require_Metric = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueType = undefined;
var ValueType;
(function(ValueType2) {
ValueType2[ValueType2["INT"] = 0] = "INT";
ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE";
})(ValueType = exports.ValueType || (exports.ValueType = {}));
});
// node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js
var require_TextMapPropagator = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultTextMapSetter = exports.defaultTextMapGetter = undefined;
exports.defaultTextMapGetter = {
get(carrier, key) {
if (carrier == null) {
return;
}
return carrier[key];
},
keys(carrier) {
if (carrier == null) {
return [];
}
return Object.keys(carrier);
}
};
exports.defaultTextMapSetter = {
set(carrier, key, value) {
if (carrier == null) {
return;
}
carrier[key] = value;
}
};
});
// node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js
var require_NoopContextManager = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopContextManager = undefined;
var context_1 = require_context();
class NoopContextManager {
active() {
return context_1.ROOT_CONTEXT;
}
with(_context, fn, thisArg, ...args) {
return fn.call(thisArg, ...args);
}
bind(_context, target) {
return target;
}
enable() {
return this;
}
disable() {
return this;
}
}
exports.NoopContextManager = NoopContextManager;
});
// node_modules/@opentelemetry/api/build/src/api/context.js
var require_context2 = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextAPI = undefined;
var NoopContextManager_1 = require_NoopContextManager();
var global_utils_1 = require_global_utils();
var diag_1 = require_diag();
var API_NAME = "context";
var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager;
class ContextAPI {
constructor() {}
static getInstance() {
if (!this._instance) {
this._instance = new ContextAPI;
}
return this._instance;
}
setGlobalContextManager(contextManager) {
return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance());
}
active() {
return this._getContextManager().active();
}
with(context, fn, thisArg, ...args) {
return this._getContextManager().with(context, fn, thisArg, ...args);
}
bind(context, target) {
return this._getContextManager().bind(context, target);
}
_getContextManager() {
return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER;
}
disable() {
this._getContextManager().disable();
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
}
exports.ContextAPI = ContextAPI;
});
// node_modules/@opentelemetry/api/build/src/trace/trace_flags.js
var require_trace_flags = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceFlags = undefined;
var TraceFlags;
(function(TraceFlags2) {
TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
})(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {}));
});
// node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js
var require_invalid_span_constants = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = undefined;
var trace_flags_1 = require_trace_flags();
exports.INVALID_SPANID = "0000000000000000";
exports.INVALID_TRACEID = "00000000000000000000000000000000";
exports.INVALID_SPAN_CONTEXT = {
traceId: exports.INVALID_TRACEID,
spanId: exports.INVALID_SPANID,
traceFlags: trace_flags_1.TraceFlags.NONE
};
});
// node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js
var require_NonRecordingSpan = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NonRecordingSpan = undefined;
var invalid_span_constants_1 = require_invalid_span_constants();
class NonRecordingSpan {
constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) {
this._spanContext = _spanContext;
}
spanContext() {
return this._spanContext;
}
setAttribute(_key, _value) {
return this;
}
setAttributes(_attributes) {
return this;
}
addEvent(_name, _attributes) {
return this;
}
addLink(_link) {
return this;
}
addLinks(_links) {
return this;
}
setStatus(_status) {
return this;
}
updateName(_name) {
return this;
}
end(_endTime) {}
isRecording() {
return false;
}
recordException(_exception, _time) {}
}
exports.NonRecordingSpan = NonRecordingSpan;
});
// node_modules/@opentelemetry/api/build/src/trace/context-utils.js
var require_context_utils = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = undefined;
var context_1 = require_context();
var NonRecordingSpan_1 = require_NonRecordingSpan();
var context_2 = require_context2();
var SPAN_KEY = (0, context_1.createContextKey)("OpenTelemetry Context Key SPAN");
function getSpan(context) {
return context.getValue(SPAN_KEY) || undefined;
}
exports.getSpan = getSpan;
function getActiveSpan() {
return getSpan(context_2.ContextAPI.getInstance().active());
}
exports.getActiveSpan = getActiveSpan;
function setSpan(context, span) {
return context.setValue(SPAN_KEY, span);
}
exports.setSpan = setSpan;
function deleteSpan(context) {
return context.deleteValue(SPAN_KEY);
}
exports.deleteSpan = deleteSpan;
function setSpanContext(context, spanContext) {
return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext));
}
exports.setSpanContext = setSpanContext;
function getSpanContext(context) {
var _a15;
return (_a15 = getSpan(context)) === null || _a15 === undefined ? undefined : _a15.spanContext();
}
exports.getSpanContext = getSpanContext;
});
// node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js
var require_spancontext_utils = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = undefined;
var invalid_span_constants_1 = require_invalid_span_constants();
var NonRecordingSpan_1 = require_NonRecordingSpan();
var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
function isValidTraceId(traceId) {
return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID;
}
exports.isValidTraceId = isValidTraceId;
function isValidSpanId(spanId) {
return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID;
}
exports.isValidSpanId = isValidSpanId;
function isSpanContextValid(spanContext) {
return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
}
exports.isSpanContextValid = isSpanContextValid;
function wrapSpanContext(spanContext) {
return new NonRecordingSpan_1.NonRecordingSpan(spanContext);
}
exports.wrapSpanContext = wrapSpanContext;
});
// node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js
var require_NoopTracer = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTracer = undefined;
var context_1 = require_context2();
var context_utils_1 = require_context_utils();
var NonRecordingSpan_1 = require_NonRecordingSpan();
var spancontext_utils_1 = require_spancontext_utils();
var contextApi = context_1.ContextAPI.getInstance();
class NoopTracer {
startSpan(name14, options, context = contextApi.active()) {
const root = Boolean(options === null || options === undefined ? undefined : options.root);
if (root) {
return new NonRecordingSpan_1.NonRecordingSpan;
}
const parentFromContext = context && (0, context_utils_1.getSpanContext)(context);
if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) {
return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext);
} else {
return new NonRecordingSpan_1.NonRecordingSpan;
}
}
startActiveSpan(name14, arg2, arg3, arg4) {
let opts;
let ctx;
let fn;
if (arguments.length < 2) {
return;
} else if (arguments.length === 2) {
fn = arg2;
} else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
} else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
const parentContext = ctx !== null && ctx !== undefined ? ctx : contextApi.active();
const span = this.startSpan(name14, opts, parentContext);
const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span);
return contextApi.with(contextWithSpanSet, fn, undefined, span);
}
}
exports.NoopTracer = NoopTracer;
function isSpanContext(spanContext) {
return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
}
});
// node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js
var require_ProxyTracer = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyTracer = undefined;
var NoopTracer_1 = require_NoopTracer();
var NOOP_TRACER = new NoopTracer_1.NoopTracer;
class ProxyTracer {
constructor(_provider, name14, version, options) {
this._provider = _provider;
this.name = name14;
this.version = version;
this.options = options;
}
startSpan(name14, options, context) {
return this._getTracer().startSpan(name14, options, context);
}
startActiveSpan(_name, _options, _context, _fn) {
const tracer = this._getTracer();
return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
}
_getTracer() {
if (this._delegate) {
return this._delegate;
}
const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
if (!tracer) {
return NOOP_TRACER;
}
this._delegate = tracer;
return this._delegate;
}
}
exports.ProxyTracer = ProxyTracer;
});
// node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js
var require_NoopTracerProvider = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTracerProvider = undefined;
var NoopTracer_1 = require_NoopTracer();
class NoopTracerProvider {
getTracer(_name, _version, _options) {
return new NoopTracer_1.NoopTracer;
}
}
exports.NoopTracerProvider = NoopTracerProvider;
});
// node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js
var require_ProxyTracerProvider = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyTracerProvider = undefined;
var ProxyTracer_1 = require_ProxyTracer();
var NoopTracerProvider_1 = require_NoopTracerProvider();
var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider;
class ProxyTracerProvider {
getTracer(name14, version, options) {
var _a15;
return (_a15 = this.getDelegateTracer(name14, version, options)) !== null && _a15 !== undefined ? _a15 : new ProxyTracer_1.ProxyTracer(this, name14, version, options);
}
getDelegate() {
var _a15;
return (_a15 = this._delegate) !== null && _a15 !== undefined ? _a15 : NOOP_TRACER_PROVIDER;
}
setDelegate(delegate) {
this._delegate = delegate;
}
getDelegateTracer(name14, version, options) {
var _a15;
return (_a15 = this._delegate) === null || _a15 === undefined ? undefined : _a15.getTracer(name14, version, options);
}
}
exports.ProxyTracerProvider = ProxyTracerProvider;
});
// node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js
var require_SamplingResult = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = undefined;
var SamplingDecision;
(function(SamplingDecision2) {
SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD";
SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD";
SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));
});
// node_modules/@opentelemetry/api/build/src/trace/span_kind.js
var require_span_kind = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpanKind = undefined;
var SpanKind;
(function(SpanKind2) {
SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL";
SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER";
SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT";
SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER";
SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER";
})(SpanKind = exports.SpanKind || (exports.SpanKind = {}));
});
// node_modules/@opentelemetry/api/build/src/trace/status.js
var require_status = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpanStatusCode = undefined;
var SpanStatusCode;
(function(SpanStatusCode2) {
SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
})(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {}));
});
// node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js
var require_tracestate_validators = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateValue = exports.validateKey = undefined;
var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
var VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
var VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
var VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
function validateKey(key) {
return VALID_KEY_REGEX.test(key);
}
exports.validateKey = validateKey;
function validateValue(value) {
return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
}
exports.validateValue = validateValue;
});
// node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js
var require_tracestate_impl = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceStateImpl = undefined;
var tracestate_validators_1 = require_tracestate_validators();
var MAX_TRACE_STATE_ITEMS = 32;
var MAX_TRACE_STATE_LEN = 512;
var LIST_MEMBERS_SEPARATOR = ",";
var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
class TraceStateImpl {
constructor(rawTraceState) {
this._internalState = new Map;
if (rawTraceState)
this._parse(rawTraceState);
}
set(key, value) {
const traceState = this._clone();
if (traceState._internalState.has(key)) {
traceState._internalState.delete(key);
}
traceState._internalState.set(key, value);
return traceState;
}
unset(key) {
const traceState = this._clone();
traceState._internalState.delete(key);
return traceState;
}
get(key) {
return this._internalState.get(key);
}
serialize() {
return this._keys().reduce((agg, key) => {
agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
return agg;
}, []).join(LIST_MEMBERS_SEPARATOR);
}
_parse(rawTraceState) {
if (rawTraceState.length > MAX_TRACE_STATE_LEN)
return;
this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((agg, part) => {
const listMember = part.trim();
const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
if (i !== -1) {
const key = listMember.slice(0, i);
const value = listMember.slice(i + 1, part.length);
if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
agg.set(key, value);
} else {}
}
return agg;
}, new Map);
if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS));
}
}
_keys() {
return Array.from(this._internalState.keys()).reverse();
}
_clone() {
const traceState = new TraceStateImpl;
traceState._internalState = new Map(this._internalState);
return traceState;
}
}
exports.TraceStateImpl = TraceStateImpl;
});
// node_modules/@opentelemetry/api/build/src/trace/internal/utils.js
var require_utils2 = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTraceState = undefined;
var tracestate_impl_1 = require_tracestate_impl();
function createTraceState(rawTraceState) {
return new tracestate_impl_1.TraceStateImpl(rawTraceState);
}
exports.createTraceState = createTraceState;
});
// node_modules/@opentelemetry/api/build/src/context-api.js
var require_context_api = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.context = undefined;
var context_1 = require_context2();
exports.context = context_1.ContextAPI.getInstance();
});
// node_modules/@opentelemetry/api/build/src/diag-api.js
var require_diag_api = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.diag = undefined;
var diag_1 = require_diag();
exports.diag = diag_1.DiagAPI.instance();
});
// node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js
var require_NoopMeterProvider = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = undefined;
var NoopMeter_1 = require_NoopMeter();
class NoopMeterProvider {
getMeter(_name, _version, _options) {
return NoopMeter_1.NOOP_METER;
}
}
exports.NoopMeterProvider = NoopMeterProvider;
exports.NOOP_METER_PROVIDER = new NoopMeterProvider;
});
// node_modules/@opentelemetry/api/build/src/api/metrics.js
var require_metrics = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetricsAPI = undefined;
var NoopMeterProvider_1 = require_NoopMeterProvider();
var global_utils_1 = require_global_utils();
var diag_1 = require_diag();
var API_NAME = "metrics";
class MetricsAPI {
constructor() {}
static getInstance() {
if (!this._instance) {
this._instance = new MetricsAPI;
}
return this._instance;
}
setGlobalMeterProvider(provider) {
return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance());
}
getMeterProvider() {
return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER;
}
getMeter(name14, version, options) {
return this.getMeterProvider().getMeter(name14, version, options);
}
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
}
exports.MetricsAPI = MetricsAPI;
});
// node_modules/@opentelemetry/api/build/src/metrics-api.js
var require_metrics_api = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.metrics = undefined;
var metrics_1 = require_metrics();
exports.metrics = metrics_1.MetricsAPI.getInstance();
});
// node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js
var require_NoopTextMapPropagator = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTextMapPropagator = undefined;
class NoopTextMapPropagator {
inject(_context, _carrier) {}
extract(context, _carrier) {
return context;
}
fields() {
return [];
}
}
exports.NoopTextMapPropagator = NoopTextMapPropagator;
});
// node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js
var require_context_helpers = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = undefined;
var context_1 = require_context2();
var context_2 = require_context();
var BAGGAGE_KEY = (0, context_2.createContextKey)("OpenTelemetry Baggage Key");
function getBaggage(context) {
return context.getValue(BAGGAGE_KEY) || undefined;
}
exports.getBaggage = getBaggage;
function getActiveBaggage() {
return getBaggage(context_1.ContextAPI.getInstance().active());
}
exports.getActiveBaggage = getActiveBaggage;
function setBaggage(context, baggage) {
return context.setValue(BAGGAGE_KEY, baggage);
}
exports.setBaggage = setBaggage;
function deleteBaggage(context) {
return context.deleteValue(BAGGAGE_KEY);
}
exports.deleteBaggage = deleteBaggage;
});
// node_modules/@opentelemetry/api/build/src/api/propagation.js
var require_propagation = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropagationAPI = undefined;
var global_utils_1 = require_global_utils();
var NoopTextMapPropagator_1 = require_NoopTextMapPropagator();
var TextMapPropagator_1 = require_TextMapPropagator();
var context_helpers_1 = require_context_helpers();
var utils_1 = require_utils();
var diag_1 = require_diag();
var API_NAME = "propagation";
var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator;
class PropagationAPI {
constructor() {
this.createBaggage = utils_1.createBaggage;
this.getBaggage = context_helpers_1.getBaggage;
this.getActiveBaggage = context_helpers_1.getActiveBaggage;
this.setBaggage = context_helpers_1.setBaggage;
this.deleteBaggage = context_helpers_1.deleteBaggage;
}
static getInstance() {
if (!this._instance) {
this._instance = new PropagationAPI;
}
return this._instance;
}
setGlobalPropagator(propagator) {
return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance());
}
inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) {
return this._getGlobalPropagator().inject(context, carrier, setter);
}
extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) {
return this._getGlobalPropagator().extract(context, carrier, getter);
}
fields() {
return this._getGlobalPropagator().fields();
}
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
_getGlobalPropagator() {
return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
}
}
exports.PropagationAPI = PropagationAPI;
});
// node_modules/@opentelemetry/api/build/src/propagation-api.js
var require_propagation_api = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.propagation = undefined;
var propagation_1 = require_propagation();
exports.propagation = propagation_1.PropagationAPI.getInstance();
});
// node_modules/@opentelemetry/api/build/src/api/trace.js
var require_trace = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceAPI = undefined;
var global_utils_1 = require_global_utils();
var ProxyTracerProvider_1 = require_ProxyTracerProvider();
var spancontext_utils_1 = require_spancontext_utils();
var context_utils_1 = require_context_utils();
var diag_1 = require_diag();
var API_NAME = "trace";
class TraceAPI {
constructor() {
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider;
this.wrapSpanContext = spancontext_utils_1.wrapSpanContext;
this.isSpanContextValid = spancontext_utils_1.isSpanContextValid;
this.deleteSpan = context_utils_1.deleteSpan;
this.getSpan = context_utils_1.getSpan;
this.getActiveSpan = context_utils_1.getActiveSpan;
this.getSpanContext = context_utils_1.getSpanContext;
this.setSpan = context_utils_1.setSpan;
this.setSpanContext = context_utils_1.setSpanContext;
}
static getInstance() {
if (!this._instance) {
this._instance = new TraceAPI;
}
return this._instance;
}
setGlobalTracerProvider(provider) {
const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance());
if (success) {
this._proxyTracerProvider.setDelegate(provider);
}
return success;
}
getTracerProvider() {
return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider;
}
getTracer(name14, version) {
return this.getTracerProvider().getTracer(name14, version);
}
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider;
}
}
exports.TraceAPI = TraceAPI;
});
// node_modules/@opentelemetry/api/build/src/trace-api.js
var require_trace_api = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = undefined;
var trace_1 = require_trace();
exports.trace = trace_1.TraceAPI.getInstance();
});
// node_modules/@opentelemetry/api/build/src/index.js
var require_src = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = undefined;
var utils_1 = require_utils();
Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function() {
return utils_1.baggageEntryMetadataFromString;
} });
var context_1 = require_context();
Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function() {
return context_1.createContextKey;
} });
Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function() {
return context_1.ROOT_CONTEXT;
} });
var consoleLogger_1 = require_consoleLogger();
Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function() {
return consoleLogger_1.DiagConsoleLogger;
} });
var types_1 = require_types();
Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function() {
return types_1.DiagLogLevel;
} });
var NoopMeter_1 = require_NoopMeter();
Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function() {
return NoopMeter_1.createNoopMeter;
} });
var Metric_1 = require_Metric();
Object.defineProperty(exports, "ValueType", { enumerable: true, get: function() {
return Metric_1.ValueType;
} });
var TextMapPropagator_1 = require_TextMapPropagator();
Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function() {
return TextMapPropagator_1.defaultTextMapGetter;
} });
Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function() {
return TextMapPropagator_1.defaultTextMapSetter;
} });
var ProxyTracer_1 = require_ProxyTracer();
Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function() {
return ProxyTracer_1.ProxyTracer;
} });
var ProxyTracerProvider_1 = require_ProxyTracerProvider();
Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function() {
return ProxyTracerProvider_1.ProxyTracerProvider;
} });
var SamplingResult_1 = require_SamplingResult();
Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function() {
return SamplingResult_1.SamplingDecision;
} });
var span_kind_1 = require_span_kind();
Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function() {
return span_kind_1.SpanKind;
} });
var status_1 = require_status();
Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function() {
return status_1.SpanStatusCode;
} });
var trace_flags_1 = require_trace_flags();
Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function() {
return trace_flags_1.TraceFlags;
} });
var utils_2 = require_utils2();
Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function() {
return utils_2.createTraceState;
} });
var spancontext_utils_1 = require_spancontext_utils();
Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function() {
return spancontext_utils_1.isSpanContextValid;
} });
Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function() {
return spancontext_utils_1.isValidTraceId;
} });
Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function() {
return spancontext_utils_1.isValidSpanId;
} });
var invalid_span_constants_1 = require_invalid_span_constants();
Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function() {
return invalid_span_constants_1.INVALID_SPANID;
} });
Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function() {
return invalid_span_constants_1.INVALID_TRACEID;
} });
Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function() {
return invalid_span_constants_1.INVALID_SPAN_CONTEXT;
} });
var context_api_1 = require_context_api();
Object.defineProperty(exports, "context", { enumerable: true, get: function() {
return context_api_1.context;
} });
var diag_api_1 = require_diag_api();
Object.defineProperty(exports, "diag", { enumerable: true, get: function() {
return diag_api_1.diag;
} });
var metrics_api_1 = require_metrics_api();
Object.defineProperty(exports, "metrics", { enumerable: true, get: function() {
return metrics_api_1.metrics;
} });
var propagation_api_1 = require_propagation_api();
Object.defineProperty(exports, "propagation", { enumerable: true, get: function() {
return propagation_api_1.propagation;
} });
var trace_api_1 = require_trace_api();
Object.defineProperty(exports, "trace", { enumerable: true, get: function() {
return trace_api_1.trace;
} });
exports.default = {
context: context_api_1.context,
diag: diag_api_1.diag,
metrics: metrics_api_1.metrics,
propagation: propagation_api_1.propagation,
trace: trace_api_1.trace
};
});
// node_modules/dotenv/package.json
var require_package = __commonJS((exports, module) => {
module.exports = {
name: "dotenv",
version: "16.5.0",
description: "Loads environment variables from .env file",
main: "lib/main.js",
types: "lib/main.d.ts",
exports: {
".": {
types: "./lib/main.d.ts",
require: "./lib/main.js",
default: "./lib/main.js"
},
"./config": "./config.js",
"./config.js": "./config.js",
"./lib/env-options": "./lib/env-options.js",
"./lib/env-options.js": "./lib/env-options.js",
"./lib/cli-options": "./lib/cli-options.js",
"./lib/cli-options.js": "./lib/cli-options.js",
"./package.json": "./package.json"
},
scripts: {
"dts-check": "tsc --project tests/types/tsconfig.json",
lint: "standard",
pretest: "npm run lint && npm run dts-check",
test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
"test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
prerelease: "npm test",
release: "standard-version"
},
repository: {
type: "git",
url: "git://github.com/motdotla/dotenv.git"
},
homepage: "https://github.com/motdotla/dotenv#readme",
funding: "https://dotenvx.com",
keywords: [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
readmeFilename: "README.md",
license: "BSD-2-Clause",
devDependencies: {
"@types/node": "^18.11.3",
decache: "^4.6.2",
sinon: "^14.0.1",
standard: "^17.0.0",
"standard-version": "^9.5.0",
tap: "^19.2.0",
typescript: "^4.8.4"
},
engines: {
node: ">=12"
},
browser: {
fs: false
}
};
});
// node_modules/dotenv/lib/main.js
var require_main = __commonJS((exports, module) => {
var fs = __require("fs");
var path = __require("path");
var os = __require("os");
var crypto = __require("crypto");
var packageJson = require_package();
var version = packageJson.version;
var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
function parse(src) {
const obj = {};
let lines = src.toString();
lines = lines.replace(/\r\n?/mg, `
`);
let match;
while ((match = LINE.exec(lines)) != null) {
const key = match[1];
let value = match[2] || "";
value = value.trim();
const maybeQuote = value[0];
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
if (maybeQuote === '"') {
value = value.replace(/\\n/g, `
`);
value = value.replace(/\\r/g, "\r");
}
obj[key] = value;
}
return obj;
}
function _parseVault(options) {
const vaultPath = _vaultPath(options);
const result = DotenvModule.configDotenv({ path: vaultPath });
if (!result.parsed) {
const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
err.code = "MISSING_DATA";
throw err;
}
const keys = _dotenvKey(options).split(",");
const length = keys.length;
let decrypted;
for (let i = 0;i < length; i++) {
try {
const key = keys[i].trim();
const attrs = _instructions(result, key);
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
break;
} catch (error) {
if (i + 1 >= length) {
throw error;
}
}
}
return DotenvModule.parse(decrypted);
}
function _warn(message) {
console.log(`[dotenv@${version}][WARN] ${message}`);
}
function _debug(message) {
console.log(`[dotenv@${version}][DEBUG] ${message}`);
}
function _dotenvKey(options) {
if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
return options.DOTENV_KEY;
}
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY;
}
return "";
}
function _instructions(result, dotenvKey) {
let uri;
try {
uri = new URL(dotenvKey);
} catch (error) {
if (error.code === "ERR_INVALID_URL") {
const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
err.code = "INVALID_DOTENV_KEY";
throw err;
}
throw error;
}
const key = uri.password;
if (!key) {
const err = new Error("INVALID_DOTENV_KEY: Missing key part");
err.code = "INVALID_DOTENV_KEY";
throw err;
}
const environment = uri.searchParams.get("environment");
if (!environment) {
const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
err.code = "INVALID_DOTENV_KEY";
throw err;
}
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
const ciphertext = result.parsed[environmentKey];
if (!ciphertext) {
const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
throw err;
}
return { ciphertext, key };
}
function _vaultPath(options) {
let possibleVaultPath = null;
if (options && options.path && options.path.length > 0) {
if (Array.isArray(options.path)) {
for (const filepath of options.path) {
if (fs.existsSync(filepath)) {
possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
}
}
} else {
possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
}
} else {
possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
}
if (fs.existsSync(possibleVaultPath)) {
return possibleVaultPath;
}
return null;
}
function _resolveHome(envPath) {
return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
}
function _configVault(options) {
const debug = Boolean(options && options.debug);
if (debug) {
_debug("Loading env from encrypted .env.vault");
}
const parsed = DotenvModule._parseVault(options);
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
DotenvModule.populate(processEnv, parsed, options);
return { parsed };
}
function configDotenv(options) {
const dotenvPath = path.resolve(process.cwd(), ".env");
let encoding = "utf8";
const debug = Boolean(options && options.debug);
if (options && options.encoding) {
encoding = options.encoding;
} else {
if (debug) {
_debug("No encoding is specified. UTF-8 is used by default");
}
}
let optionPaths = [dotenvPath];
if (options && options.path) {
if (!Array.isArray(options.path)) {
optionPaths = [_resolveHome(options.path)];
} else {
optionPaths = [];
for (const filepath of options.path) {
optionPaths.push(_resolveHome(filepath));
}
}
}
let lastError;
const parsedAll = {};
for (const path2 of optionPaths) {
try {
const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
DotenvModule.populate(parsedAll, parsed, options);
} catch (e) {
if (debug) {
_debug(`Failed to load ${path2} ${e.message}`);
}
lastError = e;
}
}
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
DotenvModule.populate(processEnv, parsedAll, options);
if (lastError) {
return { parsed: parsedAll, error: lastError };
} else {
return { parsed: parsedAll };
}
}
function config(options) {
if (_dotenvKey(options).length === 0) {
return DotenvModule.configDotenv(options);
}
const vaultPath = _vaultPath(options);
if (!vaultPath) {
_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
return DotenvModule.configDotenv(options);
}
return DotenvModule._configVault(options);
}
function decrypt(encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), "hex");
let ciphertext = Buffer.from(encrypted, "base64");
const nonce = ciphertext.subarray(0, 12);
const authTag = ciphertext.subarray(-16);
ciphertext = ciphertext.subarray(12, -16);
try {
const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
aesgcm.setAuthTag(authTag);
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
} catch (error) {
const isRange = error instanceof RangeError;
const invalidKeyLength = error.message === "Invalid key length";
const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
if (isRange || invalidKeyLength) {
const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
err.code = "INVALID_DOTENV_KEY";
throw err;
} else if (decryptionFailed) {
const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
err.code = "DECRYPTION_FAILED";
throw err;
} else {
throw error;
}
}
}
function populate(processEnv, parsed, options = {}) {
const debug = Boolean(options && options.debug);
const override = Boolean(options && options.override);
if (typeof parsed !== "object") {
const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
err.code = "OBJECT_REQUIRED";
throw err;
}
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key];
}
if (debug) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`);
} else {
_debug(`"${key}" is already defined and was NOT overwritten`);
}
}
} else {
processEnv[key] = parsed[key];
}
}
}
var DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse,
populate
};
exports.configDotenv = DotenvModule.configDotenv;
exports._configVault = DotenvModule._configVault;
exports._parseVault = DotenvModule._parseVault;
exports.config = DotenvModule.config;
exports.decrypt = DotenvModule.decrypt;
exports.parse = DotenvModule.parse;
exports.populate = DotenvModule.populate;
module.exports = DotenvModule;
});
// node_modules/dotenv/lib/env-options.js
var require_env_options = __commonJS((exports, module) => {
var options = {};
if (process.env.DOTENV_CONFIG_ENCODING != null) {
options.encoding = process.env.DOTENV_CONFIG_ENCODING;
}
if (process.env.DOTENV_CONFIG_PATH != null) {
options.path = process.env.DOTENV_CONFIG_PATH;
}
if (process.env.DOTENV_CONFIG_DEBUG != null) {
options.debug = process.env.DOTENV_CONFIG_DEBUG;
}
if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
options.override = process.env.DOTENV_CONFIG_OVERRIDE;
}
if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
}
module.exports = options;
});
// node_modules/dotenv/lib/cli-options.js
var require_cli_options = __commonJS((exports, module) => {
var re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/;
module.exports = function optionMatcher(args) {
return args.reduce(function(acc, cur) {
const matches = cur.match(re);
if (matches) {
acc[matches[1]] = matches[2];
}
return acc;
}, {});
};
});
// node_modules/dotenv/config.js
var require_config = __commonJS(() => {
(function() {
require_main().config(Object.assign({}, require_env_options(), require_cli_options()(process.argv)));
})();
});
// node_modules/zod/dist/esm/v3/external.js
var exports_external = {};
__export(exports_external, {
void: () => voidType,
util: () => util,
unknown: () => unknownType,
union: () => unionType,
undefined: () => undefinedType,
tuple: () => tupleType,
transformer: () => effectsType,
symbol: () => symbolType,
string: () => stringType,
strictObject: () => strictObjectType,
setErrorMap: () => setErrorMap,
set: () => setType,
record: () => recordType,
quotelessJson: () => quotelessJson,
promise: () => promiseType,
preprocess: () => preprocessType,
pipeline: () => pipelineType,
ostring: () => ostring,
optional: () => optionalType,
onumber: () => onumber,
oboolean: () => oboolean,
objectUtil: () => objectUtil,
object: () => objectType,
number: () => numberType,
nullable: () => nullableType,
null: () => nullType,
never: () => neverType,
nativeEnum: () => nativeEnumType,
nan: () => nanType,
map: () => mapType,
makeIssue: () => makeIssue,
literal: () => literalType,
lazy: () => lazyType,
late: () => late,
isValid: () => isValid,
isDirty: () => isDirty,
isAsync: () => isAsync,
isAborted: () => isAborted,
intersection: () => intersectionType,
instanceof: () => instanceOfType,
getParsedType: () => getParsedType,
getErrorMap: () => getErrorMap,
function: () => functionType,
enum: () => enumType,
effect: () => effectsType,
discriminatedUnion: () => discriminatedUnionType,
defaultErrorMap: () => en_default,
datetimeRegex: () => datetimeRegex,
date: () => dateType,
custom: () => custom,
coerce: () => coerce,
boolean: () => booleanType,
bigint: () => bigIntType,
array: () => arrayType,
any: () => anyType,
addIssueToContext: () => addIssueToContext,
ZodVoid: () => ZodVoid,
ZodUnknown: () => ZodUnknown,
ZodUnion: () => ZodUnion,
ZodUndefined: () => ZodUndefined,
ZodType: () => ZodType,
ZodTuple: () => ZodTuple,
ZodTransformer: () => ZodEffects,
ZodSymbol: () => ZodSymbol,
ZodString: () => ZodString,
ZodSet: () => ZodSet,
ZodSchema: () => ZodType,
ZodRecord: () => ZodRecord,
ZodReadonly: () => ZodReadonly,
ZodPromise: () => ZodPromise,
ZodPipeline: () => ZodPipeline,
ZodParsedType: () => ZodParsedType,
ZodOptional: () => ZodOptional,
ZodObject: () => ZodObject,
ZodNumber: () => ZodNumber,
ZodNullable: () => ZodNullable,
ZodNull: () => ZodNull,
ZodNever: () => ZodNever,
ZodNativeEnum: () => ZodNativeEnum,
ZodNaN: () => ZodNaN,
ZodMap: () => ZodMap,
ZodLiteral: () => ZodLiteral,
ZodLazy: () => ZodLazy,
ZodIssueCode: () => ZodIssueCode,
ZodIntersection: () => ZodIntersection,
ZodFunction: () => ZodFunction,
ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
ZodError: () => ZodError,
ZodEnum: () => ZodEnum,
ZodEffects: () => ZodEffects,
ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
ZodDefault: () => ZodDefault,
ZodDate: () => ZodDate,
ZodCatch: () => ZodCatch,
ZodBranded: () => ZodBranded,
ZodBoolean: () => ZodBoolean,
ZodBigInt: () => ZodBigInt,
ZodArray: () => ZodArray,
ZodAny: () => ZodAny,
Schema: () => ZodType,
ParseStatus: () => ParseStatus,
OK: () => OK,
NEVER: () => NEVER,
INVALID: () => INVALID,
EMPTY_PATH: () => EMPTY_PATH,
DIRTY: () => DIRTY,
BRAND: () => BRAND
});
// node_modules/zod/dist/esm/v3/helpers/util.js
var util;
(function(util2) {
util2.assertEqual = (_) => {};
function assertIs(_arg) {}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error;
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
};
};
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
var getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
// node_modules/zod/dist/esm/v3/ZodError.js
var ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
}
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
// node_modules/zod/dist/esm/v3/locales/en.js
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var en_default = errorMap;
// node_modules/zod/dist/esm/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
// node_modules/zod/dist/esm/v3/helpers/parseUtil.js
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== undefined) {
return {
...issueData,
path: fullPath,
message: issueData.message
};
}
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === en_default ? undefined : en_default
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
}
var INVALID = Object.freeze({
status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
// node_modules/zod/dist/esm/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
// node_modules/zod/dist/esm/v3/types.js
class ParseInputLazyPath {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (Array.isArray(this._key)) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
}
var handleResult = (ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message ?? ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: message ?? required_error ?? ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: message ?? invalid_type_error ?? ctx.defaultError };
};
return { errorMap: customMap, description };
}
class ZodType {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus,
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
"~validate"(data) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) {
try {
const result = this._parseSync({ data, path: [], parent: ctx });
return isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
};
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) {
this["~standard"].async = true;
}
ctx.common = {
issues: [],
async: true
};
}
}
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
});
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(undefined).success;
}
isNullable() {
return this.safeParse(null).success;
}
}
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[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}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?: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])$/;
var ipv4CidrRegex = /^(?:(?: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])$/;
var ipv6Regex = /^(([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]))$/;
var ipv6CidrRegex = /^(([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])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) {
secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
}
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return false;
try {
const [header] = jwt.split(".");
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null)
return false;
if ("typ" in decoded && decoded?.typ !== "JWT")
return false;
if (!decoded.alg)
return false;
if (alg && decoded.alg !== alg)
return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
return true;
}
return false;
}
class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
});
return INVALID;
}
const status = new ParseStatus;
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check) {
return new ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
nanoid(message) {
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
base64(message) {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
cidr(options) {
return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
}
datetime(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck({
kind: "datetime",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options
});
}
return this._addCheck({
kind: "time",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
...errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options?.position,
...errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodString.create = (params) => {
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / 10 ** decCount;
}
class ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = undefined;
const status = new ParseStatus;
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
}
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
class ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
return this._getInvalidInput(input);
}
let ctx = undefined;
const status = new ParseStatus;
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, check]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodBigInt.create = (params) => {
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
class ZodBoolean extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status = new ParseStatus;
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
}
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
class ZodSymbol extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
class ZodUndefined extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
class ZodNull extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
class ZodAny extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
class ZodUnknown extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
class ZodNever extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
}
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
class ZodVoid extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : undefined,
maximum: tooBig ? def.exactLength.value : undefined,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) }
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) }
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) }
});
}
nonempty(message) {
return this.min(1, message);
}
}
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
} else {
return schema;
}
}
class ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
this._cached = { shape, keys };
return this._cached;
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {} else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) {
return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...message !== undefined ? {
errorMap: (issue, ctx) => {
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: errorUtil.errToObj(message).message ?? defaultError
};
return {
message: defaultError
};
}
} : {}
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
merge(merging) {
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
setKey(key, schema) {
return this.augment({ [key]: schema });
}
catchall(index) {
return new ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) {
if (!mask[key]) {
shape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => shape
});
}
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
}
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
class ZodUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
} else {
let dirty = undefined;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
}
ZodUnion.create = (types, params) => {
return new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
var getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return util.objectValues(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [undefined];
} else if (type instanceof ZodNull) {
return [null];
} else if (type instanceof ZodOptional) {
return [undefined, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodNullable) {
return [null, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodBranded) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodReadonly) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodCatch) {
return getDiscriminator(type._def.innerType);
} else {
return [];
}
};
class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
static create(discriminator, options, params) {
const optionsMap = new Map;
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
}
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0;index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
class ZodIntersection extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
}
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema)
return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest
});
}
}
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
}
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
}
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
};
});
if (ctx.common.async) {
const finalMap = new Map;
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
const finalMap = new Map;
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
}
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = new Set;
for (const element of elements2) {
if (element.status === "aborted")
return INVALID;
if (element.status === "dirty")
status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
}
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
class ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
}
class ZodLazy extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
}
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
class ZodLiteral extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
}
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
class ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(this._def.values);
}
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
}
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(util.getValidEnumValues(this._def.values));
}
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
}
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
class ZodPromise extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
}
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
class ZodEffects extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
const result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
});
} else {
if (status.value === "aborted")
return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid(base))
return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
}
}
util.assertNever(effect);
}
}
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
class ZodOptional extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(undefined);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
class ZodNullable extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
class ZodDefault extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
}
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
class ZodCatch extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
}
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
class ZodNaN extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
}
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
var BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}
class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
}
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
}
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
function cleanParams(params, data) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const p2 = typeof p === "string" ? { message: p } : p;
return p2;
}
function custom(check, _params = {}, fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
const r = check(data);
if (r instanceof Promise) {
return r.then((r2) => {
if (!r2) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
});
}
if (!r) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
return;
});
return ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
string: (arg) => ZodString.create({ ...arg, coerce: true }),
number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
boolean: (arg) => ZodBoolean.create({
...arg,
coerce: true
}),
bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
date: (arg) => ZodDate.create({ ...arg, coerce: true })
};
var NEVER = INVALID;
// node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
var LATEST_PROTOCOL_VERSION = "2025-03-26";
var SUPPORTED_PROTOCOL_VERSIONS = [
LATEST_PROTOCOL_VERSION,
"2024-11-05",
"2024-10-07"
];
var JSONRPC_VERSION = "2.0";
var ProgressTokenSchema = exports_external.union([exports_external.string(), exports_external.number().int()]);
var CursorSchema = exports_external.string();
var RequestMetaSchema = exports_external.object({
progressToken: exports_external.optional(ProgressTokenSchema)
}).passthrough();
var BaseRequestParamsSchema = exports_external.object({
_meta: exports_external.optional(RequestMetaSchema)
}).passthrough();
var RequestSchema = exports_external.object({
method: exports_external.string(),
params: exports_external.optional(BaseRequestParamsSchema)
});
var BaseNotificationParamsSchema = exports_external.object({
_meta: exports_external.optional(exports_external.object({}).passthrough())
}).passthrough();
var NotificationSchema = exports_external.object({
method: exports_external.string(),
params: exports_external.optional(BaseNotificationParamsSchema)
});
var ResultSchema = exports_external.object({
_meta: exports_external.optional(exports_external.object({}).passthrough())
}).passthrough();
var RequestIdSchema = exports_external.union([exports_external.string(), exports_external.number().int()]);
var JSONRPCRequestSchema = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION),
id: RequestIdSchema
}).merge(RequestSchema).strict();
var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
var JSONRPCNotificationSchema = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION)
}).merge(NotificationSchema).strict();
var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
var JSONRPCResponseSchema = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION),
id: RequestIdSchema,
result: ResultSchema
}).strict();
var isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success;
var ErrorCode;
(function(ErrorCode2) {
ErrorCode2[ErrorCode2["ConnectionClosed"] = -32000] = "ConnectionClosed";
ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";
ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
})(ErrorCode || (ErrorCode = {}));
var JSONRPCErrorSchema = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION),
id: RequestIdSchema,
error: exports_external.object({
code: exports_external.number().int(),
message: exports_external.string(),
data: exports_external.optional(exports_external.unknown())
})
}).strict();
var isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success;
var JSONRPCMessageSchema = exports_external.union([
JSONRPCRequestSchema,
JSONRPCNotificationSchema,
JSONRPCResponseSchema,
JSONRPCErrorSchema
]);
var EmptyResultSchema = ResultSchema.strict();
var CancelledNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/cancelled"),
params: BaseNotificationParamsSchema.extend({
requestId: RequestIdSchema,
reason: exports_external.string().optional()
})
});
var ImplementationSchema = exports_external.object({
name: exports_external.string(),
version: exports_external.string()
}).passthrough();
var ClientCapabilitiesSchema = exports_external.object({
experimental: exports_external.optional(exports_external.object({}).passthrough()),
sampling: exports_external.optional(exports_external.object({}).passthrough()),
roots: exports_external.optional(exports_external.object({
listChanged: exports_external.optional(exports_external.boolean())
}).passthrough())
}).passthrough();
var InitializeRequestSchema = RequestSchema.extend({
method: exports_external.literal("initialize"),
params: BaseRequestParamsSchema.extend({
protocolVersion: exports_external.string(),
capabilities: ClientCapabilitiesSchema,
clientInfo: ImplementationSchema
})
});
var ServerCapabilitiesSchema = exports_external.object({
experimental: exports_external.optional(exports_external.object({}).passthrough()),
logging: exports_external.optional(exports_external.object({}).passthrough()),
completions: exports_external.optional(exports_external.object({}).passthrough()),
prompts: exports_external.optional(exports_external.object({
listChanged: exports_external.optional(exports_external.boolean())
}).passthrough()),
resources: exports_external.optional(exports_external.object({
subscribe: exports_external.optional(exports_external.boolean()),
listChanged: exports_external.optional(exports_external.boolean())
}).passthrough()),
tools: exports_external.optional(exports_external.object({
listChanged: exports_external.optional(exports_external.boolean())
}).passthrough())
}).passthrough();
var InitializeResultSchema = ResultSchema.extend({
protocolVersion: exports_external.string(),
capabilities: ServerCapabilitiesSchema,
serverInfo: ImplementationSchema,
instructions: exports_external.optional(exports_external.string())
});
var InitializedNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/initialized")
});
var PingRequestSchema = RequestSchema.extend({
method: exports_external.literal("ping")
});
var ProgressSchema = exports_external.object({
progress: exports_external.number(),
total: exports_external.optional(exports_external.number()),
message: exports_external.optional(exports_external.string())
}).passthrough();
var ProgressNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/progress"),
params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
progressToken: ProgressTokenSchema
})
});
var PaginatedRequestSchema = RequestSchema.extend({
params: BaseRequestParamsSchema.extend({
cursor: exports_external.optional(CursorSchema)
}).optional()
});
var PaginatedResultSchema = ResultSchema.extend({
nextCursor: exports_external.optional(CursorSchema)
});
var ResourceContentsSchema = exports_external.object({
uri: exports_external.string(),
mimeType: exports_external.optional(exports_external.string())
}).passthrough();
var TextResourceContentsSchema = ResourceContentsSchema.extend({
text: exports_external.string()
});
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
blob: exports_external.string().base64()
});
var ResourceSchema = exports_external.object({
uri: exports_external.string(),
name: exports_external.string(),
description: exports_external.optional(exports_external.string()),
mimeType: exports_external.optional(exports_external.string())
}).passthrough();
var ResourceTemplateSchema = exports_external.object({
uriTemplate: exports_external.string(),
name: exports_external.string(),
description: exports_external.optional(exports_external.string()),
mimeType: exports_external.optional(exports_external.string())
}).passthrough();
var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
method: exports_external.literal("resources/list")
});
var ListResourcesResultSchema = PaginatedResultSchema.extend({
resources: exports_external.array(ResourceSchema)
});
var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
method: exports_external.literal("resources/templates/list")
});
var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
resourceTemplates: exports_external.array(ResourceTemplateSchema)
});
var ReadResourceRequestSchema = RequestSchema.extend({
method: exports_external.literal("resources/read"),
params: BaseRequestParamsSchema.extend({
uri: exports_external.string()
})
});
var ReadResourceResultSchema = ResultSchema.extend({
contents: exports_external.array(exports_external.union([TextResourceContentsSchema, BlobResourceContentsSchema]))
});
var ResourceListChangedNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/resources/list_changed")
});
var SubscribeRequestSchema = RequestSchema.extend({
method: exports_external.literal("resources/subscribe"),
params: BaseRequestParamsSchema.extend({
uri: exports_external.string()
})
});
var UnsubscribeRequestSchema = RequestSchema.extend({
method: exports_external.literal("resources/unsubscribe"),
params: BaseRequestParamsSchema.extend({
uri: exports_external.string()
})
});
var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/resources/updated"),
params: BaseNotificationParamsSchema.extend({
uri: exports_external.string()
})
});
var PromptArgumentSchema = exports_external.object({
name: exports_external.string(),
description: exports_external.optional(exports_external.string()),
required: exports_external.optional(exports_external.boolean())
}).passthrough();
var PromptSchema = exports_external.object({
name: exports_external.string(),
description: exports_external.optional(exports_external.string()),
arguments: exports_external.optional(exports_external.array(PromptArgumentSchema))
}).passthrough();
var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
method: exports_external.literal("prompts/list")
});
var ListPromptsResultSchema = PaginatedResultSchema.extend({
prompts: exports_external.array(PromptSchema)
});
var GetPromptRequestSchema = RequestSchema.extend({
method: exports_external.literal("prompts/get"),
params: BaseRequestParamsSchema.extend({
name: exports_external.string(),
arguments: exports_external.optional(exports_external.record(exports_external.string()))
})
});
var TextContentSchema = exports_external.object({
type: exports_external.literal("text"),
text: exports_external.string()
}).passthrough();
var ImageContentSchema = exports_external.object({
type: exports_external.literal("image"),
data: exports_external.string().base64(),
mimeType: exports_external.string()
}).passthrough();
var AudioContentSchema = exports_external.object({
type: exports_external.literal("audio"),
data: exports_external.string().base64(),
mimeType: exports_external.string()
}).passthrough();
var EmbeddedResourceSchema = exports_external.object({
type: exports_external.literal("resource"),
resource: exports_external.union([TextResourceContentsSchema, BlobResourceContentsSchema])
}).passthrough();
var PromptMessageSchema = exports_external.object({
role: exports_external.enum(["user", "assistant"]),
content: exports_external.union([
TextContentSchema,
ImageContentSchema,
AudioContentSchema,
EmbeddedResourceSchema
])
}).passthrough();
var GetPromptResultSchema = ResultSchema.extend({
description: exports_external.optional(exports_external.string()),
messages: exports_external.array(PromptMessageSchema)
});
var PromptListChangedNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/prompts/list_changed")
});
var ToolAnnotationsSchema = exports_external.object({
title: exports_external.optional(exports_external.string()),
readOnlyHint: exports_external.optional(exports_external.boolean()),
destructiveHint: exports_external.optional(exports_external.boolean()),
idempotentHint: exports_external.optional(exports_external.boolean()),
openWorldHint: exports_external.optional(exports_external.boolean())
}).passthrough();
var ToolSchema = exports_external.object({
name: exports_external.string(),
description: exports_external.optional(exports_external.string()),
inputSchema: exports_external.object({
type: exports_external.literal("object"),
properties: exports_external.optional(exports_external.object({}).passthrough()),
required: exports_external.optional(exports_external.array(exports_external.string()))
}).passthrough(),
outputSchema: exports_external.optional(exports_external.object({
type: exports_external.literal("object"),
properties: exports_external.optional(exports_external.object({}).passthrough()),
required: exports_external.optional(exports_external.array(exports_external.string()))
}).passthrough()),
annotations: exports_external.optional(ToolAnnotationsSchema)
}).passthrough();
var ListToolsRequestSchema = PaginatedRequestSchema.extend({
method: exports_external.literal("tools/list")
});
var ListToolsResultSchema = PaginatedResultSchema.extend({
tools: exports_external.array(ToolSchema)
});
var CallToolResultSchema = ResultSchema.extend({
content: exports_external.array(exports_external.union([
TextContentSchema,
ImageContentSchema,
AudioContentSchema,
EmbeddedResourceSchema
])).default([]),
structuredContent: exports_external.object({}).passthrough().optional(),
isError: exports_external.optional(exports_external.boolean())
});
var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
toolResult: exports_external.unknown()
}));
var CallToolRequestSchema = RequestSchema.extend({
method: exports_external.literal("tools/call"),
params: BaseRequestParamsSchema.extend({
name: exports_external.string(),
arguments: exports_external.optional(exports_external.record(exports_external.unknown()))
})
});
var ToolListChangedNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/tools/list_changed")
});
var LoggingLevelSchema = exports_external.enum([
"debug",
"info",
"notice",
"warning",
"error",
"critical",
"alert",
"emergency"
]);
var SetLevelRequestSchema = RequestSchema.extend({
method: exports_external.literal("logging/setLevel"),
params: BaseRequestParamsSchema.extend({
level: LoggingLevelSchema
})
});
var LoggingMessageNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/message"),
params: BaseNotificationParamsSchema.extend({
level: LoggingLevelSchema,
logger: exports_external.optional(exports_external.string()),
data: exports_external.unknown()
})
});
var ModelHintSchema = exports_external.object({
name: exports_external.string().optional()
}).passthrough();
var ModelPreferencesSchema = exports_external.object({
hints: exports_external.optional(exports_external.array(ModelHintSchema)),
costPriority: exports_external.optional(exports_external.number().min(0).max(1)),
speedPriority: exports_external.optional(exports_external.number().min(0).max(1)),
intelligencePriority: exports_external.optional(exports_external.number().min(0).max(1))
}).passthrough();
var SamplingMessageSchema = exports_external.object({
role: exports_external.enum(["user", "assistant"]),
content: exports_external.union([TextContentSchema, ImageContentSchema, AudioContentSchema])
}).passthrough();
var CreateMessageRequestSchema = RequestSchema.extend({
method: exports_external.literal("sampling/createMessage"),
params: BaseRequestParamsSchema.extend({
messages: exports_external.array(SamplingMessageSchema),
systemPrompt: exports_external.optional(exports_external.string()),
includeContext: exports_external.optional(exports_external.enum(["none", "thisServer", "allServers"])),
temperature: exports_external.optional(exports_external.number()),
maxTokens: exports_external.number().int(),
stopSequences: exports_external.optional(exports_external.array(exports_external.string())),
metadata: exports_external.optional(exports_external.object({}).passthrough()),
modelPreferences: exports_external.optional(ModelPreferencesSchema)
})
});
var CreateMessageResultSchema = ResultSchema.extend({
model: exports_external.string(),
stopReason: exports_external.optional(exports_external.enum(["endTurn", "stopSequence", "maxTokens"]).or(exports_external.string())),
role: exports_external.enum(["user", "assistant"]),
content: exports_external.discriminatedUnion("type", [
TextContentSchema,
ImageContentSchema,
AudioContentSchema
])
});
var ResourceReferenceSchema = exports_external.object({
type: exports_external.literal("ref/resource"),
uri: exports_external.string()
}).passthrough();
var PromptReferenceSchema = exports_external.object({
type: exports_external.literal("ref/prompt"),
name: exports_external.string()
}).passthrough();
var CompleteRequestSchema = RequestSchema.extend({
method: exports_external.literal("completion/complete"),
params: BaseRequestParamsSchema.extend({
ref: exports_external.union([PromptReferenceSchema, ResourceReferenceSchema]),
argument: exports_external.object({
name: exports_external.string(),
value: exports_external.string()
}).passthrough()
})
});
var CompleteResultSchema = ResultSchema.extend({
completion: exports_external.object({
values: exports_external.array(exports_external.string()).max(100),
total: exports_external.optional(exports_external.number().int()),
hasMore: exports_external.optional(exports_external.boolean())
}).passthrough()
});
var RootSchema = exports_external.object({
uri: exports_external.string().startsWith("file://"),
name: exports_external.optional(exports_external.string())
}).passthrough();
var ListRootsRequestSchema = RequestSchema.extend({
method: exports_external.literal("roots/list")
});
var ListRootsResultSchema = ResultSchema.extend({
roots: exports_external.array(RootSchema)
});
var RootsListChangedNotificationSchema = NotificationSchema.extend({
method: exports_external.literal("notifications/roots/list_changed")
});
var ClientRequestSchema = exports_external.union([
PingRequestSchema,
InitializeRequestSchema,
CompleteRequestSchema,
SetLevelRequestSchema,
GetPromptRequestSchema,
ListPromptsRequestSchema,
ListResourcesRequestSchema,
ListResourceTemplatesRequestSchema,
ReadResourceRequestSchema,
SubscribeRequestSchema,
UnsubscribeRequestSchema,
CallToolRequestSchema,
ListToolsRequestSchema
]);
var ClientNotificationSchema = exports_external.union([
CancelledNotificationSchema,
ProgressNotificationSchema,
InitializedNotificationSchema,
RootsListChangedNotificationSchema
]);
var ClientResultSchema = exports_external.union([
EmptyResultSchema,
CreateMessageResultSchema,
ListRootsResultSchema
]);
var ServerRequestSchema = exports_external.union([
PingRequestSchema,
CreateMessageRequestSchema,
ListRootsRequestSchema
]);
var ServerNotificationSchema = exports_external.union([
CancelledNotificationSchema,
ProgressNotificationSchema,
LoggingMessageNotificationSchema,
ResourceUpdatedNotificationSchema,
ResourceListChangedNotificationSchema,
ToolListChangedNotificationSchema,
PromptListChangedNotificationSchema
]);
var ServerResultSchema = exports_external.union([
EmptyResultSchema,
InitializeResultSchema,
CompleteResultSchema,
GetPromptResultSchema,
ListPromptsResultSchema,
ListResourcesResultSchema,
ListResourceTemplatesResultSchema,
ReadResourceResultSchema,
CallToolResultSchema,
ListToolsResultSchema
]);
class McpError extends Error {
constructor(code, message, data) {
super(`MCP error ${code}: ${message}`);
this.code = code;
this.data = data;
this.name = "McpError";
}
}
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
var DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;
class Protocol {
constructor(_options) {
this._options = _options;
this._requestMessageId = 0;
this._requestHandlers = new Map;
this._requestHandlerAbortControllers = new Map;
this._notificationHandlers = new Map;
this._responseHandlers = new Map;
this._progressHandlers = new Map;
this._timeoutInfo = new Map;
this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
controller === null || controller === undefined || controller.abort(notification.params.reason);
});
this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
this._onprogress(notification);
});
this.setRequestHandler(PingRequestSchema, (_request) => ({}));
}
_setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
this._timeoutInfo.set(messageId, {
timeoutId: setTimeout(onTimeout, timeout),
startTime: Date.now(),
timeout,
maxTotalTimeout,
resetTimeoutOnProgress,
onTimeout
});
}
_resetTimeout(messageId) {
const info = this._timeoutInfo.get(messageId);
if (!info)
return false;
const totalElapsed = Date.now() - info.startTime;
if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
this._timeoutInfo.delete(messageId);
throw new McpError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { maxTotalTimeout: info.maxTotalTimeout, totalElapsed });
}
clearTimeout(info.timeoutId);
info.timeoutId = setTimeout(info.onTimeout, info.timeout);
return true;
}
_cleanupTimeout(messageId) {
const info = this._timeoutInfo.get(messageId);
if (info) {
clearTimeout(info.timeoutId);
this._timeoutInfo.delete(messageId);
}
}
async connect(transport) {
this._transport = transport;
this._transport.onclose = () => {
this._onclose();
};
this._transport.onerror = (error) => {
this._onerror(error);
};
this._transport.onmessage = (message, extra) => {
if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
this._onresponse(message);
} else if (isJSONRPCRequest(message)) {
this._onrequest(message, extra);
} else if (isJSONRPCNotification(message)) {
this._onnotification(message);
} else {
this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
}
};
await this._transport.start();
}
_onclose() {
var _a;
const responseHandlers = this._responseHandlers;
this._responseHandlers = new Map;
this._progressHandlers.clear();
this._transport = undefined;
(_a = this.onclose) === null || _a === undefined || _a.call(this);
const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed");
for (const handler of responseHandlers.values()) {
handler(error);
}
}
_onerror(error) {
var _a;
(_a = this.onerror) === null || _a === undefined || _a.call(this, error);
}
_onnotification(notification) {
var _a;
const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== undefined ? _a : this.fallbackNotificationHandler;
if (handler === undefined) {
return;
}
Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
}
_onrequest(request, extra) {
var _a, _b, _c, _d;
const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== undefined ? _a : this.fallbackRequestHandler;
if (handler === undefined) {
(_b = this._transport) === null || _b === undefined || _b.send({
jsonrpc: "2.0",
id: request.id,
error: {
code: ErrorCode.MethodNotFound,
message: "Method not found"
}
}).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
return;
}
const abortController = new AbortController;
this._requestHandlerAbortControllers.set(request.id, abortController);
const fullExtra = {
signal: abortController.signal,
sessionId: (_c = this._transport) === null || _c === undefined ? undefined : _c.sessionId,
_meta: (_d = request.params) === null || _d === undefined ? undefined : _d._meta,
sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }),
sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }),
authInfo: extra === null || extra === undefined ? undefined : extra.authInfo,
requestId: request.id
};
Promise.resolve().then(() => handler(request, fullExtra)).then((result) => {
var _a2;
if (abortController.signal.aborted) {
return;
}
return (_a2 = this._transport) === null || _a2 === undefined ? undefined : _a2.send({
result,
jsonrpc: "2.0",
id: request.id
});
}, (error) => {
var _a2, _b2;
if (abortController.signal.aborted) {
return;
}
return (_a2 = this._transport) === null || _a2 === undefined ? undefined : _a2.send({
jsonrpc: "2.0",
id: request.id,
error: {
code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
message: (_b2 = error.message) !== null && _b2 !== undefined ? _b2 : "Internal error"
}
});
}).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
this._requestHandlerAbortControllers.delete(request.id);
});
}
_onprogress(notification) {
const { progressToken, ...params } = notification.params;
const messageId = Number(progressToken);
const handler = this._progressHandlers.get(messageId);
if (!handler) {
this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
return;
}
const responseHandler = this._responseHandlers.get(messageId);
const timeoutInfo = this._timeoutInfo.get(messageId);
if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
try {
this._resetTimeout(messageId);
} catch (error) {
responseHandler(error);
return;
}
}
handler(params);
}
_onresponse(response) {
const messageId = Number(response.id);
const handler = this._responseHandlers.get(messageId);
if (handler === undefined) {
this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
return;
}
this._responseHandlers.delete(messageId);
this._progressHandlers.delete(messageId);
this._cleanupTimeout(messageId);
if (isJSONRPCResponse(response)) {
handler(response);
} else {
const error = new McpError(response.error.code, response.error.message, response.error.data);
handler(error);
}
}
get transport() {
return this._transport;
}
async close() {
var _a;
await ((_a = this._transport) === null || _a === undefined ? undefined : _a.close());
}
request(request, resultSchema, options) {
const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== undefined ? options : {};
return new Promise((resolve, reject) => {
var _a, _b, _c, _d, _e, _f;
if (!this._transport) {
reject(new Error("Not connected"));
return;
}
if (((_a = this._options) === null || _a === undefined ? undefined : _a.enforceStrictCapabilities) === true) {
this.assertCapabilityForMethod(request.method);
}
(_b = options === null || options === undefined ? undefined : options.signal) === null || _b === undefined || _b.throwIfAborted();
const messageId = this._requestMessageId++;
const jsonrpcRequest = {
...request,
jsonrpc: "2.0",
id: messageId
};
if (options === null || options === undefined ? undefined : options.onprogress) {
this._progressHandlers.set(messageId, options.onprogress);
jsonrpcRequest.params = {
...request.params,
_meta: {
...((_c = request.params) === null || _c === undefined ? undefined : _c._meta) || {},
progressToken: messageId
}
};
}
const cancel = (reason) => {
var _a2;
this._responseHandlers.delete(messageId);
this._progressHandlers.delete(messageId);
this._cleanupTimeout(messageId);
(_a2 = this._transport) === null || _a2 === undefined || _a2.send({
jsonrpc: "2.0",
method: "notifications/cancelled",
params: {
requestId: messageId,
reason: String(reason)
}
}, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
reject(reason);
};
this._responseHandlers.set(messageId, (response) => {
var _a2;
if ((_a2 = options === null || options === undefined ? undefined : options.signal) === null || _a2 === undefined ? undefined : _a2.aborted) {
return;
}
if (response instanceof Error) {
return reject(response);
}
try {
const result = resultSchema.parse(response.result);
resolve(result);
} catch (error) {
reject(error);
}
});
(_d = options === null || options === undefined ? undefined : options.signal) === null || _d === undefined || _d.addEventListener("abort", () => {
var _a2;
cancel((_a2 = options === null || options === undefined ? undefined : options.signal) === null || _a2 === undefined ? undefined : _a2.reason);
});
const timeout = (_e = options === null || options === undefined ? undefined : options.timeout) !== null && _e !== undefined ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
this._setupTimeout(messageId, timeout, options === null || options === undefined ? undefined : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === undefined ? undefined : options.resetTimeoutOnProgress) !== null && _f !== undefined ? _f : false);
this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
this._cleanupTimeout(messageId);
reject(error);
});
});
}
async notification(notification, options) {
if (!this._transport) {
throw new Error("Not connected");
}
this.assertNotificationCapability(notification.method);
const jsonrpcNotification = {
...notification,
jsonrpc: "2.0"
};
await this._transport.send(jsonrpcNotification, options);
}
setRequestHandler(requestSchema, handler) {
const method = requestSchema.shape.method.value;
this.assertRequestHandlerCapability(method);
this._requestHandlers.set(method, (request, extra) => {
return Promise.resolve(handler(requestSchema.parse(request), extra));
});
}
removeRequestHandler(method) {
this._requestHandlers.delete(method);
}
assertCanSetRequestHandler(method) {
if (this._requestHandlers.has(method)) {
throw new Error(`A request handler for ${method} already exists, which would be overridden`);
}
}
setNotificationHandler(notificationSchema, handler) {
this._notificationHandlers.set(notificationSchema.shape.method.value, (notification) => Promise.resolve(handler(notificationSchema.parse(notification))));
}
removeNotificationHandler(method) {
this._notificationHandlers.delete(method);
}
}
function mergeCapabilities(base, additional) {
return Object.entries(additional).reduce((acc, [key, value]) => {
if (value && typeof value === "object") {
acc[key] = acc[key] ? { ...acc[key], ...value } : value;
} else {
acc[key] = value;
}
return acc;
}, { ...base });
}
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
class Server extends Protocol {
constructor(_serverInfo, options) {
var _a;
super(options);
this._serverInfo = _serverInfo;
this._capabilities = (_a = options === null || options === undefined ? undefined : options.capabilities) !== null && _a !== undefined ? _a : {};
this._instructions = options === null || options === undefined ? undefined : options.instructions;
this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
this.setNotificationHandler(InitializedNotificationSchema, () => {
var _a2;
return (_a2 = this.oninitialized) === null || _a2 === undefined ? undefined : _a2.call(this);
});
}
registerCapabilities(capabilities) {
if (this.transport) {
throw new Error("Cannot register capabilities after connecting to transport");
}
this._capabilities = mergeCapabilities(this._capabilities, capabilities);
}
assertCapabilityForMethod(method) {
var _a, _b;
switch (method) {
case "sampling/createMessage":
if (!((_a = this._clientCapabilities) === null || _a === undefined ? undefined : _a.sampling)) {
throw new Error(`Client does not support sampling (required for ${method})`);
}
break;
case "roots/list":
if (!((_b = this._clientCapabilities) === null || _b === undefined ? undefined : _b.roots)) {
throw new Error(`Client does not support listing roots (required for ${method})`);
}
break;
case "ping":
break;
}
}
assertNotificationCapability(method) {
switch (method) {
case "notifications/message":
if (!this._capabilities.logging) {
throw new Error(`Server does not support logging (required for ${method})`);
}
break;
case "notifications/resources/updated":
case "notifications/resources/list_changed":
if (!this._capabilities.resources) {
throw new Error(`Server does not support notifying about resources (required for ${method})`);
}
break;
case "notifications/tools/list_changed":
if (!this._capabilities.tools) {
throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
}
break;
case "notifications/prompts/list_changed":
if (!this._capabilities.prompts) {
throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
}
break;
case "notifications/cancelled":
break;
case "notifications/progress":
break;
}
}
assertRequestHandlerCapability(method) {
switch (method) {
case "sampling/createMessage":
if (!this._capabilities.sampling) {
throw new Error(`Server does not support sampling (required for ${method})`);
}
break;
case "logging/setLevel":
if (!this._capabilities.logging) {
throw new Error(`Server does not support logging (required for ${method})`);
}
break;
case "prompts/get":
case "prompts/list":
if (!this._capabilities.prompts) {
throw new Error(`Server does not support prompts (required for ${method})`);
}
break;
case "resources/list":
case "resources/templates/list":
case "resources/read":
if (!this._capabilities.resources) {
throw new Error(`Server does not support resources (required for ${method})`);
}
break;
case "tools/call":
case "tools/list":
if (!this._capabilities.tools) {
throw new Error(`Server does not support tools (required for ${method})`);
}
break;
case "ping":
case "initialize":
break;
}
}
async _oninitialize(request) {
const requestedVersion = request.params.protocolVersion;
this._clientCapabilities = request.params.capabilities;
this._clientVersion = request.params.clientInfo;
return {
protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION,
capabilities: this.getCapabilities(),
serverInfo: this._serverInfo,
...this._instructions && { instructions: this._instructions }
};
}
getClientCapabilities() {
return this._clientCapabilities;
}
getClientVersion() {
return this._clientVersion;
}
getCapabilities() {
return this._capabilities;
}
async ping() {
return this.request({ method: "ping" }, EmptyResultSchema);
}
async createMessage(params, options) {
return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);
}
async listRoots(params, options) {
return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);
}
async sendLoggingMessage(params) {
return this.notification({ method: "notifications/message", params });
}
async sendResourceUpdated(params) {
return this.notification({
method: "notifications/resources/updated",
params
});
}
async sendResourceListChanged() {
return this.notification({
method: "notifications/resources/list_changed"
});
}
async sendToolListChanged() {
return this.notification({ method: "notifications/tools/list_changed" });
}
async sendPromptListChanged() {
return this.notification({ method: "notifications/prompts/list_changed" });
}
}
// node_modules/zod-to-json-schema/dist/esm/Options.js
var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions = {
name: undefined,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
target: "jsonSchema7",
strictUnions: false,
definitions: {},
errorMessages: false,
markdownDescription: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
...defaultOptions,
name: options
} : {
...defaultOptions,
...options
};
// node_modules/zod-to-json-schema/dist/esm/Refs.js
var getRefs = (options) => {
const _options = getDefaultOptions(options);
const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
return {
..._options,
currentPath,
propertyPath: undefined,
seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
def._def,
{
def: def._def,
path: [..._options.basePath, _options.definitionPath, name],
jsonSchema: undefined
}
]))
};
};
// node_modules/zod-to-json-schema/dist/esm/errorMessages.js
function addErrorMessage(res, key, errorMessage, refs) {
if (!refs?.errorMessages)
return;
if (errorMessage) {
res.errorMessage = {
...res.errorMessage,
[key]: errorMessage
};
}
}
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
res[key] = value;
addErrorMessage(res, key, errorMessage, refs);
}
// node_modules/zod-to-json-schema/dist/esm/parsers/any.js
function parseAnyDef() {
return {};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/array.js
function parseArrayDef(def, refs) {
const res = {
type: "array"
};
if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
res.items = parseDef(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
}
if (def.minLength) {
setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
}
if (def.maxLength) {
setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
}
if (def.exactLength) {
setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
}
return res;
}
// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
function parseBigintDef(def, refs) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks)
return res;
for (const check of def.checks) {
switch (check.kind) {
case "min":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
} else {
setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
}
} else {
if (!check.inclusive) {
res.exclusiveMinimum = true;
}
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
break;
case "max":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
} else {
setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
}
} else {
if (!check.inclusive) {
res.exclusiveMaximum = true;
}
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
break;
case "multipleOf":
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
break;
}
}
return res;
}
// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
function parseBooleanDef() {
return {
type: "boolean"
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
function parseBrandedDef(_def, refs) {
return parseDef(_def.type._def, refs);
}
// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
var parseCatchDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
// node_modules/zod-to-json-schema/dist/esm/parsers/date.js
function parseDateDef(def, refs, overrideDateStrategy) {
const strategy = 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, refs);
}
}
var integerDateParser = (def, refs) => {
const res = {
type: "integer",
format: "unix-time"
};
if (refs.target === "openApi3") {
return res;
}
for (const check of def.checks) {
switch (check.kind) {
case "min":
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
break;
case "max":
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
break;
}
}
return res;
};
// node_modules/zod-to-json-schema/dist/esm/parsers/default.js
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
function parseEffectsDef(_def, refs) {
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
function parseEnumDef(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
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, {
...refs,
currentPath: [...refs.currentPath, "allOf", "0"]
}),
parseDef(def.right._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "1"]
})
].filter((x) => !!x);
let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : undefined;
const mergedAllOf = [];
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType(schema)) {
mergedAllOf.push(...schema.allOf);
if (schema.unevaluatedProperties === undefined) {
unevaluatedProperties = undefined;
}
} else {
let nestedSchema = schema;
if ("additionalProperties" in schema && schema.additionalProperties === false) {
const { additionalProperties, ...rest } = schema;
nestedSchema = rest;
} else {
unevaluatedProperties = undefined;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? {
allOf: mergedAllOf,
...unevaluatedProperties
} : undefined;
}
// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
function parseLiteralDef(def, refs) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
return {
type: Array.isArray(def.value) ? "array" : "object"
};
}
if (refs.target === "openApi3") {
return {
type: parsedType === "bigint" ? "integer" : parsedType,
enum: [def.value]
};
}
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/string.js
var emojiRegex2 = undefined;
var zodPatterns = {
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
emoji: () => {
if (emojiRegex2 === undefined) {
emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
}
return emojiRegex2;
},
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}$/,
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])$/,
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":
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
break;
case "max":
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
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":
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
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": {
setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
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:
((_) => {})(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) {
if (schema.format || schema.anyOf?.some((x) => x.format)) {
if (!schema.anyOf) {
schema.anyOf = [];
}
if (schema.format) {
schema.anyOf.push({
format: schema.format,
...schema.errorMessage && refs.errorMessages && {
errorMessage: { format: schema.errorMessage.format }
}
});
delete schema.format;
if (schema.errorMessage) {
delete schema.errorMessage.format;
if (Object.keys(schema.errorMessage).length === 0) {
delete schema.errorMessage;
}
}
}
schema.anyOf.push({
format: value,
...message && refs.errorMessages && { errorMessage: { format: message } }
});
} else {
setResponseValueAndErrors(schema, "format", value, message, refs);
}
}
function addPattern(schema, regex, message, refs) {
if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
if (!schema.allOf) {
schema.allOf = [];
}
if (schema.pattern) {
schema.allOf.push({
pattern: schema.pattern,
...schema.errorMessage && refs.errorMessages && {
errorMessage: { pattern: schema.errorMessage.pattern }
}
});
delete schema.pattern;
if (schema.errorMessage) {
delete schema.errorMessage.pattern;
if (Object.keys(schema.errorMessage).length === 0) {
delete schema.errorMessage;
}
}
}
schema.allOf.push({
pattern: stringifyRegExpWithFlags(regex, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else {
setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
}
}
function stringifyRegExpWithFlags(regex, refs) {
if (!refs.applyRegexFlags || !regex.flags) {
return regex.source;
}
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s")
};
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] === "-" && source[i + 2]?.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 {
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;
}
// node_modules/zod-to-json-schema/dist/esm/parsers/record.js
function parseRecordDef(def, refs) {
if (refs.target === "openAi") {
console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
}
if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
return {
type: "object",
required: def.keyType._def.values,
properties: def.keyType._def.values.reduce((acc, key) => ({
...acc,
[key]: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "properties", key]
}) ?? {}
}), {}),
additionalProperties: refs.rejectedAdditionalProperties
};
}
const schema = {
type: "object",
additionalProperties: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
}) ?? refs.allowedAdditionalProperties
};
if (refs.target === "openApi3") {
return schema;
}
if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
} else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
return {
...schema,
propertyNames: {
enum: def.keyType._def.values
}
};
} else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
}
return schema;
}
// node_modules/zod-to-json-schema/dist/esm/parsers/map.js
function parseMapDef(def, refs) {
if (refs.mapStrategy === "record") {
return parseRecordDef(def, refs);
}
const keys = parseDef(def.keyType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "0"]
}) || {};
const values = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "1"]
}) || {};
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [keys, values],
minItems: 2,
maxItems: 2
}
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
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
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/never.js
function parseNeverDef() {
return {
not: {}
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/null.js
function parseNullDef(refs) {
return refs.target === "openApi3" ? {
enum: ["null"],
nullable: true
} : {
type: "null"
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/union.js
var primitiveMappings = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null"
};
function parseUnionDef(def, refs) {
if (refs.target === "openApi3")
return asAnyOf(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 types2 = options.reduce((types3, x) => {
const type = primitiveMappings[x._def.typeName];
return type && !types3.includes(type) ? [...types3, type] : types3;
}, []);
return {
type: types2.length > 1 ? types2 : types2[0]
};
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
const types2 = 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 (types2.length === options.length) {
const uniqueTypes = types2.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, {
...refs,
currentPath: [...refs.currentPath, "anyOf", `${i}`]
})).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
return anyOf.length ? { anyOf } : undefined;
};
// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
function parseNullableDef(def, refs) {
if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
if (refs.target === "openApi3") {
return {
type: primitiveMappings[def.innerType._def.typeName],
nullable: true
};
}
return {
type: [
primitiveMappings[def.innerType._def.typeName],
"null"
]
};
}
if (refs.target === "openApi3") {
const base2 = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath]
});
if (base2 && "$ref" in base2)
return { allOf: [base2], nullable: true };
return base2 && { ...base2, nullable: true };
}
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", "0"]
});
return base && { anyOf: [base, { type: "null" }] };
}
// node_modules/zod-to-json-schema/dist/esm/parsers/number.js
function parseNumberDef(def, refs) {
const res = {
type: "number"
};
if (!def.checks)
return res;
for (const check of def.checks) {
switch (check.kind) {
case "int":
res.type = "integer";
addErrorMessage(res, "type", check.message, refs);
break;
case "min":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
} else {
setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
}
} else {
if (!check.inclusive) {
res.exclusiveMinimum = true;
}
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
break;
case "max":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
} else {
setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
}
} else {
if (!check.inclusive) {
res.exclusiveMaximum = true;
}
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
break;
case "multipleOf":
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
break;
}
}
return res;
}
// node_modules/zod-to-json-schema/dist/esm/parsers/object.js
function parseObjectDef(def, refs) {
const forceOptionalIntoNullable = refs.target === "openAi";
const result = {
type: "object",
properties: {}
};
const required = [];
const shape = def.shape();
for (const propName in shape) {
let propDef = shape[propName];
if (propDef === undefined || propDef._def === undefined) {
continue;
}
let propOptional = safeIsOptional(propDef);
if (propOptional && forceOptionalIntoNullable) {
if (propDef instanceof ZodOptional) {
propDef = propDef._def.innerType;
}
if (!propDef.isNullable()) {
propDef = propDef.nullable();
}
propOptional = false;
}
const parsedDef = parseDef(propDef._def, {
...refs,
currentPath: [...refs.currentPath, "properties", propName],
propertyPath: [...refs.currentPath, "properties", propName]
});
if (parsedDef === undefined) {
continue;
}
result.properties[propName] = parsedDef;
if (!propOptional) {
required.push(propName);
}
}
if (required.length) {
result.required = required;
}
const additionalProperties = decideAdditionalProperties(def, refs);
if (additionalProperties !== undefined) {
result.additionalProperties = additionalProperties;
}
return result;
}
function decideAdditionalProperties(def, refs) {
if (def.catchall._def.typeName !== "ZodNever") {
return parseDef(def.catchall._def, {
...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 {
return true;
}
}
// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
var parseOptionalDef = (def, refs) => {
if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
return parseDef(def.innerType._def, refs);
}
const innerSchema = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", "1"]
});
return innerSchema ? {
anyOf: [
{
not: {}
},
innerSchema
]
} : {};
};
// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
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, {
...refs,
currentPath: [...refs.currentPath, "allOf", "0"]
});
const b = parseDef(def.out._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
});
return {
allOf: [a, b].filter((x) => x !== undefined)
};
};
// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
function parsePromiseDef(def, refs) {
return parseDef(def.type._def, refs);
}
// node_modules/zod-to-json-schema/dist/esm/parsers/set.js
function parseSetDef(def, refs) {
const items = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
const schema = {
type: "array",
uniqueItems: true,
items
};
if (def.minSize) {
setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
}
if (def.maxSize) {
setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
}
return schema;
}
// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
function parseTupleDef(def, refs) {
if (def.rest) {
return {
type: "array",
minItems: def.items.length,
items: def.items.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i}`]
})).reduce((acc, x) => x === undefined ? acc : [...acc, x], []),
additionalItems: parseDef(def.rest._def, {
...refs,
currentPath: [...refs.currentPath, "additionalItems"]
})
};
} else {
return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i}`]
})).reduce((acc, x) => x === undefined ? acc : [...acc, x], [])
};
}
}
// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
function parseUndefinedDef() {
return {
not: {}
};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
function parseUnknownDef() {
return {};
}
// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
var parseReadonlyDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
// node_modules/zod-to-json-schema/dist/esm/selectParser.js
var selectParser = (def, typeName, refs) => {
switch (typeName) {
case ZodFirstPartyTypeKind.ZodString:
return parseStringDef(def, refs);
case ZodFirstPartyTypeKind.ZodNumber:
return parseNumberDef(def, refs);
case ZodFirstPartyTypeKind.ZodObject:
return parseObjectDef(def, refs);
case ZodFirstPartyTypeKind.ZodBigInt:
return parseBigintDef(def, refs);
case ZodFirstPartyTypeKind.ZodBoolean:
return parseBooleanDef();
case ZodFirstPartyTypeKind.ZodDate:
return parseDateDef(def, refs);
case ZodFirstPartyTypeKind.ZodUndefined:
return parseUndefinedDef();
case ZodFirstPartyTypeKind.ZodNull:
return parseNullDef(refs);
case ZodFirstPartyTypeKind.ZodArray:
return parseArrayDef(def, refs);
case ZodFirstPartyTypeKind.ZodUnion:
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
return parseUnionDef(def, refs);
case ZodFirstPartyTypeKind.ZodIntersection:
return parseIntersectionDef(def, refs);
case ZodFirstPartyTypeKind.ZodTuple:
return parseTupleDef(def, refs);
case ZodFirstPartyTypeKind.ZodRecord:
return parseRecordDef(def, refs);
case ZodFirstPartyTypeKind.ZodLiteral:
return parseLiteralDef(def, refs);
case ZodFirstPartyTypeKind.ZodEnum:
return parseEnumDef(def);
case ZodFirstPartyTypeKind.ZodNativeEnum:
return parseNativeEnumDef(def);
case ZodFirstPartyTypeKind.ZodNullable:
return parseNullableDef(def, refs);
case ZodFirstPartyTypeKind.ZodOptional:
return parseOptionalDef(def, refs);
case ZodFirstPartyTypeKind.ZodMap:
return parseMapDef(def, refs);
case ZodFirstPartyTypeKind.ZodSet:
return parseSetDef(def, refs);
case ZodFirstPartyTypeKind.ZodLazy:
return () => def.getter()._def;
case ZodFirstPartyTypeKind.ZodPromise:
return parsePromiseDef(def, refs);
case ZodFirstPartyTypeKind.ZodNaN:
case ZodFirstPartyTypeKind.ZodNever:
return parseNeverDef();
case ZodFirstPartyTypeKind.ZodEffects:
return parseEffectsDef(def, refs);
case ZodFirstPartyTypeKind.ZodAny:
return parseAnyDef();
case ZodFirstPartyTypeKind.ZodUnknown:
return parseUnknownDef();
case ZodFirstPartyTypeKind.ZodDefault:
return parseDefaultDef(def, refs);
case ZodFirstPartyTypeKind.ZodBranded:
return parseBrandedDef(def, refs);
case ZodFirstPartyTypeKind.ZodReadonly:
return parseReadonlyDef(def, refs);
case ZodFirstPartyTypeKind.ZodCatch:
return parseCatchDef(def, refs);
case ZodFirstPartyTypeKind.ZodPipeline:
return parsePipelineDef(def, refs);
case ZodFirstPartyTypeKind.ZodFunction:
case ZodFirstPartyTypeKind.ZodVoid:
case ZodFirstPartyTypeKind.ZodSymbol:
return;
default:
return ((_) => {
return;
})(typeName);
}
};
// node_modules/zod-to-json-schema/dist/esm/parseDef.js
function parseDef(def, refs, forceResolution = false) {
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride) {
return overrideResult;
}
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref(seenItem, refs);
if (seenSchema !== undefined) {
return seenSchema;
}
}
const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema) {
addMeta(def, refs, jsonSchema);
}
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema, def, refs);
newItem.jsonSchema = jsonSchema;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema;
return jsonSchema;
}
var get$ref = (item, refs) => {
switch (refs.$refStrategy) {
case "root":
return { $ref: item.path.join("/") };
case "relative":
return { $ref: getRelativePath(refs.currentPath, item.path) };
case "none":
case "seen": {
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return {};
}
return refs.$refStrategy === "seen" ? {} : undefined;
}
}
};
var getRelativePath = (pathA, pathB) => {
let i = 0;
for (;i < pathA.length && i < pathB.length; i++) {
if (pathA[i] !== pathB[i])
break;
}
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
var addMeta = (def, refs, jsonSchema) => {
if (def.description) {
jsonSchema.description = def.description;
if (refs.markdownDescription) {
jsonSchema.markdownDescription = def.description;
}
}
return jsonSchema;
};
// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
var zodToJsonSchema = (schema, options) => {
const refs = getRefs(options);
const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
...acc,
[name2]: parseDef(schema2._def, {
...refs,
currentPath: [...refs.basePath, refs.definitionPath, name2]
}, true) ?? {}
}), {}) : undefined;
const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name;
const main = parseDef(schema._def, name === undefined ? refs : {
...refs,
currentPath: [...refs.basePath, refs.definitionPath, name]
}, false) ?? {};
const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
if (title !== undefined) {
main.title = title;
}
const combined = name === undefined ? definitions ? {
...main,
[refs.definitionPath]: definitions
} : main : {
$ref: [
...refs.$refStrategy === "relative" ? [] : refs.basePath,
refs.definitionPath,
name
].join("/"),
[refs.definitionPath]: {
...definitions,
[name]: main
}
};
if (refs.target === "jsonSchema7") {
combined.$schema = "http://json-schema.org/draft-07/schema#";
} else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
}
if (refs.target === "openAi" && (("anyOf" in combined) || ("oneOf" in combined) || ("allOf" in combined) || ("type" in combined) && Array.isArray(combined.type))) {
console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
}
return combined;
};
// node_modules/zod-to-json-schema/dist/esm/index.js
var esm_default = zodToJsonSchema;
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js
var McpZodTypeKind;
(function(McpZodTypeKind2) {
McpZodTypeKind2["Completable"] = "McpCompletable";
})(McpZodTypeKind || (McpZodTypeKind = {}));
class Completable extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}
Completable.create = (type, params) => {
return new Completable({
type,
typeName: McpZodTypeKind.Completable,
complete: params.complete,
...processCreateParams2(params)
});
};
function processCreateParams2(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
var _a, _b;
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message !== null && message !== undefined ? message : ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: (_a = message !== null && message !== undefined ? message : required_error) !== null && _a !== undefined ? _a : ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: (_b = message !== null && message !== undefined ? message : invalid_type_error) !== null && _b !== undefined ? _b : ctx.defaultError };
};
return { errorMap: customMap, description };
}
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
class McpServer {
constructor(serverInfo, options) {
this._registeredResources = {};
this._registeredResourceTemplates = {};
this._registeredTools = {};
this._registeredPrompts = {};
this._toolHandlersInitialized = false;
this._completionHandlerInitialized = false;
this._resourceHandlersInitialized = false;
this._promptHandlersInitialized = false;
this.server = new Server(serverInfo, options);
}
async connect(transport) {
return await this.server.connect(transport);
}
async close() {
await this.server.close();
}
setToolRequestHandlers() {
if (this._toolHandlersInitialized) {
return;
}
this.server.assertCanSetRequestHandler(ListToolsRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(CallToolRequestSchema.shape.method.value);
this.server.registerCapabilities({
tools: {
listChanged: true
}
});
this.server.setRequestHandler(ListToolsRequestSchema, () => ({
tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
const toolDefinition = {
name,
description: tool.description,
inputSchema: tool.inputSchema ? zodToJsonSchema(tool.inputSchema, {
strictUnions: true
}) : EMPTY_OBJECT_JSON_SCHEMA,
annotations: tool.annotations
};
if (tool.outputSchema) {
toolDefinition.outputSchema = zodToJsonSchema(tool.outputSchema, { strictUnions: true });
}
return toolDefinition;
})
}));
this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
const tool = this._registeredTools[request.params.name];
if (!tool) {
throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
}
if (!tool.enabled) {
throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
}
let result;
if (tool.inputSchema) {
const parseResult = await tool.inputSchema.safeParseAsync(request.params.arguments);
if (!parseResult.success) {
throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${request.params.name}: ${parseResult.error.message}`);
}
const args = parseResult.data;
const cb = tool.callback;
try {
result = await Promise.resolve(cb(args, extra));
} catch (error) {
result = {
content: [
{
type: "text",
text: error instanceof Error ? error.message : String(error)
}
],
isError: true
};
}
} else {
const cb = tool.callback;
try {
result = await Promise.resolve(cb(extra));
} catch (error) {
result = {
content: [
{
type: "text",
text: error instanceof Error ? error.message : String(error)
}
],
isError: true
};
}
}
if (tool.outputSchema) {
if (!result.structuredContent) {
throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} has an output schema but no structured content was provided`);
}
const parseResult = await tool.outputSchema.safeParseAsync(result.structuredContent);
if (!parseResult.success) {
throw new McpError(ErrorCode.InvalidParams, `Invalid structured content for tool ${request.params.name}: ${parseResult.error.message}`);
}
}
return result;
});
this._toolHandlersInitialized = true;
}
setCompletionRequestHandler() {
if (this._completionHandlerInitialized) {
return;
}
this.server.assertCanSetRequestHandler(CompleteRequestSchema.shape.method.value);
this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
switch (request.params.ref.type) {
case "ref/prompt":
return this.handlePromptCompletion(request, request.params.ref);
case "ref/resource":
return this.handleResourceCompletion(request, request.params.ref);
default:
throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
}
});
this._completionHandlerInitialized = true;
}
async handlePromptCompletion(request, ref) {
const prompt = this._registeredPrompts[ref.name];
if (!prompt) {
throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
}
if (!prompt.enabled) {
throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
}
if (!prompt.argsSchema) {
return EMPTY_COMPLETION_RESULT;
}
const field = prompt.argsSchema.shape[request.params.argument.name];
if (!(field instanceof Completable)) {
return EMPTY_COMPLETION_RESULT;
}
const def = field._def;
const suggestions = await def.complete(request.params.argument.value);
return createCompletionResult(suggestions);
}
async handleResourceCompletion(request, ref) {
const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
if (!template) {
if (this._registeredResources[ref.uri]) {
return EMPTY_COMPLETION_RESULT;
}
throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
}
const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
if (!completer) {
return EMPTY_COMPLETION_RESULT;
}
const suggestions = await completer(request.params.argument.value);
return createCompletionResult(suggestions);
}
setResourceRequestHandlers() {
if (this._resourceHandlersInitialized) {
return;
}
this.server.assertCanSetRequestHandler(ListResourcesRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(ListResourceTemplatesRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(ReadResourceRequestSchema.shape.method.value);
this.server.registerCapabilities({
resources: {
listChanged: true
}
});
this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({
uri,
name: resource.name,
...resource.metadata
}));
const templateResources = [];
for (const template of Object.values(this._registeredResourceTemplates)) {
if (!template.resourceTemplate.listCallback) {
continue;
}
const result = await template.resourceTemplate.listCallback(extra);
for (const resource of result.resources) {
templateResources.push({
...resource,
...template.metadata
});
}
}
return { resources: [...resources, ...templateResources] };
});
this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
name,
uriTemplate: template.resourceTemplate.uriTemplate.toString(),
...template.metadata
}));
return { resourceTemplates };
});
this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
const uri = new URL(request.params.uri);
const resource = this._registeredResources[uri.toString()];
if (resource) {
if (!resource.enabled) {
throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);
}
return resource.readCallback(uri, extra);
}
for (const template of Object.values(this._registeredResourceTemplates)) {
const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
if (variables) {
return template.readCallback(uri, variables, extra);
}
}
throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
});
this.setCompletionRequestHandler();
this._resourceHandlersInitialized = true;
}
setPromptRequestHandlers() {
if (this._promptHandlersInitialized) {
return;
}
this.server.assertCanSetRequestHandler(ListPromptsRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(GetPromptRequestSchema.shape.method.value);
this.server.registerCapabilities({
prompts: {
listChanged: true
}
});
this.server.setRequestHandler(ListPromptsRequestSchema, () => ({
prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
return {
name,
description: prompt.description,
arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined
};
})
}));
this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
const prompt = this._registeredPrompts[request.params.name];
if (!prompt) {
throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
}
if (!prompt.enabled) {
throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
}
if (prompt.argsSchema) {
const parseResult = await prompt.argsSchema.safeParseAsync(request.params.arguments);
if (!parseResult.success) {
throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${parseResult.error.message}`);
}
const args = parseResult.data;
const cb = prompt.callback;
return await Promise.resolve(cb(args, extra));
} else {
const cb = prompt.callback;
return await Promise.resolve(cb(extra));
}
});
this.setCompletionRequestHandler();
this._promptHandlersInitialized = true;
}
resource(name, uriOrTemplate, ...rest) {
let metadata;
if (typeof rest[0] === "object") {
metadata = rest.shift();
}
const readCallback = rest[0];
if (typeof uriOrTemplate === "string") {
if (this._registeredResources[uriOrTemplate]) {
throw new Error(`Resource ${uriOrTemplate} is already registered`);
}
const registeredResource = {
name,
metadata,
readCallback,
enabled: true,
disable: () => registeredResource.update({ enabled: false }),
enable: () => registeredResource.update({ enabled: true }),
remove: () => registeredResource.update({ uri: null }),
update: (updates) => {
if (typeof updates.uri !== "undefined" && updates.uri !== uriOrTemplate) {
delete this._registeredResources[uriOrTemplate];
if (updates.uri)
this._registeredResources[updates.uri] = registeredResource;
}
if (typeof updates.name !== "undefined")
registeredResource.name = updates.name;
if (typeof updates.metadata !== "undefined")
registeredResource.metadata = updates.metadata;
if (typeof updates.callback !== "undefined")
registeredResource.readCallback = updates.callback;
if (typeof updates.enabled !== "undefined")
registeredResource.enabled = updates.enabled;
this.sendResourceListChanged();
}
};
this._registeredResources[uriOrTemplate] = registeredResource;
this.setResourceRequestHandlers();
this.sendResourceListChanged();
return registeredResource;
} else {
if (this._registeredResourceTemplates[name]) {
throw new Error(`Resource template ${name} is already registered`);
}
const registeredResourceTemplate = {
resourceTemplate: uriOrTemplate,
metadata,
readCallback,
enabled: true,
disable: () => registeredResourceTemplate.update({ enabled: false }),
enable: () => registeredResourceTemplate.update({ enabled: true }),
remove: () => registeredResourceTemplate.update({ name: null }),
update: (updates) => {
if (typeof updates.name !== "undefined" && updates.name !== name) {
delete this._registeredResourceTemplates[name];
if (updates.name)
this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
}
if (typeof updates.template !== "undefined")
registeredResourceTemplate.resourceTemplate = updates.template;
if (typeof updates.metadata !== "undefined")
registeredResourceTemplate.metadata = updates.metadata;
if (typeof updates.callback !== "undefined")
registeredResourceTemplate.readCallback = updates.callback;
if (typeof updates.enabled !== "undefined")
registeredResourceTemplate.enabled = updates.enabled;
this.sendResourceListChanged();
}
};
this._registeredResourceTemplates[name] = registeredResourceTemplate;
this.setResourceRequestHandlers();
this.sendResourceListChanged();
return registeredResourceTemplate;
}
}
_createRegisteredTool(name, description, inputSchema, outputSchema, annotations, callback) {
const registeredTool = {
description,
inputSchema: inputSchema === undefined ? undefined : exports_external.object(inputSchema),
outputSchema: outputSchema === undefined ? undefined : exports_external.object(outputSchema),
annotations,
callback,
enabled: true,
disable: () => registeredTool.update({ enabled: false }),
enable: () => registeredTool.update({ enabled: true }),
remove: () => registeredTool.update({ name: null }),
update: (updates) => {
if (typeof updates.name !== "undefined" && updates.name !== name) {
delete this._registeredTools[name];
if (updates.name)
this._registeredTools[updates.name] = registeredTool;
}
if (typeof updates.description !== "undefined")
registeredTool.description = updates.description;
if (typeof updates.paramsSchema !== "undefined")
registeredTool.inputSchema = exports_external.object(updates.paramsSchema);
if (typeof updates.callback !== "undefined")
registeredTool.callback = updates.callback;
if (typeof updates.annotations !== "undefined")
registeredTool.annotations = updates.annotations;
if (typeof updates.enabled !== "undefined")
registeredTool.enabled = updates.enabled;
this.sendToolListChanged();
}
};
this._registeredTools[name] = registeredTool;
this.setToolRequestHandlers();
this.sendToolListChanged();
return registeredTool;
}
tool(name, ...rest) {
if (this._registeredTools[name]) {
throw new Error(`Tool ${name} is already registered`);
}
let description;
let inputSchema;
let outputSchema;
let annotations;
if (typeof rest[0] === "string") {
description = rest.shift();
}
if (rest.length > 1) {
const firstArg = rest[0];
if (isZodRawShape(firstArg)) {
inputSchema = rest.shift();
if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShape(rest[0])) {
annotations = rest.shift();
}
} else if (typeof firstArg === "object" && firstArg !== null) {
annotations = rest.shift();
}
}
const callback = rest[0];
return this._createRegisteredTool(name, description, inputSchema, outputSchema, annotations, callback);
}
registerTool(name, config, cb) {
if (this._registeredTools[name]) {
throw new Error(`Tool ${name} is already registered`);
}
const { description, inputSchema, outputSchema, annotations } = config;
return this._createRegisteredTool(name, description, inputSchema, outputSchema, annotations, cb);
}
prompt(name, ...rest) {
if (this._registeredPrompts[name]) {
throw new Error(`Prompt ${name} is already registered`);
}
let description;
if (typeof rest[0] === "string") {
description = rest.shift();
}
let argsSchema;
if (rest.length > 1) {
argsSchema = rest.shift();
}
const cb = rest[0];
const registeredPrompt = {
description,
argsSchema: argsSchema === undefined ? undefined : exports_external.object(argsSchema),
callback: cb,
enabled: true,
disable: () => registeredPrompt.update({ enabled: false }),
enable: () => registeredPrompt.update({ enabled: true }),
remove: () => registeredPrompt.update({ name: null }),
update: (updates) => {
if (typeof updates.name !== "undefined" && updates.name !== name) {
delete this._registeredPrompts[name];
if (updates.name)
this._registeredPrompts[updates.name] = registeredPrompt;
}
if (typeof updates.description !== "undefined")
registeredPrompt.description = updates.description;
if (typeof updates.argsSchema !== "undefined")
registeredPrompt.argsSchema = exports_external.object(updates.argsSchema);
if (typeof updates.callback !== "undefined")
registeredPrompt.callback = updates.callback;
if (typeof updates.enabled !== "undefined")
registeredPrompt.enabled = updates.enabled;
this.sendPromptListChanged();
}
};
this._registeredPrompts[name] = registeredPrompt;
this.setPromptRequestHandlers();
this.sendPromptListChanged();
return registeredPrompt;
}
isConnected() {
return this.server.transport !== undefined;
}
sendResourceListChanged() {
if (this.isConnected()) {
this.server.sendResourceListChanged();
}
}
sendToolListChanged() {
if (this.isConnected()) {
this.server.sendToolListChanged();
}
}
sendPromptListChanged() {
if (this.isConnected()) {
this.server.sendPromptListChanged();
}
}
}
var EMPTY_OBJECT_JSON_SCHEMA = {
type: "object"
};
function isZodRawShape(obj) {
if (typeof obj !== "object" || obj === null)
return false;
const isEmptyObject = Object.keys(obj).length === 0;
return isEmptyObject || Object.values(obj).some(isZodTypeLike);
}
function isZodTypeLike(value) {
return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
}
function promptArgumentsFromSchema(schema) {
return Object.entries(schema.shape).map(([name, field]) => ({
name,
description: field.description,
required: !field.isOptional()
}));
}
function createCompletionResult(suggestions) {
return {
completion: {
values: suggestions.slice(0, 100),
total: suggestions.length,
hasMore: suggestions.length > 100
}
};
}
var EMPTY_COMPLETION_RESULT = {
completion: {
values: [],
hasMore: false
}
};
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
import process2 from "node:process";
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
class ReadBuffer {
append(chunk) {
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
}
readMessage() {
if (!this._buffer) {
return null;
}
const index = this._buffer.indexOf(`
`);
if (index === -1) {
return null;
}
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
this._buffer = this._buffer.subarray(index + 1);
return deserializeMessage(line);
}
clear() {
this._buffer = undefined;
}
}
function deserializeMessage(line) {
return JSONRPCMessageSchema.parse(JSON.parse(line));
}
function serializeMessage(message) {
return JSON.stringify(message) + `
`;
}
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
class StdioServerTransport {
constructor(_stdin = process2.stdin, _stdout = process2.stdout) {
this._stdin = _stdin;
this._stdout = _stdout;
this._readBuffer = new ReadBuffer;
this._started = false;
this._ondata = (chunk) => {
this._readBuffer.append(chunk);
this.processReadBuffer();
};
this._onerror = (error) => {
var _a;
(_a = this.onerror) === null || _a === undefined || _a.call(this, error);
};
}
async start() {
if (this._started) {
throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
}
this._started = true;
this._stdin.on("data", this._ondata);
this._stdin.on("error", this._onerror);
}
processReadBuffer() {
var _a, _b;
while (true) {
try {
const message = this._readBuffer.readMessage();
if (message === null) {
break;
}
(_a = this.onmessage) === null || _a === undefined || _a.call(this, message);
} catch (error) {
(_b = this.onerror) === null || _b === undefined || _b.call(this, error);
}
}
}
async close() {
var _a;
this._stdin.off("data", this._ondata);
this._stdin.off("error", this._onerror);
const remainingDataListeners = this._stdin.listenerCount("data");
if (remainingDataListeners === 0) {
this._stdin.pause();
}
this._readBuffer.clear();
(_a = this.onclose) === null || _a === undefined || _a.call(this);
}
send(message) {
return new Promise((resolve) => {
const json = serializeMessage(message);
if (this._stdout.write(json)) {
resolve();
} else {
this._stdout.once("drain", resolve);
}
});
}
}
// node_modules/@ai-sdk/provider/dist/index.mjs
var marker = "vercel.ai.error";
var symbol = Symbol.for(marker);
var _a;
var _AISDKError = class _AISDKError2 extends Error {
constructor({
name: name14,
message,
cause
}) {
super(message);
this[_a] = true;
this.name = name14;
this.cause = cause;
}
static isInstance(error) {
return _AISDKError2.hasMarker(error, marker);
}
static hasMarker(error, marker15) {
const markerSymbol = Symbol.for(marker15);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
_a = symbol;
var AISDKError = _AISDKError;
var name = "AI_APICallError";
var marker2 = `vercel.ai.error.${name}`;
var symbol2 = Symbol.for(marker2);
var _a2;
var APICallError = class extends AISDKError {
constructor({
message,
url,
requestBodyValues,
statusCode,
responseHeaders,
responseBody,
cause,
isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500),
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);
}
};
_a2 = symbol2;
var name2 = "AI_EmptyResponseBodyError";
var marker3 = `vercel.ai.error.${name2}`;
var symbol3 = Symbol.for(marker3);
var _a3;
var EmptyResponseBodyError = class extends AISDKError {
constructor({ message = "Empty response body" } = {}) {
super({ name: name2, message });
this[_a3] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker3);
}
};
_a3 = symbol3;
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 InvalidArgumentError = class extends AISDKError {
constructor({
message,
cause,
argument
}) {
super({ name: name3, message, cause });
this[_a4] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker4);
}
};
_a4 = symbol4;
var name4 = "AI_InvalidPromptError";
var marker5 = `vercel.ai.error.${name4}`;
var symbol5 = Symbol.for(marker5);
var _a5;
var InvalidPromptError = class extends AISDKError {
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);
}
};
_a5 = symbol5;
var name5 = "AI_InvalidResponseDataError";
var marker6 = `vercel.ai.error.${name5}`;
var symbol6 = Symbol.for(marker6);
var _a6;
var InvalidResponseDataError = class extends AISDKError {
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);
}
};
_a6 = symbol6;
var name6 = "AI_JSONParseError";
var marker7 = `vercel.ai.error.${name6}`;
var symbol7 = Symbol.for(marker7);
var _a7;
var JSONParseError = class extends AISDKError {
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);
}
};
_a7 = symbol7;
var name7 = "AI_LoadAPIKeyError";
var marker8 = `vercel.ai.error.${name7}`;
var symbol8 = Symbol.for(marker8);
var _a8;
var LoadAPIKeyError = class extends AISDKError {
constructor({ message }) {
super({ name: name7, message });
this[_a8] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker8);
}
};
_a8 = symbol8;
var name8 = "AI_LoadSettingError";
var marker9 = `vercel.ai.error.${name8}`;
var symbol9 = Symbol.for(marker9);
var _a9;
_a9 = symbol9;
var name9 = "AI_NoContentGeneratedError";
var marker10 = `vercel.ai.error.${name9}`;
var symbol10 = Symbol.for(marker10);
var _a10;
_a10 = symbol10;
var name10 = "AI_NoSuchModelError";
var marker11 = `vercel.ai.error.${name10}`;
var symbol11 = Symbol.for(marker11);
var _a11;
var NoSuchModelError = class extends AISDKError {
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);
}
};
_a11 = symbol11;
var name11 = "AI_TooManyEmbeddingValuesForCallError";
var marker12 = `vercel.ai.error.${name11}`;
var symbol12 = Symbol.for(marker12);
var _a12;
_a12 = symbol12;
var name12 = "AI_TypeValidationError";
var marker13 = `vercel.ai.error.${name12}`;
var symbol13 = Symbol.for(marker13);
var _a13;
var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
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);
}
static wrap({
value,
cause
}) {
return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
}
};
_a13 = symbol13;
var TypeValidationError = _TypeValidationError;
var name13 = "AI_UnsupportedFunctionalityError";
var marker14 = `vercel.ai.error.${name13}`;
var symbol14 = Symbol.for(marker14);
var _a14;
var UnsupportedFunctionalityError = class extends AISDKError {
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);
}
};
_a14 = symbol14;
// node_modules/nanoid/non-secure/index.js
var customAlphabet = (alphabet, defaultSize = 21) => {
return (size = defaultSize) => {
let id = "";
let i = size | 0;
while (i--) {
id += alphabet[Math.random() * alphabet.length | 0];
}
return id;
};
};
// node_modules/@ai-sdk/provider-utils/dist/index.mjs
var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);
function combineHeaders(...headers) {
return headers.reduce((combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders != null ? currentHeaders : {}
}), {});
}
function convertAsyncIteratorToReadableStream(iterator) {
return new ReadableStream({
async pull(controller) {
try {
const { value, done } = await iterator.next();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
},
cancel() {}
});
}
async function delay(delayInMs) {
return delayInMs == null ? Promise.resolve() : new Promise((resolve2) => setTimeout(resolve2, delayInMs));
}
function createEventSourceParserStream() {
let buffer = "";
let event = undefined;
let data = [];
let lastEventId = undefined;
let retry = undefined;
function parseLine(line, controller) {
if (line === "") {
dispatchEvent(controller);
return;
}
if (line.startsWith(":")) {
return;
}
const colonIndex = line.indexOf(":");
if (colonIndex === -1) {
handleField(line, "");
return;
}
const field = line.slice(0, colonIndex);
const valueStart = colonIndex + 1;
const value = valueStart < line.length && line[valueStart] === " " ? line.slice(valueStart + 1) : line.slice(valueStart);
handleField(field, value);
}
function dispatchEvent(controller) {
if (data.length > 0) {
controller.enqueue({
event,
data: data.join(`
`),
id: lastEventId,
retry
});
data = [];
event = undefined;
retry = undefined;
}
}
function handleField(field, value) {
switch (field) {
case "event":
event = value;
break;
case "data":
data.push(value);
break;
case "id":
lastEventId = value;
break;
case "retry":
const parsedRetry = parseInt(value, 10);
if (!isNaN(parsedRetry)) {
retry = parsedRetry;
}
break;
}
}
return new TransformStream({
transform(chunk, controller) {
const { lines, incompleteLine } = splitLines(buffer, chunk);
buffer = incompleteLine;
for (let i = 0;i < lines.length; i++) {
parseLine(lines[i], controller);
}
},
flush(controller) {
parseLine(buffer, controller);
dispatchEvent(controller);
}
});
}
function splitLines(buffer, chunk) {
const lines = [];
let currentLine = buffer;
for (let i = 0;i < chunk.length; ) {
const char = chunk[i++];
if (char === `
`) {
lines.push(currentLine);
currentLine = "";
} else if (char === "\r") {
lines.push(currentLine);
currentLine = "";
if (chunk[i] === `
`) {
i++;
}
} else {
currentLine += char;
}
}
return { lines, incompleteLine: currentLine };
}
function extractResponseHeaders(response) {
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
return headers;
}
var createIdGenerator = ({
prefix,
size: defaultSize = 16,
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
separator = "-"
} = {}) => {
const generator = customAlphabet(alphabet, defaultSize);
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 (size) => `${prefix}${separator}${generator(size)}`;
};
var generateId = createIdGenerator();
function getErrorMessage2(error) {
if (error == null) {
return "unknown error";
}
if (typeof error === "string") {
return error;
}
if (error instanceof Error) {
return error.message;
}
return JSON.stringify(error);
}
function removeUndefinedEntries(record2) {
return Object.fromEntries(Object.entries(record2).filter(([_key, value]) => value != null));
}
function isAbortError(error) {
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
}
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 validatorSymbol = Symbol.for("vercel.ai.validator");
function validator(validate) {
return { [validatorSymbol]: true, validate };
}
function isValidator(value) {
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
}
function asValidator(value) {
return isValidator(value) ? value : zodValidator(value);
}
function zodValidator(zodSchema) {
return validator((value) => {
const result = zodSchema.safeParse(value);
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
});
}
function validateTypes({
value,
schema: inputSchema
}) {
const result = safeValidateTypes({ value, schema: inputSchema });
if (!result.success) {
throw TypeValidationError.wrap({ value, cause: result.error });
}
return result.value;
}
function safeValidateTypes({
value,
schema
}) {
const validator2 = asValidator(schema);
try {
if (validator2.validate == null) {
return { success: true, value };
}
const result = validator2.validate(value);
if (result.success) {
return result;
}
return {
success: false,
error: TypeValidationError.wrap({ value, cause: result.error })
};
} catch (error) {
return {
success: false,
error: TypeValidationError.wrap({ value, cause: error })
};
}
}
function parseJSON({
text,
schema
}) {
try {
const value = import_secure_json_parse.default.parse(text);
if (schema == null) {
return value;
}
return validateTypes({ value, schema });
} catch (error) {
if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
throw error;
}
throw new JSONParseError({ text, cause: error });
}
}
function safeParseJSON({
text,
schema
}) {
try {
const value = import_secure_json_parse.default.parse(text);
if (schema == null) {
return { success: true, value, rawValue: value };
}
const validationResult = safeValidateTypes({ value, schema });
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
} catch (error) {
return {
success: false,
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
};
}
}
function isParsableJson(input) {
try {
import_secure_json_parse.default.parse(input);
return true;
} catch (e) {
return false;
}
}
var getOriginalFetch2 = () => globalThis.fetch;
var postJsonToApi = async ({
url,
headers,
body,
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch: fetch2
}) => postToApi({
url,
headers: {
"Content-Type": "application/json",
...headers
},
body: {
content: JSON.stringify(body),
values: body
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch: fetch2
});
var postToApi = async ({
url,
headers = {},
body,
successfulResponseHandler,
failedResponseHandler,
abortSignal,
fetch: fetch2 = getOriginalFetch2()
}) => {
try {
const response = await fetch2(url, {
method: "POST",
headers: removeUndefinedEntries(headers),
body: body.content,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) {
throw error;
}
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) {
throw error;
}
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
} catch (error) {
if (isAbortError(error)) {
throw error;
}
if (error instanceof TypeError && error.message === "fetch failed") {
const cause = error.cause;
if (cause != null) {
throw new APICallError({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues: body.values,
isRetryable: true
});
}
}
throw error;
}
};
var createJsonErrorResponseHandler = ({
errorSchema,
errorToMessage,
isRetryable
}) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const responseHeaders = extractResponseHeaders(response);
if (responseBody.trim() === "") {
return {
responseHeaders,
value: new APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? undefined : isRetryable(response)
})
};
}
try {
const parsedError = parseJSON({
text: responseBody,
schema: errorSchema
});
return {
responseHeaders,
value: new APICallError({
message: errorToMessage(parsedError),
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
data: parsedError,
isRetryable: isRetryable == null ? undefined : isRetryable(response, parsedError)
})
};
} catch (parseError) {
return {
responseHeaders,
value: new APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? undefined : isRetryable(response)
})
};
}
};
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) {
throw new EmptyResponseBodyError({});
}
return {
responseHeaders,
value: response.body.pipeThrough(new TextDecoderStream).pipeThrough(createEventSourceParserStream()).pipeThrough(new TransformStream({
transform({ data }, controller) {
if (data === "[DONE]") {
return;
}
controller.enqueue(safeParseJSON({
text: data,
schema: chunkSchema
}));
}
}))
};
};
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const parsedResult = safeParseJSON({
text: responseBody,
schema: responseSchema
});
const responseHeaders = extractResponseHeaders(response);
if (!parsedResult.success) {
throw new APICallError({
message: "Invalid JSON response",
cause: parsedResult.error,
statusCode: response.status,
responseHeaders,
responseBody,
url,
requestBodyValues
});
}
return {
responseHeaders,
value: parsedResult.value,
rawValue: parsedResult.rawValue
};
};
var { btoa, atob: atob2 } = globalThis;
function convertBase64ToUint8Array(base64String) {
const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
const latin1string = atob2(base64Url);
return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
}
function convertUint8ArrayToBase64(array2) {
let latin1string = "";
for (let i = 0;i < array2.length; i++) {
latin1string += String.fromCodePoint(array2[i]);
}
return btoa(latin1string);
}
function withoutTrailingSlash(url) {
return url == null ? undefined : url.replace(/\/$/, "");
}
// node_modules/@ai-sdk/ui-utils/dist/index.mjs
var textStreamPart = {
code: "0",
name: "text",
parse: (value) => {
if (typeof value !== "string") {
throw new Error('"text" parts expect a string value.');
}
return { type: "text", value };
}
};
var errorStreamPart = {
code: "3",
name: "error",
parse: (value) => {
if (typeof value !== "string") {
throw new Error('"error" parts expect a string value.');
}
return { type: "error", value };
}
};
var assistantMessageStreamPart = {
code: "4",
name: "assistant_message",
parse: (value) => {
if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every((item) => item != null && typeof item === "object" && ("type" in item) && item.type === "text" && ("text" in item) && item.text != null && typeof item.text === "object" && ("value" in item.text) && typeof item.text.value === "string")) {
throw new Error('"assistant_message" parts expect an object with an "id", "role", and "content" property.');
}
return {
type: "assistant_message",
value
};
}
};
var assistantControlDataStreamPart = {
code: "5",
name: "assistant_control_data",
parse: (value) => {
if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
throw new Error('"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.');
}
return {
type: "assistant_control_data",
value: {
threadId: value.threadId,
messageId: value.messageId
}
};
}
};
var dataMessageStreamPart = {
code: "6",
name: "data_message",
parse: (value) => {
if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
throw new Error('"data_message" parts expect an object with a "role" and "data" property.');
}
return {
type: "data_message",
value
};
}
};
var assistantStreamParts = [
textStreamPart,
errorStreamPart,
assistantMessageStreamPart,
assistantControlDataStreamPart,
dataMessageStreamPart
];
var assistantStreamPartsByCode = {
[textStreamPart.code]: textStreamPart,
[errorStreamPart.code]: errorStreamPart,
[assistantMessageStreamPart.code]: assistantMessageStreamPart,
[assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
[dataMessageStreamPart.code]: dataMessageStreamPart
};
var StreamStringPrefixes = {
[textStreamPart.name]: textStreamPart.code,
[errorStreamPart.name]: errorStreamPart.code,
[assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
[assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
[dataMessageStreamPart.name]: dataMessageStreamPart.code
};
var validCodes = assistantStreamParts.map((part) => part.code);
function fixJson(input) {
const stack = ["ROOT"];
let lastValidIndex = -1;
let literalStart = null;
function processValueStart(char, i, swapState) {
{
switch (char) {
case '"': {
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_STRING");
break;
}
case "f":
case "t":
case "n": {
lastValidIndex = i;
literalStart = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_LITERAL");
break;
}
case "-": {
stack.pop();
stack.push(swapState);
stack.push("INSIDE_NUMBER");
break;
}
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": {
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_NUMBER");
break;
}
case "{": {
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_OBJECT_START");
break;
}
case "[": {
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_ARRAY_START");
break;
}
}
}
}
function processAfterObjectValue(char, i) {
switch (char) {
case ",": {
stack.pop();
stack.push("INSIDE_OBJECT_AFTER_COMMA");
break;
}
case "}": {
lastValidIndex = i;
stack.pop();
break;
}
}
}
function processAfterArrayValue(char, i) {
switch (char) {
case ",": {
stack.pop();
stack.push("INSIDE_ARRAY_AFTER_COMMA");
break;
}
case "]": {
lastValidIndex = i;
stack.pop();
break;
}
}
}
for (let i = 0;i < input.length; i++) {
const char = input[i];
const currentState = stack[stack.length - 1];
switch (currentState) {
case "ROOT":
processValueStart(char, i, "FINISH");
break;
case "INSIDE_OBJECT_START": {
switch (char) {
case '"': {
stack.pop();
stack.push("INSIDE_OBJECT_KEY");
break;
}
case "}": {
lastValidIndex = i;
stack.pop();
break;
}
}
break;
}
case "INSIDE_OBJECT_AFTER_COMMA": {
switch (char) {
case '"': {
stack.pop();
stack.push("INSIDE_OBJECT_KEY");
break;
}
}
break;
}
case "INSIDE_OBJECT_KEY": {
switch (char) {
case '"': {
stack.pop();
stack.push("INSIDE_OBJECT_AFTER_KEY");
break;
}
}
break;
}
case "INSIDE_OBJECT_AFTER_KEY": {
switch (char) {
case ":": {
stack.pop();
stack.push("INSIDE_OBJECT_BEFORE_VALUE");
break;
}
}
break;
}
case "INSIDE_OBJECT_BEFORE_VALUE": {
processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
break;
}
case "INSIDE_OBJECT_AFTER_VALUE": {
processAfterObjectValue(char, i);
break;
}
case "INSIDE_STRING": {
switch (char) {
case '"': {
stack.pop();
lastValidIndex = i;
break;
}
case "\\": {
stack.push("INSIDE_STRING_ESCAPE");
break;
}
default: {
lastValidIndex = i;
}
}
break;
}
case "INSIDE_ARRAY_START": {
switch (char) {
case "]": {
lastValidIndex = i;
stack.pop();
break;
}
default: {
lastValidIndex = i;
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
break;
}
}
break;
}
case "INSIDE_ARRAY_AFTER_VALUE": {
switch (char) {
case ",": {
stack.pop();
stack.push("INSIDE_ARRAY_AFTER_COMMA");
break;
}
case "]": {
lastValidIndex = i;
stack.pop();
break;
}
default: {
lastValidIndex = i;
break;
}
}
break;
}
case "INSIDE_ARRAY_AFTER_COMMA": {
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
break;
}
case "INSIDE_STRING_ESCAPE": {
stack.pop();
lastValidIndex = i;
break;
}
case "INSIDE_NUMBER": {
switch (char) {
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": {
lastValidIndex = i;
break;
}
case "e":
case "E":
case "-":
case ".": {
break;
}
case ",": {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
processAfterArrayValue(char, i);
}
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
processAfterObjectValue(char, i);
}
break;
}
case "}": {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
processAfterObjectValue(char, i);
}
break;
}
case "]": {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
processAfterArrayValue(char, i);
}
break;
}
default: {
stack.pop();
break;
}
}
break;
}
case "INSIDE_LITERAL": {
const partialLiteral = input.substring(literalStart, i + 1);
if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
processAfterObjectValue(char, i);
} else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
processAfterArrayValue(char, i);
}
} else {
lastValidIndex = i;
}
break;
}
}
}
let result = input.slice(0, lastValidIndex + 1);
for (let i = stack.length - 1;i >= 0; i--) {
const state = stack[i];
switch (state) {
case "INSIDE_STRING": {
result += '"';
break;
}
case "INSIDE_OBJECT_KEY":
case "INSIDE_OBJECT_AFTER_KEY":
case "INSIDE_OBJECT_AFTER_COMMA":
case "INSIDE_OBJECT_START":
case "INSIDE_OBJECT_BEFORE_VALUE":
case "INSIDE_OBJECT_AFTER_VALUE": {
result += "}";
break;
}
case "INSIDE_ARRAY_START":
case "INSIDE_ARRAY_AFTER_COMMA":
case "INSIDE_ARRAY_AFTER_VALUE": {
result += "]";
break;
}
case "INSIDE_LITERAL": {
const partialLiteral = input.substring(literalStart, input.length);
if ("true".startsWith(partialLiteral)) {
result += "true".slice(partialLiteral.length);
} else if ("false".startsWith(partialLiteral)) {
result += "false".slice(partialLiteral.length);
} else if ("null".startsWith(partialLiteral)) {
result += "null".slice(partialLiteral.length);
}
}
}
}
return result;
}
function parsePartialJson(jsonText) {
if (jsonText === undefined) {
return { value: undefined, state: "undefined-input" };
}
let result = safeParseJSON({ text: jsonText });
if (result.success) {
return { value: result.value, state: "successful-parse" };
}
result = safeParseJSON({ text: fixJson(jsonText) });
if (result.success) {
return { value: result.value, state: "repaired-parse" };
}
return { value: undefined, state: "failed-parse" };
}
var textStreamPart2 = {
code: "0",
name: "text",
parse: (value) => {
if (typeof value !== "string") {
throw new Error('"text" parts expect a string value.');
}
return { type: "text", value };
}
};
var dataStreamPart = {
code: "2",
name: "data",
parse: (value) => {
if (!Array.isArray(value)) {
throw new Error('"data" parts expect an array value.');
}
return { type: "data", value };
}
};
var errorStreamPart2 = {
code: "3",
name: "error",
parse: (value) => {
if (typeof value !== "string") {
throw new Error('"error" parts expect a string value.');
}
return { type: "error", value };
}
};
var messageAnnotationsStreamPart = {
code: "8",
name: "message_annotations",
parse: (value) => {
if (!Array.isArray(value)) {
throw new Error('"message_annotations" parts expect an array value.');
}
return { type: "message_annotations", value };
}
};
var toolCallStreamPart = {
code: "9",
name: "tool_call",
parse: (value) => {
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
throw new Error('"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.');
}
return {
type: "tool_call",
value
};
}
};
var toolResultStreamPart = {
code: "a",
name: "tool_result",
parse: (value) => {
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) {
throw new Error('"tool_result" parts expect an object with a "toolCallId" and a "result" property.');
}
return {
type: "tool_result",
value
};
}
};
var toolCallStreamingStartStreamPart = {
code: "b",
name: "tool_call_streaming_start",
parse: (value) => {
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") {
throw new Error('"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.');
}
return {
type: "tool_call_streaming_start",
value
};
}
};
var toolCallDeltaStreamPart = {
code: "c",
name: "tool_call_delta",
parse: (value) => {
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") {
throw new Error('"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.');
}
return {
type: "tool_call_delta",
value
};
}
};
var finishMessageStreamPart = {
code: "d",
name: "finish_message",
parse: (value) => {
if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
throw new Error('"finish_message" parts expect an object with a "finishReason" property.');
}
const result = {
finishReason: value.finishReason
};
if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
result.usage = {
promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
};
}
return {
type: "finish_message",
value: result
};
}
};
var finishStepStreamPart = {
code: "e",
name: "finish_step",
parse: (value) => {
if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
throw new Error('"finish_step" parts expect an object with a "finishReason" property.');
}
const result = {
finishReason: value.finishReason,
isContinued: false
};
if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
result.usage = {
promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
};
}
if ("isContinued" in value && typeof value.isContinued === "boolean") {
result.isContinued = value.isContinued;
}
return {
type: "finish_step",
value: result
};
}
};
var startStepStreamPart = {
code: "f",
name: "start_step",
parse: (value) => {
if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") {
throw new Error('"start_step" parts expect an object with an "id" property.');
}
return {
type: "start_step",
value: {
messageId: value.messageId
}
};
}
};
var reasoningStreamPart = {
code: "g",
name: "reasoning",
parse: (value) => {
if (typeof value !== "string") {
throw new Error('"reasoning" parts expect a string value.');
}
return { type: "reasoning", value };
}
};
var sourcePart = {
code: "h",
name: "source",
parse: (value) => {
if (value == null || typeof value !== "object") {
throw new Error('"source" parts expect a Source object.');
}
return {
type: "source",
value
};
}
};
var redactedReasoningStreamPart = {
code: "i",
name: "redacted_reasoning",
parse: (value) => {
if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string") {
throw new Error('"redacted_reasoning" parts expect an object with a "data" property.');
}
return { type: "redacted_reasoning", value: { data: value.data } };
}
};
var reasoningSignatureStreamPart = {
code: "j",
name: "reasoning_signature",
parse: (value) => {
if (value == null || typeof value !== "object" || !("signature" in value) || typeof value.signature !== "string") {
throw new Error('"reasoning_signature" parts expect an object with a "signature" property.');
}
return {
type: "reasoning_signature",
value: { signature: value.signature }
};
}
};
var fileStreamPart = {
code: "k",
name: "file",
parse: (value) => {
if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string" || !("mimeType" in value) || typeof value.mimeType !== "string") {
throw new Error('"file" parts expect an object with a "data" and "mimeType" property.');
}
return { type: "file", value };
}
};
var dataStreamParts = [
textStreamPart2,
dataStreamPart,
errorStreamPart2,
messageAnnotationsStreamPart,
toolCallStreamPart,
toolResultStreamPart,
toolCallStreamingStartStreamPart,
toolCallDeltaStreamPart,
finishMessageStreamPart,
finishStepStreamPart,
startStepStreamPart,
reasoningStreamPart,
sourcePart,
redactedReasoningStreamPart,
reasoningSignatureStreamPart,
fileStreamPart
];
var dataStreamPartsByCode = Object.fromEntries(dataStreamParts.map((part) => [part.code, part]));
var DataStreamStringPrefixes = Object.fromEntries(dataStreamParts.map((part) => [part.name, part.code]));
var validCodes2 = dataStreamParts.map((part) => part.code);
function formatDataStreamPart(type, value) {
const streamPart = dataStreamParts.find((part) => part.name === type);
if (!streamPart) {
throw new Error(`Invalid stream part type: ${type}`);
}
return `${streamPart.code}:${JSON.stringify(value)}
`;
}
function zodSchema(zodSchema2, options) {
var _a15;
const useReferences = (_a15 = options == null ? undefined : options.useReferences) != null ? _a15 : false;
return jsonSchema(esm_default(zodSchema2, {
$refStrategy: useReferences ? "root" : "none",
target: "jsonSchema7"
}), {
validate: (value) => {
const result = zodSchema2.safeParse(value);
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
}
});
}
var schemaSymbol = Symbol.for("vercel.ai.schema");
function jsonSchema(jsonSchema2, {
validate
} = {}) {
return {
[schemaSymbol]: true,
_type: undefined,
[validatorSymbol]: true,
jsonSchema: jsonSchema2,
validate
};
}
function isSchema(value) {
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
}
function asSchema(schema) {
return isSchema(schema) ? schema : zodSchema(schema);
}
// node_modules/ai/dist/index.mjs
var import_api = __toESM(require_src(), 1);
var import_api2 = __toESM(require_src(), 1);
var __defProp2 = Object.defineProperty;
var __export2 = (target, all) => {
for (var name17 in all)
__defProp2(target, name17, { get: all[name17], enumerable: true });
};
function prepareResponseHeaders(headers, {
contentType,
dataStreamVersion
}) {
const responseHeaders = new Headers(headers != null ? headers : {});
if (!responseHeaders.has("Content-Type")) {
responseHeaders.set("Content-Type", contentType);
}
if (dataStreamVersion !== undefined) {
responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
}
return responseHeaders;
}
function prepareOutgoingHttpHeaders(headers, {
contentType,
dataStreamVersion
}) {
const outgoingHeaders = {};
if (headers != null) {
for (const [key, value] of Object.entries(headers)) {
outgoingHeaders[key] = value;
}
}
if (outgoingHeaders["Content-Type"] == null) {
outgoingHeaders["Content-Type"] = contentType;
}
if (dataStreamVersion !== undefined) {
outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
}
return outgoingHeaders;
}
function writeToServerResponse({
response,
status,
statusText,
headers,
stream
}) {
response.writeHead(status != null ? status : 200, statusText, headers);
const reader = stream.getReader();
const read = async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done)
break;
response.write(value);
}
} catch (error) {
throw error;
} finally {
response.end();
}
};
read();
}
var name14 = "AI_InvalidArgumentError";
var marker15 = `vercel.ai.error.${name14}`;
var symbol15 = Symbol.for(marker15);
var _a15;
var InvalidArgumentError2 = class extends AISDKError {
constructor({
parameter,
value,
message
}) {
super({
name: name14,
message: `Invalid argument for parameter ${parameter}: ${message}`
});
this[_a15] = true;
this.parameter = parameter;
this.value = value;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker15);
}
};
_a15 = symbol15;
var name22 = "AI_RetryError";
var marker22 = `vercel.ai.error.${name22}`;
var symbol22 = Symbol.for(marker22);
var _a22;
var RetryError = class extends AISDKError {
constructor({
message,
reason,
errors: errors2
}) {
super({ name: name22, message });
this[_a22] = true;
this.reason = reason;
this.errors = errors2;
this.lastError = errors2[errors2.length - 1];
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker22);
}
};
_a22 = symbol22;
var retryWithExponentialBackoff = ({
maxRetries = 2,
initialDelayInMs = 2000,
backoffFactor = 2
} = {}) => async (f) => _retryWithExponentialBackoff(f, {
maxRetries,
delayInMs: initialDelayInMs,
backoffFactor
});
async function _retryWithExponentialBackoff(f, {
maxRetries,
delayInMs,
backoffFactor
}, errors2 = []) {
try {
return await f();
} catch (error) {
if (isAbortError(error)) {
throw error;
}
if (maxRetries === 0) {
throw error;
}
const errorMessage = getErrorMessage2(error);
const newErrors = [...errors2, error];
const tryNumber = newErrors.length;
if (tryNumber > maxRetries) {
throw new RetryError({
message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
reason: "maxRetriesExceeded",
errors: newErrors
});
}
if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
await delay(delayInMs);
return _retryWithExponentialBackoff(f, { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor }, newErrors);
}
if (tryNumber === 1) {
throw error;
}
throw new RetryError({
message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
reason: "errorNotRetryable",
errors: newErrors
});
}
}
function prepareRetries({
maxRetries
}) {
if (maxRetries != null) {
if (!Number.isInteger(maxRetries)) {
throw new InvalidArgumentError2({
parameter: "maxRetries",
value: maxRetries,
message: "maxRetries must be an integer"
});
}
if (maxRetries < 0) {
throw new InvalidArgumentError2({
parameter: "maxRetries",
value: maxRetries,
message: "maxRetries must be >= 0"
});
}
}
const maxRetriesResult = maxRetries != null ? maxRetries : 2;
return {
maxRetries: maxRetriesResult,
retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
};
}
function assembleOperationName({
operationId,
telemetry
}) {
return {
"operation.name": `${operationId}${(telemetry == null ? undefined : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`,
"resource.name": telemetry == null ? undefined : telemetry.functionId,
"ai.operationId": operationId,
"ai.telemetry.functionId": telemetry == null ? undefined : telemetry.functionId
};
}
function getBaseTelemetryAttributes({
model,
settings,
telemetry,
headers
}) {
var _a17;
return {
"ai.model.provider": model.provider,
"ai.model.id": model.modelId,
...Object.entries(settings).reduce((attributes, [key, value]) => {
attributes[`ai.settings.${key}`] = value;
return attributes;
}, {}),
...Object.entries((_a17 = telemetry == null ? undefined : telemetry.metadata) != null ? _a17 : {}).reduce((attributes, [key, value]) => {
attributes[`ai.telemetry.metadata.${key}`] = value;
return attributes;
}, {}),
...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {
if (value !== undefined) {
attributes[`ai.request.headers.${key}`] = value;
}
return attributes;
}, {})
};
}
var noopTracer = {
startSpan() {
return noopSpan;
},
startActiveSpan(name17, arg1, arg2, arg3) {
if (typeof arg1 === "function") {
return arg1(noopSpan);
}
if (typeof arg2 === "function") {
return arg2(noopSpan);
}
if (typeof arg3 === "function") {
return arg3(noopSpan);
}
}
};
var noopSpan = {
spanContext() {
return noopSpanContext;
},
setAttribute() {
return this;
},
setAttributes() {
return this;
},
addEvent() {
return this;
},
addLink() {
return this;
},
addLinks() {
return this;
},
setStatus() {
return this;
},
updateName() {
return this;
},
end() {
return this;
},
isRecording() {
return false;
},
recordException() {
return this;
}
};
var noopSpanContext = {
traceId: "",
spanId: "",
traceFlags: 0
};
function getTracer({
isEnabled = false,
tracer
} = {}) {
if (!isEnabled) {
return noopTracer;
}
if (tracer) {
return tracer;
}
return import_api.trace.getTracer("ai");
}
function recordSpan({
name: name17,
tracer,
attributes,
fn,
endWhenDone = true
}) {
return tracer.startActiveSpan(name17, { attributes }, async (span) => {
try {
const result = await fn(span);
if (endWhenDone) {
span.end();
}
return result;
} catch (error) {
try {
if (error instanceof Error) {
span.recordException({
name: error.name,
message: error.message,
stack: error.stack
});
span.setStatus({
code: import_api2.SpanStatusCode.ERROR,
message: error.message
});
} else {
span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
}
} finally {
span.end();
}
throw error;
}
});
}
function selectTelemetryAttributes({
telemetry,
attributes
}) {
if ((telemetry == null ? undefined : telemetry.isEnabled) !== true) {
return {};
}
return Object.entries(attributes).reduce((attributes2, [key, value]) => {
if (value === undefined) {
return attributes2;
}
if (typeof value === "object" && "input" in value && typeof value.input === "function") {
if ((telemetry == null ? undefined : telemetry.recordInputs) === false) {
return attributes2;
}
const result = value.input();
return result === undefined ? attributes2 : { ...attributes2, [key]: result };
}
if (typeof value === "object" && "output" in value && typeof value.output === "function") {
if ((telemetry == null ? undefined : telemetry.recordOutputs) === false) {
return attributes2;
}
const result = value.output();
return result === undefined ? attributes2 : { ...attributes2, [key]: result };
}
return { ...attributes2, [key]: value };
}, {});
}
var name32 = "AI_NoImageGeneratedError";
var marker32 = `vercel.ai.error.${name32}`;
var symbol32 = Symbol.for(marker32);
var _a32;
_a32 = symbol32;
var DefaultGeneratedFile = class {
constructor({
data,
mimeType
}) {
const isUint8Array = data instanceof Uint8Array;
this.base64Data = isUint8Array ? undefined : data;
this.uint8ArrayData = isUint8Array ? data : undefined;
this.mimeType = mimeType;
}
get base64() {
if (this.base64Data == null) {
this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
}
return this.base64Data;
}
get uint8Array() {
if (this.uint8ArrayData == null) {
this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);
}
return this.uint8ArrayData;
}
};
var DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {
constructor(options) {
super(options);
this.type = "file";
}
};
var imageMimeTypeSignatures = [
{
mimeType: "image/gif",
bytesPrefix: [71, 73, 70],
base64Prefix: "R0lG"
},
{
mimeType: "image/png",
bytesPrefix: [137, 80, 78, 71],
base64Prefix: "iVBORw"
},
{
mimeType: "image/jpeg",
bytesPrefix: [255, 216],
base64Prefix: "/9j/"
},
{
mimeType: "image/webp",
bytesPrefix: [82, 73, 70, 70],
base64Prefix: "UklGRg"
},
{
mimeType: "image/bmp",
bytesPrefix: [66, 77],
base64Prefix: "Qk"
},
{
mimeType: "image/tiff",
bytesPrefix: [73, 73, 42, 0],
base64Prefix: "SUkqAA"
},
{
mimeType: "image/tiff",
bytesPrefix: [77, 77, 0, 42],
base64Prefix: "TU0AKg"
},
{
mimeType: "image/avif",
bytesPrefix: [
0,
0,
0,
32,
102,
116,
121,
112,
97,
118,
105,
102
],
base64Prefix: "AAAAIGZ0eXBhdmlm"
},
{
mimeType: "image/heic",
bytesPrefix: [
0,
0,
0,
32,
102,
116,
121,
112,
104,
101,
105,
99
],
base64Prefix: "AAAAIGZ0eXBoZWlj"
}
];
var stripID3 = (data) => {
const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data;
const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
return bytes.slice(id3Size + 10);
};
function stripID3TagsIfPresent(data) {
const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && data[1] === 68 && data[2] === 51;
return hasId3 ? stripID3(data) : data;
}
function detectMimeType({
data,
signatures
}) {
const processedData = stripID3TagsIfPresent(data);
for (const signature of signatures) {
if (typeof processedData === "string" ? processedData.startsWith(signature.base64Prefix) : processedData.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => processedData[index] === byte)) {
return signature.mimeType;
}
}
return;
}
var name42 = "AI_NoObjectGeneratedError";
var marker42 = `vercel.ai.error.${name42}`;
var symbol42 = Symbol.for(marker42);
var _a42;
var NoObjectGeneratedError = class extends AISDKError {
constructor({
message = "No object generated.",
cause,
text: text2,
response,
usage,
finishReason
}) {
super({ name: name42, message, cause });
this[_a42] = true;
this.text = text2;
this.response = response;
this.usage = usage;
this.finishReason = finishReason;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker42);
}
};
_a42 = symbol42;
var name52 = "AI_DownloadError";
var marker52 = `vercel.ai.error.${name52}`;
var symbol52 = Symbol.for(marker52);
var _a52;
var DownloadError = class extends AISDKError {
constructor({
url,
statusCode,
statusText,
cause,
message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
}) {
super({ name: name52, message, cause });
this[_a52] = true;
this.url = url;
this.statusCode = statusCode;
this.statusText = statusText;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker52);
}
};
_a52 = symbol52;
async function download({ url }) {
var _a17;
const urlText = url.toString();
try {
const response = await fetch(urlText);
if (!response.ok) {
throw new DownloadError({
url: urlText,
statusCode: response.status,
statusText: response.statusText
});
}
return {
data: new Uint8Array(await response.arrayBuffer()),
mimeType: (_a17 = response.headers.get("content-type")) != null ? _a17 : undefined
};
} catch (error) {
if (DownloadError.isInstance(error)) {
throw error;
}
throw new DownloadError({ url: urlText, cause: error });
}
}
var name62 = "AI_InvalidDataContentError";
var marker62 = `vercel.ai.error.${name62}`;
var symbol62 = Symbol.for(marker62);
var _a62;
var InvalidDataContentError = class extends AISDKError {
constructor({
content,
cause,
message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
}) {
super({ name: name62, message, cause });
this[_a62] = true;
this.content = content;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker62);
}
};
_a62 = symbol62;
var dataContentSchema = exports_external.union([
exports_external.string(),
exports_external.instanceof(Uint8Array),
exports_external.instanceof(ArrayBuffer),
exports_external.custom((value) => {
var _a17, _b;
return (_b = (_a17 = globalThis.Buffer) == null ? undefined : _a17.isBuffer(value)) != null ? _b : false;
}, { message: "Must be a Buffer" })
]);
function convertDataContentToBase64String(content) {
if (typeof content === "string") {
return content;
}
if (content instanceof ArrayBuffer) {
return convertUint8ArrayToBase64(new Uint8Array(content));
}
return convertUint8ArrayToBase64(content);
}
function convertDataContentToUint8Array(content) {
if (content instanceof Uint8Array) {
return content;
}
if (typeof content === "string") {
try {
return convertBase64ToUint8Array(content);
} catch (error) {
throw new InvalidDataContentError({
message: "Invalid data content. Content string is not a base64-encoded media.",
content,
cause: error
});
}
}
if (content instanceof ArrayBuffer) {
return new Uint8Array(content);
}
throw new InvalidDataContentError({ content });
}
function convertUint8ArrayToText(uint8Array) {
try {
return new TextDecoder().decode(uint8Array);
} catch (error) {
throw new Error("Error decoding Uint8Array to text");
}
}
var name72 = "AI_InvalidMessageRoleError";
var marker72 = `vercel.ai.error.${name72}`;
var symbol72 = Symbol.for(marker72);
var _a72;
var InvalidMessageRoleError = class extends AISDKError {
constructor({
role,
message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
}) {
super({ name: name72, message });
this[_a72] = true;
this.role = role;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker72);
}
};
_a72 = symbol72;
function splitDataUrl(dataUrl) {
try {
const [header, base64Content] = dataUrl.split(",");
return {
mimeType: header.split(";")[0].split(":")[1],
base64Content
};
} catch (error) {
return {
mimeType: undefined,
base64Content: undefined
};
}
}
async function convertToLanguageModelPrompt({
prompt,
modelSupportsImageUrls = true,
modelSupportsUrl = () => false,
downloadImplementation = download
}) {
const downloadedAssets = await downloadAssets(prompt.messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl);
return [
...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
...prompt.messages.map((message) => convertToLanguageModelMessage(message, downloadedAssets))
];
}
function convertToLanguageModelMessage(message, downloadedAssets) {
var _a17, _b, _c, _d, _e, _f;
const role = message.role;
switch (role) {
case "system": {
return {
role: "system",
content: message.content,
providerMetadata: (_a17 = message.providerOptions) != null ? _a17 : message.experimental_providerMetadata
};
}
case "user": {
if (typeof message.content === "string") {
return {
role: "user",
content: [{ type: "text", text: message.content }],
providerMetadata: (_b = message.providerOptions) != null ? _b : message.experimental_providerMetadata
};
}
return {
role: "user",
content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
providerMetadata: (_c = message.providerOptions) != null ? _c : message.experimental_providerMetadata
};
}
case "assistant": {
if (typeof message.content === "string") {
return {
role: "assistant",
content: [{ type: "text", text: message.content }],
providerMetadata: (_d = message.providerOptions) != null ? _d : message.experimental_providerMetadata
};
}
return {
role: "assistant",
content: message.content.filter((part) => part.type !== "text" || part.text !== "").map((part) => {
var _a18;
const providerOptions = (_a18 = part.providerOptions) != null ? _a18 : part.experimental_providerMetadata;
switch (part.type) {
case "file": {
return {
type: "file",
data: part.data instanceof URL ? part.data : convertDataContentToBase64String(part.data),
filename: part.filename,
mimeType: part.mimeType,
providerMetadata: providerOptions
};
}
case "reasoning": {
return {
type: "reasoning",
text: part.text,
signature: part.signature,
providerMetadata: providerOptions
};
}
case "redacted-reasoning": {
return {
type: "redacted-reasoning",
data: part.data,
providerMetadata: providerOptions
};
}
case "text": {
return {
type: "text",
text: part.text,
providerMetadata: providerOptions
};
}
case "tool-call": {
return {
type: "tool-call",
toolCallId: part.toolCallId,
toolName: part.toolName,
args: part.args,
providerMetadata: providerOptions
};
}
}
}),
providerMetadata: (_e = message.providerOptions) != null ? _e : message.experimental_providerMetadata
};
}
case "tool": {
return {
role: "tool",
content: message.content.map((part) => {
var _a18;
return {
type: "tool-result",
toolCallId: part.toolCallId,
toolName: part.toolName,
result: part.result,
content: part.experimental_content,
isError: part.isError,
providerMetadata: (_a18 = part.providerOptions) != null ? _a18 : part.experimental_providerMetadata
};
}),
providerMetadata: (_f = message.providerOptions) != null ? _f : message.experimental_providerMetadata
};
}
default: {
const _exhaustiveCheck = role;
throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
}
}
}
async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter((content) => Array.isArray(content)).flat().filter((part) => part.type === "image" || part.type === "file").filter((part) => !(part.type === "image" && modelSupportsImageUrls === true)).map((part) => part.type === "image" ? part.image : part.data).map((part) => typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
const downloadedImages = await Promise.all(urls.map(async (url) => ({
url,
data: await downloadImplementation({ url })
})));
return Object.fromEntries(downloadedImages.map(({ url, data }) => [url.toString(), data]));
}
function convertPartToLanguageModelPart(part, downloadedAssets) {
var _a17, _b, _c, _d;
if (part.type === "text") {
return {
type: "text",
text: part.text,
providerMetadata: (_a17 = part.providerOptions) != null ? _a17 : part.experimental_providerMetadata
};
}
let mimeType = part.mimeType;
let data;
let content;
let normalizedData;
const type = part.type;
switch (type) {
case "image":
data = part.image;
break;
case "file":
data = part.data;
break;
default:
throw new Error(`Unsupported part type: ${type}`);
}
try {
content = typeof data === "string" ? new URL(data) : data;
} catch (error) {
content = data;
}
if (content instanceof URL) {
if (content.protocol === "data:") {
const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(content.toString());
if (dataUrlMimeType == null || base64Content == null) {
throw new Error(`Invalid data URL format in part ${type}`);
}
mimeType = dataUrlMimeType;
normalizedData = convertDataContentToUint8Array(base64Content);
} else {
const downloadedFile = downloadedAssets[content.toString()];
if (downloadedFile) {
normalizedData = downloadedFile.data;
mimeType != null || (mimeType = downloadedFile.mimeType);
} else {
normalizedData = content;
}
}
} else {
normalizedData = convertDataContentToUint8Array(content);
}
switch (type) {
case "image": {
if (normalizedData instanceof Uint8Array) {
mimeType = (_b = detectMimeType({
data: normalizedData,
signatures: imageMimeTypeSignatures
})) != null ? _b : mimeType;
}
return {
type: "image",
image: normalizedData,
mimeType,
providerMetadata: (_c = part.providerOptions) != null ? _c : part.experimental_providerMetadata
};
}
case "file": {
if (mimeType == null) {
throw new Error(`Mime type is missing for file part`);
}
return {
type: "file",
data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
filename: part.filename,
mimeType,
providerMetadata: (_d = part.providerOptions) != null ? _d : part.experimental_providerMetadata
};
}
}
}
function prepareCallSettings({
maxTokens,
temperature,
topP,
topK,
presencePenalty,
frequencyPenalty,
stopSequences,
seed
}) {
if (maxTokens != null) {
if (!Number.isInteger(maxTokens)) {
throw new InvalidArgumentError2({
parameter: "maxTokens",
value: maxTokens,
message: "maxTokens must be an integer"
});
}
if (maxTokens < 1) {
throw new InvalidArgumentError2({
parameter: "maxTokens",
value: maxTokens,
message: "maxTokens must be >= 1"
});
}
}
if (temperature != null) {
if (typeof temperature !== "number") {
throw new InvalidArgumentError2({
parameter: "temperature",
value: temperature,
message: "temperature must be a number"
});
}
}
if (topP != null) {
if (typeof topP !== "number") {
throw new InvalidArgumentError2({
parameter: "topP",
value: topP,
message: "topP must be a number"
});
}
}
if (topK != null) {
if (typeof topK !== "number") {
throw new InvalidArgumentError2({
parameter: "topK",
value: topK,
message: "topK must be a number"
});
}
}
if (presencePenalty != null) {
if (typeof presencePenalty !== "number") {
throw new InvalidArgumentError2({
parameter: "presencePenalty",
value: presencePenalty,
message: "presencePenalty must be a number"
});
}
}
if (frequencyPenalty != null) {
if (typeof frequencyPenalty !== "number") {
throw new InvalidArgumentError2({
parameter: "frequencyPenalty",
value: frequencyPenalty,
message: "frequencyPenalty must be a number"
});
}
}
if (seed != null) {
if (!Number.isInteger(seed)) {
throw new InvalidArgumentError2({
parameter: "seed",
value: seed,
message: "seed must be an integer"
});
}
}
return {
maxTokens,
temperature: temperature != null ? temperature : 0,
topP,
topK,
presencePenalty,
frequencyPenalty,
stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : undefined,
seed
};
}
function attachmentsToParts(attachments) {
var _a17, _b, _c;
const parts = [];
for (const attachment of attachments) {
let url;
try {
url = new URL(attachment.url);
} catch (error) {
throw new Error(`Invalid URL: ${attachment.url}`);
}
switch (url.protocol) {
case "http:":
case "https:": {
if ((_a17 = attachment.contentType) == null ? undefined : _a17.startsWith("image/")) {
parts.push({ type: "image", image: url });
} else {
if (!attachment.contentType) {
throw new Error("If the attachment is not an image, it must specify a content type");
}
parts.push({
type: "file",
data: url,
mimeType: attachment.contentType
});
}
break;
}
case "data:": {
let header;
let base64Content;
let mimeType;
try {
[header, base64Content] = attachment.url.split(",");
mimeType = header.split(";")[0].split(":")[1];
} catch (error) {
throw new Error(`Error processing data URL: ${attachment.url}`);
}
if (mimeType == null || base64Content == null) {
throw new Error(`Invalid data URL format: ${attachment.url}`);
}
if ((_b = attachment.contentType) == null ? undefined : _b.startsWith("image/")) {
parts.push({
type: "image",
image: convertDataContentToUint8Array(base64Content)
});
} else if ((_c = attachment.contentType) == null ? undefined : _c.startsWith("text/")) {
parts.push({
type: "text",
text: convertUint8ArrayToText(convertDataContentToUint8Array(base64Content))
});
} else {
if (!attachment.contentType) {
throw new Error("If the attachment is not an image or text, it must specify a content type");
}
parts.push({
type: "file",
data: base64Content,
mimeType: attachment.contentType
});
}
break;
}
default: {
throw new Error(`Unsupported URL protocol: ${url.protocol}`);
}
}
}
return parts;
}
var name82 = "AI_MessageConversionError";
var marker82 = `vercel.ai.error.${name82}`;
var symbol82 = Symbol.for(marker82);
var _a82;
var MessageConversionError = class extends AISDKError {
constructor({
originalMessage,
message
}) {
super({ name: name82, message });
this[_a82] = true;
this.originalMessage = originalMessage;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker82);
}
};
_a82 = symbol82;
function convertToCoreMessages(messages, options) {
var _a17, _b;
const tools = (_a17 = options == null ? undefined : options.tools) != null ? _a17 : {};
const coreMessages = [];
for (let i = 0;i < messages.length; i++) {
const message = messages[i];
const isLastMessage = i === messages.length - 1;
const { role, content, experimental_attachments } = message;
switch (role) {
case "system": {
coreMessages.push({
role: "system",
content
});
break;
}
case "user": {
if (message.parts == null) {
coreMessages.push({
role: "user",
content: experimental_attachments ? [
{ type: "text", text: content },
...attachmentsToParts(experimental_attachments)
] : content
});
} else {
const textParts = message.parts.filter((part) => part.type === "text").map((part) => ({
type: "text",
text: part.text
}));
coreMessages.push({
role: "user",
content: experimental_attachments ? [...textParts, ...attachmentsToParts(experimental_attachments)] : textParts
});
}
break;
}
case "assistant": {
if (message.parts != null) {
let processBlock2 = function() {
const content2 = [];
for (const part of block) {
switch (part.type) {
case "file":
case "text": {
content2.push(part);
break;
}
case "reasoning": {
for (const detail of part.details) {
switch (detail.type) {
case "text":
content2.push({
type: "reasoning",
text: detail.text,
signature: detail.signature
});
break;
case "redacted":
content2.push({
type: "redacted-reasoning",
data: detail.data
});
break;
}
}
break;
}
case "tool-invocation":
content2.push({
type: "tool-call",
toolCallId: part.toolInvocation.toolCallId,
toolName: part.toolInvocation.toolName,
args: part.toolInvocation.args
});
break;
default: {
const _exhaustiveCheck = part;
throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
}
}
}
coreMessages.push({
role: "assistant",
content: content2
});
const stepInvocations = block.filter((part) => part.type === "tool-invocation").map((part) => part.toolInvocation);
if (stepInvocations.length > 0) {
coreMessages.push({
role: "tool",
content: stepInvocations.map((toolInvocation) => {
if (!("result" in toolInvocation)) {
throw new MessageConversionError({
originalMessage: message,
message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
});
}
const { toolCallId, toolName, result } = toolInvocation;
const tool2 = tools[toolName];
return (tool2 == null ? undefined : tool2.experimental_toToolResultContent) != null ? {
type: "tool-result",
toolCallId,
toolName,
result: tool2.experimental_toToolResultContent(result),
experimental_content: tool2.experimental_toToolResultContent(result)
} : {
type: "tool-result",
toolCallId,
toolName,
result
};
})
});
}
block = [];
blockHasToolInvocations = false;
currentStep++;
};
var processBlock = processBlock2;
let currentStep = 0;
let blockHasToolInvocations = false;
let block = [];
for (const part of message.parts) {
switch (part.type) {
case "text": {
if (blockHasToolInvocations) {
processBlock2();
}
block.push(part);
break;
}
case "file":
case "reasoning": {
block.push(part);
break;
}
case "tool-invocation": {
if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
processBlock2();
}
block.push(part);
blockHasToolInvocations = true;
break;
}
}
}
processBlock2();
break;
}
const toolInvocations = message.toolInvocations;
if (toolInvocations == null || toolInvocations.length === 0) {
coreMessages.push({ role: "assistant", content });
break;
}
const maxStep = toolInvocations.reduce((max, toolInvocation) => {
var _a18;
return Math.max(max, (_a18 = toolInvocation.step) != null ? _a18 : 0);
}, 0);
for (let i2 = 0;i2 <= maxStep; i2++) {
const stepInvocations = toolInvocations.filter((toolInvocation) => {
var _a18;
return ((_a18 = toolInvocation.step) != null ? _a18 : 0) === i2;
});
if (stepInvocations.length === 0) {
continue;
}
coreMessages.push({
role: "assistant",
content: [
...isLastMessage && content && i2 === 0 ? [{ type: "text", text: content }] : [],
...stepInvocations.map(({ toolCallId, toolName, args }) => ({
type: "tool-call",
toolCallId,
toolName,
args
}))
]
});
coreMessages.push({
role: "tool",
content: stepInvocations.map((toolInvocation) => {
if (!("result" in toolInvocation)) {
throw new MessageConversionError({
originalMessage: message,
message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
});
}
const { toolCallId, toolName, result } = toolInvocation;
const tool2 = tools[toolName];
return (tool2 == null ? undefined : tool2.experimental_toToolResultContent) != null ? {
type: "tool-result",
toolCallId,
toolName,
result: tool2.experimental_toToolResultContent(result),
experimental_content: tool2.experimental_toToolResultContent(result)
} : {
type: "tool-result",
toolCallId,
toolName,
result
};
})
});
}
if (content && !isLastMessage) {
coreMessages.push({ role: "assistant", content });
}
break;
}
case "data": {
break;
}
default: {
const _exhaustiveCheck = role;
throw new MessageConversionError({
originalMessage: message,
message: `Unsupported role: ${_exhaustiveCheck}`
});
}
}
}
return coreMessages;
}
var jsonValueSchema = exports_external.lazy(() => exports_external.union([
exports_external.null(),
exports_external.string(),
exports_external.number(),
exports_external.boolean(),
exports_external.record(exports_external.string(), jsonValueSchema),
exports_external.array(jsonValueSchema)
]));
var providerMetadataSchema = exports_external.record(exports_external.string(), exports_external.record(exports_external.string(), jsonValueSchema));
var toolResultContentSchema = exports_external.array(exports_external.union([
exports_external.object({ type: exports_external.literal("text"), text: exports_external.string() }),
exports_external.object({
type: exports_external.literal("image"),
data: exports_external.string(),
mimeType: exports_external.string().optional()
})
]));
var textPartSchema = exports_external.object({
type: exports_external.literal("text"),
text: exports_external.string(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var imagePartSchema = exports_external.object({
type: exports_external.literal("image"),
image: exports_external.union([dataContentSchema, exports_external.instanceof(URL)]),
mimeType: exports_external.string().optional(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var filePartSchema = exports_external.object({
type: exports_external.literal("file"),
data: exports_external.union([dataContentSchema, exports_external.instanceof(URL)]),
filename: exports_external.string().optional(),
mimeType: exports_external.string(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var reasoningPartSchema = exports_external.object({
type: exports_external.literal("reasoning"),
text: exports_external.string(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var redactedReasoningPartSchema = exports_external.object({
type: exports_external.literal("redacted-reasoning"),
data: exports_external.string(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var toolCallPartSchema = exports_external.object({
type: exports_external.literal("tool-call"),
toolCallId: exports_external.string(),
toolName: exports_external.string(),
args: exports_external.unknown(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var toolResultPartSchema = exports_external.object({
type: exports_external.literal("tool-result"),
toolCallId: exports_external.string(),
toolName: exports_external.string(),
result: exports_external.unknown(),
content: toolResultContentSchema.optional(),
isError: exports_external.boolean().optional(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreSystemMessageSchema = exports_external.object({
role: exports_external.literal("system"),
content: exports_external.string(),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreUserMessageSchema = exports_external.object({
role: exports_external.literal("user"),
content: exports_external.union([
exports_external.string(),
exports_external.array(exports_external.union([textPartSchema, imagePartSchema, filePartSchema]))
]),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreAssistantMessageSchema = exports_external.object({
role: exports_external.literal("assistant"),
content: exports_external.union([
exports_external.string(),
exports_external.array(exports_external.union([
textPartSchema,
filePartSchema,
reasoningPartSchema,
redactedReasoningPartSchema,
toolCallPartSchema
]))
]),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreToolMessageSchema = exports_external.object({
role: exports_external.literal("tool"),
content: exports_external.array(toolResultPartSchema),
providerOptions: providerMetadataSchema.optional(),
experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreMessageSchema = exports_external.union([
coreSystemMessageSchema,
coreUserMessageSchema,
coreAssistantMessageSchema,
coreToolMessageSchema
]);
function standardizePrompt({
prompt,
tools
}) {
if (prompt.prompt == null && prompt.messages == null) {
throw new InvalidPromptError({
prompt,
message: "prompt or messages must be defined"
});
}
if (prompt.prompt != null && prompt.messages != null) {
throw new InvalidPromptError({
prompt,
message: "prompt and messages cannot be defined at the same time"
});
}
if (prompt.system != null && typeof prompt.system !== "string") {
throw new InvalidPromptError({
prompt,
message: "system must be a string"
});
}
if (prompt.prompt != null) {
if (typeof prompt.prompt !== "string") {
throw new InvalidPromptError({
prompt,
message: "prompt must be a string"
});
}
return {
type: "prompt",
system: prompt.system,
messages: [
{
role: "user",
content: prompt.prompt
}
]
};
}
if (prompt.messages != null) {
const promptType = detectPromptType(prompt.messages);
const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
tools
}) : prompt.messages;
if (messages.length === 0) {
throw new InvalidPromptError({
prompt,
message: "messages must not be empty"
});
}
const validationResult = safeValidateTypes({
value: messages,
schema: exports_external.array(coreMessageSchema)
});
if (!validationResult.success) {
throw new InvalidPromptError({
prompt,
message: [
"message must be a CoreMessage or a UI message",
`Validation error: ${validationResult.error.message}`
].join(`
`),
cause: validationResult.error
});
}
return {
type: "messages",
messages,
system: prompt.system
};
}
throw new Error("unreachable");
}
function detectPromptType(prompt) {
if (!Array.isArray(prompt)) {
throw new InvalidPromptError({
prompt,
message: [
"messages must be an array of CoreMessage or UIMessage",
`Received non-array value: ${JSON.stringify(prompt)}`
].join(`
`),
cause: prompt
});
}
if (prompt.length === 0) {
return "messages";
}
const characteristics = prompt.map(detectSingleMessageCharacteristics);
if (characteristics.some((c) => c === "has-ui-specific-parts")) {
return "ui-messages";
}
const nonMessageIndex = characteristics.findIndex((c) => c !== "has-core-specific-parts" && c !== "message");
if (nonMessageIndex === -1) {
return "messages";
}
throw new InvalidPromptError({
prompt,
message: [
"messages must be an array of CoreMessage or UIMessage",
`Received message of type: "${characteristics[nonMessageIndex]}" at index ${nonMessageIndex}`,
`messages[${nonMessageIndex}]: ${JSON.stringify(prompt[nonMessageIndex])}`
].join(`
`),
cause: prompt
});
}
function detectSingleMessageCharacteristics(message) {
if (typeof message === "object" && message !== null && (message.role === "function" || message.role === "data" || ("toolInvocations" in message) || ("parts" in message) || ("experimental_attachments" in message))) {
return "has-ui-specific-parts";
} else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || ("experimental_providerMetadata" in message) || ("providerOptions" in message))) {
return "has-core-specific-parts";
} else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
return "message";
} else {
return "other";
}
}
function calculateLanguageModelUsage({
promptTokens,
completionTokens
}) {
return {
promptTokens,
completionTokens,
totalTokens: promptTokens + completionTokens
};
}
function addLanguageModelUsage(usage1, usage2) {
return {
promptTokens: usage1.promptTokens + usage2.promptTokens,
completionTokens: usage1.completionTokens + usage2.completionTokens,
totalTokens: usage1.totalTokens + usage2.totalTokens
};
}
var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
function injectJsonInstruction({
prompt,
schema,
schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : undefined,
schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
}) {
return [
prompt != null && prompt.length > 0 ? prompt : undefined,
prompt != null && prompt.length > 0 ? "" : undefined,
schemaPrefix,
schema != null ? JSON.stringify(schema) : undefined,
schemaSuffix
].filter((line) => line != null).join(`
`);
}
function createAsyncIterableStream(source) {
const stream = source.pipeThrough(new TransformStream);
stream[Symbol.asyncIterator] = () => {
const reader = stream.getReader();
return {
async next() {
const { done, value } = await reader.read();
return done ? { done: true, value: undefined } : { done: false, value };
}
};
};
return stream;
}
function stringifyForTelemetry(prompt) {
const processedPrompt = prompt.map((message) => {
return {
...message,
content: typeof message.content === "string" ? message.content : message.content.map(processPart)
};
});
return JSON.stringify(processedPrompt);
}
function processPart(part) {
if (part.type === "image") {
return {
...part,
image: part.image instanceof Uint8Array ? convertDataContentToBase64String(part.image) : part.image
};
}
return part;
}
var originalGenerateId = createIdGenerator({ prefix: "aiobj", size: 24 });
var DelayedPromise = class {
constructor() {
this.status = { type: "pending" };
this._resolve = undefined;
this._reject = undefined;
}
get value() {
if (this.promise) {
return this.promise;
}
this.promise = new Promise((resolve, reject) => {
if (this.status.type === "resolved") {
resolve(this.status.value);
} else if (this.status.type === "rejected") {
reject(this.status.error);
}
this._resolve = resolve;
this._reject = reject;
});
return this.promise;
}
resolve(value) {
var _a17;
this.status = { type: "resolved", value };
if (this.promise) {
(_a17 = this._resolve) == null || _a17.call(this, value);
}
}
reject(error) {
var _a17;
this.status = { type: "rejected", error };
if (this.promise) {
(_a17 = this._reject) == null || _a17.call(this, error);
}
}
};
function createResolvablePromise() {
let resolve;
let reject;
const promise2 = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return {
promise: promise2,
resolve,
reject
};
}
function createStitchableStream() {
let innerStreamReaders = [];
let controller = null;
let isClosed = false;
let waitForNewStream = createResolvablePromise();
const processPull = async () => {
if (isClosed && innerStreamReaders.length === 0) {
controller == null || controller.close();
return;
}
if (innerStreamReaders.length === 0) {
waitForNewStream = createResolvablePromise();
await waitForNewStream.promise;
return processPull();
}
try {
const { value, done } = await innerStreamReaders[0].read();
if (done) {
innerStreamReaders.shift();
if (innerStreamReaders.length > 0) {
await processPull();
} else if (isClosed) {
controller == null || controller.close();
}
} else {
controller == null || controller.enqueue(value);
}
} catch (error) {
controller == null || controller.error(error);
innerStreamReaders.shift();
if (isClosed && innerStreamReaders.length === 0) {
controller == null || controller.close();
}
}
};
return {
stream: new ReadableStream({
start(controllerParam) {
controller = controllerParam;
},
pull: processPull,
async cancel() {
for (const reader of innerStreamReaders) {
await reader.cancel();
}
innerStreamReaders = [];
isClosed = true;
}
}),
addStream: (innerStream) => {
if (isClosed) {
throw new Error("Cannot add inner stream: outer stream is closed");
}
innerStreamReaders.push(innerStream.getReader());
waitForNewStream.resolve();
},
close: () => {
isClosed = true;
waitForNewStream.resolve();
if (innerStreamReaders.length === 0) {
controller == null || controller.close();
}
},
terminate: () => {
isClosed = true;
waitForNewStream.resolve();
innerStreamReaders.forEach((reader) => reader.cancel());
innerStreamReaders = [];
controller == null || controller.close();
}
};
}
function now() {
var _a17, _b;
return (_b = (_a17 = globalThis == null ? undefined : globalThis.performance) == null ? undefined : _a17.now()) != null ? _b : Date.now();
}
var originalGenerateId2 = createIdGenerator({ prefix: "aiobj", size: 24 });
var name92 = "AI_NoOutputSpecifiedError";
var marker92 = `vercel.ai.error.${name92}`;
var symbol92 = Symbol.for(marker92);
var _a92;
var NoOutputSpecifiedError = class extends AISDKError {
constructor({ message = "No output specified." } = {}) {
super({ name: name92, message });
this[_a92] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker92);
}
};
_a92 = symbol92;
var name102 = "AI_ToolExecutionError";
var marker102 = `vercel.ai.error.${name102}`;
var symbol102 = Symbol.for(marker102);
var _a102;
var ToolExecutionError = class extends AISDKError {
constructor({
toolArgs,
toolName,
toolCallId,
cause,
message = `Error executing tool ${toolName}: ${getErrorMessage(cause)}`
}) {
super({ name: name102, message, cause });
this[_a102] = true;
this.toolArgs = toolArgs;
this.toolName = toolName;
this.toolCallId = toolCallId;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker102);
}
};
_a102 = symbol102;
function isNonEmptyObject(object2) {
return object2 != null && Object.keys(object2).length > 0;
}
function prepareToolsAndToolChoice({
tools,
toolChoice,
activeTools
}) {
if (!isNonEmptyObject(tools)) {
return {
tools: undefined,
toolChoice: undefined
};
}
const filteredTools = activeTools != null ? Object.entries(tools).filter(([name17]) => activeTools.includes(name17)) : Object.entries(tools);
return {
tools: filteredTools.map(([name17, tool2]) => {
const toolType = tool2.type;
switch (toolType) {
case undefined:
case "function":
return {
type: "function",
name: name17,
description: tool2.description,
parameters: asSchema(tool2.parameters).jsonSchema
};
case "provider-defined":
return {
type: "provider-defined",
name: name17,
id: tool2.id,
args: tool2.args
};
default: {
const exhaustiveCheck = toolType;
throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
}
}
}),
toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
};
}
var lastWhitespaceRegexp = /^([\s\S]*?)(\s+)(\S*)$/;
function splitOnLastWhitespace(text2) {
const match = text2.match(lastWhitespaceRegexp);
return match ? { prefix: match[1], whitespace: match[2], suffix: match[3] } : undefined;
}
function removeTextAfterLastWhitespace(text2) {
const match = splitOnLastWhitespace(text2);
return match ? match.prefix + match.whitespace : text2;
}
var name112 = "AI_InvalidToolArgumentsError";
var marker112 = `vercel.ai.error.${name112}`;
var symbol112 = Symbol.for(marker112);
var _a112;
var InvalidToolArgumentsError = class extends AISDKError {
constructor({
toolArgs,
toolName,
cause,
message = `Invalid arguments for tool ${toolName}: ${getErrorMessage(cause)}`
}) {
super({ name: name112, message, cause });
this[_a112] = true;
this.toolArgs = toolArgs;
this.toolName = toolName;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker112);
}
};
_a112 = symbol112;
var name122 = "AI_NoSuchToolError";
var marker122 = `vercel.ai.error.${name122}`;
var symbol122 = Symbol.for(marker122);
var _a122;
var NoSuchToolError = class extends AISDKError {
constructor({
toolName,
availableTools = undefined,
message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === undefined ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
}) {
super({ name: name122, message });
this[_a122] = true;
this.toolName = toolName;
this.availableTools = availableTools;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker122);
}
};
_a122 = symbol122;
var name132 = "AI_ToolCallRepairError";
var marker132 = `vercel.ai.error.${name132}`;
var symbol132 = Symbol.for(marker132);
var _a132;
var ToolCallRepairError = class extends AISDKError {
constructor({
cause,
originalError,
message = `Error repairing tool call: ${getErrorMessage(cause)}`
}) {
super({ name: name132, message, cause });
this[_a132] = true;
this.originalError = originalError;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker132);
}
};
_a132 = symbol132;
async function parseToolCall({
toolCall,
tools,
repairToolCall,
system,
messages
}) {
if (tools == null) {
throw new NoSuchToolError({ toolName: toolCall.toolName });
}
try {
return await doParseToolCall({ toolCall, tools });
} catch (error) {
if (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolArgumentsError.isInstance(error))) {
throw error;
}
let repairedToolCall = null;
try {
repairedToolCall = await repairToolCall({
toolCall,
tools,
parameterSchema: ({ toolName }) => asSchema(tools[toolName].parameters).jsonSchema,
system,
messages,
error
});
} catch (repairError) {
throw new ToolCallRepairError({
cause: repairError,
originalError: error
});
}
if (repairedToolCall == null) {
throw error;
}
return await doParseToolCall({ toolCall: repairedToolCall, tools });
}
}
async function doParseToolCall({
toolCall,
tools
}) {
const toolName = toolCall.toolName;
const tool2 = tools[toolName];
if (tool2 == null) {
throw new NoSuchToolError({
toolName: toolCall.toolName,
availableTools: Object.keys(tools)
});
}
const schema = asSchema(tool2.parameters);
const parseResult = toolCall.args.trim() === "" ? safeValidateTypes({ value: {}, schema }) : safeParseJSON({ text: toolCall.args, schema });
if (parseResult.success === false) {
throw new InvalidToolArgumentsError({
toolName,
toolArgs: toolCall.args,
cause: parseResult.error
});
}
return {
type: "tool-call",
toolCallId: toolCall.toolCallId,
toolName,
args: parseResult.value
};
}
function asReasoningText(reasoning) {
const reasoningText = reasoning.filter((part) => part.type === "text").map((part) => part.text).join("");
return reasoningText.length > 0 ? reasoningText : undefined;
}
function toResponseMessages({
text: text2 = "",
files,
reasoning,
tools,
toolCalls,
toolResults,
messageId,
generateMessageId
}) {
const responseMessages = [];
const content = [];
if (reasoning.length > 0) {
content.push(...reasoning.map((part) => part.type === "text" ? { ...part, type: "reasoning" } : { ...part, type: "redacted-reasoning" }));
}
if (files.length > 0) {
content.push(...files.map((file) => ({
type: "file",
data: file.base64,
mimeType: file.mimeType
})));
}
if (text2.length > 0) {
content.push({ type: "text", text: text2 });
}
if (toolCalls.length > 0) {
content.push(...toolCalls);
}
if (content.length > 0) {
responseMessages.push({
role: "assistant",
content,
id: messageId
});
}
if (toolResults.length > 0) {
responseMessages.push({
role: "tool",
id: generateMessageId(),
content: toolResults.map((toolResult) => {
const tool2 = tools[toolResult.toolName];
return (tool2 == null ? undefined : tool2.experimental_toToolResultContent) != null ? {
type: "tool-result",
toolCallId: toolResult.toolCallId,
toolName: toolResult.toolName,
result: tool2.experimental_toToolResultContent(toolResult.result),
experimental_content: tool2.experimental_toToolResultContent(toolResult.result)
} : {
type: "tool-result",
toolCallId: toolResult.toolCallId,
toolName: toolResult.toolName,
result: toolResult.result
};
})
});
}
return responseMessages;
}
var originalGenerateId3 = createIdGenerator({
prefix: "aitxt",
size: 24
});
var originalGenerateMessageId = createIdGenerator({
prefix: "msg",
size: 24
});
async function generateText({
model,
tools,
toolChoice,
system,
prompt,
messages,
maxRetries: maxRetriesArg,
abortSignal,
headers,
maxSteps = 1,
experimental_generateMessageId: generateMessageId = originalGenerateMessageId,
experimental_output: output,
experimental_continueSteps: continueSteps = false,
experimental_telemetry: telemetry,
experimental_providerMetadata,
providerOptions = experimental_providerMetadata,
experimental_activeTools: activeTools,
experimental_prepareStep: prepareStep,
experimental_repairToolCall: repairToolCall,
_internal: {
generateId: generateId3 = originalGenerateId3,
currentDate = () => /* @__PURE__ */ new Date
} = {},
onStepFinish,
...settings
}) {
var _a17;
if (maxSteps < 1) {
throw new InvalidArgumentError2({
parameter: "maxSteps",
value: maxSteps,
message: "maxSteps must be at least 1"
});
}
const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg });
const baseTelemetryAttributes = getBaseTelemetryAttributes({
model,
telemetry,
headers,
settings: { ...settings, maxRetries }
});
const initialPrompt = standardizePrompt({
prompt: {
system: (_a17 = output == null ? undefined : output.injectIntoSystemPrompt({ system, model })) != null ? _a17 : system,
prompt,
messages
},
tools
});
const tracer = getTracer(telemetry);
return recordSpan({
name: "ai.generateText",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({
operationId: "ai.generateText",
telemetry
}),
...baseTelemetryAttributes,
"ai.model.provider": model.provider,
"ai.model.id": model.modelId,
"ai.prompt": {
input: () => JSON.stringify({ system, prompt, messages })
},
"ai.settings.maxSteps": maxSteps
}
}),
tracer,
fn: async (span) => {
var _a18, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
const callSettings = prepareCallSettings(settings);
let currentModelResponse;
let currentToolCalls = [];
let currentToolResults = [];
let currentReasoningDetails = [];
let stepCount = 0;
const responseMessages = [];
let text2 = "";
const sources = [];
const steps = [];
let usage = {
completionTokens: 0,
promptTokens: 0,
totalTokens: 0
};
let stepType = "initial";
do {
const promptFormat = stepCount === 0 ? initialPrompt.type : "messages";
const stepInputMessages = [
...initialPrompt.messages,
...responseMessages
];
const prepareStepResult = await (prepareStep == null ? undefined : prepareStep({
model,
steps,
maxSteps,
stepNumber: stepCount
}));
const stepToolChoice = (_a18 = prepareStepResult == null ? undefined : prepareStepResult.toolChoice) != null ? _a18 : toolChoice;
const stepActiveTools = (_b = prepareStepResult == null ? undefined : prepareStepResult.experimental_activeTools) != null ? _b : activeTools;
const stepModel = (_c = prepareStepResult == null ? undefined : prepareStepResult.model) != null ? _c : model;
const promptMessages = await convertToLanguageModelPrompt({
prompt: {
type: promptFormat,
system: initialPrompt.system,
messages: stepInputMessages
},
modelSupportsImageUrls: stepModel.supportsImageUrls,
modelSupportsUrl: (_d = stepModel.supportsUrl) == null ? undefined : _d.bind(stepModel)
});
const mode = {
type: "regular",
...prepareToolsAndToolChoice({
tools,
toolChoice: stepToolChoice,
activeTools: stepActiveTools
})
};
currentModelResponse = await retry(() => recordSpan({
name: "ai.generateText.doGenerate",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({
operationId: "ai.generateText.doGenerate",
telemetry
}),
...baseTelemetryAttributes,
"ai.model.provider": stepModel.provider,
"ai.model.id": stepModel.modelId,
"ai.prompt.format": { input: () => promptFormat },
"ai.prompt.messages": {
input: () => stringifyForTelemetry(promptMessages)
},
"ai.prompt.tools": {
input: () => {
var _a19;
return (_a19 = mode.tools) == null ? undefined : _a19.map((tool2) => JSON.stringify(tool2));
}
},
"ai.prompt.toolChoice": {
input: () => mode.toolChoice != null ? JSON.stringify(mode.toolChoice) : undefined
},
"gen_ai.system": stepModel.provider,
"gen_ai.request.model": stepModel.modelId,
"gen_ai.request.frequency_penalty": settings.frequencyPenalty,
"gen_ai.request.max_tokens": settings.maxTokens,
"gen_ai.request.presence_penalty": settings.presencePenalty,
"gen_ai.request.stop_sequences": settings.stopSequences,
"gen_ai.request.temperature": settings.temperature,
"gen_ai.request.top_k": settings.topK,
"gen_ai.request.top_p": settings.topP
}
}),
tracer,
fn: async (span2) => {
var _a19, _b2, _c2, _d2, _e2, _f2;
const result = await stepModel.doGenerate({
mode,
...callSettings,
inputFormat: promptFormat,
responseFormat: output == null ? undefined : output.responseFormat({ model }),
prompt: promptMessages,
providerMetadata: providerOptions,
abortSignal,
headers
});
const responseData = {
id: (_b2 = (_a19 = result.response) == null ? undefined : _a19.id) != null ? _b2 : generateId3(),
timestamp: (_d2 = (_c2 = result.response) == null ? undefined : _c2.timestamp) != null ? _d2 : currentDate(),
modelId: (_f2 = (_e2 = result.response) == null ? undefined : _e2.modelId) != null ? _f2 : stepModel.modelId
};
span2.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.response.finishReason": result.finishReason,
"ai.response.text": {
output: () => result.text
},
"ai.response.toolCalls": {
output: () => JSON.stringify(result.toolCalls)
},
"ai.response.id": responseData.id,
"ai.response.model": responseData.modelId,
"ai.response.timestamp": responseData.timestamp.toISOString(),
"ai.usage.promptTokens": result.usage.promptTokens,
"ai.usage.completionTokens": result.usage.completionTokens,
"gen_ai.response.finish_reasons": [result.finishReason],
"gen_ai.response.id": responseData.id,
"gen_ai.response.model": responseData.modelId,
"gen_ai.usage.input_tokens": result.usage.promptTokens,
"gen_ai.usage.output_tokens": result.usage.completionTokens
}
}));
return { ...result, response: responseData };
}
}));
currentToolCalls = await Promise.all(((_e = currentModelResponse.toolCalls) != null ? _e : []).map((toolCall) => parseToolCall({
toolCall,
tools,
repairToolCall,
system,
messages: stepInputMessages
})));
currentToolResults = tools == null ? [] : await executeTools({
toolCalls: currentToolCalls,
tools,
tracer,
telemetry,
messages: stepInputMessages,
abortSignal
});
const currentUsage = calculateLanguageModelUsage(currentModelResponse.usage);
usage = addLanguageModelUsage(usage, currentUsage);
let nextStepType = "done";
if (++stepCount < maxSteps) {
if (continueSteps && currentModelResponse.finishReason === "length" && currentToolCalls.length === 0) {
nextStepType = "continue";
} else if (currentToolCalls.length > 0 && currentToolResults.length === currentToolCalls.length) {
nextStepType = "tool-result";
}
}
const originalText = (_f = currentModelResponse.text) != null ? _f : "";
const stepTextLeadingWhitespaceTrimmed = stepType === "continue" && text2.trimEnd() !== text2 ? originalText.trimStart() : originalText;
const stepText = nextStepType === "continue" ? removeTextAfterLastWhitespace(stepTextLeadingWhitespaceTrimmed) : stepTextLeadingWhitespaceTrimmed;
text2 = nextStepType === "continue" || stepType === "continue" ? text2 + stepText : stepText;
currentReasoningDetails = asReasoningDetails(currentModelResponse.reasoning);
sources.push(...(_g = currentModelResponse.sources) != null ? _g : []);
if (stepType === "continue") {
const lastMessage = responseMessages[responseMessages.length - 1];
if (typeof lastMessage.content === "string") {
lastMessage.content += stepText;
} else {
lastMessage.content.push({
text: stepText,
type: "text"
});
}
} else {
responseMessages.push(...toResponseMessages({
text: text2,
files: asFiles(currentModelResponse.files),
reasoning: asReasoningDetails(currentModelResponse.reasoning),
tools: tools != null ? tools : {},
toolCalls: currentToolCalls,
toolResults: currentToolResults,
messageId: generateMessageId(),
generateMessageId
}));
}
const currentStepResult = {
stepType,
text: stepText,
reasoning: asReasoningText(currentReasoningDetails),
reasoningDetails: currentReasoningDetails,
files: asFiles(currentModelResponse.files),
sources: (_h = currentModelResponse.sources) != null ? _h : [],
toolCalls: currentToolCalls,
toolResults: currentToolResults,
finishReason: currentModelResponse.finishReason,
usage: currentUsage,
warnings: currentModelResponse.warnings,
logprobs: currentModelResponse.logprobs,
request: (_i = currentModelResponse.request) != null ? _i : {},
response: {
...currentModelResponse.response,
headers: (_j = currentModelResponse.rawResponse) == null ? undefined : _j.headers,
body: (_k = currentModelResponse.rawResponse) == null ? undefined : _k.body,
messages: structuredClone(responseMessages)
},
providerMetadata: currentModelResponse.providerMetadata,
experimental_providerMetadata: currentModelResponse.providerMetadata,
isContinued: nextStepType === "continue"
};
steps.push(currentStepResult);
await (onStepFinish == null ? undefined : onStepFinish(currentStepResult));
stepType = nextStepType;
} while (stepType !== "done");
span.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.response.finishReason": currentModelResponse.finishReason,
"ai.response.text": {
output: () => currentModelResponse.text
},
"ai.response.toolCalls": {
output: () => JSON.stringify(currentModelResponse.toolCalls)
},
"ai.usage.promptTokens": currentModelResponse.usage.promptTokens,
"ai.usage.completionTokens": currentModelResponse.usage.completionTokens
}
}));
return new DefaultGenerateTextResult({
text: text2,
files: asFiles(currentModelResponse.files),
reasoning: asReasoningText(currentReasoningDetails),
reasoningDetails: currentReasoningDetails,
sources,
outputResolver: () => {
if (output == null) {
throw new NoOutputSpecifiedError;
}
return output.parseOutput({ text: text2 }, {
response: currentModelResponse.response,
usage,
finishReason: currentModelResponse.finishReason
});
},
toolCalls: currentToolCalls,
toolResults: currentToolResults,
finishReason: currentModelResponse.finishReason,
usage,
warnings: currentModelResponse.warnings,
request: (_l = currentModelResponse.request) != null ? _l : {},
response: {
...currentModelResponse.response,
headers: (_m = currentModelResponse.rawResponse) == null ? undefined : _m.headers,
body: (_n = currentModelResponse.rawResponse) == null ? undefined : _n.body,
messages: responseMessages
},
logprobs: currentModelResponse.logprobs,
steps,
providerMetadata: currentModelResponse.providerMetadata
});
}
});
}
async function executeTools({
toolCalls,
tools,
tracer,
telemetry,
messages,
abortSignal
}) {
const toolResults = await Promise.all(toolCalls.map(async ({ toolCallId, toolName, args }) => {
const tool2 = tools[toolName];
if ((tool2 == null ? undefined : tool2.execute) == null) {
return;
}
const result = await recordSpan({
name: "ai.toolCall",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({
operationId: "ai.toolCall",
telemetry
}),
"ai.toolCall.name": toolName,
"ai.toolCall.id": toolCallId,
"ai.toolCall.args": {
output: () => JSON.stringify(args)
}
}
}),
tracer,
fn: async (span) => {
try {
const result2 = await tool2.execute(args, {
toolCallId,
messages,
abortSignal
});
try {
span.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.toolCall.result": {
output: () => JSON.stringify(result2)
}
}
}));
} catch (ignored) {}
return result2;
} catch (error) {
throw new ToolExecutionError({
toolCallId,
toolName,
toolArgs: args,
cause: error
});
}
}
});
return {
type: "tool-result",
toolCallId,
toolName,
args,
result
};
}));
return toolResults.filter((result) => result != null);
}
var DefaultGenerateTextResult = class {
constructor(options) {
this.text = options.text;
this.files = options.files;
this.reasoning = options.reasoning;
this.reasoningDetails = options.reasoningDetails;
this.toolCalls = options.toolCalls;
this.toolResults = options.toolResults;
this.finishReason = options.finishReason;
this.usage = options.usage;
this.warnings = options.warnings;
this.request = options.request;
this.response = options.response;
this.steps = options.steps;
this.experimental_providerMetadata = options.providerMetadata;
this.providerMetadata = options.providerMetadata;
this.logprobs = options.logprobs;
this.outputResolver = options.outputResolver;
this.sources = options.sources;
}
get experimental_output() {
return this.outputResolver();
}
};
function asReasoningDetails(reasoning) {
if (reasoning == null) {
return [];
}
if (typeof reasoning === "string") {
return [{ type: "text", text: reasoning }];
}
return reasoning;
}
function asFiles(files) {
var _a17;
return (_a17 = files == null ? undefined : files.map((file) => new DefaultGeneratedFile(file))) != null ? _a17 : [];
}
var output_exports = {};
__export2(output_exports, {
object: () => object2,
text: () => text
});
var name142 = "AI_InvalidStreamPartError";
var marker142 = `vercel.ai.error.${name142}`;
var symbol142 = Symbol.for(marker142);
var _a142;
var InvalidStreamPartError = class extends AISDKError {
constructor({
chunk,
message
}) {
super({ name: name142, message });
this[_a142] = true;
this.chunk = chunk;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker142);
}
};
_a142 = symbol142;
var name15 = "AI_MCPClientError";
var marker152 = `vercel.ai.error.${name15}`;
var symbol152 = Symbol.for(marker152);
var _a152;
_a152 = symbol152;
var text = () => ({
type: "text",
responseFormat: () => ({ type: "text" }),
injectIntoSystemPrompt({ system }) {
return system;
},
parsePartial({ text: text2 }) {
return { partial: text2 };
},
parseOutput({ text: text2 }) {
return text2;
}
});
var object2 = ({
schema: inputSchema
}) => {
const schema = asSchema(inputSchema);
return {
type: "object",
responseFormat: ({ model }) => ({
type: "json",
schema: model.supportsStructuredOutputs ? schema.jsonSchema : undefined
}),
injectIntoSystemPrompt({ system, model }) {
return model.supportsStructuredOutputs ? system : injectJsonInstruction({
prompt: system,
schema: schema.jsonSchema
});
},
parsePartial({ text: text2 }) {
const result = parsePartialJson(text2);
switch (result.state) {
case "failed-parse":
case "undefined-input":
return;
case "repaired-parse":
case "successful-parse":
return {
partial: result.value
};
default: {
const _exhaustiveCheck = result.state;
throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
}
}
},
parseOutput({ text: text2 }, context) {
const parseResult = safeParseJSON({ text: text2 });
if (!parseResult.success) {
throw new NoObjectGeneratedError({
message: "No object generated: could not parse the response.",
cause: parseResult.error,
text: text2,
response: context.response,
usage: context.usage,
finishReason: context.finishReason
});
}
const validationResult = safeValidateTypes({
value: parseResult.value,
schema
});
if (!validationResult.success) {
throw new NoObjectGeneratedError({
message: "No object generated: response did not match schema.",
cause: validationResult.error,
text: text2,
response: context.response,
usage: context.usage,
finishReason: context.finishReason
});
}
return validationResult.value;
}
};
};
function asArray(value) {
return value === undefined ? [] : Array.isArray(value) ? value : [value];
}
async function consumeStream({
stream,
onError
}) {
const reader = stream.getReader();
try {
while (true) {
const { done } = await reader.read();
if (done)
break;
}
} catch (error) {
onError == null || onError(error);
} finally {
reader.releaseLock();
}
}
function mergeStreams(stream1, stream2) {
const reader1 = stream1.getReader();
const reader2 = stream2.getReader();
let lastRead1 = undefined;
let lastRead2 = undefined;
let stream1Done = false;
let stream2Done = false;
async function readStream1(controller) {
try {
if (lastRead1 == null) {
lastRead1 = reader1.read();
}
const result = await lastRead1;
lastRead1 = undefined;
if (!result.done) {
controller.enqueue(result.value);
} else {
controller.close();
}
} catch (error) {
controller.error(error);
}
}
async function readStream2(controller) {
try {
if (lastRead2 == null) {
lastRead2 = reader2.read();
}
const result = await lastRead2;
lastRead2 = undefined;
if (!result.done) {
controller.enqueue(result.value);
} else {
controller.close();
}
} catch (error) {
controller.error(error);
}
}
return new ReadableStream({
async pull(controller) {
try {
if (stream1Done) {
await readStream2(controller);
return;
}
if (stream2Done) {
await readStream1(controller);
return;
}
if (lastRead1 == null) {
lastRead1 = reader1.read();
}
if (lastRead2 == null) {
lastRead2 = reader2.read();
}
const { result, reader } = await Promise.race([
lastRead1.then((result2) => ({ result: result2, reader: reader1 })),
lastRead2.then((result2) => ({ result: result2, reader: reader2 }))
]);
if (!result.done) {
controller.enqueue(result.value);
}
if (reader === reader1) {
lastRead1 = undefined;
if (result.done) {
await readStream2(controller);
stream1Done = true;
}
} else {
lastRead2 = undefined;
if (result.done) {
stream2Done = true;
await readStream1(controller);
}
}
} catch (error) {
controller.error(error);
}
},
cancel() {
reader1.cancel();
reader2.cancel();
}
});
}
function runToolsTransformation({
tools,
generatorStream,
toolCallStreaming,
tracer,
telemetry,
system,
messages,
abortSignal,
repairToolCall
}) {
let toolResultsStreamController = null;
const toolResultsStream = new ReadableStream({
start(controller) {
toolResultsStreamController = controller;
}
});
const activeToolCalls = {};
const outstandingToolResults = /* @__PURE__ */ new Set;
let canClose = false;
let finishChunk = undefined;
function attemptClose() {
if (canClose && outstandingToolResults.size === 0) {
if (finishChunk != null) {
toolResultsStreamController.enqueue(finishChunk);
}
toolResultsStreamController.close();
}
}
const forwardStream = new TransformStream({
async transform(chunk, controller) {
const chunkType = chunk.type;
switch (chunkType) {
case "text-delta":
case "reasoning":
case "reasoning-signature":
case "redacted-reasoning":
case "source":
case "response-metadata":
case "error": {
controller.enqueue(chunk);
break;
}
case "file": {
controller.enqueue(new DefaultGeneratedFileWithType({
data: chunk.data,
mimeType: chunk.mimeType
}));
break;
}
case "tool-call-delta": {
if (toolCallStreaming) {
if (!activeToolCalls[chunk.toolCallId]) {
controller.enqueue({
type: "tool-call-streaming-start",
toolCallId: chunk.toolCallId,
toolName: chunk.toolName
});
activeToolCalls[chunk.toolCallId] = true;
}
controller.enqueue({
type: "tool-call-delta",
toolCallId: chunk.toolCallId,
toolName: chunk.toolName,
argsTextDelta: chunk.argsTextDelta
});
}
break;
}
case "tool-call": {
try {
const toolCall = await parseToolCall({
toolCall: chunk,
tools,
repairToolCall,
system,
messages
});
controller.enqueue(toolCall);
const tool2 = tools[toolCall.toolName];
if (tool2.execute != null) {
const toolExecutionId = generateId();
outstandingToolResults.add(toolExecutionId);
recordSpan({
name: "ai.toolCall",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({
operationId: "ai.toolCall",
telemetry
}),
"ai.toolCall.name": toolCall.toolName,
"ai.toolCall.id": toolCall.toolCallId,
"ai.toolCall.args": {
output: () => JSON.stringify(toolCall.args)
}
}
}),
tracer,
fn: async (span) => tool2.execute(toolCall.args, {
toolCallId: toolCall.toolCallId,
messages,
abortSignal
}).then((result) => {
toolResultsStreamController.enqueue({
...toolCall,
type: "tool-result",
result
});
outstandingToolResults.delete(toolExecutionId);
attemptClose();
try {
span.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.toolCall.result": {
output: () => JSON.stringify(result)
}
}
}));
} catch (ignored) {}
}, (error) => {
toolResultsStreamController.enqueue({
type: "error",
error: new ToolExecutionError({
toolCallId: toolCall.toolCallId,
toolName: toolCall.toolName,
toolArgs: toolCall.args,
cause: error
})
});
outstandingToolResults.delete(toolExecutionId);
attemptClose();
})
});
}
} catch (error) {
toolResultsStreamController.enqueue({
type: "error",
error
});
}
break;
}
case "finish": {
finishChunk = {
type: "finish",
finishReason: chunk.finishReason,
logprobs: chunk.logprobs,
usage: calculateLanguageModelUsage(chunk.usage),
experimental_providerMetadata: chunk.providerMetadata
};
break;
}
default: {
const _exhaustiveCheck = chunkType;
throw new Error(`Unhandled chunk type: ${_exhaustiveCheck}`);
}
}
},
flush() {
canClose = true;
attemptClose();
}
});
return new ReadableStream({
async start(controller) {
return Promise.all([
generatorStream.pipeThrough(forwardStream).pipeTo(new WritableStream({
write(chunk) {
controller.enqueue(chunk);
},
close() {}
})),
toolResultsStream.pipeTo(new WritableStream({
write(chunk) {
controller.enqueue(chunk);
},
close() {
controller.close();
}
}))
]);
}
});
}
var originalGenerateId4 = createIdGenerator({
prefix: "aitxt",
size: 24
});
var originalGenerateMessageId2 = createIdGenerator({
prefix: "msg",
size: 24
});
function streamText({
model,
tools,
toolChoice,
system,
prompt,
messages,
maxRetries,
abortSignal,
headers,
maxSteps = 1,
experimental_generateMessageId: generateMessageId = originalGenerateMessageId2,
experimental_output: output,
experimental_continueSteps: continueSteps = false,
experimental_telemetry: telemetry,
experimental_providerMetadata,
providerOptions = experimental_providerMetadata,
experimental_toolCallStreaming = false,
toolCallStreaming = experimental_toolCallStreaming,
experimental_activeTools: activeTools,
experimental_repairToolCall: repairToolCall,
experimental_transform: transform,
onChunk,
onError,
onFinish,
onStepFinish,
_internal: {
now: now2 = now,
generateId: generateId3 = originalGenerateId4,
currentDate = () => /* @__PURE__ */ new Date
} = {},
...settings
}) {
return new DefaultStreamTextResult({
model,
telemetry,
headers,
settings,
maxRetries,
abortSignal,
system,
prompt,
messages,
tools,
toolChoice,
toolCallStreaming,
transforms: asArray(transform),
activeTools,
repairToolCall,
maxSteps,
output,
continueSteps,
providerOptions,
onChunk,
onError,
onFinish,
onStepFinish,
now: now2,
currentDate,
generateId: generateId3,
generateMessageId
});
}
function createOutputTransformStream(output) {
if (!output) {
return new TransformStream({
transform(chunk, controller) {
controller.enqueue({ part: chunk, partialOutput: undefined });
}
});
}
let text2 = "";
let textChunk = "";
let lastPublishedJson = "";
function publishTextChunk({
controller,
partialOutput = undefined
}) {
controller.enqueue({
part: { type: "text-delta", textDelta: textChunk },
partialOutput
});
textChunk = "";
}
return new TransformStream({
transform(chunk, controller) {
if (chunk.type === "step-finish") {
publishTextChunk({ controller });
}
if (chunk.type !== "text-delta") {
controller.enqueue({ part: chunk, partialOutput: undefined });
return;
}
text2 += chunk.textDelta;
textChunk += chunk.textDelta;
const result = output.parsePartial({ text: text2 });
if (result != null) {
const currentJson = JSON.stringify(result.partial);
if (currentJson !== lastPublishedJson) {
publishTextChunk({ controller, partialOutput: result.partial });
lastPublishedJson = currentJson;
}
}
},
flush(controller) {
if (textChunk.length > 0) {
publishTextChunk({ controller });
}
}
});
}
var DefaultStreamTextResult = class {
constructor({
model,
telemetry,
headers,
settings,
maxRetries: maxRetriesArg,
abortSignal,
system,
prompt,
messages,
tools,
toolChoice,
toolCallStreaming,
transforms,
activeTools,
repairToolCall,
maxSteps,
output,
continueSteps,
providerOptions,
now: now2,
currentDate,
generateId: generateId3,
generateMessageId,
onChunk,
onError,
onFinish,
onStepFinish
}) {
this.warningsPromise = new DelayedPromise;
this.usagePromise = new DelayedPromise;
this.finishReasonPromise = new DelayedPromise;
this.providerMetadataPromise = new DelayedPromise;
this.textPromise = new DelayedPromise;
this.reasoningPromise = new DelayedPromise;
this.reasoningDetailsPromise = new DelayedPromise;
this.sourcesPromise = new DelayedPromise;
this.filesPromise = new DelayedPromise;
this.toolCallsPromise = new DelayedPromise;
this.toolResultsPromise = new DelayedPromise;
this.requestPromise = new DelayedPromise;
this.responsePromise = new DelayedPromise;
this.stepsPromise = new DelayedPromise;
var _a17;
if (maxSteps < 1) {
throw new InvalidArgumentError2({
parameter: "maxSteps",
value: maxSteps,
message: "maxSteps must be at least 1"
});
}
this.output = output;
let recordedStepText = "";
let recordedContinuationText = "";
let recordedFullText = "";
let stepReasoning = [];
let stepFiles = [];
let activeReasoningText = undefined;
let recordedStepSources = [];
const recordedSources = [];
const recordedResponse = {
id: generateId3(),
timestamp: currentDate(),
modelId: model.modelId,
messages: []
};
let recordedToolCalls = [];
let recordedToolResults = [];
let recordedFinishReason = undefined;
let recordedUsage = undefined;
let stepType = "initial";
const recordedSteps = [];
let rootSpan;
const eventProcessor = new TransformStream({
async transform(chunk, controller) {
controller.enqueue(chunk);
const { part } = chunk;
if (part.type === "text-delta" || part.type === "reasoning" || part.type === "source" || part.type === "tool-call" || part.type === "tool-result" || part.type === "tool-call-streaming-start" || part.type === "tool-call-delta") {
await (onChunk == null ? undefined : onChunk({ chunk: part }));
}
if (part.type === "error") {
await (onError == null ? undefined : onError({ error: part.error }));
}
if (part.type === "text-delta") {
recordedStepText += part.textDelta;
recordedContinuationText += part.textDelta;
recordedFullText += part.textDelta;
}
if (part.type === "reasoning") {
if (activeReasoningText == null) {
activeReasoningText = { type: "text", text: part.textDelta };
stepReasoning.push(activeReasoningText);
} else {
activeReasoningText.text += part.textDelta;
}
}
if (part.type === "reasoning-signature") {
if (activeReasoningText == null) {
throw new AISDKError({
name: "InvalidStreamPart",
message: "reasoning-signature without reasoning"
});
}
activeReasoningText.signature = part.signature;
activeReasoningText = undefined;
}
if (part.type === "redacted-reasoning") {
stepReasoning.push({ type: "redacted", data: part.data });
}
if (part.type === "file") {
stepFiles.push(part);
}
if (part.type === "source") {
recordedSources.push(part.source);
recordedStepSources.push(part.source);
}
if (part.type === "tool-call") {
recordedToolCalls.push(part);
}
if (part.type === "tool-result") {
recordedToolResults.push(part);
}
if (part.type === "step-finish") {
const stepMessages = toResponseMessages({
text: recordedContinuationText,
files: stepFiles,
reasoning: stepReasoning,
tools: tools != null ? tools : {},
toolCalls: recordedToolCalls,
toolResults: recordedToolResults,
messageId: part.messageId,
generateMessageId
});
const currentStep = recordedSteps.length;
let nextStepType = "done";
if (currentStep + 1 < maxSteps) {
if (continueSteps && part.finishReason === "length" && recordedToolCalls.length === 0) {
nextStepType = "continue";
} else if (recordedToolCalls.length > 0 && recordedToolResults.length === recordedToolCalls.length) {
nextStepType = "tool-result";
}
}
const currentStepResult = {
stepType,
text: recordedStepText,
reasoning: asReasoningText(stepReasoning),
reasoningDetails: stepReasoning,
files: stepFiles,
sources: recordedStepSources,
toolCalls: recordedToolCalls,
toolResults: recordedToolResults,
finishReason: part.finishReason,
usage: part.usage,
warnings: part.warnings,
logprobs: part.logprobs,
request: part.request,
response: {
...part.response,
messages: [...recordedResponse.messages, ...stepMessages]
},
providerMetadata: part.experimental_providerMetadata,
experimental_providerMetadata: part.experimental_providerMetadata,
isContinued: part.isContinued
};
await (onStepFinish == null ? undefined : onStepFinish(currentStepResult));
recordedSteps.push(currentStepResult);
recordedToolCalls = [];
recordedToolResults = [];
recordedStepText = "";
recordedStepSources = [];
stepReasoning = [];
stepFiles = [];
activeReasoningText = undefined;
if (nextStepType !== "done") {
stepType = nextStepType;
}
if (nextStepType !== "continue") {
recordedResponse.messages.push(...stepMessages);
recordedContinuationText = "";
}
}
if (part.type === "finish") {
recordedResponse.id = part.response.id;
recordedResponse.timestamp = part.response.timestamp;
recordedResponse.modelId = part.response.modelId;
recordedResponse.headers = part.response.headers;
recordedUsage = part.usage;
recordedFinishReason = part.finishReason;
}
},
async flush(controller) {
var _a18;
try {
if (recordedSteps.length === 0) {
return;
}
const lastStep = recordedSteps[recordedSteps.length - 1];
self.warningsPromise.resolve(lastStep.warnings);
self.requestPromise.resolve(lastStep.request);
self.responsePromise.resolve(lastStep.response);
self.toolCallsPromise.resolve(lastStep.toolCalls);
self.toolResultsPromise.resolve(lastStep.toolResults);
self.providerMetadataPromise.resolve(lastStep.experimental_providerMetadata);
self.reasoningPromise.resolve(lastStep.reasoning);
self.reasoningDetailsPromise.resolve(lastStep.reasoningDetails);
const finishReason = recordedFinishReason != null ? recordedFinishReason : "unknown";
const usage = recordedUsage != null ? recordedUsage : {
completionTokens: NaN,
promptTokens: NaN,
totalTokens: NaN
};
self.finishReasonPromise.resolve(finishReason);
self.usagePromise.resolve(usage);
self.textPromise.resolve(recordedFullText);
self.sourcesPromise.resolve(recordedSources);
self.filesPromise.resolve(lastStep.files);
self.stepsPromise.resolve(recordedSteps);
await (onFinish == null ? undefined : onFinish({
finishReason,
logprobs: undefined,
usage,
text: recordedFullText,
reasoning: lastStep.reasoning,
reasoningDetails: lastStep.reasoningDetails,
files: lastStep.files,
sources: lastStep.sources,
toolCalls: lastStep.toolCalls,
toolResults: lastStep.toolResults,
request: (_a18 = lastStep.request) != null ? _a18 : {},
response: lastStep.response,
warnings: lastStep.warnings,
providerMetadata: lastStep.providerMetadata,
experimental_providerMetadata: lastStep.experimental_providerMetadata,
steps: recordedSteps
}));
rootSpan.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.response.finishReason": finishReason,
"ai.response.text": { output: () => recordedFullText },
"ai.response.toolCalls": {
output: () => {
var _a19;
return ((_a19 = lastStep.toolCalls) == null ? undefined : _a19.length) ? JSON.stringify(lastStep.toolCalls) : undefined;
}
},
"ai.usage.promptTokens": usage.promptTokens,
"ai.usage.completionTokens": usage.completionTokens
}
}));
} catch (error) {
controller.error(error);
} finally {
rootSpan.end();
}
}
});
const stitchableStream = createStitchableStream();
this.addStream = stitchableStream.addStream;
this.closeStream = stitchableStream.close;
let stream = stitchableStream.stream;
for (const transform of transforms) {
stream = stream.pipeThrough(transform({
tools,
stopStream() {
stitchableStream.terminate();
}
}));
}
this.baseStream = stream.pipeThrough(createOutputTransformStream(output)).pipeThrough(eventProcessor);
const { maxRetries, retry } = prepareRetries({
maxRetries: maxRetriesArg
});
const tracer = getTracer(telemetry);
const baseTelemetryAttributes = getBaseTelemetryAttributes({
model,
telemetry,
headers,
settings: { ...settings, maxRetries }
});
const initialPrompt = standardizePrompt({
prompt: {
system: (_a17 = output == null ? undefined : output.injectIntoSystemPrompt({ system, model })) != null ? _a17 : system,
prompt,
messages
},
tools
});
const self = this;
recordSpan({
name: "ai.streamText",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({ operationId: "ai.streamText", telemetry }),
...baseTelemetryAttributes,
"ai.prompt": {
input: () => JSON.stringify({ system, prompt, messages })
},
"ai.settings.maxSteps": maxSteps
}
}),
tracer,
endWhenDone: false,
fn: async (rootSpanArg) => {
rootSpan = rootSpanArg;
async function streamStep({
currentStep,
responseMessages,
usage,
stepType: stepType2,
previousStepText,
hasLeadingWhitespace,
messageId
}) {
var _a18;
const promptFormat = responseMessages.length === 0 ? initialPrompt.type : "messages";
const stepInputMessages = [
...initialPrompt.messages,
...responseMessages
];
const promptMessages = await convertToLanguageModelPrompt({
prompt: {
type: promptFormat,
system: initialPrompt.system,
messages: stepInputMessages
},
modelSupportsImageUrls: model.supportsImageUrls,
modelSupportsUrl: (_a18 = model.supportsUrl) == null ? undefined : _a18.bind(model)
});
const mode = {
type: "regular",
...prepareToolsAndToolChoice({ tools, toolChoice, activeTools })
};
const {
result: { stream: stream2, warnings, rawResponse, request },
doStreamSpan,
startTimestampMs
} = await retry(() => recordSpan({
name: "ai.streamText.doStream",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({
operationId: "ai.streamText.doStream",
telemetry
}),
...baseTelemetryAttributes,
"ai.prompt.format": {
input: () => promptFormat
},
"ai.prompt.messages": {
input: () => stringifyForTelemetry(promptMessages)
},
"ai.prompt.tools": {
input: () => {
var _a19;
return (_a19 = mode.tools) == null ? undefined : _a19.map((tool2) => JSON.stringify(tool2));
}
},
"ai.prompt.toolChoice": {
input: () => mode.toolChoice != null ? JSON.stringify(mode.toolChoice) : undefined
},
"gen_ai.system": model.provider,
"gen_ai.request.model": model.modelId,
"gen_ai.request.frequency_penalty": settings.frequencyPenalty,
"gen_ai.request.max_tokens": settings.maxTokens,
"gen_ai.request.presence_penalty": settings.presencePenalty,
"gen_ai.request.stop_sequences": settings.stopSequences,
"gen_ai.request.temperature": settings.temperature,
"gen_ai.request.top_k": settings.topK,
"gen_ai.request.top_p": settings.topP
}
}),
tracer,
endWhenDone: false,
fn: async (doStreamSpan2) => ({
startTimestampMs: now2(),
doStreamSpan: doStreamSpan2,
result: await model.doStream({
mode,
...prepareCallSettings(settings),
inputFormat: promptFormat,
responseFormat: output == null ? undefined : output.responseFormat({ model }),
prompt: promptMessages,
providerMetadata: providerOptions,
abortSignal,
headers
})
})
}));
const transformedStream = runToolsTransformation({
tools,
generatorStream: stream2,
toolCallStreaming,
tracer,
telemetry,
system,
messages: stepInputMessages,
repairToolCall,
abortSignal
});
const stepRequest = request != null ? request : {};
const stepToolCalls = [];
const stepToolResults = [];
const stepReasoning2 = [];
const stepFiles2 = [];
let activeReasoningText2 = undefined;
let stepFinishReason = "unknown";
let stepUsage = {
promptTokens: 0,
completionTokens: 0,
totalTokens: 0
};
let stepProviderMetadata;
let stepFirstChunk = true;
let stepText = "";
let fullStepText = stepType2 === "continue" ? previousStepText : "";
let stepLogProbs;
let stepResponse = {
id: generateId3(),
timestamp: currentDate(),
modelId: model.modelId
};
let chunkBuffer = "";
let chunkTextPublished = false;
let inWhitespacePrefix = true;
let hasWhitespaceSuffix = false;
async function publishTextChunk({
controller,
chunk
}) {
controller.enqueue(chunk);
stepText += chunk.textDelta;
fullStepText += chunk.textDelta;
chunkTextPublished = true;
hasWhitespaceSuffix = chunk.textDelta.trimEnd() !== chunk.textDelta;
}
self.addStream(transformedStream.pipeThrough(new TransformStream({
async transform(chunk, controller) {
var _a19, _b, _c;
if (stepFirstChunk) {
const msToFirstChunk = now2() - startTimestampMs;
stepFirstChunk = false;
doStreamSpan.addEvent("ai.stream.firstChunk", {
"ai.response.msToFirstChunk": msToFirstChunk
});
doStreamSpan.setAttributes({
"ai.response.msToFirstChunk": msToFirstChunk
});
controller.enqueue({
type: "step-start",
messageId,
request: stepRequest,
warnings: warnings != null ? warnings : []
});
}
if (chunk.type === "text-delta" && chunk.textDelta.length === 0) {
return;
}
const chunkType = chunk.type;
switch (chunkType) {
case "text-delta": {
if (continueSteps) {
const trimmedChunkText = inWhitespacePrefix && hasLeadingWhitespace ? chunk.textDelta.trimStart() : chunk.textDelta;
if (trimmedChunkText.length === 0) {
break;
}
inWhitespacePrefix = false;
chunkBuffer += trimmedChunkText;
const split = splitOnLastWhitespace(chunkBuffer);
if (split != null) {
chunkBuffer = split.suffix;
await publishTextChunk({
controller,
chunk: {
type: "text-delta",
textDelta: split.prefix + split.whitespace
}
});
}
} else {
await publishTextChunk({ controller, chunk });
}
break;
}
case "reasoning": {
controller.enqueue(chunk);
if (activeReasoningText2 == null) {
activeReasoningText2 = {
type: "text",
text: chunk.textDelta
};
stepReasoning2.push(activeReasoningText2);
} else {
activeReasoningText2.text += chunk.textDelta;
}
break;
}
case "reasoning-signature": {
controller.enqueue(chunk);
if (activeReasoningText2 == null) {
throw new InvalidStreamPartError({
chunk,
message: "reasoning-signature without reasoning"
});
}
activeReasoningText2.signature = chunk.signature;
activeReasoningText2 = undefined;
break;
}
case "redacted-reasoning": {
controller.enqueue(chunk);
stepReasoning2.push({
type: "redacted",
data: chunk.data
});
break;
}
case "tool-call": {
controller.enqueue(chunk);
stepToolCalls.push(chunk);
break;
}
case "tool-result": {
controller.enqueue(chunk);
stepToolResults.push(chunk);
break;
}
case "response-metadata": {
stepResponse = {
id: (_a19 = chunk.id) != null ? _a19 : stepResponse.id,
timestamp: (_b = chunk.timestamp) != null ? _b : stepResponse.timestamp,
modelId: (_c = chunk.modelId) != null ? _c : stepResponse.modelId
};
break;
}
case "finish": {
stepUsage = chunk.usage;
stepFinishReason = chunk.finishReason;
stepProviderMetadata = chunk.experimental_providerMetadata;
stepLogProbs = chunk.logprobs;
const msToFinish = now2() - startTimestampMs;
doStreamSpan.addEvent("ai.stream.finish");
doStreamSpan.setAttributes({
"ai.response.msToFinish": msToFinish,
"ai.response.avgCompletionTokensPerSecond": 1000 * stepUsage.completionTokens / msToFinish
});
break;
}
case "file": {
stepFiles2.push(chunk);
controller.enqueue(chunk);
break;
}
case "source":
case "tool-call-streaming-start":
case "tool-call-delta": {
controller.enqueue(chunk);
break;
}
case "error": {
controller.enqueue(chunk);
stepFinishReason = "error";
break;
}
default: {
const exhaustiveCheck = chunkType;
throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);
}
}
},
async flush(controller) {
const stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : undefined;
let nextStepType = "done";
if (currentStep + 1 < maxSteps) {
if (continueSteps && stepFinishReason === "length" && stepToolCalls.length === 0) {
nextStepType = "continue";
} else if (stepToolCalls.length > 0 && stepToolResults.length === stepToolCalls.length) {
nextStepType = "tool-result";
}
}
if (continueSteps && chunkBuffer.length > 0 && (nextStepType !== "continue" || stepType2 === "continue" && !chunkTextPublished)) {
await publishTextChunk({
controller,
chunk: {
type: "text-delta",
textDelta: chunkBuffer
}
});
chunkBuffer = "";
}
try {
doStreamSpan.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.response.finishReason": stepFinishReason,
"ai.response.text": { output: () => stepText },
"ai.response.toolCalls": {
output: () => stepToolCallsJson
},
"ai.response.id": stepResponse.id,
"ai.response.model": stepResponse.modelId,
"ai.response.timestamp": stepResponse.timestamp.toISOString(),
"ai.usage.promptTokens": stepUsage.promptTokens,
"ai.usage.completionTokens": stepUsage.completionTokens,
"gen_ai.response.finish_reasons": [stepFinishReason],
"gen_ai.response.id": stepResponse.id,
"gen_ai.response.model": stepResponse.modelId,
"gen_ai.usage.input_tokens": stepUsage.promptTokens,
"gen_ai.usage.output_tokens": stepUsage.completionTokens
}
}));
} catch (error) {} finally {
doStreamSpan.end();
}
controller.enqueue({
type: "step-finish",
finishReason: stepFinishReason,
usage: stepUsage,
providerMetadata: stepProviderMetadata,
experimental_providerMetadata: stepProviderMetadata,
logprobs: stepLogProbs,
request: stepRequest,
response: {
...stepResponse,
headers: rawResponse == null ? undefined : rawResponse.headers
},
warnings,
isContinued: nextStepType === "continue",
messageId
});
const combinedUsage = addLanguageModelUsage(usage, stepUsage);
if (nextStepType === "done") {
controller.enqueue({
type: "finish",
finishReason: stepFinishReason,
usage: combinedUsage,
providerMetadata: stepProviderMetadata,
experimental_providerMetadata: stepProviderMetadata,
logprobs: stepLogProbs,
response: {
...stepResponse,
headers: rawResponse == null ? undefined : rawResponse.headers
}
});
self.closeStream();
} else {
if (stepType2 === "continue") {
const lastMessage = responseMessages[responseMessages.length - 1];
if (typeof lastMessage.content === "string") {
lastMessage.content += stepText;
} else {
lastMessage.content.push({
text: stepText,
type: "text"
});
}
} else {
responseMessages.push(...toResponseMessages({
text: stepText,
files: stepFiles2,
reasoning: stepReasoning2,
tools: tools != null ? tools : {},
toolCalls: stepToolCalls,
toolResults: stepToolResults,
messageId,
generateMessageId
}));
}
await streamStep({
currentStep: currentStep + 1,
responseMessages,
usage: combinedUsage,
stepType: nextStepType,
previousStepText: fullStepText,
hasLeadingWhitespace: hasWhitespaceSuffix,
messageId: nextStepType === "continue" ? messageId : generateMessageId()
});
}
}
})));
}
await streamStep({
currentStep: 0,
responseMessages: [],
usage: {
promptTokens: 0,
completionTokens: 0,
totalTokens: 0
},
previousStepText: "",
stepType: "initial",
hasLeadingWhitespace: false,
messageId: generateMessageId()
});
}
}).catch((error) => {
self.addStream(new ReadableStream({
start(controller) {
controller.enqueue({ type: "error", error });
controller.close();
}
}));
self.closeStream();
});
}
get warnings() {
return this.warningsPromise.value;
}
get usage() {
return this.usagePromise.value;
}
get finishReason() {
return this.finishReasonPromise.value;
}
get experimental_providerMetadata() {
return this.providerMetadataPromise.value;
}
get providerMetadata() {
return this.providerMetadataPromise.value;
}
get text() {
return this.textPromise.value;
}
get reasoning() {
return this.reasoningPromise.value;
}
get reasoningDetails() {
return this.reasoningDetailsPromise.value;
}
get sources() {
return this.sourcesPromise.value;
}
get files() {
return this.filesPromise.value;
}
get toolCalls() {
return this.toolCallsPromise.value;
}
get toolResults() {
return this.toolResultsPromise.value;
}
get request() {
return this.requestPromise.value;
}
get response() {
return this.responsePromise.value;
}
get steps() {
return this.stepsPromise.value;
}
teeStream() {
const [stream1, stream2] = this.baseStream.tee();
this.baseStream = stream2;
return stream1;
}
get textStream() {
return createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({
transform({ part }, controller) {
if (part.type === "text-delta") {
controller.enqueue(part.textDelta);
}
}
})));
}
get fullStream() {
return createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({
transform({ part }, controller) {
controller.enqueue(part);
}
})));
}
async consumeStream(options) {
var _a17;
try {
await consumeStream({
stream: this.fullStream,
onError: options == null ? undefined : options.onError
});
} catch (error) {
(_a17 = options == null ? undefined : options.onError) == null || _a17.call(options, error);
}
}
get experimental_partialOutputStream() {
if (this.output == null) {
throw new NoOutputSpecifiedError;
}
return createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({
transform({ partialOutput }, controller) {
if (partialOutput != null) {
controller.enqueue(partialOutput);
}
}
})));
}
toDataStreamInternal({
getErrorMessage: getErrorMessage5 = () => "An error occurred.",
sendUsage = true,
sendReasoning = false,
sendSources = false,
experimental_sendFinish = true
}) {
return this.fullStream.pipeThrough(new TransformStream({
transform: async (chunk, controller) => {
const chunkType = chunk.type;
switch (chunkType) {
case "text-delta": {
controller.enqueue(formatDataStreamPart("text", chunk.textDelta));
break;
}
case "reasoning": {
if (sendReasoning) {
controller.enqueue(formatDataStreamPart("reasoning", chunk.textDelta));
}
break;
}
case "redacted-reasoning": {
if (sendReasoning) {
controller.enqueue(formatDataStreamPart("redacted_reasoning", {
data: chunk.data
}));
}
break;
}
case "reasoning-signature": {
if (sendReasoning) {
controller.enqueue(formatDataStreamPart("reasoning_signature", {
signature: chunk.signature
}));
}
break;
}
case "file": {
controller.enqueue(formatDataStreamPart("file", {
mimeType: chunk.mimeType,
data: chunk.base64
}));
break;
}
case "source": {
if (sendSources) {
controller.enqueue(formatDataStreamPart("source", chunk.source));
}
break;
}
case "tool-call-streaming-start": {
controller.enqueue(formatDataStreamPart("tool_call_streaming_start", {
toolCallId: chunk.toolCallId,
toolName: chunk.toolName
}));
break;
}
case "tool-call-delta": {
controller.enqueue(formatDataStreamPart("tool_call_delta", {
toolCallId: chunk.toolCallId,
argsTextDelta: chunk.argsTextDelta
}));
break;
}
case "tool-call": {
controller.enqueue(formatDataStreamPart("tool_call", {
toolCallId: chunk.toolCallId,
toolName: chunk.toolName,
args: chunk.args
}));
break;
}
case "tool-result": {
controller.enqueue(formatDataStreamPart("tool_result", {
toolCallId: chunk.toolCallId,
result: chunk.result
}));
break;
}
case "error": {
controller.enqueue(formatDataStreamPart("error", getErrorMessage5(chunk.error)));
break;
}
case "step-start": {
controller.enqueue(formatDataStreamPart("start_step", {
messageId: chunk.messageId
}));
break;
}
case "step-finish": {
controller.enqueue(formatDataStreamPart("finish_step", {
finishReason: chunk.finishReason,
usage: sendUsage ? {
promptTokens: chunk.usage.promptTokens,
completionTokens: chunk.usage.completionTokens
} : undefined,
isContinued: chunk.isContinued
}));
break;
}
case "finish": {
if (experimental_sendFinish) {
controller.enqueue(formatDataStreamPart("finish_message", {
finishReason: chunk.finishReason,
usage: sendUsage ? {
promptTokens: chunk.usage.promptTokens,
completionTokens: chunk.usage.completionTokens
} : undefined
}));
}
break;
}
default: {
const exhaustiveCheck = chunkType;
throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);
}
}
}
}));
}
pipeDataStreamToResponse(response, {
status,
statusText,
headers,
data,
getErrorMessage: getErrorMessage5,
sendUsage,
sendReasoning,
sendSources,
experimental_sendFinish
} = {}) {
writeToServerResponse({
response,
status,
statusText,
headers: prepareOutgoingHttpHeaders(headers, {
contentType: "text/plain; charset=utf-8",
dataStreamVersion: "v1"
}),
stream: this.toDataStream({
data,
getErrorMessage: getErrorMessage5,
sendUsage,
sendReasoning,
sendSources,
experimental_sendFinish
})
});
}
pipeTextStreamToResponse(response, init) {
writeToServerResponse({
response,
status: init == null ? undefined : init.status,
statusText: init == null ? undefined : init.statusText,
headers: prepareOutgoingHttpHeaders(init == null ? undefined : init.headers, {
contentType: "text/plain; charset=utf-8"
}),
stream: this.textStream.pipeThrough(new TextEncoderStream)
});
}
toDataStream(options) {
const stream = this.toDataStreamInternal({
getErrorMessage: options == null ? undefined : options.getErrorMessage,
sendUsage: options == null ? undefined : options.sendUsage,
sendReasoning: options == null ? undefined : options.sendReasoning,
sendSources: options == null ? undefined : options.sendSources,
experimental_sendFinish: options == null ? undefined : options.experimental_sendFinish
}).pipeThrough(new TextEncoderStream);
return (options == null ? undefined : options.data) ? mergeStreams(options == null ? undefined : options.data.stream, stream) : stream;
}
mergeIntoDataStream(writer, options) {
writer.merge(this.toDataStreamInternal({
getErrorMessage: writer.onError,
sendUsage: options == null ? undefined : options.sendUsage,
sendReasoning: options == null ? undefined : options.sendReasoning,
sendSources: options == null ? undefined : options.sendSources,
experimental_sendFinish: options == null ? undefined : options.experimental_sendFinish
}));
}
toDataStreamResponse({
headers,
status,
statusText,
data,
getErrorMessage: getErrorMessage5,
sendUsage,
sendReasoning,
sendSources,
experimental_sendFinish
} = {}) {
return new Response(this.toDataStream({
data,
getErrorMessage: getErrorMessage5,
sendUsage,
sendReasoning,
sendSources,
experimental_sendFinish
}), {
status,
statusText,
headers: prepareResponseHeaders(headers, {
contentType: "text/plain; charset=utf-8",
dataStreamVersion: "v1"
})
});
}
toTextStreamResponse(init) {
var _a17;
return new Response(this.textStream.pipeThrough(new TextEncoderStream), {
status: (_a17 = init == null ? undefined : init.status) != null ? _a17 : 200,
headers: prepareResponseHeaders(init == null ? undefined : init.headers, {
contentType: "text/plain; charset=utf-8"
})
});
}
};
var name16 = "AI_NoSuchProviderError";
var marker16 = `vercel.ai.error.${name16}`;
var symbol16 = Symbol.for(marker16);
var _a16;
_a16 = symbol16;
var ClientOrServerImplementationSchema = exports_external.object({
name: exports_external.string(),
version: exports_external.string()
}).passthrough();
var BaseParamsSchema = exports_external.object({
_meta: exports_external.optional(exports_external.object({}).passthrough())
}).passthrough();
var ResultSchema2 = BaseParamsSchema;
var RequestSchema2 = exports_external.object({
method: exports_external.string(),
params: exports_external.optional(BaseParamsSchema)
});
var ServerCapabilitiesSchema2 = exports_external.object({
experimental: exports_external.optional(exports_external.object({}).passthrough()),
logging: exports_external.optional(exports_external.object({}).passthrough()),
prompts: exports_external.optional(exports_external.object({
listChanged: exports_external.optional(exports_external.boolean())
}).passthrough()),
resources: exports_external.optional(exports_external.object({
subscribe: exports_external.optional(exports_external.boolean()),
listChanged: exports_external.optional(exports_external.boolean())
}).passthrough()),
tools: exports_external.optional(exports_external.object({
listChanged: exports_external.optional(exports_external.boolean())
}).passthrough())
}).passthrough();
var InitializeResultSchema2 = ResultSchema2.extend({
protocolVersion: exports_external.string(),
capabilities: ServerCapabilitiesSchema2,
serverInfo: ClientOrServerImplementationSchema,
instructions: exports_external.optional(exports_external.string())
});
var PaginatedResultSchema2 = ResultSchema2.extend({
nextCursor: exports_external.optional(exports_external.string())
});
var ToolSchema2 = exports_external.object({
name: exports_external.string(),
description: exports_external.optional(exports_external.string()),
inputSchema: exports_external.object({
type: exports_external.literal("object"),
properties: exports_external.optional(exports_external.object({}).passthrough())
}).passthrough()
}).passthrough();
var ListToolsResultSchema2 = PaginatedResultSchema2.extend({
tools: exports_external.array(ToolSchema2)
});
var TextContentSchema2 = exports_external.object({
type: exports_external.literal("text"),
text: exports_external.string()
}).passthrough();
var ImageContentSchema2 = exports_external.object({
type: exports_external.literal("image"),
data: exports_external.string().base64(),
mimeType: exports_external.string()
}).passthrough();
var ResourceContentsSchema2 = exports_external.object({
uri: exports_external.string(),
mimeType: exports_external.optional(exports_external.string())
}).passthrough();
var TextResourceContentsSchema2 = ResourceContentsSchema2.extend({
text: exports_external.string()
});
var BlobResourceContentsSchema2 = ResourceContentsSchema2.extend({
blob: exports_external.string().base64()
});
var EmbeddedResourceSchema2 = exports_external.object({
type: exports_external.literal("resource"),
resource: exports_external.union([TextResourceContentsSchema2, BlobResourceContentsSchema2])
}).passthrough();
var CallToolResultSchema2 = ResultSchema2.extend({
content: exports_external.array(exports_external.union([TextContentSchema2, ImageContentSchema2, EmbeddedResourceSchema2])),
isError: exports_external.boolean().default(false).optional()
}).or(ResultSchema2.extend({
toolResult: exports_external.unknown()
}));
var JSONRPC_VERSION2 = "2.0";
var JSONRPCRequestSchema2 = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION2),
id: exports_external.union([exports_external.string(), exports_external.number().int()])
}).merge(RequestSchema2).strict();
var JSONRPCResponseSchema2 = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION2),
id: exports_external.union([exports_external.string(), exports_external.number().int()]),
result: ResultSchema2
}).strict();
var JSONRPCErrorSchema2 = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION2),
id: exports_external.union([exports_external.string(), exports_external.number().int()]),
error: exports_external.object({
code: exports_external.number().int(),
message: exports_external.string(),
data: exports_external.optional(exports_external.unknown())
})
}).strict();
var JSONRPCNotificationSchema2 = exports_external.object({
jsonrpc: exports_external.literal(JSONRPC_VERSION2)
}).merge(exports_external.object({
method: exports_external.string(),
params: exports_external.optional(BaseParamsSchema)
})).strict();
var JSONRPCMessageSchema2 = exports_external.union([
JSONRPCRequestSchema2,
JSONRPCNotificationSchema2,
JSONRPCResponseSchema2,
JSONRPCErrorSchema2
]);
var langchain_adapter_exports = {};
__export2(langchain_adapter_exports, {
mergeIntoDataStream: () => mergeIntoDataStream,
toDataStream: () => toDataStream,
toDataStreamResponse: () => toDataStreamResponse
});
function createCallbacksTransformer(callbacks = {}) {
const textEncoder = new TextEncoder;
let aggregatedResponse = "";
return new TransformStream({
async start() {
if (callbacks.onStart)
await callbacks.onStart();
},
async transform(message, controller) {
controller.enqueue(textEncoder.encode(message));
aggregatedResponse += message;
if (callbacks.onToken)
await callbacks.onToken(message);
if (callbacks.onText && typeof message === "string") {
await callbacks.onText(message);
}
},
async flush() {
if (callbacks.onCompletion) {
await callbacks.onCompletion(aggregatedResponse);
}
if (callbacks.onFinal) {
await callbacks.onFinal(aggregatedResponse);
}
}
});
}
function toDataStreamInternal(stream, callbacks) {
return stream.pipeThrough(new TransformStream({
transform: async (value, controller) => {
var _a17;
if (typeof value === "string") {
controller.enqueue(value);
return;
}
if ("event" in value) {
if (value.event === "on_chat_model_stream") {
forwardAIMessageChunk((_a17 = value.data) == null ? undefined : _a17.chunk, controller);
}
return;
}
forwardAIMessageChunk(value, controller);
}
})).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({
transform: async (chunk, controller) => {
controller.enqueue(formatDataStreamPart("text", chunk));
}
}));
}
function toDataStream(stream, callbacks) {
return toDataStreamInternal(stream, callbacks).pipeThrough(new TextEncoderStream);
}
function toDataStreamResponse(stream, options) {
var _a17;
const dataStream = toDataStreamInternal(stream, options == null ? undefined : options.callbacks).pipeThrough(new TextEncoderStream);
const data = options == null ? undefined : options.data;
const init = options == null ? undefined : options.init;
const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
return new Response(responseStream, {
status: (_a17 = init == null ? undefined : init.status) != null ? _a17 : 200,
statusText: init == null ? undefined : init.statusText,
headers: prepareResponseHeaders(init == null ? undefined : init.headers, {
contentType: "text/plain; charset=utf-8",
dataStreamVersion: "v1"
})
});
}
function mergeIntoDataStream(stream, options) {
options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
}
function forwardAIMessageChunk(chunk, controller) {
if (typeof chunk.content === "string") {
controller.enqueue(chunk.content);
} else {
const content = chunk.content;
for (const item of content) {
if (item.type === "text") {
controller.enqueue(item.text);
}
}
}
}
var llamaindex_adapter_exports = {};
__export2(llamaindex_adapter_exports, {
mergeIntoDataStream: () => mergeIntoDataStream2,
toDataStream: () => toDataStream2,
toDataStreamResponse: () => toDataStreamResponse2
});
function toDataStreamInternal2(stream, callbacks) {
const trimStart = trimStartOfStream();
return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough(new TransformStream({
async transform(message, controller) {
controller.enqueue(trimStart(message.delta));
}
})).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({
transform: async (chunk, controller) => {
controller.enqueue(formatDataStreamPart("text", chunk));
}
}));
}
function toDataStream2(stream, callbacks) {
return toDataStreamInternal2(stream, callbacks).pipeThrough(new TextEncoderStream);
}
function toDataStreamResponse2(stream, options = {}) {
var _a17;
const { init, data, callbacks } = options;
const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(new TextEncoderStream);
const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
return new Response(responseStream, {
status: (_a17 = init == null ? undefined : init.status) != null ? _a17 : 200,
statusText: init == null ? undefined : init.statusText,
headers: prepareResponseHeaders(init == null ? undefined : init.headers, {
contentType: "text/plain; charset=utf-8",
dataStreamVersion: "v1"
})
});
}
function mergeIntoDataStream2(stream, options) {
options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
}
function trimStartOfStream() {
let isStreamStart = true;
return (text2) => {
if (isStreamStart) {
text2 = text2.trimStart();
if (text2)
isStreamStart = false;
}
return text2;
};
}
var HANGING_STREAM_WARNING_TIME_MS = 15 * 1000;
// node_modules/@ai-sdk/openai-compatible/dist/index.mjs
function getOpenAIMetadata(message) {
var _a17, _b;
return (_b = (_a17 = message == null ? undefined : message.providerMetadata) == null ? undefined : _a17.openaiCompatible) != null ? _b : {};
}
function convertToOpenAICompatibleChatMessages(prompt) {
const messages = [];
for (const { role, content, ...message } of prompt) {
const metadata = getOpenAIMetadata({ ...message });
switch (role) {
case "system": {
messages.push({ role: "system", content, ...metadata });
break;
}
case "user": {
if (content.length === 1 && content[0].type === "text") {
messages.push({
role: "user",
content: content[0].text,
...getOpenAIMetadata(content[0])
});
break;
}
messages.push({
role: "user",
content: content.map((part) => {
var _a17;
const partMetadata = getOpenAIMetadata(part);
switch (part.type) {
case "text": {
return { type: "text", text: part.text, ...partMetadata };
}
case "image": {
return {
type: "image_url",
image_url: {
url: part.image instanceof URL ? part.image.toString() : `data:${(_a17 = part.mimeType) != null ? _a17 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`
},
...partMetadata
};
}
case "file": {
throw new UnsupportedFunctionalityError({
functionality: "File content parts in user messages"
});
}
}
}),
...metadata
});
break;
}
case "assistant": {
let text2 = "";
const toolCalls = [];
for (const part of content) {
const partMetadata = getOpenAIMetadata(part);
switch (part.type) {
case "text": {
text2 += part.text;
break;
}
case "tool-call": {
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.args)
},
...partMetadata
});
break;
}
}
}
messages.push({
role: "assistant",
content: text2,
tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
...metadata
});
break;
}
case "tool": {
for (const toolResponse of content) {
const toolResponseMetadata = getOpenAIMetadata(toolResponse);
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: JSON.stringify(toolResponse.result),
...toolResponseMetadata
});
}
break;
}
default: {
const _exhaustiveCheck = role;
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
}
}
}
return messages;
}
function getResponseMetadata({
id,
model,
created
}) {
return {
id: id != null ? id : undefined,
modelId: model != null ? model : undefined,
timestamp: created != null ? new Date(created * 1000) : undefined
};
}
function mapOpenAICompatibleFinishReason(finishReason) {
switch (finishReason) {
case "stop":
return "stop";
case "length":
return "length";
case "content_filter":
return "content-filter";
case "function_call":
case "tool_calls":
return "tool-calls";
default:
return "unknown";
}
}
var openaiCompatibleErrorDataSchema = exports_external.object({
error: exports_external.object({
message: exports_external.string(),
type: exports_external.string().nullish(),
param: exports_external.any().nullish(),
code: exports_external.union([exports_external.string(), exports_external.number()]).nullish()
})
});
var defaultOpenAICompatibleErrorStructure = {
errorSchema: openaiCompatibleErrorDataSchema,
errorToMessage: (data) => data.error.message
};
function prepareTools({
mode,
structuredOutputs
}) {
var _a17;
const tools = ((_a17 = mode.tools) == null ? undefined : _a17.length) ? mode.tools : undefined;
const toolWarnings = [];
if (tools == null) {
return { tools: undefined, tool_choice: undefined, toolWarnings };
}
const toolChoice = mode.toolChoice;
const openaiCompatTools = [];
for (const tool of tools) {
if (tool.type === "provider-defined") {
toolWarnings.push({ type: "unsupported-tool", tool });
} else {
openaiCompatTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.parameters
}
});
}
}
if (toolChoice == null) {
return { tools: openaiCompatTools, tool_choice: undefined, toolWarnings };
}
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required":
return { tools: openaiCompatTools, tool_choice: type, toolWarnings };
case "tool":
return {
tools: openaiCompatTools,
tool_choice: {
type: "function",
function: {
name: toolChoice.toolName
}
},
toolWarnings
};
default: {
const _exhaustiveCheck = type;
throw new UnsupportedFunctionalityError({
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
});
}
}
}
var OpenAICompatibleChatLanguageModel = class {
constructor(modelId, settings, config) {
this.specificationVersion = "v1";
var _a17, _b;
this.modelId = modelId;
this.settings = settings;
this.config = config;
const errorStructure = (_a17 = config.errorStructure) != null ? _a17 : defaultOpenAICompatibleErrorStructure;
this.chunkSchema = createOpenAICompatibleChatChunkSchema(errorStructure.errorSchema);
this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
this.supportsStructuredOutputs = (_b = config.supportsStructuredOutputs) != null ? _b : false;
}
get defaultObjectGenerationMode() {
return this.config.defaultObjectGenerationMode;
}
get provider() {
return this.config.provider;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
getArgs({
mode,
prompt,
maxTokens,
temperature,
topP,
topK,
frequencyPenalty,
presencePenalty,
providerMetadata,
stopSequences,
responseFormat,
seed
}) {
var _a17, _b, _c, _d, _e;
const type = mode.type;
const warnings = [];
if (topK != null) {
warnings.push({
type: "unsupported-setting",
setting: "topK"
});
}
if ((responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) {
warnings.push({
type: "unsupported-setting",
setting: "responseFormat",
details: "JSON response format schema is only supported with structuredOutputs"
});
}
const baseArgs = {
model: this.modelId,
user: this.settings.user,
max_tokens: maxTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
response_format: (responseFormat == null ? undefined : responseFormat.type) === "json" ? this.supportsStructuredOutputs === true && responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
name: (_a17 = responseFormat.name) != null ? _a17 : "response",
description: responseFormat.description
}
} : { type: "json_object" } : undefined,
stop: stopSequences,
seed,
...providerMetadata == null ? undefined : providerMetadata[this.providerOptionsName],
reasoning_effort: (_d = (_b = providerMetadata == null ? undefined : providerMetadata[this.providerOptionsName]) == null ? undefined : _b.reasoningEffort) != null ? _d : (_c = providerMetadata == null ? undefined : providerMetadata["openai-compatible"]) == null ? undefined : _c.reasoningEffort,
messages: convertToOpenAICompatibleChatMessages(prompt)
};
switch (type) {
case "regular": {
const { tools, tool_choice, toolWarnings } = prepareTools({
mode,
structuredOutputs: this.supportsStructuredOutputs
});
return {
args: { ...baseArgs, tools, tool_choice },
warnings: [...warnings, ...toolWarnings]
};
}
case "object-json": {
return {
args: {
...baseArgs,
response_format: this.supportsStructuredOutputs === true && mode.schema != null ? {
type: "json_schema",
json_schema: {
schema: mode.schema,
name: (_e = mode.name) != null ? _e : "response",
description: mode.description
}
} : { type: "json_object" }
},
warnings
};
}
case "object-tool": {
return {
args: {
...baseArgs,
tool_choice: {
type: "function",
function: { name: mode.tool.name }
},
tools: [
{
type: "function",
function: {
name: mode.tool.name,
description: mode.tool.description,
parameters: mode.tool.parameters
}
}
]
},
warnings
};
}
default: {
const _exhaustiveCheck = type;
throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
}
}
}
async doGenerate(options) {
var _a17, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
const { args, warnings } = this.getArgs({ ...options });
const body = JSON.stringify(args);
const {
responseHeaders,
value: responseBody,
rawValue: rawResponse
} = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(this.config.headers(), options.headers),
body: args,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(OpenAICompatibleChatResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const { messages: rawPrompt, ...rawSettings } = args;
const choice = responseBody.choices[0];
const providerMetadata = {
[this.providerOptionsName]: {},
...(_b = (_a17 = this.config.metadataExtractor) == null ? undefined : _a17.extractMetadata) == null ? undefined : _b.call(_a17, {
parsedBody: rawResponse
})
};
const completionTokenDetails = (_c = responseBody.usage) == null ? undefined : _c.completion_tokens_details;
const promptTokenDetails = (_d = responseBody.usage) == null ? undefined : _d.prompt_tokens_details;
if ((completionTokenDetails == null ? undefined : completionTokenDetails.reasoning_tokens) != null) {
providerMetadata[this.providerOptionsName].reasoningTokens = completionTokenDetails == null ? undefined : completionTokenDetails.reasoning_tokens;
}
if ((completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens) != null) {
providerMetadata[this.providerOptionsName].acceptedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens;
}
if ((completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens) != null) {
providerMetadata[this.providerOptionsName].rejectedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens;
}
if ((promptTokenDetails == null ? undefined : promptTokenDetails.cached_tokens) != null) {
providerMetadata[this.providerOptionsName].cachedPromptTokens = promptTokenDetails == null ? undefined : promptTokenDetails.cached_tokens;
}
return {
text: (_e = choice.message.content) != null ? _e : undefined,
reasoning: (_f = choice.message.reasoning_content) != null ? _f : undefined,
toolCalls: (_g = choice.message.tool_calls) == null ? undefined : _g.map((toolCall) => {
var _a23;
return {
toolCallType: "function",
toolCallId: (_a23 = toolCall.id) != null ? _a23 : generateId(),
toolName: toolCall.function.name,
args: toolCall.function.arguments
};
}),
finishReason: mapOpenAICompatibleFinishReason(choice.finish_reason),
usage: {
promptTokens: (_i = (_h = responseBody.usage) == null ? undefined : _h.prompt_tokens) != null ? _i : NaN,
completionTokens: (_k = (_j = responseBody.usage) == null ? undefined : _j.completion_tokens) != null ? _k : NaN
},
providerMetadata,
rawCall: { rawPrompt, rawSettings },
rawResponse: { headers: responseHeaders, body: rawResponse },
response: getResponseMetadata(responseBody),
warnings,
request: { body }
};
}
async doStream(options) {
var _a17;
if (this.settings.simulateStreaming) {
const result = await this.doGenerate(options);
const simulatedStream = new ReadableStream({
start(controller) {
controller.enqueue({ type: "response-metadata", ...result.response });
if (result.reasoning) {
if (Array.isArray(result.reasoning)) {
for (const part of result.reasoning) {
if (part.type === "text") {
controller.enqueue({
type: "reasoning",
textDelta: part.text
});
}
}
} else {
controller.enqueue({
type: "reasoning",
textDelta: result.reasoning
});
}
}
if (result.text) {
controller.enqueue({
type: "text-delta",
textDelta: result.text
});
}
if (result.toolCalls) {
for (const toolCall of result.toolCalls) {
controller.enqueue({
type: "tool-call",
...toolCall
});
}
}
controller.enqueue({
type: "finish",
finishReason: result.finishReason,
usage: result.usage,
logprobs: result.logprobs,
providerMetadata: result.providerMetadata
});
controller.close();
}
});
return {
stream: simulatedStream,
rawCall: result.rawCall,
rawResponse: result.rawResponse,
warnings: result.warnings
};
}
const { args, warnings } = this.getArgs({ ...options });
const body = {
...args,
stream: true,
stream_options: this.config.includeUsage ? { include_usage: true } : undefined
};
const metadataExtractor = (_a17 = this.config.metadataExtractor) == null ? undefined : _a17.createStreamExtractor();
const { responseHeaders, value: response } = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(this.config.headers(), options.headers),
body,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler(this.chunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const { messages: rawPrompt, ...rawSettings } = args;
const toolCalls = [];
let finishReason = "unknown";
let usage = {
completionTokens: undefined,
completionTokensDetails: {
reasoningTokens: undefined,
acceptedPredictionTokens: undefined,
rejectedPredictionTokens: undefined
},
promptTokens: undefined,
promptTokensDetails: {
cachedTokens: undefined
}
};
let isFirstChunk = true;
let providerOptionsName = this.providerOptionsName;
return {
stream: response.pipeThrough(new TransformStream({
transform(chunk, controller) {
var _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
if (!chunk.success) {
finishReason = "error";
controller.enqueue({ type: "error", error: chunk.error });
return;
}
const value = chunk.value;
metadataExtractor == null || metadataExtractor.processChunk(chunk.rawValue);
if ("error" in value) {
finishReason = "error";
controller.enqueue({ type: "error", error: value.error.message });
return;
}
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...getResponseMetadata(value)
});
}
if (value.usage != null) {
const {
prompt_tokens,
completion_tokens,
prompt_tokens_details,
completion_tokens_details
} = value.usage;
usage.promptTokens = prompt_tokens != null ? prompt_tokens : undefined;
usage.completionTokens = completion_tokens != null ? completion_tokens : undefined;
if ((completion_tokens_details == null ? undefined : completion_tokens_details.reasoning_tokens) != null) {
usage.completionTokensDetails.reasoningTokens = completion_tokens_details == null ? undefined : completion_tokens_details.reasoning_tokens;
}
if ((completion_tokens_details == null ? undefined : completion_tokens_details.accepted_prediction_tokens) != null) {
usage.completionTokensDetails.acceptedPredictionTokens = completion_tokens_details == null ? undefined : completion_tokens_details.accepted_prediction_tokens;
}
if ((completion_tokens_details == null ? undefined : completion_tokens_details.rejected_prediction_tokens) != null) {
usage.completionTokensDetails.rejectedPredictionTokens = completion_tokens_details == null ? undefined : completion_tokens_details.rejected_prediction_tokens;
}
if ((prompt_tokens_details == null ? undefined : prompt_tokens_details.cached_tokens) != null) {
usage.promptTokensDetails.cachedTokens = prompt_tokens_details == null ? undefined : prompt_tokens_details.cached_tokens;
}
}
const choice = value.choices[0];
if ((choice == null ? undefined : choice.finish_reason) != null) {
finishReason = mapOpenAICompatibleFinishReason(choice.finish_reason);
}
if ((choice == null ? undefined : choice.delta) == null) {
return;
}
const delta = choice.delta;
if (delta.reasoning_content != null) {
controller.enqueue({
type: "reasoning",
textDelta: delta.reasoning_content
});
}
if (delta.content != null) {
controller.enqueue({
type: "text-delta",
textDelta: delta.content
});
}
if (delta.tool_calls != null) {
for (const toolCallDelta of delta.tool_calls) {
const index = toolCallDelta.index;
if (toolCalls[index] == null) {
if (toolCallDelta.type !== "function") {
throw new InvalidResponseDataError({
data: toolCallDelta,
message: `Expected 'function' type.`
});
}
if (toolCallDelta.id == null) {
throw new InvalidResponseDataError({
data: toolCallDelta,
message: `Expected 'id' to be a string.`
});
}
if (((_a23 = toolCallDelta.function) == null ? undefined : _a23.name) == null) {
throw new InvalidResponseDataError({
data: toolCallDelta,
message: `Expected 'function.name' to be a string.`
});
}
toolCalls[index] = {
id: toolCallDelta.id,
type: "function",
function: {
name: toolCallDelta.function.name,
arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
},
hasFinished: false
};
const toolCall2 = toolCalls[index];
if (((_c = toolCall2.function) == null ? undefined : _c.name) != null && ((_d = toolCall2.function) == null ? undefined : _d.arguments) != null) {
if (toolCall2.function.arguments.length > 0) {
controller.enqueue({
type: "tool-call-delta",
toolCallType: "function",
toolCallId: toolCall2.id,
toolName: toolCall2.function.name,
argsTextDelta: toolCall2.function.arguments
});
}
if (isParsableJson(toolCall2.function.arguments)) {
controller.enqueue({
type: "tool-call",
toolCallType: "function",
toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
toolName: toolCall2.function.name,
args: toolCall2.function.arguments
});
toolCall2.hasFinished = true;
}
}
continue;
}
const toolCall = toolCalls[index];
if (toolCall.hasFinished) {
continue;
}
if (((_f = toolCallDelta.function) == null ? undefined : _f.arguments) != null) {
toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? undefined : _g.arguments) != null ? _h : "";
}
controller.enqueue({
type: "tool-call-delta",
toolCallType: "function",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
});
if (((_j = toolCall.function) == null ? undefined : _j.name) != null && ((_k = toolCall.function) == null ? undefined : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
controller.enqueue({
type: "tool-call",
toolCallType: "function",
toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
toolName: toolCall.function.name,
args: toolCall.function.arguments
});
toolCall.hasFinished = true;
}
}
}
},
flush(controller) {
var _a23, _b;
const providerMetadata = {
[providerOptionsName]: {},
...metadataExtractor == null ? undefined : metadataExtractor.buildMetadata()
};
if (usage.completionTokensDetails.reasoningTokens != null) {
providerMetadata[providerOptionsName].reasoningTokens = usage.completionTokensDetails.reasoningTokens;
}
if (usage.completionTokensDetails.acceptedPredictionTokens != null) {
providerMetadata[providerOptionsName].acceptedPredictionTokens = usage.completionTokensDetails.acceptedPredictionTokens;
}
if (usage.completionTokensDetails.rejectedPredictionTokens != null) {
providerMetadata[providerOptionsName].rejectedPredictionTokens = usage.completionTokensDetails.rejectedPredictionTokens;
}
if (usage.promptTokensDetails.cachedTokens != null) {
providerMetadata[providerOptionsName].cachedPromptTokens = usage.promptTokensDetails.cachedTokens;
}
controller.enqueue({
type: "finish",
finishReason,
usage: {
promptTokens: (_a23 = usage.promptTokens) != null ? _a23 : NaN,
completionTokens: (_b = usage.completionTokens) != null ? _b : NaN
},
providerMetadata
});
}
})),
rawCall: { rawPrompt, rawSettings },
rawResponse: { headers: responseHeaders },
warnings,
request: { body: JSON.stringify(body) }
};
}
};
var openaiCompatibleTokenUsageSchema = exports_external.object({
prompt_tokens: exports_external.number().nullish(),
completion_tokens: exports_external.number().nullish(),
prompt_tokens_details: exports_external.object({
cached_tokens: exports_external.number().nullish()
}).nullish(),
completion_tokens_details: exports_external.object({
reasoning_tokens: exports_external.number().nullish(),
accepted_prediction_tokens: exports_external.number().nullish(),
rejected_prediction_tokens: exports_external.number().nullish()
}).nullish()
}).nullish();
var OpenAICompatibleChatResponseSchema = exports_external.object({
id: exports_external.string().nullish(),
created: exports_external.number().nullish(),
model: exports_external.string().nullish(),
choices: exports_external.array(exports_external.object({
message: exports_external.object({
role: exports_external.literal("assistant").nullish(),
content: exports_external.string().nullish(),
reasoning_content: exports_external.string().nullish(),
tool_calls: exports_external.array(exports_external.object({
id: exports_external.string().nullish(),
type: exports_external.literal("function"),
function: exports_external.object({
name: exports_external.string(),
arguments: exports_external.string()
})
})).nullish()
}),
finish_reason: exports_external.string().nullish()
})),
usage: openaiCompatibleTokenUsageSchema
});
var createOpenAICompatibleChatChunkSchema = (errorSchema) => exports_external.union([
exports_external.object({
id: exports_external.string().nullish(),
created: exports_external.number().nullish(),
model: exports_external.string().nullish(),
choices: exports_external.array(exports_external.object({
delta: exports_external.object({
role: exports_external.enum(["assistant"]).nullish(),
content: exports_external.string().nullish(),
reasoning_content: exports_external.string().nullish(),
tool_calls: exports_external.array(exports_external.object({
index: exports_external.number(),
id: exports_external.string().nullish(),
type: exports_external.literal("function").nullish(),
function: exports_external.object({
name: exports_external.string().nullish(),
arguments: exports_external.string().nullish()
})
})).nullish()
}).nullish(),
finish_reason: exports_external.string().nullish()
})),
usage: openaiCompatibleTokenUsageSchema
}),
errorSchema
]);
var openaiCompatibleCompletionResponseSchema = exports_external.object({
id: exports_external.string().nullish(),
created: exports_external.number().nullish(),
model: exports_external.string().nullish(),
choices: exports_external.array(exports_external.object({
text: exports_external.string(),
finish_reason: exports_external.string()
})),
usage: exports_external.object({
prompt_tokens: exports_external.number(),
completion_tokens: exports_external.number()
}).nullish()
});
var openaiTextEmbeddingResponseSchema = exports_external.object({
data: exports_external.array(exports_external.object({ embedding: exports_external.array(exports_external.number()) })),
usage: exports_external.object({ prompt_tokens: exports_external.number() }).nullish()
});
var openaiCompatibleImageResponseSchema = exports_external.object({
data: exports_external.array(exports_external.object({ b64_json: exports_external.string() }))
});
// node_modules/@ai-sdk/vercel/dist/index.mjs
function createVercel(options = {}) {
var _a17;
const baseURL = withoutTrailingSlash((_a17 = options.baseURL) != null ? _a17 : "https://api.v0.dev/v1");
const getHeaders = () => ({
Authorization: `Bearer ${loadApiKey({
apiKey: options.apiKey,
environmentVariableName: "VERCEL_API_KEY",
description: "Vercel"
})}`,
...options.headers
});
const getCommonModelConfig = (modelType) => ({
provider: `vercel.${modelType}`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createChatModel = (modelId, settings = {}) => {
return new OpenAICompatibleChatLanguageModel(modelId, settings, {
...getCommonModelConfig("chat"),
defaultObjectGenerationMode: "json"
});
};
const provider = (modelId, settings) => createChatModel(modelId, settings);
provider.chatModel = createChatModel;
provider.languageModel = createChatModel;
provider.textEmbeddingModel = (modelId) => {
throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
};
return provider;
}
var vercel = createVercel();
// src/index.ts
var import_config = __toESM(require_config(), 1);
var V0_API_KEY = process.env["V0_API_KEY"];
if (!V0_API_KEY) {
console.error("V0_API_KEY environment variable is required");
process.exit(1);
}
var server = new McpServer({
name: "v0-mcp-ts",
version: "1.0.0",
description: "A powerful MCP server integrating v0.dev AI capabilities for modern web development"
});
var vercelProvider = createVercel({
apiKey: V0_API_KEY
});
var v0Model = vercelProvider("v0-1.0-md");
async function generateWithOptimalStreaming(prompt, maxTokens = 4000, useStreaming = true) {
if (useStreaming) {
const result = await streamText({
model: v0Model,
prompt,
maxTokens,
temperature: 0.7
});
let fullText = "";
const chunks = [];
for await (const textPart of result.textStream) {
fullText += textPart;
chunks.push(textPart);
if (chunks.length % 100 === 0) {
await new Promise((resolve) => setImmediate(resolve));
}
}
return {
text: fullText,
usage: await result.usage,
streamed: true,
chunkCount: chunks.length
};
} else {
const result = await generateText({
model: v0Model,
prompt,
maxTokens,
temperature: 0.7
});
return {
text: result.text,
usage: result.usage,
streamed: false,
chunkCount: 0
};
}
}
server.tool("generate_webapp", "Generate complete web applications with AI assistance", {
prompt: exports_external.string().describe("Description of the web application to generate"),
framework: exports_external.enum(["nextjs", "react", "vue", "svelte"]).optional().describe("Preferred framework (default: nextjs)"),
features: exports_external.array(exports_external.string()).optional().describe('Specific features to include (e.g., ["authentication", "database", "api"])'),
stream: exports_external.boolean().optional().default(true).describe("Whether to stream the response (default: true for better performance)")
}, async ({ prompt, framework = "nextjs", features = [], stream = true }) => {
try {
let enhancedPrompt = `Create a ${framework} application: ${prompt}`;
if (features.length > 0) {
enhancedPrompt += `
Required features: ${features.join(", ")}`;
}
enhancedPrompt += `
Please provide complete, production-ready code with proper file structure, dependencies, and best practices.`;
const result = await generateWithOptimalStreaming(enhancedPrompt, 4000, stream);
return {
content: [
{
type: "text",
text: result.text
}
],
metadata: {
framework,
features,
streamed: result.streamed,
chunkCount: result.chunkCount,
performance: {
streamingEnabled: stream,
responseTime: Date.now()
},
usage: result.usage
}
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error generating web application: ${error instanceof Error ? error.message : "Unknown error"}`
}
],
isError: true
};
}
});
server.tool("enhance_code", "Improve existing code with AI-powered suggestions", {
code: exports_external.string().describe("Existing code to enhance"),
enhancement: exports_external.string().describe("Description of the enhancement needed"),
language: exports_external.string().optional().default("typescript").describe("Programming language of the code"),
stream: exports_external.boolean().optional().default(true).describe("Whether to stream the response for faster feedback")
}, async ({ code, enhancement, language, stream = true }) => {
try {
const prompt = `Enhance this ${language} code: ${enhancement}
Existing code:
\`\`\`${language}
${code}
\`\`\`
Please provide the enhanced version with explanations of the changes made.`;
const result = await generateWithOptimalStreaming(prompt, 3000, stream);
return {
content: [
{
type: "text",
text: result.text
}
],
metadata: {
language,
streamed: result.streamed,
chunkCount: result.chunkCount,
codeLength: code.length,
usage: result.usage
}
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error enhancing code: ${error instanceof Error ? error.message : "Unknown error"}`
}
],
isError: true
};
}
});
server.tool("debug_code", "Debug and fix code issues automatically", {
code: exports_external.string().describe("Code with issues to debug"),
error_message: exports_external.string().optional().describe("Error message if available"),
language: exports_external.string().optional().default("typescript").describe("Programming language"),
stream: exports_external.boolean().optional().default(true).describe("Whether to stream the response for real-time debugging")
}, async ({ code, error_message, language, stream = true }) => {
try {
let prompt = `Debug and fix this ${language} code:
\`\`\`${language}
${code}
\`\`\``;
if (error_message) {
prompt += `
Error message: ${error_message}`;
}
prompt += `
Please identify the issues and provide the corrected code with explanations.`;
const result = await generateWithOptimalStreaming(prompt, 3000, stream);
return {
content: [
{
type: "text",
text: result.text
}
],
metadata: {
language,
had_error_message: !!error_message,
streamed: result.streamed,
chunkCount: result.chunkCount,
usage: result.usage
}
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error debugging code: ${error instanceof Error ? error.message : "Unknown error"}`
}
],
isError: true
};
}
});
server.tool("generate_component", "Create reusable components with proper TypeScript types", {
component_name: exports_external.string().describe("Name of the component to generate"),
description: exports_external.string().describe("Description of what the component should do"),
framework: exports_external.enum(["react", "vue", "svelte"]).optional().default("react").describe("Component framework"),
props: exports_external.array(exports_external.object({
name: exports_external.string(),
type: exports_external.string(),
required: exports_external.boolean().optional().default(false),
description: exports_external.string().optional()
})).optional().describe("Component props specification"),
stream: exports_external.boolean().optional().default(true).describe("Whether to stream the response for faster component generation")
}, async ({
component_name,
description,
framework,
props = [],
stream = true
}) => {
try {
let prompt = `Create a ${framework} component named "${component_name}": ${description}`;
if (props.length > 0) {
prompt += `
Props:`;
props.forEach((prop) => {
prompt += `
- ${prop.name}: ${prop.type}${prop.required ? " (required)" : " (optional)"}`;
if (prop.description) {
prompt += ` - ${prop.description}`;
}
});
}
prompt += `
Please provide a complete, reusable component with TypeScript types, proper styling, and documentation.`;
const result = await generateWithOptimalStreaming(prompt, 2500, stream);
return {
content: [
{
type: "text",
text: result.text
}
],
metadata: {
component_name,
framework,
props_count: props.length,
streamed: result.streamed,
chunkCount: result.chunkCount,
usage: result.usage
}
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error generating component: ${error instanceof Error ? error.message : "Unknown error"}`
}
],
isError: true
};
}
});
server.resource("v0-api-docs", "v0://api-docs", async () => ({
contents: [
{
uri: "v0://api-docs",
mimeType: "text/markdown",
text: `# v0.dev API Documentation
## Model: v0-1.0-md
The v0-1.0-md model is designed for building modern web applications with the following features:
- **Framework aware**: Optimized for Next.js, React, Vue, Svelte and other modern frameworks
- **Auto-fix**: Automatically identifies and corrects common coding issues
- **Quick edit**: Provides streaming inline edits
- **Multimodal**: Supports both text and image inputs
- **OpenAI compatible**: Works with standard OpenAI API format
## Usage Limits
- Max messages per day: 200
- Max context window: 128,000 tokens
- Max output: 32,000 tokens
## Best Practices
1. Be specific about the framework and features you want
2. Provide context about existing code when asking for enhancements
3. Include error messages when debugging
4. Specify component props and styling requirements
## Supported Frameworks
- Next.js (recommended)
- React
- Vue
- Svelte
- And other modern web frameworks
For more information, visit: https://vercel.com/docs/v0/api`
}
]
}));
server.prompt("create-webapp", {
description: exports_external.string().describe("Description of the web application"),
framework: exports_external.string().optional().describe("Preferred framework"),
features: exports_external.string().optional().describe("Comma-separated list of features")
}, ({ description, framework = "nextjs", features = "" }) => ({
messages: [
{
role: "user",
content: {
type: "text",
text: `Create a ${framework} web application: ${description}
${features ? `Required features: ${features}` : ""}
Please provide:
1. Complete file structure
2. All necessary code files
3. Package.json with dependencies
4. Setup instructions
5. Best practices implementation
Make it production-ready with proper error handling, TypeScript types, and modern patterns.`
}
}
]
}));
process.on("unhandledRejection", (reason, promise2) => {
console.error("Unhandled Rejection at:", promise2, "reason:", reason);
});
process.on("uncaughtException", (error) => {
console.error("Uncaught Exception:", error);
process.exit(1);
});
async function main() {
try {
const transport = new StdioServerTransport;
await server.connect(transport);
console.error("v0-mcp-ts server started successfully");
} catch (error) {
console.error("Failed to start server:", error);
process.exit(1);
}
}
main().catch(console.error);