/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[Object.keys(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod3) => function __require() { return mod3 || (0, cb[Object.keys(cb)[0]])((mod3 = { exports: {} }).exports, mod3), mod3.exports; }; var __export = (target, all) => { __markAsModule(target); for (var name2 in all) __defProp(target, name2, { get: all[name2], enumerable: true }); }; var __reExport = (target, module2, desc) => { if (module2 && typeof module2 === "object" || typeof module2 === "function") { for (let key of __getOwnPropNames(module2)) if (!__hasOwnProp.call(target, key) && key !== "default") __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); } return target; }; var __toModule = (module2) => { return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2); }; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var __toBinary = /* @__PURE__ */ (() => { var table = new Uint8Array(128); for (var i2 = 0; i2 < 64; i2++) table[i2 < 26 ? i2 + 65 : i2 < 52 ? i2 + 71 : i2 < 62 ? i2 - 4 : i2 * 4 - 205] = i2; return (base642) => { var n2 = base642.length, bytes = new Uint8Array((n2 - (base642[n2 - 1] == "=") - (base642[n2 - 2] == "=")) * 3 / 4 | 0); for (var i3 = 0, j2 = 0; i3 < n2; ) { var c0 = table[base642.charCodeAt(i3++)], c1 = table[base642.charCodeAt(i3++)]; var c2 = table[base642.charCodeAt(i3++)], c3 = table[base642.charCodeAt(i3++)]; bytes[j2++] = c0 << 2 | c1 >> 4; bytes[j2++] = c1 << 4 | c2 >> 2; bytes[j2++] = c2 << 6 | c3; } return bytes; }; })(); // node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js var require_ms = __commonJS({ "node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js"(exports2, module2) { var s2 = 1e3; var m2 = s2 * 60; var h2 = m2 * 60; var d2 = h2 * 24; var y2 = d2 * 365.25; module2.exports = function(val, options) { options = options || {}; var type2 = typeof val; if (type2 === "string" && val.length > 0) { return parse3(val); } else if (type2 === "number" && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); }; function parse3(str3) { str3 = String(str3); if (str3.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str3); if (!match) { return; } var n2 = parseFloat(match[1]); var type2 = (match[2] || "ms").toLowerCase(); switch (type2) { case "years": case "year": case "yrs": case "yr": case "y": return n2 * y2; case "days": case "day": case "d": return n2 * d2; case "hours": case "hour": case "hrs": case "hr": case "h": return n2 * h2; case "minutes": case "minute": case "mins": case "min": case "m": return n2 * m2; case "seconds": case "second": case "secs": case "sec": case "s": return n2 * s2; case "milliseconds": case "millisecond": case "msecs": case "msec": case "ms": return n2; default: return void 0; } } function fmtShort(ms) { if (ms >= d2) { return Math.round(ms / d2) + "d"; } if (ms >= h2) { return Math.round(ms / h2) + "h"; } if (ms >= m2) { return Math.round(ms / m2) + "m"; } if (ms >= s2) { return Math.round(ms / s2) + "s"; } return ms + "ms"; } function fmtLong(ms) { return plural(ms, d2, "day") || plural(ms, h2, "hour") || plural(ms, m2, "minute") || plural(ms, s2, "second") || ms + " ms"; } function plural(ms, n2, name2) { if (ms < n2) { return; } if (ms < n2 * 1.5) { return Math.floor(ms / n2) + " " + name2; } return Math.ceil(ms / n2) + " " + name2 + "s"; } } }); // node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/debug.js var require_debug = __commonJS({ "node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/debug.js"(exports2, module2) { exports2 = module2.exports = createDebug.debug = createDebug["default"] = createDebug; exports2.coerce = coerce2; exports2.disable = disable; exports2.enable = enable; exports2.enabled = enabled; exports2.humanize = require_ms(); exports2.names = []; exports2.skips = []; exports2.formatters = {}; var prevTime; function selectColor(namespace) { var hash = 0, i2; for (i2 in namespace) { hash = (hash << 5) - hash + namespace.charCodeAt(i2); hash |= 0; } return exports2.colors[Math.abs(hash) % exports2.colors.length]; } function createDebug(namespace) { function debug44() { if (!debug44.enabled) return; var self2 = debug44; var curr = +new Date(); var ms = curr - (prevTime || curr); self2.diff = ms; self2.prev = prevTime; self2.curr = curr; prevTime = curr; var args = new Array(arguments.length); for (var i2 = 0; i2 < args.length; i2++) { args[i2] = arguments[i2]; } args[0] = exports2.coerce(args[0]); if (typeof args[0] !== "string") { args.unshift("%O"); } var index2 = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { if (match === "%%") return match; index2++; var formatter = exports2.formatters[format]; if (typeof formatter === "function") { var val = args[index2]; match = formatter.call(self2, val); args.splice(index2, 1); index2--; } return match; }); exports2.formatArgs.call(self2, args); var logFn = debug44.log || exports2.log || console.log.bind(console); logFn.apply(self2, args); } debug44.namespace = namespace; debug44.enabled = exports2.enabled(namespace); debug44.useColors = exports2.useColors(); debug44.color = selectColor(namespace); if (typeof exports2.init === "function") { exports2.init(debug44); } return debug44; } function enable(namespaces) { exports2.save(namespaces); exports2.names = []; exports2.skips = []; var split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/); var len = split.length; for (var i2 = 0; i2 < len; i2++) { if (!split[i2]) continue; namespaces = split[i2].replace(/\*/g, ".*?"); if (namespaces[0] === "-") { exports2.skips.push(new RegExp("^" + namespaces.substr(1) + "$")); } else { exports2.names.push(new RegExp("^" + namespaces + "$")); } } } function disable() { exports2.enable(""); } function enabled(name2) { var i2, len; for (i2 = 0, len = exports2.skips.length; i2 < len; i2++) { if (exports2.skips[i2].test(name2)) { return false; } } for (i2 = 0, len = exports2.names.length; i2 < len; i2++) { if (exports2.names[i2].test(name2)) { return true; } } return false; } function coerce2(val) { if (val instanceof Error) return val.stack || val.message; return val; } } }); // node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/browser.js var require_browser = __commonJS({ "node_modules/.pnpm/debug@2.6.9/node_modules/debug/src/browser.js"(exports2, module2) { exports2 = module2.exports = require_debug(); exports2.log = log; exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load4; exports2.useColors = useColors; exports2.storage = typeof chrome != "undefined" && typeof chrome.storage != "undefined" ? chrome.storage.local : localstorage(); exports2.colors = [ "lightseagreen", "forestgreen", "goldenrod", "dodgerblue", "darkorchid", "crimson" ]; function useColors() { if (typeof window !== "undefined" && window.process && window.process.type === "renderer") { return true; } return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } exports2.formatters.j = function(v2) { try { return JSON.stringify(v2); } catch (err) { return "[UnexpectedJSONParseError]: " + err.message; } }; function formatArgs(args) { var useColors2 = this.useColors; args[0] = (useColors2 ? "%c" : "") + this.namespace + (useColors2 ? " %c" : " ") + args[0] + (useColors2 ? "%c " : " ") + "+" + exports2.humanize(this.diff); if (!useColors2) return; var c2 = "color: " + this.color; args.splice(1, 0, c2, "color: inherit"); var index2 = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if (match === "%%") return; index2++; if (match === "%c") { lastC = index2; } }); args.splice(lastC, 0, c2); } function log() { return typeof console === "object" && console.log && Function.prototype.apply.call(console.log, console, arguments); } function save(namespaces) { try { if (namespaces == null) { exports2.storage.removeItem("debug"); } else { exports2.storage.debug = namespaces; } } catch (e2) { } } function load4() { var r3; try { r3 = exports2.storage.debug; } catch (e2) { } if (!r3 && typeof process !== "undefined" && "env" in process) { r3 = process.env.DEBUG; } return r3; } exports2.enable(load4()); function localstorage() { try { return window.localStorage; } catch (e2) { } } } }); // node_modules/.pnpm/decamelize@1.2.0/node_modules/decamelize/index.js var require_decamelize = __commonJS({ "node_modules/.pnpm/decamelize@1.2.0/node_modules/decamelize/index.js"(exports2, module2) { "use strict"; module2.exports = function(str3, sep) { if (typeof str3 !== "string") { throw new TypeError("Expected a string"); } sep = typeof sep === "undefined" ? "_" : sep; return str3.replace(/([a-z\d])([A-Z])/g, "$1" + sep + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + sep + "$2").toLowerCase(); }; } }); // node_modules/.pnpm/camelcase@6.3.0/node_modules/camelcase/index.js var require_camelcase = __commonJS({ "node_modules/.pnpm/camelcase@6.3.0/node_modules/camelcase/index.js"(exports2, module2) { "use strict"; var UPPERCASE = /[\p{Lu}]/u; var LOWERCASE = /[\p{Ll}]/u; var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; var SEPARATORS = /[_.\- ]+/; var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source); var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu"); var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu"); var preserveCamelCase = (string, toLowerCase, toUpperCase) => { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; for (let i2 = 0; i2 < string.length; i2++) { const character = string[i2]; if (isLastCharLower && UPPERCASE.test(character)) { string = string.slice(0, i2) + "-" + string.slice(i2); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; i2++; } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { string = string.slice(0, i2 - 1) + "-" + string.slice(i2 - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; } } return string; }; var preserveConsecutiveUppercase = (input, toLowerCase) => { LEADING_CAPITAL.lastIndex = 0; return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1)); }; var postProcess2 = (input, toUpperCase) => { SEPARATORS_AND_IDENTIFIER.lastIndex = 0; NUMBERS_AND_IDENTIFIER.lastIndex = 0; return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m2) => toUpperCase(m2)); }; var camelCase2 = (input, options) => { if (!(typeof input === "string" || Array.isArray(input))) { throw new TypeError("Expected the input to be `string | string[]`"); } options = { pascalCase: false, preserveConsecutiveUppercase: false, ...options }; if (Array.isArray(input)) { input = input.map((x2) => x2.trim()).filter((x2) => x2.length).join("-"); } else { input = input.trim(); } if (input.length === 0) { return ""; } const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale); const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale); if (input.length === 1) { return options.pascalCase ? toUpperCase(input) : toLowerCase(input); } const hasUpperCase = input !== toLowerCase(input); if (hasUpperCase) { input = preserveCamelCase(input, toLowerCase, toUpperCase); } input = input.replace(LEADING_SEPARATORS, ""); if (options.preserveConsecutiveUppercase) { input = preserveConsecutiveUppercase(input, toLowerCase); } else { input = toLowerCase(input); } if (options.pascalCase) { input = toUpperCase(input.charAt(0)) + input.slice(1); } return postProcess2(input, toUpperCase); }; module2.exports = camelCase2; module2.exports.default = camelCase2; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/load/map_keys.js function keyToJson(key, map2) { return map2?.[key] || (0, import_decamelize.default)(key); } function keyFromJson(key, map2) { return map2?.[key] || (0, import_camelcase.default)(key); } function mapKeys(fields2, mapper, map2) { const mapped = {}; for (const key in fields2) { if (Object.hasOwn(fields2, key)) { mapped[mapper(key, map2)] = fields2[key]; } } return mapped; } var import_decamelize, import_camelcase; var init_map_keys = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/load/map_keys.js"() { import_decamelize = __toModule(require_decamelize()); import_camelcase = __toModule(require_camelcase()); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/load/serializable.js var serializable_exports = {}; __export(serializable_exports, { Serializable: () => Serializable, get_lc_unique_name: () => get_lc_unique_name }); function shallowCopy(obj) { return Array.isArray(obj) ? [...obj] : { ...obj }; } function replaceSecrets(root3, secretsMap) { const result = shallowCopy(root3); for (const [path, secretId] of Object.entries(secretsMap)) { const [last, ...partsReverse] = path.split(".").reverse(); let current = result; for (const part of partsReverse.reverse()) { if (current[part] === void 0) { break; } current[part] = shallowCopy(current[part]); current = current[part]; } if (current[last] !== void 0) { current[last] = { lc: 1, type: "secret", id: [secretId] }; } } return result; } function get_lc_unique_name(serializableClass) { const parentClass = Object.getPrototypeOf(serializableClass); const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name()); if (lcNameIsSubclassed) { return serializableClass.lc_name(); } else { return serializableClass.name; } } var Serializable; var init_serializable = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/load/serializable.js"() { init_map_keys(); Serializable = class { static lc_name() { return this.name; } get lc_id() { return [ ...this.lc_namespace, get_lc_unique_name(this.constructor) ]; } get lc_secrets() { return void 0; } get lc_attributes() { return void 0; } get lc_aliases() { return void 0; } constructor(kwargs, ..._args) { Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "lc_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.lc_kwargs = kwargs || {}; } toJSON() { if (!this.lc_serializable) { return this.toJSONNotImplemented(); } if (this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)) { return this.toJSONNotImplemented(); } const aliases = {}; const secrets = {}; const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { acc[key] = key in this ? this[key] : this.lc_kwargs[key]; return acc; }, {}); for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); } Object.keys(secrets).forEach((keyPath) => { let read2 = this; let write = kwargs; const [last, ...partsReverse] = keyPath.split(".").reverse(); for (const key of partsReverse.reverse()) { if (!(key in read2) || read2[key] === void 0) return; if (!(key in write) || write[key] === void 0) { if (typeof read2[key] === "object" && read2[key] != null) { write[key] = {}; } else if (Array.isArray(read2[key])) { write[key] = []; } } read2 = read2[key]; write = write[key]; } if (last in read2 && read2[last] !== void 0) { write[last] = write[last] || read2[last]; } }); return { lc: 1, type: "constructor", id: this.lc_id, kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases) }; } toJSONNotImplemented() { return { lc: 1, type: "not_implemented", id: this.lc_id }; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/messages/index.js var messages_exports = {}; __export(messages_exports, { AIMessage: () => AIMessage, AIMessageChunk: () => AIMessageChunk, BaseMessage: () => BaseMessage, BaseMessageChunk: () => BaseMessageChunk, ChatMessage: () => ChatMessage, ChatMessageChunk: () => ChatMessageChunk, FunctionMessage: () => FunctionMessage, FunctionMessageChunk: () => FunctionMessageChunk, HumanMessage: () => HumanMessage, HumanMessageChunk: () => HumanMessageChunk, SystemMessage: () => SystemMessage, SystemMessageChunk: () => SystemMessageChunk, ToolMessage: () => ToolMessage, ToolMessageChunk: () => ToolMessageChunk, coerceMessageLikeToMessage: () => coerceMessageLikeToMessage, getBufferString: () => getBufferString, isBaseMessage: () => isBaseMessage, isBaseMessageChunk: () => isBaseMessageChunk, mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages }); function mergeContent(firstContent, secondContent) { if (typeof firstContent === "string") { if (typeof secondContent === "string") { return firstContent + secondContent; } else { return [{ type: "text", text: firstContent }, ...secondContent]; } } else if (Array.isArray(secondContent)) { return [...firstContent, ...secondContent]; } else { return [...firstContent, { type: "text", text: secondContent }]; } } function isOpenAIToolCallArray(value) { return Array.isArray(value) && value.every((v2) => typeof v2.index === "number"); } function _mergeDicts(left, right) { const merged = { ...left }; for (const [key, value] of Object.entries(right)) { if (merged[key] == null) { merged[key] = value; } else if (value == null) { continue; } else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) { throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); } else if (typeof merged[key] === "string") { merged[key] = merged[key] + value; } else if (!Array.isArray(merged[key]) && typeof merged[key] === "object") { merged[key] = _mergeDicts(merged[key], value); } else if (key === "tool_calls" && isOpenAIToolCallArray(merged[key]) && isOpenAIToolCallArray(value)) { for (const toolCall of value) { if (merged[key]?.[toolCall.index] !== void 0) { merged[key] = merged[key]?.map((value2, i2) => { if (i2 !== toolCall.index) { return value2; } return { ...value2, ...toolCall, function: { name: toolCall.function.name ?? value2.function.name, arguments: (value2.function.arguments ?? "") + (toolCall.function.arguments ?? "") } }; }); } else { merged[key][toolCall.index] = toolCall; } } } else if (Array.isArray(merged[key])) { merged[key] = merged[key].concat(value); } else if (merged[key] === value) { continue; } else { console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); } } return merged; } function isBaseMessage(messageLike) { return typeof messageLike?._getType === "function"; } function isBaseMessageChunk(messageLike) { return isBaseMessage(messageLike) && typeof messageLike.concat === "function"; } function coerceMessageLikeToMessage(messageLike) { if (typeof messageLike === "string") { return new HumanMessage(messageLike); } else if (isBaseMessage(messageLike)) { return messageLike; } const [type2, content] = messageLike; if (type2 === "human" || type2 === "user") { return new HumanMessage({ content }); } else if (type2 === "ai" || type2 === "assistant") { return new AIMessage({ content }); } else if (type2 === "system") { return new SystemMessage({ content }); } else { throw new Error(`Unable to coerce message from array: only human, AI, or system message coercion is currently supported.`); } } function getBufferString(messages4, humanPrefix = "Human", aiPrefix = "AI") { const string_messages = []; for (const m2 of messages4) { let role; if (m2._getType() === "human") { role = humanPrefix; } else if (m2._getType() === "ai") { role = aiPrefix; } else if (m2._getType() === "system") { role = "System"; } else if (m2._getType() === "function") { role = "Function"; } else if (m2._getType() === "tool") { role = "Tool"; } else if (m2._getType() === "generic") { role = m2.role; } else { throw new Error(`Got unsupported message type: ${m2._getType()}`); } const nameStr = m2.name ? `${m2.name}, ` : ""; string_messages.push(`${role}: ${nameStr}${m2.content}`); } return string_messages.join("\n"); } function mapV1MessageToStoredMessage(message) { if (message.data !== void 0) { return message; } else { const v1Message = message; return { type: v1Message.type, data: { content: v1Message.text, role: v1Message.role, name: void 0, tool_call_id: void 0 } }; } } function mapStoredMessageToChatMessage(message) { const storedMessage = mapV1MessageToStoredMessage(message); switch (storedMessage.type) { case "human": return new HumanMessage(storedMessage.data); case "ai": return new AIMessage(storedMessage.data); case "system": return new SystemMessage(storedMessage.data); case "function": if (storedMessage.data.name === void 0) { throw new Error("Name must be defined for function messages"); } return new FunctionMessage(storedMessage.data); case "tool": if (storedMessage.data.tool_call_id === void 0) { throw new Error("Tool call ID must be defined for tool messages"); } return new ToolMessage(storedMessage.data); case "chat": { if (storedMessage.data.role === void 0) { throw new Error("Role must be defined for chat messages"); } return new ChatMessage(storedMessage.data); } default: throw new Error(`Got unexpected type: ${storedMessage.type}`); } } function mapStoredMessagesToChatMessages(messages4) { return messages4.map(mapStoredMessageToChatMessage); } function mapChatMessagesToStoredMessages(messages4) { return messages4.map((message) => message.toDict()); } var BaseMessage, BaseMessageChunk, HumanMessage, HumanMessageChunk, AIMessage, AIMessageChunk, SystemMessage, SystemMessageChunk, FunctionMessage, FunctionMessageChunk, ToolMessage, ToolMessageChunk, ChatMessage, ChatMessageChunk; var init_messages = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/messages/index.js"() { init_serializable(); BaseMessage = class extends Serializable { get lc_aliases() { return { additional_kwargs: "additional_kwargs", response_metadata: "response_metadata" }; } get text() { return typeof this.content === "string" ? this.content : ""; } constructor(fields2, kwargs) { if (typeof fields2 === "string") { fields2 = { content: fields2, additional_kwargs: kwargs, response_metadata: {} }; } if (!fields2.additional_kwargs) { fields2.additional_kwargs = {}; } if (!fields2.response_metadata) { fields2.response_metadata = {}; } super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "messages"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "content", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "additional_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "response_metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.name = fields2.name; this.content = fields2.content; this.additional_kwargs = fields2.additional_kwargs; this.response_metadata = fields2.response_metadata; } toDict() { return { type: this._getType(), data: this.toJSON().kwargs }; } toChunk() { const type2 = this._getType(); if (type2 === "human") { return new HumanMessageChunk({ ...this }); } else if (type2 === "ai") { return new AIMessageChunk({ ...this }); } else if (type2 === "system") { return new SystemMessageChunk({ ...this }); } else if (type2 === "function") { return new FunctionMessageChunk({ ...this }); } else if (ChatMessage.isInstance(this)) { return new ChatMessageChunk({ ...this }); } else { throw new Error("Unknown message type."); } } }; BaseMessageChunk = class extends BaseMessage { }; HumanMessage = class extends BaseMessage { static lc_name() { return "HumanMessage"; } _getType() { return "human"; } }; HumanMessageChunk = class extends BaseMessageChunk { static lc_name() { return "HumanMessageChunk"; } _getType() { return "human"; } concat(chunk) { return new HumanMessageChunk({ content: mergeContent(this.content, chunk.content), additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata) }); } }; AIMessage = class extends BaseMessage { static lc_name() { return "AIMessage"; } _getType() { return "ai"; } }; AIMessageChunk = class extends BaseMessageChunk { static lc_name() { return "AIMessageChunk"; } _getType() { return "ai"; } concat(chunk) { return new AIMessageChunk({ content: mergeContent(this.content, chunk.content), additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata) }); } }; SystemMessage = class extends BaseMessage { static lc_name() { return "SystemMessage"; } _getType() { return "system"; } }; SystemMessageChunk = class extends BaseMessageChunk { static lc_name() { return "SystemMessageChunk"; } _getType() { return "system"; } concat(chunk) { return new SystemMessageChunk({ content: mergeContent(this.content, chunk.content), additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata) }); } }; FunctionMessage = class extends BaseMessage { static lc_name() { return "FunctionMessage"; } constructor(fields2, name2) { if (typeof fields2 === "string") { fields2 = { content: fields2, name: name2 }; } super(fields2); } _getType() { return "function"; } }; FunctionMessageChunk = class extends BaseMessageChunk { static lc_name() { return "FunctionMessageChunk"; } _getType() { return "function"; } concat(chunk) { return new FunctionMessageChunk({ content: mergeContent(this.content, chunk.content), additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), name: this.name ?? "" }); } }; ToolMessage = class extends BaseMessage { static lc_name() { return "ToolMessage"; } get lc_aliases() { return { tool_call_id: "tool_call_id" }; } constructor(fields2, tool_call_id, name2) { if (typeof fields2 === "string") { fields2 = { content: fields2, name: name2, tool_call_id }; } super(fields2); Object.defineProperty(this, "tool_call_id", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.tool_call_id = fields2.tool_call_id; } _getType() { return "tool"; } static isInstance(message) { return message._getType() === "tool"; } }; ToolMessageChunk = class extends BaseMessageChunk { constructor(fields2) { super(fields2); Object.defineProperty(this, "tool_call_id", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.tool_call_id = fields2.tool_call_id; } static lc_name() { return "ToolMessageChunk"; } _getType() { return "tool"; } concat(chunk) { return new ToolMessageChunk({ content: mergeContent(this.content, chunk.content), additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), tool_call_id: this.tool_call_id }); } }; ChatMessage = class extends BaseMessage { static lc_name() { return "ChatMessage"; } static _chatMessageClass() { return ChatMessage; } constructor(fields2, role) { if (typeof fields2 === "string") { fields2 = { content: fields2, role }; } super(fields2); Object.defineProperty(this, "role", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.role = fields2.role; } _getType() { return "generic"; } static isInstance(message) { return message._getType() === "generic"; } }; ChatMessageChunk = class extends BaseMessageChunk { static lc_name() { return "ChatMessageChunk"; } constructor(fields2, role) { if (typeof fields2 === "string") { fields2 = { content: fields2, role }; } super(fields2); Object.defineProperty(this, "role", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.role = fields2.role; } _getType() { return "generic"; } concat(chunk) { return new ChatMessageChunk({ content: mergeContent(this.content, chunk.content), additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), role: this.role }); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/messages.js var init_messages2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/messages.js"() { init_messages(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/env.js var env_exports = {}; __export(env_exports, { getEnv: () => getEnv, getEnvironmentVariable: () => getEnvironmentVariable, getRuntimeEnvironment: () => getRuntimeEnvironment, isBrowser: () => isBrowser, isDeno: () => isDeno, isJsDom: () => isJsDom, isNode: () => isNode, isWebWorker: () => isWebWorker }); async function getRuntimeEnvironment() { if (runtimeEnvironment === void 0) { const env = getEnv(); runtimeEnvironment = { library: "langchain-js", runtime: env }; } return runtimeEnvironment; } function getEnvironmentVariable(name2) { try { return typeof process !== "undefined" ? process.env?.[name2] : void 0; } catch (e2) { return void 0; } } var isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, runtimeEnvironment; var init_env = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/env.js"() { isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom")); isDeno = () => typeof Deno !== "undefined"; isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); getEnv = () => { let env; if (isBrowser()) { env = "browser"; } else if (isNode()) { env = "node"; } else if (isWebWorker()) { env = "webworker"; } else if (isJsDom()) { env = "jsdom"; } else if (isDeno()) { env = "deno"; } else { env = "other"; } return env; }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/utils/env.js var init_env2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/utils/env.js"() { init_env(); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/util/env.js var init_env3 = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/util/env.js"() { init_env2(); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/util/entrypoint_deprecation.js var init_entrypoint_deprecation = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/util/entrypoint_deprecation.js"() { init_env3(); } }); // node_modules/.pnpm/zod@3.22.4/node_modules/zod/lib/index.mjs function setErrorMap(map2) { overrideErrorMap = map2; } function getErrorMap() { return overrideErrorMap; } function addIssueToContext(ctx, issueData) { const issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap ].filter((x2) => !!x2) }); ctx.common.issues.push(issue); } function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description: description2 } = 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: description2 }; const customMap = (iss, ctx) => { if (iss.code !== "invalid_type") return { message: ctx.defaultError }; if (typeof ctx.data === "undefined") { return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; } return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; }; return { errorMap: customMap, description: description2 }; } function isValidIP(ip, version3) { if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) { return true; } if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) { return true; } return false; } 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 = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / Math.pow(10, decCount); } function deepPartialify(schema3) { if (schema3 instanceof ZodObject) { const newShape = {}; for (const key in schema3.shape) { const fieldSchema = schema3.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema3._def, shape: () => newShape }); } else if (schema3 instanceof ZodArray) { return new ZodArray({ ...schema3._def, type: deepPartialify(schema3.element) }); } else if (schema3 instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema3.unwrap())); } else if (schema3 instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema3.unwrap())); } else if (schema3 instanceof ZodTuple) { return ZodTuple.create(schema3.items.map((item) => deepPartialify(item))); } else { return schema3; } } function mergeValues(a2, b2) { const aType = getParsedType(a2); const bType = getParsedType(b2); if (a2 === b2) { return { valid: true, data: a2 }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b2); const sharedKeys = util.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a2, ...b2 }; for (const key of sharedKeys) { const sharedValue = mergeValues(a2[key], b2[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 (a2.length !== b2.length) { return { valid: false }; } const newArray = []; for (let index2 = 0; index2 < a2.length; index2++) { const itemA = a2[index2]; const itemB = b2[index2]; 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 && +a2 === +b2) { return { valid: true, data: a2 }; } else { return { valid: false }; } } function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, quotelessJson, ZodError, errorMap, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv6Regex, datetimeRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, custom, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER, z; var init_lib = __esm({ "node_modules/.pnpm/zod@3.22.4/node_modules/zod/lib/index.mjs"() { (function(util3) { util3.assertEqual = (val) => val; function assertIs(_arg) { } util3.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util3.assertNever = assertNever; util3.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util3.getValidEnumValues = (obj) => { const validKeys = util3.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number"); const filtered = {}; for (const k2 of validKeys) { filtered[k2] = obj[k2]; } return util3.objectValues(filtered); }; util3.objectValues = (obj) => { return util3.objectKeys(obj).map(function(e2) { return obj[e2]; }); }; util3.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; }; util3.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util3.joinValues = joinValues; util3.jsonStringifyReplacer = (_2, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second }; }; })(objectUtil || (objectUtil = {})); ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); getParsedType = (data) => { const t2 = typeof data; switch (t2) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return 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; } }; 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" ]); quotelessJson = (obj) => { const json2 = JSON.stringify(obj, null, 2); return json2.replace(/"([^"]+)":/g, "$1:"); }; ZodError = class extends Error { 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; } get errors() { return this.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 i2 = 0; while (i2 < issue.path.length) { const el = issue.path[i2]; const terminal = i2 === 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]; i2++; } } } }; processError(this); return fieldErrors; } 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; }; 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 }; }; overrideErrorMap = errorMap; makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; let errorMessage = ""; const maps = errorMaps.filter((m2) => !!m2).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: issueData.message || errorMessage }; }; EMPTY_PATH = []; ParseStatus = class { 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 s2 of results) { if (s2.status === "aborted") return INVALID; if (s2.status === "dirty") status.dirty(); arrayValue.push(s2.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs2) { const syncPairs = []; for (const pair of pairs2) { syncPairs.push({ key: await pair.key, value: await pair.value }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs2) { const finalObject = {}; for (const pair of pairs2) { 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 }; } }; INVALID = Object.freeze({ status: "aborted" }); DIRTY = (value) => ({ status: "dirty", value }); OK = (value) => ({ status: "valid", value }); isAborted = (x2) => x2.status === "aborted"; isDirty = (x2) => x2.status === "dirty"; isValid = (x2) => x2.status === "valid"; isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil || (errorUtil = {})); ParseInputLazyPath = class { 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 (this._key instanceof Array) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; 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; } }; } }; ZodType = class { 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); } 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) { var _a4; const ctx = { common: { issues: [], async: (_a4 = params === null || params === void 0 ? void 0 : params.async) !== null && _a4 !== void 0 ? _a4 : false, contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap }, path: (params === null || params === void 0 ? void 0 : 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); } 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 === null || params === void 0 ? void 0 : params.errorMap, async: true }, path: (params === null || params === void 0 ? void 0 : 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); } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this, this._def); } 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(transform2) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform: transform2 } }); } 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(description2) { const This = this.constructor; return new This({ ...this._def, description: description2 }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; cuidRegex = /^c[^\s-]{8,}$/i; cuid2Regex = /^[a-z][a-z0-9]*$/; ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; 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; emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; ipv4Regex = /^(((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}))$/; ipv6Regex = /^(([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})))$/; datetimeRegex = (args) => { if (args.precision) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); } } else if (args.precision === 0) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); } } else { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); } } }; ZodString = class 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 = void 0; 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 === "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 (_a4) { 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 regex2 = datetimeRegex(check); if (!regex2.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 === "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 { util.assertNever(check); } } return { status: status.value, value: input.data }; } _regex(regex2, validation, message) { return this.refinement((data) => regex2.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) }); } 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) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } datetime(options) { var _a4; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, offset: (_a4 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a4 !== void 0 ? _a4 : false, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } regex(regex2, message) { return this._addCheck({ kind: "regex", regex: regex2, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options === null || options === void 0 ? void 0 : options.position, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : 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 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 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 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) => { var _a4; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (_a4 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a4 !== void 0 ? _a4 : false, ...processCreateParams(params) }); }; ZodNumber = class 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 = void 0; 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(kind4, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: kind4, 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, 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 === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; ZodBigInt = class extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { input.data = BigInt(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; 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 }; } 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(kind4, value, inclusive, message) { return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind: kind4, 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) => { var _a4; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (_a4 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a4 !== void 0 ? _a4 : false, ...processCreateParams(params) }); }; ZodBoolean = class 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 === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; ZodDate = class 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 (isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; 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 === null || params === void 0 ? void 0 : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; ZodSymbol = class 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) }); }; ZodUndefined = class 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) }); }; ZodNull = class 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) }); }; ZodAny = class 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) }); }; ZodUnknown = class 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) }); }; ZodNever = class 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) }); }; ZodVoid = class 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) }); }; ZodArray = class 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 : void 0, maximum: tooBig ? def.exactLength.value : void 0, 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, i2) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i2) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); }); 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 = (schema3, params) => { return new ZodArray({ type: schema3, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; ZodObject = class 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); return this._cached = { shape, keys }; } _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 pairs2 = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs2.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) { pairs2.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]; pairs2.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 pairs2) { const key = await pair.key; syncPairs.push({ key, value: await pair.value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs2); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue, ctx) => { var _a4, _b, _c, _d; const defaultError = (_c = (_b = (_a4 = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a4, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : 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, schema3) { return this.augment({ [key]: schema3 }); } catchall(index2) { return new ZodObject({ ...this._def, catchall: index2 }); } pick(mask) { const shape = {}; util.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; util.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { 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 = {}; util.objectKeys(this.shape).forEach((key) => { 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) }); }; ZodUnion = class 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 = void 0; 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) }); }; getDiscriminator = (type2) => { if (type2 instanceof ZodLazy) { return getDiscriminator(type2.schema); } else if (type2 instanceof ZodEffects) { return getDiscriminator(type2.innerType()); } else if (type2 instanceof ZodLiteral) { return [type2.value]; } else if (type2 instanceof ZodEnum) { return type2.options; } else if (type2 instanceof ZodNativeEnum) { return Object.keys(type2.enum); } else if (type2 instanceof ZodDefault) { return getDiscriminator(type2._def.innerType); } else if (type2 instanceof ZodUndefined) { return [void 0]; } else if (type2 instanceof ZodNull) { return [null]; } else { return null; } }; ZodDiscriminatedUnion = class 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 type2 of options) { const discriminatorValues = getDiscriminator(type2.shape[discriminator]); if (!discriminatorValues) { 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, type2); } } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; ZodIntersection = class 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) }); }; ZodTuple = class 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 schema3 = this._def.items[itemIndex] || this._def.rest; if (!schema3) return null; return schema3._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x2) => !!x2); 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) }); }; ZodRecord = class 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 pairs2 = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs2.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)) }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs2); } else { return ParseStatus.mergeObjectSync(status, pairs2); } } 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) }); } }; ZodMap = class 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 pairs2 = [...ctx.data.entries()].map(([key, value], index2) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) }; }); if (ctx.common.async) { const finalMap = new Map(); return Promise.resolve().then(async () => { for (const pair of pairs2) { 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 pairs2) { 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) }); }; ZodSet = class 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, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2))); 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) }); }; ZodFunction = class 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(), errorMap ].filter((x2) => !!x2), 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(), errorMap ].filter((x2) => !!x2), 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 me2 = this; return OK(async function(...args) { const error = new ZodError([]); const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e2) => { error.addIssue(makeArgsIssue(args, e2)); throw error; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e2) => { error.addIssue(makeReturnsIssue(result, e2)); throw error; }); return parsedReturns; }); } else { const me2 = this; return OK(function(...args) { const parsedArgs = me2._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 = me2._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) }); } }; ZodLazy = class 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) }); }; ZodLiteral = class 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) }); }; ZodEnum = class 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._def.values.indexOf(input.data) === -1) { 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) { return ZodEnum.create(values); } exclude(values) { return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); } }; ZodEnum.create = createZodEnum; ZodNativeEnum = class 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 (nativeEnumValues.indexOf(input.data) === -1) { 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) }); }; ZodPromise = class 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 = (schema3, params) => { return new ZodPromise({ type: schema3, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; ZodEffects = class 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.issues.length) { return { status: "dirty", value: ctx.data }; } if (ctx.common.async) { return Promise.resolve(processed).then((processed2) => { return this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); }); } else { return this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); } } 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 base; 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 base; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema3, effect, params) => { return new ZodEffects({ schema: schema3, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess, schema3, params) => { return new ZodEffects({ schema: schema3, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; ZodOptional = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type2, params) => { return new ZodOptional({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; ZodNullable = class 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 = (type2, params) => { return new ZodNullable({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; ZodDefault = class 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 = (type2, params) => { return new ZodDefault({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; ZodCatch = class 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 = (type2, params) => { return new ZodCatch({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; ZodNaN = class 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) }); }; BRAND = Symbol("zod_brand"); ZodBranded = class 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; } }; ZodPipeline = class 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(a2, b2) { return new ZodPipeline({ in: a2, out: b2, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; ZodReadonly = class extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); if (isValid(result)) { result.value = Object.freeze(result.value); } return result; } }; ZodReadonly.create = (type2, params) => { return new ZodReadonly({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; custom = (check, params = {}, fatal) => { if (check) return ZodAny.create().superRefine((data, ctx) => { var _a4, _b; if (!check(data)) { const p2 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const _fatal = (_b = (_a4 = p2.fatal) !== null && _a4 !== void 0 ? _a4 : fatal) !== null && _b !== void 0 ? _b : true; const p22 = typeof p2 === "string" ? { message: p2 } : p2; ctx.addIssue({ code: "custom", ...p22, fatal: _fatal }); } }); return ZodAny.create(); }; late = { object: ZodObject.lazycreate }; (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 = {})); instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); stringType = ZodString.create; numberType = ZodNumber.create; nanType = ZodNaN.create; bigIntType = ZodBigInt.create; booleanType = ZodBoolean.create; dateType = ZodDate.create; symbolType = ZodSymbol.create; undefinedType = ZodUndefined.create; nullType = ZodNull.create; anyType = ZodAny.create; unknownType = ZodUnknown.create; neverType = ZodNever.create; voidType = ZodVoid.create; arrayType = ZodArray.create; objectType = ZodObject.create; strictObjectType = ZodObject.strictCreate; unionType = ZodUnion.create; discriminatedUnionType = ZodDiscriminatedUnion.create; intersectionType = ZodIntersection.create; tupleType = ZodTuple.create; recordType = ZodRecord.create; mapType = ZodMap.create; setType = ZodSet.create; functionType = ZodFunction.create; lazyType = ZodLazy.create; literalType = ZodLiteral.create; enumType = ZodEnum.create; nativeEnumType = ZodNativeEnum.create; promiseType = ZodPromise.create; effectsType = ZodEffects.create; optionalType = ZodOptional.create; nullableType = ZodNullable.create; preprocessType = ZodEffects.createWithPreprocess; pipelineType = ZodPipeline.create; ostring = () => stringType().optional(); onumber = () => numberType().optional(); oboolean = () => booleanType().optional(); 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 }) }; NEVER = INVALID; z = /* @__PURE__ */ Object.freeze({ __proto__: null, defaultErrorMap: errorMap, setErrorMap, getErrorMap, makeIssue, EMPTY_PATH, addIssueToContext, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, get util() { return util; }, get objectUtil() { return objectUtil; }, ZodParsedType, getParsedType, ZodType, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodTransformer: ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, custom, Schema: ZodType, ZodSchema: ZodType, late, get ZodFirstPartyTypeKind() { return ZodFirstPartyTypeKind; }, coerce, any: anyType, array: arrayType, bigint: bigIntType, boolean: booleanType, date: dateType, discriminatedUnion: discriminatedUnionType, effect: effectsType, "enum": enumType, "function": functionType, "instanceof": instanceOfType, intersection: intersectionType, lazy: lazyType, literal: literalType, map: mapType, nan: nanType, nativeEnum: nativeEnumType, never: neverType, "null": nullType, nullable: nullableType, number: numberType, object: objectType, oboolean, onumber, optional: optionalType, ostring, pipeline: pipelineType, preprocess: preprocessType, promise: promiseType, record: recordType, set: setType, strictObject: strictObjectType, string: stringType, symbol: symbolType, transformer: effectsType, tuple: tupleType, "undefined": undefinedType, union: unionType, unknown: unknownType, "void": voidType, NEVER, ZodIssueCode, quotelessJson, ZodError }); } }); // node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js var require_retry_operation = __commonJS({ "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports2, module2) { function RetryOperation(timeouts, options) { if (typeof options === "boolean") { options = { forever: options }; } this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); this._timeouts = timeouts; this._options = options || {}; this._maxRetryTime = options && options.maxRetryTime || Infinity; this._fn = null; this._errors = []; this._attempts = 1; this._operationTimeout = null; this._operationTimeoutCb = null; this._timeout = null; this._operationStart = null; this._timer = null; if (this._options.forever) { this._cachedTimeouts = this._timeouts.slice(0); } } module2.exports = RetryOperation; RetryOperation.prototype.reset = function() { this._attempts = 1; this._timeouts = this._originalTimeouts.slice(0); }; RetryOperation.prototype.stop = function() { if (this._timeout) { clearTimeout(this._timeout); } if (this._timer) { clearTimeout(this._timer); } this._timeouts = []; this._cachedTimeouts = null; }; RetryOperation.prototype.retry = function(err) { if (this._timeout) { clearTimeout(this._timeout); } if (!err) { return false; } var currentTime = new Date().getTime(); if (err && currentTime - this._operationStart >= this._maxRetryTime) { this._errors.push(err); this._errors.unshift(new Error("RetryOperation timeout occurred")); return false; } this._errors.push(err); var timeout = this._timeouts.shift(); if (timeout === void 0) { if (this._cachedTimeouts) { this._errors.splice(0, this._errors.length - 1); timeout = this._cachedTimeouts.slice(-1); } else { return false; } } var self2 = this; this._timer = setTimeout(function() { self2._attempts++; if (self2._operationTimeoutCb) { self2._timeout = setTimeout(function() { self2._operationTimeoutCb(self2._attempts); }, self2._operationTimeout); if (self2._options.unref) { self2._timeout.unref(); } } self2._fn(self2._attempts); }, timeout); if (this._options.unref) { this._timer.unref(); } return true; }; RetryOperation.prototype.attempt = function(fn, timeoutOps) { this._fn = fn; if (timeoutOps) { if (timeoutOps.timeout) { this._operationTimeout = timeoutOps.timeout; } if (timeoutOps.cb) { this._operationTimeoutCb = timeoutOps.cb; } } var self2 = this; if (this._operationTimeoutCb) { this._timeout = setTimeout(function() { self2._operationTimeoutCb(); }, self2._operationTimeout); } this._operationStart = new Date().getTime(); this._fn(this._attempts); }; RetryOperation.prototype.try = function(fn) { console.log("Using RetryOperation.try() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = function(fn) { console.log("Using RetryOperation.start() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = RetryOperation.prototype.try; RetryOperation.prototype.errors = function() { return this._errors; }; RetryOperation.prototype.attempts = function() { return this._attempts; }; RetryOperation.prototype.mainError = function() { if (this._errors.length === 0) { return null; } var counts = {}; var mainError = null; var mainErrorCount = 0; for (var i2 = 0; i2 < this._errors.length; i2++) { var error = this._errors[i2]; var message = error.message; var count = (counts[message] || 0) + 1; counts[message] = count; if (count >= mainErrorCount) { mainError = error; mainErrorCount = count; } } return mainError; }; } }); // node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js var require_retry = __commonJS({ "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports2) { var RetryOperation = require_retry_operation(); exports2.operation = function(options) { var timeouts = exports2.timeouts(options); return new RetryOperation(timeouts, { forever: options && (options.forever || options.retries === Infinity), unref: options && options.unref, maxRetryTime: options && options.maxRetryTime }); }; exports2.timeouts = function(options) { if (options instanceof Array) { return [].concat(options); } var opts = { retries: 10, factor: 2, minTimeout: 1 * 1e3, maxTimeout: Infinity, randomize: false }; for (var key in options) { opts[key] = options[key]; } if (opts.minTimeout > opts.maxTimeout) { throw new Error("minTimeout is greater than maxTimeout"); } var timeouts = []; for (var i2 = 0; i2 < opts.retries; i2++) { timeouts.push(this.createTimeout(i2, opts)); } if (options && options.forever && !timeouts.length) { timeouts.push(this.createTimeout(i2, opts)); } timeouts.sort(function(a2, b2) { return a2 - b2; }); return timeouts; }; exports2.createTimeout = function(attempt, opts) { var random = opts.randomize ? Math.random() + 1 : 1; var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); timeout = Math.min(timeout, opts.maxTimeout); return timeout; }; exports2.wrap = function(obj, options, methods) { if (options instanceof Array) { methods = options; options = null; } if (!methods) { methods = []; for (var key in obj) { if (typeof obj[key] === "function") { methods.push(key); } } } for (var i2 = 0; i2 < methods.length; i2++) { var method = methods[i2]; var original = obj[method]; obj[method] = function retryWrapper(original2) { var op = exports2.operation(options); var args = Array.prototype.slice.call(arguments, 1); var callback = args.pop(); args.push(function(err) { if (op.retry(err)) { return; } if (err) { arguments[0] = op.mainError(); } callback.apply(this, arguments); }); op.attempt(function() { original2.apply(obj, args); }); }.bind(obj, original); obj[method].options = options; } }; } }); // node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js var require_retry2 = __commonJS({ "node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports2, module2) { module2.exports = require_retry(); } }); // node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js var require_p_retry = __commonJS({ "node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js"(exports2, module2) { "use strict"; var retry = require_retry2(); var networkErrorMsgs = [ "Failed to fetch", "NetworkError when attempting to fetch resource.", "The Internet connection appears to be offline.", "Network request failed" ]; var AbortError = class extends Error { constructor(message) { super(); if (message instanceof Error) { this.originalError = message; ({ message } = message); } else { this.originalError = new Error(message); this.originalError.stack = this.stack; } this.name = "AbortError"; this.message = message; } }; var decorateErrorWithCounts = (error, attemptNumber, options) => { const retriesLeft = options.retries - (attemptNumber - 1); error.attemptNumber = attemptNumber; error.retriesLeft = retriesLeft; return error; }; var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); var pRetry4 = (input, options) => new Promise((resolve, reject) => { options = { onFailedAttempt: () => { }, retries: 10, ...options }; const operation = retry.operation(options); operation.attempt(async (attemptNumber) => { try { resolve(await input(attemptNumber)); } catch (error) { if (!(error instanceof Error)) { reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); return; } if (error instanceof AbortError) { operation.stop(); reject(error.originalError); } else if (error instanceof TypeError && !isNetworkError(error.message)) { operation.stop(); reject(error); } else { decorateErrorWithCounts(error, attemptNumber, options); try { await options.onFailedAttempt(error); } catch (error2) { reject(error2); return; } if (!operation.retry(error)) { reject(operation.mainError()); } } } }); }); module2.exports = pRetry4; module2.exports.default = pRetry4; module2.exports.AbortError = AbortError; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/rng.js function rng() { if (!getRandomValues) { getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); if (!getRandomValues) { throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); } } return getRandomValues(rnds8); } var getRandomValues, rnds8; var init_rng = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/rng.js"() { rnds8 = new Uint8Array(16); } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/regex.js var regex_default; var init_regex = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/regex.js"() { regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/validate.js function validate(uuid6) { return typeof uuid6 === "string" && regex_default.test(uuid6); } var validate_default; var init_validate = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/validate.js"() { init_regex(); validate_default = validate; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/stringify.js function unsafeStringify(arr, offset = 0) { return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; } var byteToHex; var init_stringify = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/stringify.js"() { byteToHex = []; for (let i2 = 0; i2 < 256; ++i2) { byteToHex.push((i2 + 256).toString(16).slice(1)); } } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/parse.js function parse(uuid6) { if (!validate_default(uuid6)) { throw TypeError("Invalid UUID"); } let v2; const arr = new Uint8Array(16); arr[0] = (v2 = parseInt(uuid6.slice(0, 8), 16)) >>> 24; arr[1] = v2 >>> 16 & 255; arr[2] = v2 >>> 8 & 255; arr[3] = v2 & 255; arr[4] = (v2 = parseInt(uuid6.slice(9, 13), 16)) >>> 8; arr[5] = v2 & 255; arr[6] = (v2 = parseInt(uuid6.slice(14, 18), 16)) >>> 8; arr[7] = v2 & 255; arr[8] = (v2 = parseInt(uuid6.slice(19, 23), 16)) >>> 8; arr[9] = v2 & 255; arr[10] = (v2 = parseInt(uuid6.slice(24, 36), 16)) / 1099511627776 & 255; arr[11] = v2 / 4294967296 & 255; arr[12] = v2 >>> 24 & 255; arr[13] = v2 >>> 16 & 255; arr[14] = v2 >>> 8 & 255; arr[15] = v2 & 255; return arr; } var parse_default; var init_parse = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/parse.js"() { init_validate(); parse_default = parse; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v35.js function stringToBytes(str3) { str3 = unescape(encodeURIComponent(str3)); const bytes = []; for (let i2 = 0; i2 < str3.length; ++i2) { bytes.push(str3.charCodeAt(i2)); } return bytes; } function v35(name2, version3, hashfunc) { function generateUUID(value, namespace, buf, offset) { var _namespace; if (typeof value === "string") { value = stringToBytes(value); } if (typeof namespace === "string") { namespace = parse_default(namespace); } if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); } let bytes = new Uint8Array(16 + value.length); bytes.set(namespace); bytes.set(value, namespace.length); bytes = hashfunc(bytes); bytes[6] = bytes[6] & 15 | version3; bytes[8] = bytes[8] & 63 | 128; if (buf) { offset = offset || 0; for (let i2 = 0; i2 < 16; ++i2) { buf[offset + i2] = bytes[i2]; } return buf; } return unsafeStringify(bytes); } try { generateUUID.name = name2; } catch (err) { } generateUUID.DNS = DNS; generateUUID.URL = URL2; return generateUUID; } var DNS, URL2; var init_v35 = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v35.js"() { init_stringify(); init_parse(); DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/native.js var randomUUID, native_default; var init_native = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/native.js"() { randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); native_default = { randomUUID }; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v4.js function v4(options, buf, offset) { if (native_default.randomUUID && !buf && !options) { return native_default.randomUUID(); } options = options || {}; const rnds = options.random || (options.rng || rng)(); rnds[6] = rnds[6] & 15 | 64; rnds[8] = rnds[8] & 63 | 128; if (buf) { offset = offset || 0; for (let i2 = 0; i2 < 16; ++i2) { buf[offset + i2] = rnds[i2]; } return buf; } return unsafeStringify(rnds); } var v4_default; var init_v4 = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v4.js"() { init_native(); init_rng(); init_stringify(); v4_default = v4; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/sha1.js function f(s2, x2, y2, z3) { switch (s2) { case 0: return x2 & y2 ^ ~x2 & z3; case 1: return x2 ^ y2 ^ z3; case 2: return x2 & y2 ^ x2 & z3 ^ y2 & z3; case 3: return x2 ^ y2 ^ z3; } } function ROTL(x2, n2) { return x2 << n2 | x2 >>> 32 - n2; } function sha1(bytes) { const K2 = [1518500249, 1859775393, 2400959708, 3395469782]; const H2 = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]; if (typeof bytes === "string") { const msg = unescape(encodeURIComponent(bytes)); bytes = []; for (let i2 = 0; i2 < msg.length; ++i2) { bytes.push(msg.charCodeAt(i2)); } } else if (!Array.isArray(bytes)) { bytes = Array.prototype.slice.call(bytes); } bytes.push(128); const l2 = bytes.length / 4 + 2; const N2 = Math.ceil(l2 / 16); const M2 = new Array(N2); for (let i2 = 0; i2 < N2; ++i2) { const arr = new Uint32Array(16); for (let j2 = 0; j2 < 16; ++j2) { arr[j2] = bytes[i2 * 64 + j2 * 4] << 24 | bytes[i2 * 64 + j2 * 4 + 1] << 16 | bytes[i2 * 64 + j2 * 4 + 2] << 8 | bytes[i2 * 64 + j2 * 4 + 3]; } M2[i2] = arr; } M2[N2 - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); M2[N2 - 1][14] = Math.floor(M2[N2 - 1][14]); M2[N2 - 1][15] = (bytes.length - 1) * 8 & 4294967295; for (let i2 = 0; i2 < N2; ++i2) { const W2 = new Uint32Array(80); for (let t2 = 0; t2 < 16; ++t2) { W2[t2] = M2[i2][t2]; } for (let t2 = 16; t2 < 80; ++t2) { W2[t2] = ROTL(W2[t2 - 3] ^ W2[t2 - 8] ^ W2[t2 - 14] ^ W2[t2 - 16], 1); } let a2 = H2[0]; let b2 = H2[1]; let c2 = H2[2]; let d2 = H2[3]; let e2 = H2[4]; for (let t2 = 0; t2 < 80; ++t2) { const s2 = Math.floor(t2 / 20); const T2 = ROTL(a2, 5) + f(s2, b2, c2, d2) + e2 + K2[s2] + W2[t2] >>> 0; e2 = d2; d2 = c2; c2 = ROTL(b2, 30) >>> 0; b2 = a2; a2 = T2; } H2[0] = H2[0] + a2 >>> 0; H2[1] = H2[1] + b2 >>> 0; H2[2] = H2[2] + c2 >>> 0; H2[3] = H2[3] + d2 >>> 0; H2[4] = H2[4] + e2 >>> 0; } return [H2[0] >> 24 & 255, H2[0] >> 16 & 255, H2[0] >> 8 & 255, H2[0] & 255, H2[1] >> 24 & 255, H2[1] >> 16 & 255, H2[1] >> 8 & 255, H2[1] & 255, H2[2] >> 24 & 255, H2[2] >> 16 & 255, H2[2] >> 8 & 255, H2[2] & 255, H2[3] >> 24 & 255, H2[3] >> 16 & 255, H2[3] >> 8 & 255, H2[3] & 255, H2[4] >> 24 & 255, H2[4] >> 16 & 255, H2[4] >> 8 & 255, H2[4] & 255]; } var sha1_default; var init_sha1 = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/sha1.js"() { sha1_default = sha1; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v5.js var v5, v5_default; var init_v5 = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v5.js"() { init_v35(); init_sha1(); v5 = v35("v5", 80, sha1_default); v5_default = v5; } }); // node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/index.js var init_esm_browser = __esm({ "node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/index.js"() { init_v4(); init_v5(); init_validate(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/callbacks/base.js var base_exports = {}; __export(base_exports, { BaseCallbackHandler: () => BaseCallbackHandler }); var BaseCallbackHandlerMethodsClass, BaseCallbackHandler; var init_base = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/callbacks/base.js"() { init_esm_browser(); init_serializable(); init_env(); BaseCallbackHandlerMethodsClass = class { }; BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass { get lc_namespace() { return ["langchain_core", "callbacks", this.name]; } get lc_secrets() { return void 0; } get lc_attributes() { return void 0; } get lc_aliases() { return void 0; } static lc_name() { return this.name; } get lc_id() { return [ ...this.lc_namespace, get_lc_unique_name(this.constructor) ]; } constructor(input) { super(); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "lc_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "ignoreLLM", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "ignoreChain", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "ignoreAgent", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "ignoreRetriever", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "awaitHandlers", { enumerable: true, configurable: true, writable: true, value: getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") !== "true" }); this.lc_kwargs = input || {}; if (input) { this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; this.ignoreChain = input.ignoreChain ?? this.ignoreChain; this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; this.awaitHandlers = input._awaitHandler ?? this.awaitHandlers; } } copy() { return new this.constructor(this); } toJSON() { return Serializable.prototype.toJSON.call(this); } toJSONNotImplemented() { return Serializable.prototype.toJSONNotImplemented.call(this); } static fromMethods(methods) { class Handler extends BaseCallbackHandler { constructor() { super(); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: v4_default() }); Object.assign(this, methods); } } return new Handler(); } }; } }); // node_modules/.pnpm/ansi-styles@5.2.0/node_modules/ansi-styles/index.js var require_ansi_styles = __commonJS({ "node_modules/.pnpm/ansi-styles@5.2.0/node_modules/ansi-styles/index.js"(exports2, module2) { "use strict"; var ANSI_BACKGROUND_OFFSET = 10; var wrapAnsi256 = (offset = 0) => (code) => `[${38 + offset};5;${code}m`; var wrapAnsi16m = (offset = 0) => (red, green, blue) => `[${38 + offset};2;${red};${green};${blue}m`; function assembleStyles() { const codes = new Map(); const styles2 = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; styles2.color.gray = styles2.color.blackBright; styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; styles2.color.grey = styles2.color.blackBright; styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles2)) { for (const [styleName, style] of Object.entries(group)) { styles2[styleName] = { open: `[${style[0]}m`, close: `[${style[1]}m` }; group[styleName] = styles2[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles2, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles2, "codes", { value: codes, enumerable: false }); styles2.color.close = ""; styles2.bgColor.close = ""; styles2.color.ansi256 = wrapAnsi256(); styles2.color.ansi16m = wrapAnsi16m(); styles2.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles2.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); Object.defineProperties(styles2, { rgbToAnsi256: { value: (red, green, blue) => { if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round((red - 8) / 247 * 24) + 232; } return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); }, enumerable: false }, hexToRgb: { value: (hex) => { const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let { colorString } = matches.groups; if (colorString.length === 3) { colorString = colorString.split("").map((character) => character + character).join(""); } const integer = Number.parseInt(colorString, 16); return [ integer >> 16 & 255, integer >> 8 & 255, integer & 255 ]; }, enumerable: false }, hexToAnsi256: { value: (hex) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex)), enumerable: false } }); return styles2; } Object.defineProperty(module2, "exports", { enumerable: true, get: assembleStyles }); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/base.js var base_exports2 = {}; __export(base_exports2, { BaseTracer: () => BaseTracer }); function _coerceToDict(value, defaultKey) { return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; } function stripNonAlphanumeric(input) { return input.replace(/[-:.]/g, ""); } function convertToDottedOrderFormat(epoch, runId) { return stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}000Z`) + runId; } var BaseTracer; var init_base2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/base.js"() { init_base(); BaseTracer = class extends BaseCallbackHandler { constructor(_fields) { super(...arguments); Object.defineProperty(this, "runMap", { enumerable: true, configurable: true, writable: true, value: new Map() }); } copy() { return this; } stringifyError(error) { if (error instanceof Error) { return error.message + (error?.stack ? ` ${error.stack}` : ""); } if (typeof error === "string") { return error; } return `${error}`; } _addChildRun(parentRun, childRun) { parentRun.child_runs.push(childRun); } async _startTrace(run) { const currentDottedOrder = convertToDottedOrderFormat(run.start_time, run.id); const storedRun = { ...run }; if (storedRun.parent_run_id !== void 0) { const parentRun = this.runMap.get(storedRun.parent_run_id); if (parentRun) { this._addChildRun(parentRun, storedRun); parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); storedRun.trace_id = parentRun.trace_id; if (parentRun.dotted_order !== void 0) { storedRun.dotted_order = [ parentRun.dotted_order, currentDottedOrder ].join("."); } else { } } else { } } else { storedRun.trace_id = storedRun.id; storedRun.dotted_order = currentDottedOrder; } this.runMap.set(storedRun.id, storedRun); await this.onRunCreate?.(storedRun); } async _endTrace(run) { const parentRun = run.parent_run_id !== void 0 && this.runMap.get(run.parent_run_id); if (parentRun) { parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); } else { await this.persistRun(run); } this.runMap.delete(run.id); await this.onRunUpdate?.(run); } _getExecutionOrder(parentRunId) { const parentRun = parentRunId !== void 0 && this.runMap.get(parentRunId); if (!parentRun) { return 1; } return parentRun.child_execution_order + 1; } async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name2) { const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; const run = { id: runId, name: name2 ?? llm.id[llm.id.length - 1], parent_run_id: parentRunId, start_time, serialized: llm, events: [ { name: "start", time: new Date(start_time).toISOString() } ], inputs: { prompts }, execution_order, child_runs: [], child_execution_order: execution_order, run_type: "llm", extra: finalExtraParams ?? {}, tags: tags || [] }; await this._startTrace(run); await this.onLLMStart?.(run); return run; } async handleChatModelStart(llm, messages4, runId, parentRunId, extraParams, tags, metadata, name2) { const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; const run = { id: runId, name: name2 ?? llm.id[llm.id.length - 1], parent_run_id: parentRunId, start_time, serialized: llm, events: [ { name: "start", time: new Date(start_time).toISOString() } ], inputs: { messages: messages4 }, execution_order, child_runs: [], child_execution_order: execution_order, run_type: "llm", extra: finalExtraParams ?? {}, tags: tags || [] }; await this._startTrace(run); await this.onLLMStart?.(run); return run; } async handleLLMEnd(output, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "llm") { throw new Error("No LLM run to end."); } run.end_time = Date.now(); run.outputs = output; run.events.push({ name: "end", time: new Date(run.end_time).toISOString() }); await this.onLLMEnd?.(run); await this._endTrace(run); return run; } async handleLLMError(error, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "llm") { throw new Error("No LLM run to end."); } run.end_time = Date.now(); run.error = this.stringifyError(error); run.events.push({ name: "error", time: new Date(run.end_time).toISOString() }); await this.onLLMError?.(run); await this._endTrace(run); return run; } async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name2) { const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const run = { id: runId, name: name2 ?? chain.id[chain.id.length - 1], parent_run_id: parentRunId, start_time, serialized: chain, events: [ { name: "start", time: new Date(start_time).toISOString() } ], inputs, execution_order, child_execution_order: execution_order, run_type: runType ?? "chain", child_runs: [], extra: metadata ? { metadata } : {}, tags: tags || [] }; await this._startTrace(run); await this.onChainStart?.(run); return run; } async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { const run = this.runMap.get(runId); if (!run) { throw new Error("No chain run to end."); } run.end_time = Date.now(); run.outputs = _coerceToDict(outputs, "output"); run.events.push({ name: "end", time: new Date(run.end_time).toISOString() }); if (kwargs?.inputs !== void 0) { run.inputs = _coerceToDict(kwargs.inputs, "input"); } await this.onChainEnd?.(run); await this._endTrace(run); return run; } async handleChainError(error, runId, _parentRunId, _tags, kwargs) { const run = this.runMap.get(runId); if (!run) { throw new Error("No chain run to end."); } run.end_time = Date.now(); run.error = this.stringifyError(error); run.events.push({ name: "error", time: new Date(run.end_time).toISOString() }); if (kwargs?.inputs !== void 0) { run.inputs = _coerceToDict(kwargs.inputs, "input"); } await this.onChainError?.(run); await this._endTrace(run); return run; } async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name2) { const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const run = { id: runId, name: name2 ?? tool.id[tool.id.length - 1], parent_run_id: parentRunId, start_time, serialized: tool, events: [ { name: "start", time: new Date(start_time).toISOString() } ], inputs: { input }, execution_order, child_execution_order: execution_order, run_type: "tool", child_runs: [], extra: metadata ? { metadata } : {}, tags: tags || [] }; await this._startTrace(run); await this.onToolStart?.(run); return run; } async handleToolEnd(output, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "tool") { throw new Error("No tool run to end"); } run.end_time = Date.now(); run.outputs = { output }; run.events.push({ name: "end", time: new Date(run.end_time).toISOString() }); await this.onToolEnd?.(run); await this._endTrace(run); return run; } async handleToolError(error, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "tool") { throw new Error("No tool run to end"); } run.end_time = Date.now(); run.error = this.stringifyError(error); run.events.push({ name: "error", time: new Date(run.end_time).toISOString() }); await this.onToolError?.(run); await this._endTrace(run); return run; } async handleAgentAction(action, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "chain") { return; } const agentRun = run; agentRun.actions = agentRun.actions || []; agentRun.actions.push(action); agentRun.events.push({ name: "agent_action", time: new Date().toISOString(), kwargs: { action } }); await this.onAgentAction?.(run); } async handleAgentEnd(action, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "chain") { return; } run.events.push({ name: "agent_end", time: new Date().toISOString(), kwargs: { action } }); await this.onAgentEnd?.(run); } async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name2) { const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const run = { id: runId, name: name2 ?? retriever.id[retriever.id.length - 1], parent_run_id: parentRunId, start_time, serialized: retriever, events: [ { name: "start", time: new Date(start_time).toISOString() } ], inputs: { query }, execution_order, child_execution_order: execution_order, run_type: "retriever", child_runs: [], extra: metadata ? { metadata } : {}, tags: tags || [] }; await this._startTrace(run); await this.onRetrieverStart?.(run); return run; } async handleRetrieverEnd(documents, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "retriever") { throw new Error("No retriever run to end"); } run.end_time = Date.now(); run.outputs = { documents }; run.events.push({ name: "end", time: new Date(run.end_time).toISOString() }); await this.onRetrieverEnd?.(run); await this._endTrace(run); return run; } async handleRetrieverError(error, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "retriever") { throw new Error("No retriever run to end"); } run.end_time = Date.now(); run.error = this.stringifyError(error); run.events.push({ name: "error", time: new Date(run.end_time).toISOString() }); await this.onRetrieverError?.(run); await this._endTrace(run); return run; } async handleText(text, runId) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "chain") { return; } run.events.push({ name: "text", time: new Date().toISOString(), kwargs: { text } }); await this.onText?.(run); } async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields2) { const run = this.runMap.get(runId); if (!run || run?.run_type !== "llm") { throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); } run.events.push({ name: "new_token", time: new Date().toISOString(), kwargs: { token, idx, chunk: fields2?.chunk } }); await this.onLLMNewToken?.(run, token, { chunk: fields2?.chunk }); return run; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/console.js var console_exports = {}; __export(console_exports, { ConsoleCallbackHandler: () => ConsoleCallbackHandler }); function wrap(style, text) { return `${style.open}${text}${style.close}`; } function tryJsonStringify(obj, fallback) { try { return JSON.stringify(obj, null, 2); } catch (err) { return fallback; } } function elapsed(run) { if (!run.end_time) return ""; const elapsed2 = run.end_time - run.start_time; if (elapsed2 < 1e3) { return `${elapsed2}ms`; } return `${(elapsed2 / 1e3).toFixed(2)}s`; } var import_ansi_styles, color, ConsoleCallbackHandler; var init_console = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/console.js"() { import_ansi_styles = __toModule(require_ansi_styles()); init_base2(); ({ color } = import_ansi_styles.default); ConsoleCallbackHandler = class extends BaseTracer { constructor() { super(...arguments); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "console_callback_handler" }); } persistRun(_run) { return Promise.resolve(); } getParents(run) { const parents = []; let currentRun = run; while (currentRun.parent_run_id) { const parent = this.runMap.get(currentRun.parent_run_id); if (parent) { parents.push(parent); currentRun = parent; } else { break; } } return parents; } getBreadcrumbs(run) { const parents = this.getParents(run).reverse(); const string = [...parents, run].map((parent, i2, arr) => { const name2 = `${parent.execution_order}:${parent.run_type}:${parent.name}`; return i2 === arr.length - 1 ? wrap(import_ansi_styles.default.bold, name2) : name2; }).join(" > "); return wrap(color.grey, string); } onChainStart(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); } onChainEnd(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); } onChainError(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } onLLMStart(run) { const crumbs = this.getBreadcrumbs(run); const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p2) => p2.trim()) } : run.inputs; console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); } onLLMEnd(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); } onLLMError(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } onToolStart(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${run.inputs.input?.trim()}"`); } onToolEnd(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${run.outputs?.output?.trim()}"`); } onToolError(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } onRetrieverStart(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); } onRetrieverEnd(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); } onRetrieverError(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } onAgentAction(run) { const agentRun = run; const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); } }; } }); // node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js var require_eventemitter3 = __commonJS({ "node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports2, module2) { "use strict"; var has6 = Object.prototype.hasOwnProperty; var prefix = "~"; function Events() { } if (Object.create) { Events.prototype = Object.create(null); if (!new Events().__proto__) prefix = false; } function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } function addListener(emitter, event2, fn, context, once) { if (typeof fn !== "function") { throw new TypeError("The listener must be a function"); } var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event2 : event2; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } EventEmitter.prototype.eventNames = function eventNames() { var names = [], events, name2; if (this._eventsCount === 0) return names; for (name2 in events = this._events) { if (has6.call(events, name2)) names.push(prefix ? name2.slice(1) : name2); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; EventEmitter.prototype.listeners = function listeners(event2) { var evt = prefix ? prefix + event2 : event2, handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i2 = 0, l2 = handlers.length, ee2 = new Array(l2); i2 < l2; i2++) { ee2[i2] = handlers[i2].fn; } return ee2; }; EventEmitter.prototype.listenerCount = function listenerCount(event2) { var evt = prefix ? prefix + event2 : event2, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; EventEmitter.prototype.emit = function emit(event2, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event2 : event2; if (!this._events[evt]) return false; var listeners = this._events[evt], len = arguments.length, args, i2; if (listeners.fn) { if (listeners.once) this.removeListener(event2, listeners.fn, void 0, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i2 = 1, args = new Array(len - 1); i2 < len; i2++) { args[i2 - 1] = arguments[i2]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length, j2; for (i2 = 0; i2 < length; i2++) { if (listeners[i2].once) this.removeListener(event2, listeners[i2].fn, void 0, true); switch (len) { case 1: listeners[i2].fn.call(listeners[i2].context); break; case 2: listeners[i2].fn.call(listeners[i2].context, a1); break; case 3: listeners[i2].fn.call(listeners[i2].context, a1, a2); break; case 4: listeners[i2].fn.call(listeners[i2].context, a1, a2, a3); break; default: if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { args[j2 - 1] = arguments[j2]; } listeners[i2].fn.apply(listeners[i2].context, args); } } } return true; }; EventEmitter.prototype.on = function on(event2, fn, context) { return addListener(this, event2, fn, context, false); }; EventEmitter.prototype.once = function once(event2, fn, context) { return addListener(this, event2, fn, context, true); }; EventEmitter.prototype.removeListener = function removeListener(event2, fn, context, once) { var evt = prefix ? prefix + event2 : event2; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt); } } else { for (var i2 = 0, events = [], length = listeners.length; i2 < length; i2++) { if (listeners[i2].fn !== fn || once && !listeners[i2].once || context && listeners[i2].context !== context) { events.push(listeners[i2]); } } if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(event2) { var evt; if (event2) { evt = prefix ? prefix + event2 : event2; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prefixed = prefix; EventEmitter.EventEmitter = EventEmitter; if (typeof module2 !== "undefined") { module2.exports = EventEmitter; } } }); // node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js var require_p_finally = __commonJS({ "node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js"(exports2, module2) { "use strict"; module2.exports = (promise, onFinally) => { onFinally = onFinally || (() => { }); return promise.then((val) => new Promise((resolve) => { resolve(onFinally()); }).then(() => val), (err) => new Promise((resolve) => { resolve(onFinally()); }).then(() => { throw err; })); }; } }); // node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js var require_p_timeout = __commonJS({ "node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js"(exports2, module2) { "use strict"; var pFinally = require_p_finally(); var TimeoutError = class extends Error { constructor(message) { super(message); this.name = "TimeoutError"; } }; var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { if (typeof milliseconds !== "number" || milliseconds < 0) { throw new TypeError("Expected `milliseconds` to be a positive number"); } if (milliseconds === Infinity) { resolve(promise); return; } const timer = setTimeout(() => { if (typeof fallback === "function") { try { resolve(fallback()); } catch (error) { reject(error); } return; } const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`; const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); if (typeof promise.cancel === "function") { promise.cancel(); } reject(timeoutError); }, milliseconds); pFinally(promise.then(resolve, reject), () => { clearTimeout(timer); }); }); module2.exports = pTimeout; module2.exports.default = pTimeout; module2.exports.TimeoutError = TimeoutError; } }); // node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js var require_lower_bound = __commonJS({ "node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); function lowerBound(array, value, comparator) { let first = 0; let count = array.length; while (count > 0) { const step = count / 2 | 0; let it = first + step; if (comparator(array[it], value) <= 0) { first = ++it; count -= step + 1; } else { count = step; } } return first; } exports2.default = lowerBound; } }); // node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js var require_priority_queue = __commonJS({ "node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var lower_bound_1 = require_lower_bound(); var PriorityQueue = class { constructor() { this._queue = []; } enqueue(run, options) { options = Object.assign({ priority: 0 }, options); const element = { priority: options.priority, run }; if (this.size && this._queue[this.size - 1].priority >= options.priority) { this._queue.push(element); return; } const index2 = lower_bound_1.default(this._queue, element, (a2, b2) => b2.priority - a2.priority); this._queue.splice(index2, 0, element); } dequeue() { const item = this._queue.shift(); return item === null || item === void 0 ? void 0 : item.run; } filter(options) { return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); } get size() { return this._queue.length; } }; exports2.default = PriorityQueue; } }); // node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js var require_dist = __commonJS({ "node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var EventEmitter = require_eventemitter3(); var p_timeout_1 = require_p_timeout(); var priority_queue_1 = require_priority_queue(); var empty = () => { }; var timeoutError = new p_timeout_1.TimeoutError(); var PQueue = class extends EventEmitter { constructor(options) { var _a4, _b, _c, _d; super(); this._intervalCount = 0; this._intervalEnd = 0; this._pendingCount = 0; this._resolveEmpty = empty; this._resolveIdle = empty; options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a4 = options.intervalCap) === null || _a4 === void 0 ? void 0 : _a4.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); } if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`); } this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; this._intervalCap = options.intervalCap; this._interval = options.interval; this._queue = new options.queueClass(); this._queueClass = options.queueClass; this.concurrency = options.concurrency; this._timeout = options.timeout; this._throwOnTimeout = options.throwOnTimeout === true; this._isPaused = options.autoStart === false; } get _doesIntervalAllowAnother() { return this._isIntervalIgnored || this._intervalCount < this._intervalCap; } get _doesConcurrentAllowAnother() { return this._pendingCount < this._concurrency; } _next() { this._pendingCount--; this._tryToStartAnother(); this.emit("next"); } _resolvePromises() { this._resolveEmpty(); this._resolveEmpty = empty; if (this._pendingCount === 0) { this._resolveIdle(); this._resolveIdle = empty; this.emit("idle"); } } _onResumeInterval() { this._onInterval(); this._initializeIntervalIfNeeded(); this._timeoutId = void 0; } _isIntervalPaused() { const now = Date.now(); if (this._intervalId === void 0) { const delay = this._intervalEnd - now; if (delay < 0) { this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; } else { if (this._timeoutId === void 0) { this._timeoutId = setTimeout(() => { this._onResumeInterval(); }, delay); } return true; } } return false; } _tryToStartAnother() { if (this._queue.size === 0) { if (this._intervalId) { clearInterval(this._intervalId); } this._intervalId = void 0; this._resolvePromises(); return false; } if (!this._isPaused) { const canInitializeInterval = !this._isIntervalPaused(); if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { const job = this._queue.dequeue(); if (!job) { return false; } this.emit("active"); job(); if (canInitializeInterval) { this._initializeIntervalIfNeeded(); } return true; } } return false; } _initializeIntervalIfNeeded() { if (this._isIntervalIgnored || this._intervalId !== void 0) { return; } this._intervalId = setInterval(() => { this._onInterval(); }, this._interval); this._intervalEnd = Date.now() + this._interval; } _onInterval() { if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { clearInterval(this._intervalId); this._intervalId = void 0; } this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; this._processQueue(); } _processQueue() { while (this._tryToStartAnother()) { } } get concurrency() { return this._concurrency; } set concurrency(newConcurrency) { if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); } this._concurrency = newConcurrency; this._processQueue(); } async add(fn, options = {}) { return new Promise((resolve, reject) => { const run = async () => { this._pendingCount++; this._intervalCount++; try { const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => { if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { reject(timeoutError); } return void 0; }); resolve(await operation); } catch (error) { reject(error); } this._next(); }; this._queue.enqueue(run, options); this._tryToStartAnother(); this.emit("add"); }); } async addAll(functions, options) { return Promise.all(functions.map(async (function_) => this.add(function_, options))); } start() { if (!this._isPaused) { return this; } this._isPaused = false; this._processQueue(); return this; } pause() { this._isPaused = true; } clear() { this._queue = new this._queueClass(); } async onEmpty() { if (this._queue.size === 0) { return; } return new Promise((resolve) => { const existingResolve = this._resolveEmpty; this._resolveEmpty = () => { existingResolve(); resolve(); }; }); } async onIdle() { if (this._pendingCount === 0 && this._queue.size === 0) { return; } return new Promise((resolve) => { const existingResolve = this._resolveIdle; this._resolveIdle = () => { existingResolve(); resolve(); }; }); } get size() { return this._queue.size; } sizeBy(options) { return this._queue.filter(options).length; } get pending() { return this._pendingCount; } get isPaused() { return this._isPaused; } get timeout() { return this._timeout; } set timeout(milliseconds) { this._timeout = milliseconds; } }; exports2.default = PQueue; } }); // node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/utils/async_caller.js var import_p_retry, import_p_queue, STATUS_NO_RETRY, STATUS_IGNORE, AsyncCaller; var init_async_caller = __esm({ "node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/utils/async_caller.js"() { import_p_retry = __toModule(require_p_retry()); import_p_queue = __toModule(require_dist()); STATUS_NO_RETRY = [ 400, 401, 403, 404, 405, 406, 407, 408 ]; STATUS_IGNORE = [ 409 ]; AsyncCaller = class { constructor(params) { Object.defineProperty(this, "maxConcurrency", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "maxRetries", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "queue", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "onFailedResponseHook", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.maxConcurrency = params.maxConcurrency ?? Infinity; this.maxRetries = params.maxRetries ?? 6; const PQueue = "default" in import_p_queue.default ? import_p_queue.default.default : import_p_queue.default; this.queue = new PQueue({ concurrency: this.maxConcurrency }); this.onFailedResponseHook = params?.onFailedResponseHook; } call(callable, ...args) { const onFailedResponseHook = this.onFailedResponseHook; return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => { if (error instanceof Error) { throw error; } else { throw new Error(error); } }), { async onFailedAttempt(error) { if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.message.startsWith("AbortError")) { throw error; } if (error?.code === "ECONNABORTED") { throw error; } const response = error?.response; const status = response?.status; if (status) { if (STATUS_NO_RETRY.includes(+status)) { throw error; } else if (STATUS_IGNORE.includes(+status)) { return; } if (onFailedResponseHook) { await onFailedResponseHook(response); } } }, retries: this.maxRetries, randomize: true }), { throwOnTimeout: true }); } callWithOptions(options, callable, ...args) { if (options.signal) { return Promise.race([ this.call(callable, ...args), new Promise((_2, reject) => { options.signal?.addEventListener("abort", () => { reject(new Error("AbortError")); }); }) ]); } return this.call(callable, ...args); } fetch(...args) { return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); } }; } }); // node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/utils/messages.js function isLangChainMessage(message) { return typeof message?._getType === "function"; } function convertLangChainMessageToExample(message) { const converted = { type: message._getType(), data: { content: message.content } }; if (message?.additional_kwargs && Object.keys(message.additional_kwargs).length > 0) { converted.data.additional_kwargs = { ...message.additional_kwargs }; } return converted; } var init_messages3 = __esm({ "node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/utils/messages.js"() { } }); // node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/utils/env.js async function getRuntimeEnvironment2() { if (runtimeEnvironment2 === void 0) { const env = getEnv2(); const releaseEnv = getShas(); runtimeEnvironment2 = { library: "langsmith", runtime: env, sdk: "langsmith-js", sdk_version: __version__, ...releaseEnv }; } return runtimeEnvironment2; } function getLangChainEnvVarsMetadata() { const allEnvVars = getEnvironmentVariables() || {}; const envVars = {}; const excluded = [ "LANGCHAIN_API_KEY", "LANGCHAIN_ENDPOINT", "LANGCHAIN_TRACING_V2", "LANGCHAIN_PROJECT", "LANGCHAIN_SESSION" ]; for (const [key, value] of Object.entries(allEnvVars)) { if (key.startsWith("LANGCHAIN_") && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) { if (key === "LANGCHAIN_REVISION_ID") { envVars["revision_id"] = value; } else { envVars[key] = value; } } } return envVars; } function getEnvironmentVariables() { try { if (typeof process !== "undefined" && process.env) { return Object.entries(process.env).reduce((acc, [key, value]) => { acc[key] = String(value); return acc; }, {}); } return void 0; } catch (e2) { return void 0; } } function getEnvironmentVariable2(name2) { try { return typeof process !== "undefined" ? process.env?.[name2] : void 0; } catch (e2) { return void 0; } } function getShas() { if (cachedCommitSHAs !== void 0) { return cachedCommitSHAs; } const common_release_envs = [ "VERCEL_GIT_COMMIT_SHA", "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", "COMMIT_REF", "RENDER_GIT_COMMIT", "CI_COMMIT_SHA", "CIRCLE_SHA1", "CF_PAGES_COMMIT_SHA", "REACT_APP_GIT_SHA", "SOURCE_VERSION", "GITHUB_SHA", "TRAVIS_COMMIT", "GIT_COMMIT", "BUILD_VCS_NUMBER", "bamboo_planRepository_revision", "Build.SourceVersion", "BITBUCKET_COMMIT", "DRONE_COMMIT_SHA", "SEMAPHORE_GIT_SHA", "BUILDKITE_COMMIT" ]; const shas = {}; for (const env of common_release_envs) { const envVar = getEnvironmentVariable2(env); if (envVar !== void 0) { shas[env] = envVar; } } cachedCommitSHAs = shas; return shas; } var globalEnv, isBrowser2, isWebWorker2, isJsDom2, isDeno2, isNode2, getEnv2, runtimeEnvironment2, cachedCommitSHAs; var init_env4 = __esm({ "node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/utils/env.js"() { init_dist(); isBrowser2 = () => typeof window !== "undefined" && typeof window.document !== "undefined"; isWebWorker2 = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; isJsDom2 = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom")); isDeno2 = () => typeof Deno !== "undefined"; isNode2 = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno2(); getEnv2 = () => { if (globalEnv) { return globalEnv; } if (isBrowser2()) { globalEnv = "browser"; } else if (isNode2()) { globalEnv = "node"; } else if (isWebWorker2()) { globalEnv = "webworker"; } else if (isJsDom2()) { globalEnv = "jsdom"; } else if (isDeno2()) { globalEnv = "deno"; } else { globalEnv = "other"; } return globalEnv; }; } }); // node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/client.js async function mergeRuntimeEnvIntoRunCreates(runs) { const runtimeEnv = await getRuntimeEnvironment2(); const envVars = getLangChainEnvVarsMetadata(); return runs.map((run) => { const extra = run.extra ?? {}; const metadata = extra.metadata; run.extra = { ...extra, runtime: { ...runtimeEnv, ...extra?.runtime }, metadata: { ...envVars, ...envVars.revision_id || run.revision_id ? { revision_id: run.revision_id ?? envVars.revision_id } : {}, ...metadata } }; return run; }); } async function toArray(iterable) { const result = []; for await (const item of iterable) { result.push(item); } return result; } function trimQuotes(str3) { if (str3 === void 0) { return void 0; } return str3.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1"); } function assertUuid(str3) { if (!validate_default(str3)) { throw new Error(`Invalid UUID: ${str3}`); } } var getTracingSamplingRate, isLocalhost, raiseForStatus, handle429, Queue, DEFAULT_BATCH_SIZE_LIMIT_BYTES, Client; var init_client = __esm({ "node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/client.js"() { init_esm_browser(); init_async_caller(); init_messages3(); init_env4(); init_dist(); getTracingSamplingRate = () => { const samplingRateStr = getEnvironmentVariable2("LANGCHAIN_TRACING_SAMPLING_RATE"); if (samplingRateStr === void 0) { return void 0; } const samplingRate = parseFloat(samplingRateStr); if (samplingRate < 0 || samplingRate > 1) { throw new Error(`LANGCHAIN_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); } return samplingRate; }; isLocalhost = (url) => { const strippedUrl = url.replace("http://", "").replace("https://", ""); const hostname = strippedUrl.split("/")[0].split(":")[0]; return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; }; raiseForStatus = async (response, operation) => { const body = await response.text(); if (!response.ok) { throw new Error(`Failed to ${operation}: ${response.status} ${response.statusText} ${body}`); } }; handle429 = async (response) => { if (response?.status === 429) { const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1e3; if (retryAfter > 0) { await new Promise((resolve) => setTimeout(resolve, retryAfter)); return true; } } return false; }; Queue = class { constructor() { Object.defineProperty(this, "items", { enumerable: true, configurable: true, writable: true, value: [] }); } get size() { return this.items.length; } push(item) { return new Promise((resolve) => { this.items.push([item, resolve]); }); } pop(upToN) { if (upToN < 1) { throw new Error("Number of items to pop off may not be less than 1."); } const popped = []; while (popped.length < upToN && this.items.length) { const item = this.items.shift(); if (item) { popped.push(item); } else { break; } } return [popped.map((it) => it[0]), () => popped.forEach((it) => it[1]())]; } }; DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520; Client = class { constructor(config = {}) { Object.defineProperty(this, "apiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "apiUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "webUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "batchIngestCaller", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "timeout_ms", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "_tenantId", { enumerable: true, configurable: true, writable: true, value: null }); Object.defineProperty(this, "hideInputs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "hideOutputs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "tracingSampleRate", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "sampledPostUuids", { enumerable: true, configurable: true, writable: true, value: new Set() }); Object.defineProperty(this, "autoBatchTracing", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "batchEndpointSupported", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "autoBatchQueue", { enumerable: true, configurable: true, writable: true, value: new Queue() }); Object.defineProperty(this, "pendingAutoBatchedRunLimit", { enumerable: true, configurable: true, writable: true, value: 100 }); Object.defineProperty(this, "autoBatchTimeout", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "autoBatchInitialDelayMs", { enumerable: true, configurable: true, writable: true, value: 250 }); Object.defineProperty(this, "autoBatchAggregationDelayMs", { enumerable: true, configurable: true, writable: true, value: 50 }); Object.defineProperty(this, "serverInfo", { enumerable: true, configurable: true, writable: true, value: void 0 }); const defaultConfig = Client.getDefaultClientConfig(); this.tracingSampleRate = getTracingSamplingRate(); this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); this.timeout_ms = config.timeout_ms ?? 12e3; this.caller = new AsyncCaller(config.callerOptions ?? {}); this.batchIngestCaller = new AsyncCaller({ ...config.callerOptions ?? {}, onFailedResponseHook: handle429 }); this.hideInputs = config.hideInputs ?? defaultConfig.hideInputs; this.hideOutputs = config.hideOutputs ?? defaultConfig.hideOutputs; this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; this.pendingAutoBatchedRunLimit = config.pendingAutoBatchedRunLimit ?? this.pendingAutoBatchedRunLimit; } static getDefaultClientConfig() { const apiKey = getEnvironmentVariable2("LANGCHAIN_API_KEY"); const apiUrl = getEnvironmentVariable2("LANGCHAIN_ENDPOINT") ?? "https://api.smith.langchain.com"; const hideInputs = getEnvironmentVariable2("LANGCHAIN_HIDE_INPUTS") === "true"; const hideOutputs = getEnvironmentVariable2("LANGCHAIN_HIDE_OUTPUTS") === "true"; return { apiUrl, apiKey, webUrl: void 0, hideInputs, hideOutputs }; } getHostUrl() { if (this.webUrl) { return this.webUrl; } else if (isLocalhost(this.apiUrl)) { this.webUrl = "http://localhost"; return "http://localhost"; } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) { this.webUrl = this.apiUrl.replace("/api", ""); return this.webUrl; } else if (this.apiUrl.split(".", 1)[0].includes("dev")) { this.webUrl = "https://dev.smith.langchain.com"; return "https://dev.smith.langchain.com"; } else { this.webUrl = "https://smith.langchain.com"; return "https://smith.langchain.com"; } } get headers() { const headers = { "User-Agent": `langsmith-js/${__version__}` }; if (this.apiKey) { headers["x-api-key"] = `${this.apiKey}`; } return headers; } processInputs(inputs) { if (this.hideInputs === false) { return inputs; } if (this.hideInputs === true) { return {}; } if (typeof this.hideInputs === "function") { return this.hideInputs(inputs); } return inputs; } processOutputs(outputs) { if (this.hideOutputs === false) { return outputs; } if (this.hideOutputs === true) { return {}; } if (typeof this.hideOutputs === "function") { return this.hideOutputs(outputs); } return outputs; } prepareRunCreateOrUpdateInputs(run) { const runParams = { ...run }; if (runParams.inputs !== void 0) { runParams.inputs = this.processInputs(runParams.inputs); } if (runParams.outputs !== void 0) { runParams.outputs = this.processOutputs(runParams.outputs); } return runParams; } async _getResponse(path, queryParams) { const paramsString = queryParams?.toString() ?? ""; const url = `${this.apiUrl}${path}?${paramsString}`; const response = await this.caller.call(fetch, url, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`); } return response; } async _get(path, queryParams) { const response = await this._getResponse(path, queryParams); return response.json(); } async *_getPaginated(path, queryParams = new URLSearchParams()) { let offset = Number(queryParams.get("offset")) || 0; const limit = Number(queryParams.get("limit")) || 100; while (true) { queryParams.set("offset", String(offset)); queryParams.set("limit", String(limit)); const url = `${this.apiUrl}${path}?${queryParams}`; const response = await this.caller.call(fetch, url, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`); } const items = await response.json(); if (items.length === 0) { break; } yield items; if (items.length < limit) { break; } offset += items.length; } } async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { const bodyParams = body ? { ...body } : {}; while (true) { const response = await this.caller.call(fetch, `${this.apiUrl}${path}`, { method: requestMethod, headers: { ...this.headers, "Content-Type": "application/json" }, signal: AbortSignal.timeout(this.timeout_ms), body: JSON.stringify(bodyParams) }); const responseBody = await response.json(); if (!responseBody) { break; } if (!responseBody[dataKey]) { break; } yield responseBody[dataKey]; const cursors = responseBody.cursors; if (!cursors) { break; } if (!cursors.next) { break; } bodyParams.cursor = cursors.next; } } _filterForSampling(runs, patch = false) { if (this.tracingSampleRate === void 0) { return runs; } if (patch) { const sampled = []; for (const run of runs) { if (this.sampledPostUuids.has(run.id)) { sampled.push(run); this.sampledPostUuids.delete(run.id); } } return sampled; } else { const sampled = []; for (const run of runs) { if (Math.random() < this.tracingSampleRate) { sampled.push(run); this.sampledPostUuids.add(run.id); } } return sampled; } } async drainAutoBatchQueue() { while (this.autoBatchQueue.size >= 0) { const [batch, done] = this.autoBatchQueue.pop(this.pendingAutoBatchedRunLimit); if (!batch.length) { done(); return; } try { await this.batchIngestRuns({ runCreates: batch.filter((item) => item.action === "create").map((item) => item.item), runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item) }); } finally { done(); } } } async processRunOperation(item, immediatelyTriggerBatch) { const oldTimeout = this.autoBatchTimeout; clearTimeout(this.autoBatchTimeout); this.autoBatchTimeout = void 0; const itemPromise = this.autoBatchQueue.push(item); if (immediatelyTriggerBatch || this.autoBatchQueue.size > this.pendingAutoBatchedRunLimit) { await this.drainAutoBatchQueue(); } if (this.autoBatchQueue.size > 0) { this.autoBatchTimeout = setTimeout(() => { this.autoBatchTimeout = void 0; void this.drainAutoBatchQueue().catch(console.error); }, oldTimeout ? this.autoBatchAggregationDelayMs : this.autoBatchInitialDelayMs); } return itemPromise; } async _getServerInfo() { const response = await fetch(`${this.apiUrl}/info`, { method: "GET", headers: { Accept: "application/json" }, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { await response.text(); throw new Error("Failed to retrieve server info."); } return response.json(); } async batchEndpointIsSupported() { try { this.serverInfo = await this._getServerInfo(); } catch (e2) { return false; } return true; } async createRun(run) { if (!this._filterForSampling([run]).length) { return; } const headers = { ...this.headers, "Content-Type": "application/json" }; const session_name = run.project_name; delete run.project_name; const runCreate = this.prepareRunCreateOrUpdateInputs({ session_name, ...run, start_time: run.start_time ?? Date.now() }); if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) { void this.processRunOperation({ action: "create", item: runCreate }).catch(console.error); return; } const mergedRunCreateParams = await mergeRuntimeEnvIntoRunCreates([ runCreate ]); const response = await this.caller.call(fetch, `${this.apiUrl}/runs`, { method: "POST", headers, body: JSON.stringify(mergedRunCreateParams[0]), signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "create run"); } async batchIngestRuns({ runCreates, runUpdates }) { if (runCreates === void 0 && runUpdates === void 0) { return; } let preparedCreateParams = runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []; let preparedUpdateParams = runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []; if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { const createById = preparedCreateParams.reduce((params, run) => { if (!run.id) { return params; } params[run.id] = run; return params; }, {}); const standaloneUpdates = []; for (const updateParam of preparedUpdateParams) { if (updateParam.id !== void 0 && createById[updateParam.id]) { createById[updateParam.id] = { ...createById[updateParam.id], ...updateParam }; } else { standaloneUpdates.push(updateParam); } } preparedCreateParams = Object.values(createById); preparedUpdateParams = standaloneUpdates; } const rawBatch = { post: this._filterForSampling(preparedCreateParams), patch: this._filterForSampling(preparedUpdateParams, true) }; if (!rawBatch.post.length && !rawBatch.patch.length) { return; } preparedCreateParams = await mergeRuntimeEnvIntoRunCreates(preparedCreateParams); if (this.batchEndpointSupported === void 0) { this.batchEndpointSupported = await this.batchEndpointIsSupported(); } if (!this.batchEndpointSupported) { this.autoBatchTracing = false; for (const preparedCreateParam of rawBatch.post) { await this.createRun(preparedCreateParam); } for (const preparedUpdateParam of rawBatch.patch) { if (preparedUpdateParam.id !== void 0) { await this.updateRun(preparedUpdateParam.id, preparedUpdateParam); } } return; } const sizeLimitBytes = this.serverInfo?.batch_ingest_config?.size_limit_bytes ?? DEFAULT_BATCH_SIZE_LIMIT_BYTES; const batchChunks = { post: [], patch: [] }; let currentBatchSizeBytes = 0; for (const k2 of ["post", "patch"]) { const key = k2; const batchItems = rawBatch[key].reverse(); let batchItem = batchItems.pop(); while (batchItem !== void 0) { const stringifiedBatchItem = JSON.stringify(batchItem); if (currentBatchSizeBytes > 0 && currentBatchSizeBytes + stringifiedBatchItem.length > sizeLimitBytes) { await this._postBatchIngestRuns(JSON.stringify(batchChunks)); currentBatchSizeBytes = 0; batchChunks.post = []; batchChunks.patch = []; } currentBatchSizeBytes += stringifiedBatchItem.length; batchChunks[key].push(batchItem); batchItem = batchItems.pop(); } } if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { await this._postBatchIngestRuns(JSON.stringify(batchChunks)); } } async _postBatchIngestRuns(body) { const headers = { ...this.headers, "Content-Type": "application/json", Accept: "application/json" }; const response = await this.batchIngestCaller.call(fetch, `${this.apiUrl}/runs/batch`, { method: "POST", headers, body, signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "batch create run"); } async updateRun(runId, run) { assertUuid(runId); if (run.inputs) { run.inputs = this.processInputs(run.inputs); } if (run.outputs) { run.outputs = this.processOutputs(run.outputs); } const data = { ...run, id: runId }; if (!this._filterForSampling([data], true).length) { return; } if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) { if (run.end_time !== void 0 && data.parent_run_id === void 0) { await this.processRunOperation({ action: "update", item: data }, true); return; } else { void this.processRunOperation({ action: "update", item: data }).catch(console.error); } return; } const headers = { ...this.headers, "Content-Type": "application/json" }; const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, { method: "PATCH", headers, body: JSON.stringify(run), signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "update run"); } async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { assertUuid(runId); let run = await this._get(`/runs/${runId}`); if (loadChildRuns && run.child_run_ids) { run = await this._loadChildRuns(run); } return run; } async getRunUrl({ runId, run, projectOpts }) { if (run !== void 0) { let sessionId; if (run.session_id) { sessionId = run.session_id; } else if (projectOpts?.projectName) { sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; } else if (projectOpts?.projectId) { sessionId = projectOpts?.projectId; } else { const project = await this.readProject({ projectName: getEnvironmentVariable2("LANGCHAIN_PROJECT") || "default" }); sessionId = project.id; } const tenantId = await this._getTenantId(); return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; } else if (runId !== void 0) { const run_ = await this.readRun(runId); if (!run_.app_path) { throw new Error(`Run ${runId} has no app_path`); } const baseUrl = this.getHostUrl(); return `${baseUrl}${run_.app_path}`; } else { throw new Error("Must provide either runId or run"); } } async _loadChildRuns(run) { const childRuns = await toArray(this.listRuns({ id: run.child_run_ids })); const treemap = {}; const runs = {}; childRuns.sort((a2, b2) => (a2?.dotted_order ?? "").localeCompare(b2?.dotted_order ?? "")); for (const childRun of childRuns) { if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) { throw new Error(`Child run ${childRun.id} has no parent`); } if (!(childRun.parent_run_id in treemap)) { treemap[childRun.parent_run_id] = []; } treemap[childRun.parent_run_id].push(childRun); runs[childRun.id] = childRun; } run.child_runs = treemap[run.id] || []; for (const runId in treemap) { if (runId !== run.id) { runs[runId].child_runs = treemap[runId]; } } return run; } async *listRuns(props) { const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, runType, error, id: id2, query, filter, traceFilter, treeFilter, limit } = props; let projectIds = []; if (projectId) { projectIds = Array.isArray(projectId) ? projectId : [projectId]; } if (projectName) { const projectNames = Array.isArray(projectName) ? projectName : [projectName]; const projectIds_ = await Promise.all(projectNames.map((name2) => this.readProject({ projectName: name2 }).then((project) => project.id))); projectIds.push(...projectIds_); } const body = { session: projectIds.length ? projectIds : null, run_type: runType, reference_example: referenceExampleId, query, filter, trace_filter: traceFilter, tree_filter: treeFilter, execution_order: executionOrder, parent_run: parentRunId, start_time: startTime ? startTime.toISOString() : null, error, id: id2, limit, trace: traceId }; for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { yield* runs; } } async shareRun(runId, { shareId } = {}) { const data = { run_id: runId, share_token: shareId || v4_default() }; assertUuid(runId); const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { method: "PUT", headers: this.headers, body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms) }); const result = await response.json(); if (result === null || !("share_token" in result)) { throw new Error("Invalid response from server"); } return `${this.getHostUrl()}/public/${result["share_token"]}/r`; } async unshareRun(runId) { assertUuid(runId); const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "unshare run"); } async readRunSharedLink(runId) { assertUuid(runId); const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); const result = await response.json(); if (result === null || !("share_token" in result)) { return void 0; } return `${this.getHostUrl()}/public/${result["share_token"]}/r`; } async listSharedRuns(shareToken, { runIds } = {}) { const queryParams = new URLSearchParams({ share_token: shareToken }); if (runIds !== void 0) { for (const runId of runIds) { queryParams.append("id", runId); } } assertUuid(shareToken); const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); const runs = await response.json(); return runs; } async readDatasetSharedSchema(datasetId, datasetName) { if (!datasetId && !datasetName) { throw new Error("Either datasetId or datasetName must be given"); } if (!datasetId) { const dataset = await this.readDataset({ datasetName }); datasetId = dataset.id; } assertUuid(datasetId); const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); const shareSchema = await response.json(); shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; return shareSchema; } async shareDataset(datasetId, datasetName) { if (!datasetId && !datasetName) { throw new Error("Either datasetId or datasetName must be given"); } if (!datasetId) { const dataset = await this.readDataset({ datasetName }); datasetId = dataset.id; } const data = { dataset_id: datasetId }; assertUuid(datasetId); const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, { method: "PUT", headers: this.headers, body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms) }); const shareSchema = await response.json(); shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; return shareSchema; } async unshareDataset(datasetId) { assertUuid(datasetId); const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "unshare dataset"); } async readSharedDataset(shareToken) { assertUuid(shareToken); const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/datasets`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); const dataset = await response.json(); return dataset; } async createProject({ projectName, description: description2 = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null }) { const upsert_ = upsert ? `?upsert=true` : ""; const endpoint = `${this.apiUrl}/sessions${upsert_}`; const extra = projectExtra || {}; if (metadata) { extra["metadata"] = metadata; } const body = { name: projectName, extra, description: description2 }; if (referenceDatasetId !== null) { body["reference_dataset_id"] = referenceDatasetId; } const response = await this.caller.call(fetch, endpoint, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms) }); const result = await response.json(); if (!response.ok) { throw new Error(`Failed to create session ${projectName}: ${response.status} ${response.statusText}`); } return result; } async updateProject(projectId, { name: name2 = null, description: description2 = null, metadata = null, projectExtra = null, endTime = null }) { const endpoint = `${this.apiUrl}/sessions/${projectId}`; let extra = projectExtra; if (metadata) { extra = { ...extra || {}, metadata }; } const body = { name: name2, extra, description: description2, end_time: endTime ? new Date(endTime).toISOString() : null }; const response = await this.caller.call(fetch, endpoint, { method: "PATCH", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms) }); const result = await response.json(); if (!response.ok) { throw new Error(`Failed to update project ${projectId}: ${response.status} ${response.statusText}`); } return result; } async hasProject({ projectId, projectName }) { let path = "/sessions"; const params = new URLSearchParams(); if (projectId !== void 0 && projectName !== void 0) { throw new Error("Must provide either projectName or projectId, not both"); } else if (projectId !== void 0) { assertUuid(projectId); path += `/${projectId}`; } else if (projectName !== void 0) { params.append("name", projectName); } else { throw new Error("Must provide projectName or projectId"); } const response = await this.caller.call(fetch, `${this.apiUrl}${path}?${params}`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); try { const result = await response.json(); if (!response.ok) { return false; } if (Array.isArray(result)) { return result.length > 0; } return true; } catch (e2) { return false; } } async readProject({ projectId, projectName, includeStats }) { let path = "/sessions"; const params = new URLSearchParams(); if (projectId !== void 0 && projectName !== void 0) { throw new Error("Must provide either projectName or projectId, not both"); } else if (projectId !== void 0) { assertUuid(projectId); path += `/${projectId}`; } else if (projectName !== void 0) { params.append("name", projectName); } else { throw new Error("Must provide projectName or projectId"); } if (includeStats !== void 0) { params.append("include_stats", includeStats.toString()); } const response = await this._get(path, params); let result; if (Array.isArray(response)) { if (response.length === 0) { throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); } result = response[0]; } else { result = response; } return result; } async _getTenantId() { if (this._tenantId !== null) { return this._tenantId; } const queryParams = new URLSearchParams({ limit: "1" }); for await (const projects of this._getPaginated("/sessions", queryParams)) { this._tenantId = projects[0].tenant_id; return projects[0].tenant_id; } throw new Error("No projects found to resolve tenant."); } async *listProjects({ projectIds, name: name2, nameContains, referenceDatasetId, referenceDatasetName, referenceFree } = {}) { const params = new URLSearchParams(); if (projectIds !== void 0) { for (const projectId of projectIds) { params.append("id", projectId); } } if (name2 !== void 0) { params.append("name", name2); } if (nameContains !== void 0) { params.append("name_contains", nameContains); } if (referenceDatasetId !== void 0) { params.append("reference_dataset", referenceDatasetId); } else if (referenceDatasetName !== void 0) { const dataset = await this.readDataset({ datasetName: referenceDatasetName }); params.append("reference_dataset", dataset.id); } if (referenceFree !== void 0) { params.append("reference_free", referenceFree.toString()); } for await (const projects of this._getPaginated("/sessions", params)) { yield* projects; } } async deleteProject({ projectId, projectName }) { let projectId_; if (projectId === void 0 && projectName === void 0) { throw new Error("Must provide projectName or projectId"); } else if (projectId !== void 0 && projectName !== void 0) { throw new Error("Must provide either projectName or projectId, not both"); } else if (projectId === void 0) { projectId_ = (await this.readProject({ projectName })).id; } else { projectId_ = projectId; } assertUuid(projectId_); const response = await this.caller.call(fetch, `${this.apiUrl}/sessions/${projectId_}`, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, `delete session ${projectId_} (${projectName})`); } async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description: description2, dataType, name: name2 }) { const url = `${this.apiUrl}/datasets/upload`; const formData = new FormData(); formData.append("file", csvFile, fileName); inputKeys.forEach((key) => { formData.append("input_keys", key); }); outputKeys.forEach((key) => { formData.append("output_keys", key); }); if (description2) { formData.append("description", description2); } if (dataType) { formData.append("data_type", dataType); } if (name2) { formData.append("name", name2); } const response = await this.caller.call(fetch, url, { method: "POST", headers: this.headers, body: formData, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { const result2 = await response.json(); if (result2.detail && result2.detail.includes("already exists")) { throw new Error(`Dataset ${fileName} already exists`); } throw new Error(`Failed to upload CSV: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async createDataset(name2, { description: description2, dataType } = {}) { const body = { name: name2, description: description2 }; if (dataType) { body.data_type = dataType; } const response = await this.caller.call(fetch, `${this.apiUrl}/datasets`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { const result2 = await response.json(); if (result2.detail && result2.detail.includes("already exists")) { throw new Error(`Dataset ${name2} already exists`); } throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async readDataset({ datasetId, datasetName }) { let path = "/datasets"; const params = new URLSearchParams({ limit: "1" }); if (datasetId !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId !== void 0) { assertUuid(datasetId); path += `/${datasetId}`; } else if (datasetName !== void 0) { params.append("name", datasetName); } else { throw new Error("Must provide datasetName or datasetId"); } const response = await this._get(path, params); let result; if (Array.isArray(response)) { if (response.length === 0) { throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); } result = response[0]; } else { result = response; } return result; } async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) { let datasetId_ = datasetId; if (datasetId_ === void 0 && datasetName === void 0) { throw new Error("Must provide either datasetName or datasetId"); } else if (datasetId_ !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId_ === void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } const urlParams = new URLSearchParams({ from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(), to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString() }); const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); return response; } async readDatasetOpenaiFinetuning({ datasetId, datasetName }) { const path = "/datasets"; if (datasetId !== void 0) { } else if (datasetName !== void 0) { datasetId = (await this.readDataset({ datasetName })).id; } else { throw new Error("Must provide datasetName or datasetId"); } const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); const datasetText = await response.text(); const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line)); return dataset; } async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains } = {}) { const path = "/datasets"; const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() }); if (datasetIds !== void 0) { for (const id_ of datasetIds) { params.append("id", id_); } } if (datasetName !== void 0) { params.append("name", datasetName); } if (datasetNameContains !== void 0) { params.append("name_contains", datasetNameContains); } for await (const datasets of this._getPaginated(path, params)) { yield* datasets; } } async deleteDataset({ datasetId, datasetName }) { let path = "/datasets"; let datasetId_ = datasetId; if (datasetId !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetName !== void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } if (datasetId_ !== void 0) { assertUuid(datasetId_); path += `/${datasetId_}`; } else { throw new Error("Must provide datasetName or datasetId"); } const response = await this.caller.call(fetch, this.apiUrl + path, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); } await response.json(); } async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId }) { let datasetId_ = datasetId; if (datasetId_ === void 0 && datasetName === void 0) { throw new Error("Must provide either datasetName or datasetId"); } else if (datasetId_ !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId_ === void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } const createdAt_ = createdAt || new Date(); const data = { dataset_id: datasetId_, inputs, outputs, created_at: createdAt_?.toISOString(), id: exampleId }; const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to create example: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async createExamples(props) { const { inputs, outputs, sourceRunIds, exampleIds, datasetId, datasetName } = props; let datasetId_ = datasetId; if (datasetId_ === void 0 && datasetName === void 0) { throw new Error("Must provide either datasetName or datasetId"); } else if (datasetId_ !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId_ === void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } const formattedExamples = inputs.map((input, idx) => { return { dataset_id: datasetId_, inputs: input, outputs: outputs ? outputs[idx] : void 0, id: exampleIds ? exampleIds[idx] : void 0, source_run_id: sourceRunIds ? sourceRunIds[idx] : void 0 }; }); const response = await this.caller.call(fetch, `${this.apiUrl}/examples/bulk`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(formattedExamples), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to create examples: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async createLLMExample(input, generation, options) { return this.createExample({ input }, { output: generation }, options); } async createChatExample(input, generations, options) { const finalInput = input.map((message) => { if (isLangChainMessage(message)) { return convertLangChainMessageToExample(message); } return message; }); const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations; return this.createExample({ input: finalInput }, { output: finalOutput }, options); } async readExample(exampleId) { assertUuid(exampleId); const path = `/examples/${exampleId}`; return await this._get(path); } async *listExamples({ datasetId, datasetName, exampleIds, asOf, inlineS3Urls } = {}) { let datasetId_; if (datasetId !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId !== void 0) { datasetId_ = datasetId; } else if (datasetName !== void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } else { throw new Error("Must provide a datasetName or datasetId"); } const params = new URLSearchParams({ dataset: datasetId_ }); const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; if (dataset_version) { params.append("as_of", dataset_version); } const inlineS3Urls_ = inlineS3Urls ?? true; params.append("inline_s3_urls", inlineS3Urls_.toString()); if (exampleIds !== void 0) { for (const id_ of exampleIds) { params.append("id", id_); } } for await (const examples2 of this._getPaginated("/examples", params)) { yield* examples2; } } async deleteExample(exampleId) { assertUuid(exampleId); const path = `/examples/${exampleId}`; const response = await this.caller.call(fetch, this.apiUrl + path, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); } await response.json(); } async updateExample(exampleId, update) { assertUuid(exampleId); const response = await this.caller.call(fetch, `${this.apiUrl}/examples/${exampleId}`, { method: "PATCH", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(update), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to update example ${exampleId}: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) { let run_; if (typeof run === "string") { run_ = await this.readRun(run, { loadChildRuns }); } else if (typeof run === "object" && "id" in run) { run_ = run; } else { throw new Error(`Invalid run type: ${typeof run}`); } if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) { referenceExample = await this.readExample(run_.reference_example_id); } const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); let sourceInfo_ = sourceInfo ?? {}; if (feedbackResult.evaluatorInfo) { sourceInfo_ = { ...sourceInfo_, ...feedbackResult.evaluatorInfo }; } const runId = feedbackResult.targetRunId ?? run_.id; return await this.createFeedback(runId, feedbackResult.key, { score: feedbackResult?.score, value: feedbackResult?.value, comment: feedbackResult?.comment, correction: feedbackResult?.correction, sourceInfo: sourceInfo_, feedbackSourceType: "model", sourceRunId: feedbackResult?.sourceRunId }); } async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig }) { const feedback_source = { type: feedbackSourceType ?? "api", metadata: sourceInfo ?? {} }; if (sourceRunId !== void 0 && feedback_source?.metadata !== void 0 && !feedback_source.metadata["__run"]) { feedback_source.metadata["__run"] = { run_id: sourceRunId }; } if (feedback_source?.metadata !== void 0 && feedback_source.metadata["__run"]?.run_id !== void 0) { assertUuid(feedback_source.metadata["__run"].run_id); } const feedback = { id: feedbackId ?? v4_default(), run_id: runId, key, score, value, correction, comment, feedback_source, feedbackConfig }; const url = `${this.apiUrl}/feedback`; const response = await this.caller.call(fetch, url, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(feedback), signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "create feedback"); return feedback; } async updateFeedback(feedbackId, { score, value, correction, comment }) { const feedbackUpdate = {}; if (score !== void 0 && score !== null) { feedbackUpdate["score"] = score; } if (value !== void 0 && value !== null) { feedbackUpdate["value"] = value; } if (correction !== void 0 && correction !== null) { feedbackUpdate["correction"] = correction; } if (comment !== void 0 && comment !== null) { feedbackUpdate["comment"] = comment; } assertUuid(feedbackId); const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/${feedbackId}`, { method: "PATCH", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(feedbackUpdate), signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "update feedback"); } async readFeedback(feedbackId) { assertUuid(feedbackId); const path = `/feedback/${feedbackId}`; const response = await this._get(path); return response; } async deleteFeedback(feedbackId) { assertUuid(feedbackId); const path = `/feedback/${feedbackId}`; const response = await this.caller.call(fetch, this.apiUrl + path, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); } await response.json(); } async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) { const queryParams = new URLSearchParams(); if (runIds) { queryParams.append("run", runIds.join(",")); } if (feedbackKeys) { for (const key of feedbackKeys) { queryParams.append("key", key); } } if (feedbackSourceTypes) { for (const type2 of feedbackSourceTypes) { queryParams.append("source", type2); } } for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { yield* feedbacks; } } async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) { const body = { run_id: runId, feedback_key: feedbackKey, feedback_config: feedbackConfig }; if (expiration) { if (typeof expiration === "string") { body["expires_at"] = expiration; } else if (expiration?.hours || expiration?.minutes || expiration?.days) { body["expires_in"] = expiration; } } else { body["expires_in"] = { hours: 3 }; } const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/tokens`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms) }); const result = await response.json(); return result; } async *listPresignedFeedbackTokens(runId) { assertUuid(runId); const params = new URLSearchParams({ run_id: runId }); for await (const tokens of this._getPaginated("/feedback/tokens", params)) { yield* tokens; } } }; } }); // node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/run_trees.js function warnOnce(message) { if (!warnedMessages[message]) { console.warn(message); warnedMessages[message] = true; } } function stripNonAlphanumeric2(input) { return input.replace(/[-:.]/g, ""); } function convertToDottedOrderFormat2(epoch, runId) { return stripNonAlphanumeric2(`${new Date(epoch).toISOString().slice(0, -1)}000Z`) + runId; } var warnedMessages, RunTree; var init_run_trees = __esm({ "node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/run_trees.js"() { init_esm_browser(); init_env4(); init_client(); warnedMessages = {}; RunTree = class { constructor(config) { Object.defineProperty(this, "id", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "run_type", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "project_name", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "parent_run", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "child_runs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "start_time", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "end_time", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "extra", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "error", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "serialized", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "reference_example_id", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "events", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "trace_id", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "dotted_order", { enumerable: true, configurable: true, writable: true, value: void 0 }); const defaultConfig = RunTree.getDefaultConfig(); const client = config.client ?? new Client(); Object.assign(this, { ...defaultConfig, ...config, client }); if (!this.trace_id) { if (this.parent_run) { this.trace_id = this.parent_run.trace_id ?? this.id; } else { this.trace_id = this.id; } } if (!this.dotted_order) { const currentDottedOrder = convertToDottedOrderFormat2(this.start_time, this.id); if (this.parent_run) { this.dotted_order = this.parent_run.dotted_order + "." + currentDottedOrder; } else { this.dotted_order = currentDottedOrder; } } } static fromRunnableConfig(config, props) { const callbackManager = config?.callbacks; let parentRun; let projectName; if (callbackManager) { const parentRunId = callbackManager?.getParentRunId?.() ?? ""; const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); parentRun = langChainTracer?.getRun?.(parentRunId); projectName = langChainTracer?.projectName; } const deduppedTags = [ ...new Set((parentRun?.tags ?? []).concat(config?.tags ?? [])) ]; const dedupedMetadata = { ...parentRun?.extra?.metadata, ...config?.metadata }; const rt = new RunTree({ name: props?.name ?? "", parent_run: parentRun, tags: deduppedTags, extra: { metadata: dedupedMetadata }, project_name: projectName }); return rt; } static getDefaultConfig() { return { id: v4_default(), run_type: "chain", project_name: getEnvironmentVariable2("LANGCHAIN_PROJECT") ?? getEnvironmentVariable2("LANGCHAIN_SESSION") ?? "default", child_runs: [], api_url: getEnvironmentVariable2("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", api_key: getEnvironmentVariable2("LANGCHAIN_API_KEY"), caller_options: {}, start_time: Date.now(), serialized: {}, inputs: {}, extra: {} }; } async createChild(config) { const child = new RunTree({ ...config, parent_run: this, project_name: this.project_name, client: this.client }); this.child_runs.push(child); return child; } async end(outputs, error, endTime = Date.now()) { this.outputs = outputs; this.error = error; this.end_time = endTime; } async _convertToCreate(run, excludeChildRuns = true) { const runExtra = run.extra ?? {}; if (!runExtra.runtime) { runExtra.runtime = {}; } const runtimeEnv = await getRuntimeEnvironment2(); for (const [k2, v2] of Object.entries(runtimeEnv)) { if (!runExtra.runtime[k2]) { runExtra.runtime[k2] = v2; } } let child_runs; let parent_run_id; if (!excludeChildRuns) { child_runs = await Promise.all(run.child_runs.map((child_run) => this._convertToCreate(child_run, excludeChildRuns))); parent_run_id = void 0; } else { parent_run_id = run.parent_run?.id; child_runs = []; } const persistedRun = { id: run.id, name: run.name, start_time: run.start_time, end_time: run.end_time, run_type: run.run_type, reference_example_id: run.reference_example_id, extra: runExtra, serialized: run.serialized, error: run.error, inputs: run.inputs, outputs: run.outputs, session_name: run.project_name, child_runs, parent_run_id, trace_id: run.trace_id, dotted_order: run.dotted_order, tags: run.tags }; return persistedRun; } async postRun(excludeChildRuns = true) { const runCreate = await this._convertToCreate(this, true); await this.client.createRun(runCreate); if (!excludeChildRuns) { warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); for (const childRun of this.child_runs) { await childRun.postRun(false); } } } async patchRun() { const runUpdate = { end_time: this.end_time, error: this.error, outputs: this.outputs, parent_run_id: this.parent_run?.id, reference_example_id: this.reference_example_id, extra: this.extra, events: this.events, dotted_order: this.dotted_order, trace_id: this.trace_id, tags: this.tags }; await this.client.updateRun(this.id, runUpdate); } }; } }); // node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/index.js var __version__; var init_dist = __esm({ "node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/dist/index.js"() { init_client(); init_run_trees(); __version__ = "0.1.13"; } }); // node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/index.js var init_langsmith = __esm({ "node_modules/.pnpm/langsmith@0.1.13/node_modules/langsmith/index.js"() { init_dist(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/tracer_langchain.js var tracer_langchain_exports = {}; __export(tracer_langchain_exports, { LangChainTracer: () => LangChainTracer }); var LangChainTracer; var init_tracer_langchain = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/tracer_langchain.js"() { init_langsmith(); init_env(); init_base2(); LangChainTracer = class extends BaseTracer { constructor(fields2 = {}) { super(fields2); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "langchain_tracer" }); Object.defineProperty(this, "projectName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "exampleId", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); const { exampleId, projectName, client } = fields2; this.projectName = projectName ?? getEnvironmentVariable("LANGCHAIN_PROJECT") ?? getEnvironmentVariable("LANGCHAIN_SESSION"); this.exampleId = exampleId; this.client = client ?? new Client({}); } async _convertToCreate(run, example_id = void 0) { return { ...run, extra: { ...run.extra, runtime: await getRuntimeEnvironment() }, child_runs: void 0, session_name: this.projectName, reference_example_id: run.parent_run_id ? void 0 : example_id }; } async persistRun(_run) { } async onRunCreate(run) { const persistedRun = await this._convertToCreate(run, this.exampleId); await this.client.createRun(persistedRun); } async onRunUpdate(run) { const runUpdate = { end_time: run.end_time, error: run.error, outputs: run.outputs, events: run.events, inputs: run.inputs, trace_id: run.trace_id, dotted_order: run.dotted_order, parent_run_id: run.parent_run_id }; await this.client.updateRun(run.id, runUpdate); } getRun(id2) { return this.runMap.get(id2); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/tracer_langchain_v1.js var tracer_langchain_v1_exports = {}; __export(tracer_langchain_v1_exports, { LangChainTracerV1: () => LangChainTracerV1 }); var LangChainTracerV1; var init_tracer_langchain_v1 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/tracer_langchain_v1.js"() { init_messages(); init_env(); init_base2(); LangChainTracerV1 = class extends BaseTracer { constructor() { super(); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "langchain_tracer" }); Object.defineProperty(this, "endpoint", { enumerable: true, configurable: true, writable: true, value: getEnvironmentVariable("LANGCHAIN_ENDPOINT") || "http://localhost:1984" }); Object.defineProperty(this, "headers", { enumerable: true, configurable: true, writable: true, value: { "Content-Type": "application/json" } }); Object.defineProperty(this, "session", { enumerable: true, configurable: true, writable: true, value: void 0 }); const apiKey = getEnvironmentVariable("LANGCHAIN_API_KEY"); if (apiKey) { this.headers["x-api-key"] = apiKey; } } async newSession(sessionName) { const sessionCreate = { start_time: Date.now(), name: sessionName }; const session = await this.persistSession(sessionCreate); this.session = session; return session; } async loadSession(sessionName) { const endpoint = `${this.endpoint}/sessions?name=${sessionName}`; return this._handleSessionResponse(endpoint); } async loadDefaultSession() { const endpoint = `${this.endpoint}/sessions?name=default`; return this._handleSessionResponse(endpoint); } async convertV2RunToRun(run) { const session = this.session ?? await this.loadDefaultSession(); const serialized = run.serialized; let runResult; if (run.run_type === "llm") { const prompts = run.inputs.prompts ? run.inputs.prompts : run.inputs.messages.map((x2) => getBufferString(x2)); const llmRun = { uuid: run.id, start_time: run.start_time, end_time: run.end_time, execution_order: run.execution_order, child_execution_order: run.child_execution_order, serialized, type: run.run_type, session_id: session.id, prompts, response: run.outputs }; runResult = llmRun; } else if (run.run_type === "chain") { const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); const chainRun = { uuid: run.id, start_time: run.start_time, end_time: run.end_time, execution_order: run.execution_order, child_execution_order: run.child_execution_order, serialized, type: run.run_type, session_id: session.id, inputs: run.inputs, outputs: run.outputs, child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool") }; runResult = chainRun; } else if (run.run_type === "tool") { const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); const toolRun = { uuid: run.id, start_time: run.start_time, end_time: run.end_time, execution_order: run.execution_order, child_execution_order: run.child_execution_order, serialized, type: run.run_type, session_id: session.id, tool_input: run.inputs.input, output: run.outputs?.output, action: JSON.stringify(serialized), child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool") }; runResult = toolRun; } else { throw new Error(`Unknown run type: ${run.run_type}`); } return runResult; } async persistRun(run) { let endpoint; let v1Run; if (run.run_type !== void 0) { v1Run = await this.convertV2RunToRun(run); } else { v1Run = run; } if (v1Run.type === "llm") { endpoint = `${this.endpoint}/llm-runs`; } else if (v1Run.type === "chain") { endpoint = `${this.endpoint}/chain-runs`; } else { endpoint = `${this.endpoint}/tool-runs`; } const response = await fetch(endpoint, { method: "POST", headers: this.headers, body: JSON.stringify(v1Run) }); if (!response.ok) { console.error(`Failed to persist run: ${response.status} ${response.statusText}`); } } async persistSession(sessionCreate) { const endpoint = `${this.endpoint}/sessions`; const response = await fetch(endpoint, { method: "POST", headers: this.headers, body: JSON.stringify(sessionCreate) }); if (!response.ok) { console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`); return { id: 1, ...sessionCreate }; } return { id: (await response.json()).id, ...sessionCreate }; } async _handleSessionResponse(endpoint) { const response = await fetch(endpoint, { method: "GET", headers: this.headers }); let tracerSession; if (!response.ok) { console.error(`Failed to load session: ${response.status} ${response.statusText}`); tracerSession = { id: 1, start_time: Date.now() }; this.session = tracerSession; return tracerSession; } const resp = await response.json(); if (resp.length === 0) { tracerSession = { id: 1, start_time: Date.now() }; this.session = tracerSession; return tracerSession; } [tracerSession] = resp; this.session = tracerSession; return tracerSession; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/initialize.js var initialize_exports = {}; __export(initialize_exports, { getTracingCallbackHandler: () => getTracingCallbackHandler, getTracingV2CallbackHandler: () => getTracingV2CallbackHandler }); async function getTracingCallbackHandler(session) { const tracer = new LangChainTracerV1(); if (session) { await tracer.loadSession(session); } else { await tracer.loadDefaultSession(); } return tracer; } async function getTracingV2CallbackHandler() { return new LangChainTracer(); } var init_initialize = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/initialize.js"() { init_tracer_langchain(); init_tracer_langchain_v1(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/callbacks/promises.js var promises_exports = {}; __export(promises_exports, { awaitAllCallbacks: () => awaitAllCallbacks, consumeCallback: () => consumeCallback }); function createQueue() { const PQueue = "default" in import_p_queue2.default ? import_p_queue2.default.default : import_p_queue2.default; return new PQueue({ autoStart: true, concurrency: 1 }); } async function consumeCallback(promiseFn, wait) { if (wait === true) { await promiseFn(); } else { if (typeof queue === "undefined") { queue = createQueue(); } void queue.add(promiseFn); } } function awaitAllCallbacks() { return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); } var import_p_queue2, queue; var init_promises = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/callbacks/promises.js"() { import_p_queue2 = __toModule(require_dist()); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/callbacks/manager.js var manager_exports = {}; __export(manager_exports, { BaseCallbackManager: () => BaseCallbackManager, CallbackManager: () => CallbackManager, CallbackManagerForChainRun: () => CallbackManagerForChainRun, CallbackManagerForLLMRun: () => CallbackManagerForLLMRun, CallbackManagerForRetrieverRun: () => CallbackManagerForRetrieverRun, CallbackManagerForToolRun: () => CallbackManagerForToolRun, TraceGroup: () => TraceGroup, ensureHandler: () => ensureHandler, parseCallbackConfigArg: () => parseCallbackConfigArg, traceAsGroup: () => traceAsGroup }); function parseCallbackConfigArg(arg) { if (!arg) { return {}; } else if (Array.isArray(arg) || "name" in arg) { return { callbacks: arg }; } else { return arg; } } function ensureHandler(handler) { if ("name" in handler) { return handler; } return BaseCallbackHandler.fromMethods(handler); } function _coerceToDict2(value, defaultKey) { return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; } async function traceAsGroup(groupOptions, enclosedCode, ...args) { const traceGroup = new TraceGroup(groupOptions.name, groupOptions); const callbackManager = await traceGroup.start({ ...args }); try { const result = await enclosedCode(callbackManager, ...args); await traceGroup.end(_coerceToDict2(result, "output")); return result; } catch (err) { await traceGroup.error(err); throw err; } } var BaseCallbackManager, BaseRunManager, CallbackManagerForRetrieverRun, CallbackManagerForLLMRun, CallbackManagerForChainRun, CallbackManagerForToolRun, CallbackManager, TraceGroup; var init_manager = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/callbacks/manager.js"() { init_esm_browser(); init_base(); init_console(); init_initialize(); init_messages(); init_env(); init_tracer_langchain(); init_promises(); if (/* @__PURE__ */ getEnvironmentVariable("LANGCHAIN_TRACING_V2") === "true" && /* @__PURE__ */ getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") !== "true") { /* @__PURE__ */ console.warn([ "[WARN]: You have enabled LangSmith tracing without backgrounding callbacks.", "[WARN]: If you are not using a serverless environment where you must wait for tracing calls to finish,", `[WARN]: we suggest setting "process.env.LANGCHAIN_CALLBACKS_BACKGROUND=true" to avoid additional latency.` ].join("\n")); } BaseCallbackManager = class { setHandler(handler) { return this.setHandlers([handler]); } }; BaseRunManager = class { constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { Object.defineProperty(this, "runId", { enumerable: true, configurable: true, writable: true, value: runId }); Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, value: handlers }); Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, value: inheritableHandlers }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: tags }); Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, value: inheritableTags }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: metadata }); Object.defineProperty(this, "inheritableMetadata", { enumerable: true, configurable: true, writable: true, value: inheritableMetadata }); Object.defineProperty(this, "_parentRunId", { enumerable: true, configurable: true, writable: true, value: _parentRunId }); } async handleText(text) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { try { await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleText: ${err}`); } }, handler.awaitHandlers))); } }; CallbackManagerForRetrieverRun = class extends BaseRunManager { getChild(tag) { const manager = new CallbackManager(this.runId); manager.setHandlers(this.inheritableHandlers); manager.addTags(this.inheritableTags); manager.addMetadata(this.inheritableMetadata); if (tag) { manager.addTags([tag], false); } return manager; } async handleRetrieverEnd(documents) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreRetriever) { try { await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleRetriever`); } } }, handler.awaitHandlers))); } async handleRetrieverError(err) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreRetriever) { try { await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); } catch (error) { console.error(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); } } }, handler.awaitHandlers))); } }; CallbackManagerForLLMRun = class extends BaseRunManager { async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields2) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreLLM) { try { await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields2); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); } } }, handler.awaitHandlers))); } async handleLLMError(err) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreLLM) { try { await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags); } catch (err2) { console.error(`Error in handler ${handler.constructor.name}, handleLLMError: ${err2}`); } } }, handler.awaitHandlers))); } async handleLLMEnd(output) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreLLM) { try { await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); } } }, handler.awaitHandlers))); } }; CallbackManagerForChainRun = class extends BaseRunManager { getChild(tag) { const manager = new CallbackManager(this.runId); manager.setHandlers(this.inheritableHandlers); manager.addTags(this.inheritableTags); manager.addMetadata(this.inheritableMetadata); if (tag) { manager.addTags([tag], false); } return manager; } async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreChain) { try { await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); } catch (err2) { console.error(`Error in handler ${handler.constructor.name}, handleChainError: ${err2}`); } } }, handler.awaitHandlers))); } async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreChain) { try { await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); } } }, handler.awaitHandlers))); } async handleAgentAction(action) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreAgent) { try { await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); } } }, handler.awaitHandlers))); } async handleAgentEnd(action) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreAgent) { try { await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); } } }, handler.awaitHandlers))); } }; CallbackManagerForToolRun = class extends BaseRunManager { getChild(tag) { const manager = new CallbackManager(this.runId); manager.setHandlers(this.inheritableHandlers); manager.addTags(this.inheritableTags); manager.addMetadata(this.inheritableMetadata); if (tag) { manager.addTags([tag], false); } return manager; } async handleToolError(err) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreAgent) { try { await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); } catch (err2) { console.error(`Error in handler ${handler.constructor.name}, handleToolError: ${err2}`); } } }, handler.awaitHandlers))); } async handleToolEnd(output) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreAgent) { try { await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); } } }, handler.awaitHandlers))); } }; CallbackManager = class extends BaseCallbackManager { constructor(parentRunId, options) { super(); Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "inheritableMetadata", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "callback_manager" }); Object.defineProperty(this, "_parentRunId", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.handlers = options?.handlers ?? this.handlers; this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers; this.tags = options?.tags ?? this.tags; this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; this.metadata = options?.metadata ?? this.metadata; this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata; this._parentRunId = parentRunId; } getParentRunId() { return this._parentRunId; } async handleLLMStart(llm, prompts, _runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { return Promise.all(prompts.map(async (prompt) => { const runId = v4_default(); await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreLLM) { try { await handler.handleLLMStart?.(llm, [prompt], runId, this._parentRunId, extraParams, this.tags, this.metadata, runName); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); })); } async handleChatModelStart(llm, messages4, _runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { return Promise.all(messages4.map(async (messageGroup) => { const runId = v4_default(); await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreLLM) { try { if (handler.handleChatModelStart) { await handler.handleChatModelStart?.(llm, [messageGroup], runId, this._parentRunId, extraParams, this.tags, this.metadata, runName); } else if (handler.handleLLMStart) { const messageString = getBufferString(messageGroup); await handler.handleLLMStart?.(llm, [messageString], runId, this._parentRunId, extraParams, this.tags, this.metadata, runName); } } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); })); } async handleChainStart(chain, inputs, runId = v4_default(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreChain) { try { await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } async handleToolStart(tool, input, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreAgent) { try { await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } async handleRetrieverStart(retriever, query, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { if (!handler.ignoreRetriever) { try { await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } addHandler(handler, inherit = true) { this.handlers.push(handler); if (inherit) { this.inheritableHandlers.push(handler); } } removeHandler(handler) { this.handlers = this.handlers.filter((_handler) => _handler !== handler); this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); } setHandlers(handlers, inherit = true) { this.handlers = []; this.inheritableHandlers = []; for (const handler of handlers) { this.addHandler(handler, inherit); } } addTags(tags, inherit = true) { this.removeTags(tags); this.tags.push(...tags); if (inherit) { this.inheritableTags.push(...tags); } } removeTags(tags) { this.tags = this.tags.filter((tag) => !tags.includes(tag)); this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); } addMetadata(metadata, inherit = true) { this.metadata = { ...this.metadata, ...metadata }; if (inherit) { this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; } } removeMetadata(metadata) { for (const key of Object.keys(metadata)) { delete this.metadata[key]; delete this.inheritableMetadata[key]; } } copy(additionalHandlers = [], inherit = true) { const manager = new CallbackManager(this._parentRunId); for (const handler of this.handlers) { const inheritable = this.inheritableHandlers.includes(handler); manager.addHandler(handler, inheritable); } for (const tag of this.tags) { const inheritable = this.inheritableTags.includes(tag); manager.addTags([tag], inheritable); } for (const key of Object.keys(this.metadata)) { const inheritable = Object.keys(this.inheritableMetadata).includes(key); manager.addMetadata({ [key]: this.metadata[key] }, inheritable); } for (const handler of additionalHandlers) { if (manager.handlers.filter((h2) => h2.name === "console_callback_handler").some((h2) => h2.name === handler.name)) { continue; } manager.addHandler(handler, inherit); } return manager; } static fromHandlers(handlers) { class Handler extends BaseCallbackHandler { constructor() { super(); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: v4_default() }); Object.assign(this, handlers); } } const manager = new this(); manager.addHandler(new Handler()); return manager; } static async configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { let callbackManager; if (inheritableHandlers || localHandlers) { if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { callbackManager = new CallbackManager(); callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); } else { callbackManager = inheritableHandlers; } callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false); } const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || options?.verbose; const tracingV2Enabled = getEnvironmentVariable("LANGCHAIN_TRACING_V2") === "true"; const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); if (verboseEnabled || tracingEnabled) { if (!callbackManager) { callbackManager = new CallbackManager(); } if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { const consoleHandler = new ConsoleCallbackHandler(); callbackManager.addHandler(consoleHandler, true); } if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { if (tracingV2Enabled) { callbackManager.addHandler(await getTracingV2CallbackHandler(), true); } } } if (inheritableTags || localTags) { if (callbackManager) { callbackManager.addTags(inheritableTags ?? []); callbackManager.addTags(localTags ?? [], false); } } if (inheritableMetadata || localMetadata) { if (callbackManager) { callbackManager.addMetadata(inheritableMetadata ?? {}); callbackManager.addMetadata(localMetadata ?? {}, false); } } return callbackManager; } }; TraceGroup = class { constructor(groupName, options) { Object.defineProperty(this, "groupName", { enumerable: true, configurable: true, writable: true, value: groupName }); Object.defineProperty(this, "options", { enumerable: true, configurable: true, writable: true, value: options }); Object.defineProperty(this, "runManager", { enumerable: true, configurable: true, writable: true, value: void 0 }); } async getTraceGroupCallbackManager(group_name, inputs, options) { const cb = new LangChainTracer(options); const cm = await CallbackManager.configure([cb]); const runManager = await cm?.handleChainStart({ lc: 1, type: "not_implemented", id: ["langchain", "callbacks", "groups", group_name] }, inputs ?? {}); if (!runManager) { throw new Error("Failed to create run group callback manager."); } return runManager; } async start(inputs) { if (!this.runManager) { this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); } return this.runManager.getChild(); } async error(err) { if (this.runManager) { await this.runManager.handleChainError(err); this.runManager = void 0; } } async end(output) { if (this.runManager) { await this.runManager.handleChainEnd(output ?? {}); this.runManager = void 0; } } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js function hasOwnProperty(obj, key) { return _hasOwnProperty.call(obj, key); } function _objectKeys(obj) { if (Array.isArray(obj)) { const keys2 = new Array(obj.length); for (let k2 = 0; k2 < keys2.length; k2++) { keys2[k2] = "" + k2; } return keys2; } if (Object.keys) { return Object.keys(obj); } let keys = []; for (let i2 in obj) { if (hasOwnProperty(obj, i2)) { keys.push(i2); } } return keys; } function _deepClone(obj) { switch (typeof obj) { case "object": return JSON.parse(JSON.stringify(obj)); case "undefined": return null; default: return obj; } } function isInteger(str3) { let i2 = 0; const len = str3.length; let charCode; while (i2 < len) { charCode = str3.charCodeAt(i2); if (charCode >= 48 && charCode <= 57) { i2++; continue; } return false; } return true; } function escapePathComponent(path) { if (path.indexOf("/") === -1 && path.indexOf("~") === -1) return path; return path.replace(/~/g, "~0").replace(/\//g, "~1"); } function unescapePathComponent(path) { return path.replace(/~1/g, "/").replace(/~0/g, "~"); } function hasUndefined(obj) { if (obj === void 0) { return true; } if (obj) { if (Array.isArray(obj)) { for (let i3 = 0, len = obj.length; i3 < len; i3++) { if (hasUndefined(obj[i3])) { return true; } } } else if (typeof obj === "object") { const objKeys = _objectKeys(obj); const objKeysLength = objKeys.length; for (var i2 = 0; i2 < objKeysLength; i2++) { if (hasUndefined(obj[objKeys[i2]])) { return true; } } } } return false; } function patchErrorMessageFormatter(message, args) { const messageParts = [message]; for (const key in args) { const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; if (typeof value !== "undefined") { messageParts.push(`${key}: ${value}`); } } return messageParts.join("\n"); } var _hasOwnProperty, PatchError; var init_helpers = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js"() { _hasOwnProperty = Object.prototype.hasOwnProperty; PatchError = class extends Error { constructor(message, name2, index2, operation, tree) { super(patchErrorMessageFormatter(message, { name: name2, index: index2, operation, tree })); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: name2 }); Object.defineProperty(this, "index", { enumerable: true, configurable: true, writable: true, value: index2 }); Object.defineProperty(this, "operation", { enumerable: true, configurable: true, writable: true, value: operation }); Object.defineProperty(this, "tree", { enumerable: true, configurable: true, writable: true, value: tree }); Object.setPrototypeOf(this, new.target.prototype); this.message = patchErrorMessageFormatter(message, { name: name2, index: index2, operation, tree }); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js var core_exports = {}; __export(core_exports, { JsonPatchError: () => JsonPatchError, _areEquals: () => _areEquals, applyOperation: () => applyOperation, applyPatch: () => applyPatch, applyReducer: () => applyReducer, deepClone: () => deepClone, getValueByPointer: () => getValueByPointer, validate: () => validate2, validator: () => validator }); function getValueByPointer(document2, pointer) { if (pointer == "") { return document2; } var getOriginalDestination = { op: "_get", path: pointer }; applyOperation(document2, getOriginalDestination); return getOriginalDestination.value; } function applyOperation(document2, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index2 = 0) { if (validateOperation) { if (typeof validateOperation == "function") { validateOperation(operation, 0, document2, operation.path); } else { validator(operation, 0); } } if (operation.path === "") { let returnValue = { newDocument: document2 }; if (operation.op === "add") { returnValue.newDocument = operation.value; return returnValue; } else if (operation.op === "replace") { returnValue.newDocument = operation.value; returnValue.removed = document2; return returnValue; } else if (operation.op === "move" || operation.op === "copy") { returnValue.newDocument = getValueByPointer(document2, operation.from); if (operation.op === "move") { returnValue.removed = document2; } return returnValue; } else if (operation.op === "test") { returnValue.test = _areEquals(document2, operation.value); if (returnValue.test === false) { throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); } returnValue.newDocument = document2; return returnValue; } else if (operation.op === "remove") { returnValue.removed = document2; returnValue.newDocument = null; return returnValue; } else if (operation.op === "_get") { operation.value = document2; return returnValue; } else { if (validateOperation) { throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); } else { return returnValue; } } } else { if (!mutateDocument) { document2 = _deepClone(document2); } const path = operation.path || ""; const keys = path.split("/"); let obj = document2; let t2 = 1; let len = keys.length; let existingPathFragment = void 0; let key; let validateFunction; if (typeof validateOperation == "function") { validateFunction = validateOperation; } else { validateFunction = validator; } while (true) { key = keys[t2]; if (key && key.indexOf("~") != -1) { key = unescapePathComponent(key); } if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t2 > 0 && keys[t2 - 1] == "constructor")) { throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); } if (validateOperation) { if (existingPathFragment === void 0) { if (obj[key] === void 0) { existingPathFragment = keys.slice(0, t2).join("/"); } else if (t2 == len - 1) { existingPathFragment = operation.path; } if (existingPathFragment !== void 0) { validateFunction(operation, 0, document2, existingPathFragment); } } } t2++; if (Array.isArray(obj)) { if (key === "-") { key = obj.length; } else { if (validateOperation && !isInteger(key)) { throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index2, operation, document2); } else if (isInteger(key)) { key = ~~key; } } if (t2 >= len) { if (validateOperation && operation.op === "add" && key > obj.length) { throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index2, operation, document2); } const returnValue = arrOps[operation.op].call(operation, obj, key, document2); if (returnValue.test === false) { throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); } return returnValue; } } else { if (t2 >= len) { const returnValue = objOps[operation.op].call(operation, obj, key, document2); if (returnValue.test === false) { throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); } return returnValue; } } obj = obj[key]; if (validateOperation && t2 < len && (!obj || typeof obj !== "object")) { throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); } } } } function applyPatch(document2, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { if (validateOperation) { if (!Array.isArray(patch)) { throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); } } if (!mutateDocument) { document2 = _deepClone(document2); } const results = new Array(patch.length); for (let i2 = 0, length = patch.length; i2 < length; i2++) { results[i2] = applyOperation(document2, patch[i2], validateOperation, true, banPrototypeModifications, i2); document2 = results[i2].newDocument; } results.newDocument = document2; return results; } function applyReducer(document2, operation, index2) { const operationResult = applyOperation(document2, operation); if (operationResult.test === false) { throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); } return operationResult.newDocument; } function validator(operation, index2, document2, existingPathFragment) { if (typeof operation !== "object" || operation === null || Array.isArray(operation)) { throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index2, operation, document2); } else if (!objOps[operation.op]) { throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); } else if (typeof operation.path !== "string") { throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index2, operation, document2); } else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index2, operation, document2); } else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") { throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index2, operation, document2); } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) { throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index2, operation, document2); } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) { throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index2, operation, document2); } else if (document2) { if (operation.op == "add") { var pathLen = operation.path.split("/").length; var existingPathLen = existingPathFragment.split("/").length; if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index2, operation, document2); } } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { if (operation.path !== existingPathFragment) { throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); } } else if (operation.op === "move" || operation.op === "copy") { var existingValue = { op: "_get", path: operation.from, value: void 0 }; var error = validate2([existingValue], document2); if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index2, operation, document2); } } } } function validate2(sequence, document2, externalValidator) { try { if (!Array.isArray(sequence)) { throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); } if (document2) { applyPatch(_deepClone(document2), _deepClone(sequence), externalValidator || true); } else { externalValidator = externalValidator || validator; for (var i2 = 0; i2 < sequence.length; i2++) { externalValidator(sequence[i2], i2, document2, void 0); } } } catch (e2) { if (e2 instanceof JsonPatchError) { return e2; } else { throw e2; } } } function _areEquals(a2, b2) { if (a2 === b2) return true; if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") { var arrA = Array.isArray(a2), arrB = Array.isArray(b2), i2, length, key; if (arrA && arrB) { length = a2.length; if (length != b2.length) return false; for (i2 = length; i2-- !== 0; ) if (!_areEquals(a2[i2], b2[i2])) return false; return true; } if (arrA != arrB) return false; var keys = Object.keys(a2); length = keys.length; if (length !== Object.keys(b2).length) return false; for (i2 = length; i2-- !== 0; ) if (!b2.hasOwnProperty(keys[i2])) return false; for (i2 = length; i2-- !== 0; ) { key = keys[i2]; if (!_areEquals(a2[key], b2[key])) return false; } return true; } return a2 !== a2 && b2 !== b2; } var JsonPatchError, deepClone, objOps, arrOps; var init_core = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js"() { init_helpers(); JsonPatchError = PatchError; deepClone = _deepClone; objOps = { add: function(obj, key, document2) { obj[key] = this.value; return { newDocument: document2 }; }, remove: function(obj, key, document2) { var removed = obj[key]; delete obj[key]; return { newDocument: document2, removed }; }, replace: function(obj, key, document2) { var removed = obj[key]; obj[key] = this.value; return { newDocument: document2, removed }; }, move: function(obj, key, document2) { let removed = getValueByPointer(document2, this.path); if (removed) { removed = _deepClone(removed); } const originalValue = applyOperation(document2, { op: "remove", path: this.from }).removed; applyOperation(document2, { op: "add", path: this.path, value: originalValue }); return { newDocument: document2, removed }; }, copy: function(obj, key, document2) { const valueToCopy = getValueByPointer(document2, this.from); applyOperation(document2, { op: "add", path: this.path, value: _deepClone(valueToCopy) }); return { newDocument: document2 }; }, test: function(obj, key, document2) { return { newDocument: document2, test: _areEquals(obj[key], this.value) }; }, _get: function(obj, key, document2) { this.value = obj[key]; return { newDocument: document2 }; } }; arrOps = { add: function(arr, i2, document2) { if (isInteger(i2)) { arr.splice(i2, 0, this.value); } else { arr[i2] = this.value; } return { newDocument: document2, index: i2 }; }, remove: function(arr, i2, document2) { var removedList = arr.splice(i2, 1); return { newDocument: document2, removed: removedList[0] }; }, replace: function(arr, i2, document2) { var removed = arr[i2]; arr[i2] = this.value; return { newDocument: document2, removed }; }, move: objOps.move, copy: objOps.copy, test: objOps.test, _get: objOps._get }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js function _generate(mirror, obj, patches, path, invertible) { if (obj === mirror) { return; } if (typeof obj.toJSON === "function") { obj = obj.toJSON(); } var newKeys = _objectKeys(obj); var oldKeys = _objectKeys(mirror); var changed = false; var deleted = false; for (var t2 = oldKeys.length - 1; t2 >= 0; t2--) { var key = oldKeys[t2]; var oldVal = mirror[key]; if (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) { var newVal = obj[key]; if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); } else { if (oldVal !== newVal) { changed = true; if (invertible) { patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) }); } patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: _deepClone(newVal) }); } } } else if (Array.isArray(mirror) === Array.isArray(obj)) { if (invertible) { patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) }); } patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) }); deleted = true; } else { if (invertible) { patches.push({ op: "test", path, value: mirror }); } patches.push({ op: "replace", path, value: obj }); changed = true; } } if (!deleted && newKeys.length == oldKeys.length) { return; } for (var t2 = 0; t2 < newKeys.length; t2++) { var key = newKeys[t2]; if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) { patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: _deepClone(obj[key]) }); } } } function compare(tree1, tree2, invertible = false) { var patches = []; _generate(tree1, tree2, patches, "", invertible); return patches; } var beforeDict; var init_duplex = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js"() { init_helpers(); init_core(); beforeDict = new WeakMap(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/index.js var fast_json_patch_default; var init_fast_json_patch = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/fast-json-patch/index.js"() { init_core(); init_duplex(); init_helpers(); init_core(); init_helpers(); fast_json_patch_default = { ...core_exports, JsonPatchError: PatchError, deepClone: _deepClone, escapePathComponent, unescapePathComponent }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/stream.js var stream_exports = {}; __export(stream_exports, { AsyncGeneratorWithSetup: () => AsyncGeneratorWithSetup, IterableReadableStream: () => IterableReadableStream, atee: () => atee, concat: () => concat, pipeGeneratorWithSetup: () => pipeGeneratorWithSetup }); function atee(iter, length = 2) { const buffers = Array.from({ length }, () => []); return buffers.map(async function* makeIter(buffer) { while (true) { if (buffer.length === 0) { const result = await iter.next(); for (const buffer2 of buffers) { buffer2.push(result); } } else if (buffer[0].done) { return; } else { yield buffer.shift().value; } } }); } function concat(first, second) { if (Array.isArray(first) && Array.isArray(second)) { return first.concat(second); } else if (typeof first === "string" && typeof second === "string") { return first + second; } else if (typeof first === "number" && typeof second === "number") { return first + second; } else if ("concat" in first && typeof first.concat === "function") { return first.concat(second); } else if (typeof first === "object" && typeof second === "object") { const chunk = { ...first }; for (const [key, value] of Object.entries(second)) { if (key in chunk && !Array.isArray(chunk[key])) { chunk[key] = concat(chunk[key], value); } else { chunk[key] = value; } } return chunk; } else { throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); } } async function pipeGeneratorWithSetup(to, generator, startSetup, ...args) { const gen = new AsyncGeneratorWithSetup(generator, startSetup); const setup = await gen.setup; return { output: to(gen, setup, ...args), setup }; } var IterableReadableStream, AsyncGeneratorWithSetup; var init_stream = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/stream.js"() { IterableReadableStream = class extends ReadableStream { constructor() { super(...arguments); Object.defineProperty(this, "reader", { enumerable: true, configurable: true, writable: true, value: void 0 }); } ensureReader() { if (!this.reader) { this.reader = this.getReader(); } } async next() { this.ensureReader(); try { const result = await this.reader.read(); if (result.done) { this.reader.releaseLock(); return { done: true, value: void 0 }; } else { return { done: false, value: result.value }; } } catch (e2) { this.reader.releaseLock(); throw e2; } } async return() { this.ensureReader(); if (this.locked) { const cancelPromise = this.reader.cancel(); this.reader.releaseLock(); await cancelPromise; } return { done: true, value: void 0 }; } async throw(e2) { this.ensureReader(); if (this.locked) { const cancelPromise = this.reader.cancel(); this.reader.releaseLock(); await cancelPromise; } throw e2; } [Symbol.asyncIterator]() { return this; } static fromReadableStream(stream) { const reader = stream.getReader(); return new IterableReadableStream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { if (done) { controller.close(); return; } controller.enqueue(value); return pump(); }); } }, cancel() { reader.releaseLock(); } }); } static fromAsyncGenerator(generator) { return new IterableReadableStream({ async pull(controller) { const { value, done } = await generator.next(); if (done) { controller.close(); } controller.enqueue(value); }, async cancel(reason) { await generator.return(reason); } }); } }; AsyncGeneratorWithSetup = class { constructor(generator, startSetup) { Object.defineProperty(this, "generator", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "setup", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "firstResult", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "firstResultUsed", { enumerable: true, configurable: true, writable: true, value: false }); this.generator = generator; this.setup = new Promise((resolve, reject) => { this.firstResult = generator.next(); if (startSetup) { this.firstResult.then(startSetup).then(resolve, reject); } else { this.firstResult.then((_result) => resolve(void 0), reject); } }); } async next(...args) { if (!this.firstResultUsed) { this.firstResultUsed = true; return this.firstResult; } return this.generator.next(...args); } async return(value) { return this.generator.return(value); } async throw(e2) { return this.generator.throw(e2); } [Symbol.asyncIterator]() { return this; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/log_stream.js var log_stream_exports = {}; __export(log_stream_exports, { LogStreamCallbackHandler: () => LogStreamCallbackHandler, RunLog: () => RunLog, RunLogPatch: () => RunLogPatch }); async function _getStandardizedInputs(run, schemaFormat) { if (schemaFormat === "original") { throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); } const { inputs } = run; if (["retriever", "llm", "prompt"].includes(run.run_type)) { return inputs; } if (Object.keys(inputs).length === 1 && inputs?.input === "") { return void 0; } return inputs.input; } async function _getStandardizedOutputs(run, schemaFormat) { const { outputs } = run; if (schemaFormat === "original") { return outputs; } if (["retriever", "llm", "prompt"].includes(run.run_type)) { return outputs; } if (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) { return outputs.output; } return outputs; } function isChatGenerationChunk(x2) { return x2 !== void 0 && x2.message !== void 0; } var RunLogPatch, RunLog, LogStreamCallbackHandler; var init_log_stream = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/log_stream.js"() { init_fast_json_patch(); init_base2(); init_stream(); init_messages(); RunLogPatch = class { constructor(fields2) { Object.defineProperty(this, "ops", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.ops = fields2.ops ?? []; } concat(other) { const ops = this.ops.concat(other.ops); const states = applyPatch({}, ops); return new RunLog({ ops, state: states[states.length - 1].newDocument }); } }; RunLog = class extends RunLogPatch { constructor(fields2) { super(fields2); Object.defineProperty(this, "state", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.state = fields2.state; } concat(other) { const ops = this.ops.concat(other.ops); const states = applyPatch(this.state, other.ops); return new RunLog({ ops, state: states[states.length - 1].newDocument }); } static fromRunLogPatch(patch) { const states = applyPatch({}, patch.ops); return new RunLog({ ops: patch.ops, state: states[states.length - 1].newDocument }); } }; LogStreamCallbackHandler = class extends BaseTracer { constructor(fields2) { super({ _awaitHandler: true, ...fields2 }); Object.defineProperty(this, "autoClose", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "includeNames", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "includeTypes", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "includeTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "excludeNames", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "excludeTypes", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "excludeTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "_schemaFormat", { enumerable: true, configurable: true, writable: true, value: "original" }); Object.defineProperty(this, "rootId", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "keyMapByRunId", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "counterMapByRunName", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "transformStream", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "writer", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "receiveStream", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "log_stream_tracer" }); this.autoClose = fields2?.autoClose ?? true; this.includeNames = fields2?.includeNames; this.includeTypes = fields2?.includeTypes; this.includeTags = fields2?.includeTags; this.excludeNames = fields2?.excludeNames; this.excludeTypes = fields2?.excludeTypes; this.excludeTags = fields2?.excludeTags; this._schemaFormat = fields2?._schemaFormat ?? this._schemaFormat; this.transformStream = new TransformStream(); this.writer = this.transformStream.writable.getWriter(); this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); } [Symbol.asyncIterator]() { return this.receiveStream; } async persistRun(_run) { } _includeRun(run) { if (run.id === this.rootId) { return false; } const runTags = run.tags ?? []; let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; if (this.includeNames !== void 0) { include = include || this.includeNames.includes(run.name); } if (this.includeTypes !== void 0) { include = include || this.includeTypes.includes(run.run_type); } if (this.includeTags !== void 0) { include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; } if (this.excludeNames !== void 0) { include = include && !this.excludeNames.includes(run.name); } if (this.excludeTypes !== void 0) { include = include && !this.excludeTypes.includes(run.run_type); } if (this.excludeTags !== void 0) { include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); } return include; } async *tapOutputIterable(runId, output) { for await (const chunk of output) { if (runId !== this.rootId) { const key = this.keyMapByRunId[runId]; if (key) { await this.writer.write(new RunLogPatch({ ops: [ { op: "add", path: `/logs/${key}/streamed_output/-`, value: chunk } ] })); } } yield chunk; } } async onRunCreate(run) { if (this.rootId === void 0) { this.rootId = run.id; await this.writer.write(new RunLogPatch({ ops: [ { op: "replace", path: "", value: { id: run.id, name: run.name, type: run.run_type, streamed_output: [], final_output: void 0, logs: {} } } ] })); } if (!this._includeRun(run)) { return; } if (this.counterMapByRunName[run.name] === void 0) { this.counterMapByRunName[run.name] = 0; } this.counterMapByRunName[run.name] += 1; const count = this.counterMapByRunName[run.name]; this.keyMapByRunId[run.id] = count === 1 ? run.name : `${run.name}:${count}`; const logEntry = { id: run.id, name: run.name, type: run.run_type, tags: run.tags ?? [], metadata: run.extra?.metadata ?? {}, start_time: new Date(run.start_time).toISOString(), streamed_output: [], streamed_output_str: [], final_output: void 0, end_time: void 0 }; if (this._schemaFormat === "streaming_events") { logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); } await this.writer.write(new RunLogPatch({ ops: [ { op: "add", path: `/logs/${this.keyMapByRunId[run.id]}`, value: logEntry } ] })); } async onRunUpdate(run) { try { const runName = this.keyMapByRunId[run.id]; if (runName === void 0) { return; } const ops = []; if (this._schemaFormat === "streaming_events") { ops.push({ op: "replace", path: `/logs/${runName}/inputs`, value: await _getStandardizedInputs(run, this._schemaFormat) }); } ops.push({ op: "add", path: `/logs/${runName}/final_output`, value: await _getStandardizedOutputs(run, this._schemaFormat) }); if (run.end_time !== void 0) { ops.push({ op: "add", path: `/logs/${runName}/end_time`, value: new Date(run.end_time).toISOString() }); } const patch = new RunLogPatch({ ops }); await this.writer.write(patch); } finally { if (run.id === this.rootId) { const patch = new RunLogPatch({ ops: [ { op: "replace", path: "/final_output", value: await _getStandardizedOutputs(run, this._schemaFormat) } ] }); await this.writer.write(patch); if (this.autoClose) { await this.writer.close(); } } } } async onLLMNewToken(run, token, kwargs) { const runName = this.keyMapByRunId[run.id]; if (runName === void 0) { return; } const isChatModel2 = run.inputs.messages !== void 0; let streamedOutputValue; if (isChatModel2) { if (isChatGenerationChunk(kwargs?.chunk)) { streamedOutputValue = kwargs?.chunk; } else { streamedOutputValue = new AIMessageChunk(token); } } else { streamedOutputValue = token; } const patch = new RunLogPatch({ ops: [ { op: "add", path: `/logs/${runName}/streamed_output_str/-`, value: token }, { op: "add", path: `/logs/${runName}/streamed_output/-`, value: streamedOutputValue } ] }); await this.writer.write(patch); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/singletons/index.js var MockAsyncLocalStorage, AsyncLocalStorageProvider, AsyncLocalStorageProviderSingleton; var init_singletons = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/singletons/index.js"() { MockAsyncLocalStorage = class { getStore() { return void 0; } run(_store, callback) { callback(); } }; AsyncLocalStorageProvider = class { constructor() { Object.defineProperty(this, "asyncLocalStorage", { enumerable: true, configurable: true, writable: true, value: new MockAsyncLocalStorage() }); Object.defineProperty(this, "hasBeenInitialized", { enumerable: true, configurable: true, writable: true, value: false }); } getInstance() { return this.asyncLocalStorage; } initializeGlobalInstance(instance) { if (!this.hasBeenInitialized) { this.hasBeenInitialized = true; this.asyncLocalStorage = instance; } } }; AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/config.js async function getCallbackManagerForConfig(config) { return CallbackManager.configure(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); } function mergeConfigs(...configs) { const copy = ensureConfig(); for (const options of configs.filter((c2) => !!c2)) { for (const key of Object.keys(options)) { if (key === "metadata") { copy[key] = { ...copy[key], ...options[key] }; } else if (key === "tags") { copy[key] = [...new Set(copy[key].concat(options[key] ?? []))]; } else if (key === "configurable") { copy[key] = { ...copy[key], ...options[key] }; } else if (key === "callbacks") { const baseCallbacks = copy.callbacks; const providedCallbacks = options.callbacks; if (Array.isArray(providedCallbacks)) { if (!baseCallbacks) { copy.callbacks = providedCallbacks; } else if (Array.isArray(baseCallbacks)) { copy.callbacks = baseCallbacks.concat(providedCallbacks); } else { const manager = baseCallbacks.copy(); for (const callback of providedCallbacks) { manager.addHandler(ensureHandler(callback), true); } copy.callbacks = manager; } } else if (providedCallbacks) { if (!baseCallbacks) { copy.callbacks = providedCallbacks; } else if (Array.isArray(baseCallbacks)) { const manager = providedCallbacks.copy(); for (const callback of baseCallbacks) { manager.addHandler(ensureHandler(callback), true); } copy.callbacks = manager; } else { copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), metadata: { ...baseCallbacks.metadata, ...providedCallbacks.metadata } }); } } } else { const typedKey = key; copy[typedKey] = options[typedKey] ?? copy[typedKey]; } } } return copy; } function ensureConfig(config) { const loadedConfig = config ?? AsyncLocalStorageProviderSingleton.getInstance().getStore(); let empty = { tags: [], metadata: {}, callbacks: void 0, recursionLimit: 25 }; if (loadedConfig) { empty = { ...empty, ...loadedConfig }; } if (loadedConfig?.configurable) { for (const key of Object.keys(loadedConfig.configurable)) { if (PRIMITIVES.has(typeof loadedConfig.configurable[key]) && !empty.metadata?.[key]) { if (!empty.metadata) { empty.metadata = {}; } empty.metadata[key] = loadedConfig.configurable[key]; } } } return empty; } function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable } = {}) { const newConfig = ensureConfig(config); if (callbacks !== void 0) { delete newConfig.runName; newConfig.callbacks = callbacks; } if (recursionLimit !== void 0) { newConfig.recursionLimit = recursionLimit; } if (maxConcurrency !== void 0) { newConfig.maxConcurrency = maxConcurrency; } if (runName !== void 0) { newConfig.runName = runName; } if (configurable !== void 0) { newConfig.configurable = { ...newConfig.configurable, ...configurable }; } return newConfig; } var DEFAULT_RECURSION_LIMIT, PRIMITIVES; var init_config = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/config.js"() { init_manager(); init_singletons(); DEFAULT_RECURSION_LIMIT = 25; PRIMITIVES = new Set(["string", "number", "boolean"]); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/async_caller.js var async_caller_exports = {}; __export(async_caller_exports, { AsyncCaller: () => AsyncCaller2 }); var import_p_retry2, import_p_queue3, STATUS_NO_RETRY2, defaultFailedAttemptHandler, AsyncCaller2; var init_async_caller2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/async_caller.js"() { import_p_retry2 = __toModule(require_p_retry()); import_p_queue3 = __toModule(require_dist()); STATUS_NO_RETRY2 = [ 400, 401, 402, 403, 404, 405, 406, 407, 409 ]; defaultFailedAttemptHandler = (error) => { if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") { throw error; } if (error?.code === "ECONNABORTED") { throw error; } const status = error?.response?.status ?? error?.status; if (status && STATUS_NO_RETRY2.includes(+status)) { throw error; } if (error?.error?.code === "insufficient_quota") { const err = new Error(error?.message); err.name = "InsufficientQuotaError"; throw err; } }; AsyncCaller2 = class { constructor(params) { Object.defineProperty(this, "maxConcurrency", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "maxRetries", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "onFailedAttempt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "queue", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.maxConcurrency = params.maxConcurrency ?? Infinity; this.maxRetries = params.maxRetries ?? 6; this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; const PQueue = "default" in import_p_queue3.default ? import_p_queue3.default.default : import_p_queue3.default; this.queue = new PQueue({ concurrency: this.maxConcurrency }); } call(callable, ...args) { return this.queue.add(() => (0, import_p_retry2.default)(() => callable(...args).catch((error) => { if (error instanceof Error) { throw error; } else { throw new Error(error); } }), { onFailedAttempt: this.onFailedAttempt, retries: this.maxRetries, randomize: true }), { throwOnTimeout: true }); } callWithOptions(options, callable, ...args) { if (options.signal) { return Promise.race([ this.call(callable, ...args), new Promise((_2, reject) => { options.signal?.addEventListener("abort", () => { reject(new Error("AbortError")); }); }) ]); } return this.call(callable, ...args); } fetch(...args) { return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/root_listener.js var RootListenersTracer; var init_root_listener = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tracers/root_listener.js"() { init_base2(); RootListenersTracer = class extends BaseTracer { constructor({ config, onStart, onEnd, onError }) { super({ _awaitHandler: true }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "RootListenersTracer" }); Object.defineProperty(this, "rootId", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "config", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "argOnStart", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "argOnEnd", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "argOnError", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.config = config; this.argOnStart = onStart; this.argOnEnd = onEnd; this.argOnError = onError; } persistRun(_2) { return Promise.resolve(); } async onRunCreate(run) { if (this.rootId) { return; } this.rootId = run.id; if (this.argOnStart) { if (this.argOnStart.length === 1) { await this.argOnStart(run); } else if (this.argOnStart.length === 2) { await this.argOnStart(run, this.config); } } } async onRunUpdate(run) { if (run.id !== this.rootId) { return; } if (!run.error) { if (this.argOnEnd) { if (this.argOnEnd.length === 1) { await this.argOnEnd(run); } else if (this.argOnEnd.length === 2) { await this.argOnEnd(run, this.config); } } } else if (this.argOnError) { if (this.argOnError.length === 1) { await this.argOnError(run); } else if (this.argOnError.length === 2) { await this.argOnError(run, this.config); } } } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/utils.js function isRunnableInterface(thing) { return thing ? thing.lc_runnable : false; } var _RootEventFilter; var init_utils = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/utils.js"() { _RootEventFilter = class { constructor(fields2) { Object.defineProperty(this, "includeNames", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "includeTypes", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "includeTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "excludeNames", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "excludeTypes", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "excludeTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.includeNames = fields2.includeNames; this.includeTypes = fields2.includeTypes; this.includeTags = fields2.includeTags; this.excludeNames = fields2.excludeNames; this.excludeTypes = fields2.excludeTypes; this.excludeTags = fields2.excludeTags; } includeEvent(event2, rootType) { let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0; const eventTags = event2.tags ?? []; if (this.includeNames !== void 0) { include = include || this.includeNames.includes(event2.name); } if (this.includeTypes !== void 0) { include = include || this.includeTypes.includes(rootType); } if (this.includeTags !== void 0) { include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); } if (this.excludeNames !== void 0) { include = include && !this.excludeNames.includes(event2.name); } if (this.excludeTypes !== void 0) { include = include && !this.excludeTypes.includes(rootType); } if (this.excludeTags !== void 0) { include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); } return include; } }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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); } var init_errorMessages = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/errorMessages.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/Options.js var defaultOptions, getDefaultOptions; var init_Options = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/Options.js"() { defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "string", mapStrategy: "entries", definitionPath: "definitions", target: "jsonSchema7", strictUnions: false, definitions: {}, errorMessages: false, markdownDescription: false, patternStrategy: "escape", emailStrategy: "format:email" }; getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/any.js function parseAnyDef() { return {}; } var init_any = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/any.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/array.js function parseArrayDef(def, refs) { const res = { type: "array" }; if (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; } var init_array = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/array.js"() { init_lib(); init_errorMessages(); init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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; } var init_bigint = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"() { init_errorMessages(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js function parseBooleanDef() { return { type: "boolean" }; } var init_boolean = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } var init_branded = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"() { init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js var parseCatchDef; var init_catch = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"() { init_parseDef(); parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/date.js function parseDateDef(def, refs) { if (refs.dateStrategy == "integer") { return integerDateParser(def, refs); } else { return { type: "string", format: "date-time" }; } } var integerDateParser; var init_date = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/date.js"() { init_errorMessages(); integerDateParser = (def, refs) => { const res = { type: "integer", format: "unix-time" }; for (const check of def.checks) { switch (check.kind) { case "min": if (refs.target === "jsonSchema7") { setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } break; } } return res; }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/default.js function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } var init_default = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/default.js"() { init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {}; } var init_effects = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"() { init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js function parseEnumDef(def) { return { type: "string", enum: def.values }; } var init_enum = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js 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((x2) => !!x2); let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; const mergedAllOf = []; allOf.forEach((schema3) => { if (isJsonSchema7AllOfType(schema3)) { mergedAllOf.push(...schema3.allOf); if (schema3.unevaluatedProperties === void 0) { unevaluatedProperties = void 0; } } else { let nestedSchema = schema3; if ("additionalProperties" in schema3 && schema3.additionalProperties === false) { const { additionalProperties, ...rest } = schema3; nestedSchema = rest; } else { unevaluatedProperties = void 0; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf, ...unevaluatedProperties } : void 0; } var isJsonSchema7AllOfType; var init_intersection = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"() { init_parseDef(); isJsonSchema7AllOfType = (type2) => { if ("type" in type2 && type2.type === "string") return false; return "allOf" in type2; }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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 }; } var init_literal = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/string.js function parseStringDef(def, refs) { const res = { type: "string" }; function processPattern(value) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(value) : value; } 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.source, 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, "^" + processPattern(check.value), check.message, refs); break; case "endsWith": addPattern(res, processPattern(check.value) + "$", check.message, refs); break; case "datetime": addFormat(res, "date-time", 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, processPattern(check.value), 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 "emoji": addPattern(res, zodPatterns.emoji, check.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check.message, refs); break; } case "toLowerCase": case "toUpperCase": case "trim": break; default: ((_2) => { })(check); } } } return res; } var zodPatterns, escapeNonAlphaNumeric, addFormat, addPattern; var init_string = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() { init_errorMessages(); zodPatterns = { cuid: "^[cC][^\\s-]{8,}$", cuid2: "^[a-z][a-z0-9]*$", 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: "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", 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]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$", 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})))$" }; escapeNonAlphaNumeric = (value) => Array.from(value).map((c2) => /[a-zA-Z0-9]/.test(c2) ? c2 : `\\${c2}`).join(""); addFormat = (schema3, value, message, refs) => { if (schema3.format || schema3.anyOf?.some((x2) => x2.format)) { if (!schema3.anyOf) { schema3.anyOf = []; } if (schema3.format) { schema3.anyOf.push({ format: schema3.format, ...schema3.errorMessage && refs.errorMessages && { errorMessage: { format: schema3.errorMessage.format } } }); delete schema3.format; if (schema3.errorMessage) { delete schema3.errorMessage.format; if (Object.keys(schema3.errorMessage).length === 0) { delete schema3.errorMessage; } } } schema3.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { setResponseValueAndErrors(schema3, "format", value, message, refs); } }; addPattern = (schema3, value, message, refs) => { if (schema3.pattern || schema3.allOf?.some((x2) => x2.pattern)) { if (!schema3.allOf) { schema3.allOf = []; } if (schema3.pattern) { schema3.allOf.push({ pattern: schema3.pattern, ...schema3.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema3.errorMessage.pattern } } }); delete schema3.pattern; if (schema3.errorMessage) { delete schema3.errorMessage.pattern; if (Object.keys(schema3.errorMessage).length === 0) { delete schema3.errorMessage; } } } schema3.allOf.push({ pattern: value, ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { setResponseValueAndErrors(schema3, "pattern", value, message, refs); } }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/record.js function parseRecordDef(def, refs) { 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: false }; } const schema3 = { type: "object", additionalProperties: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? {} }; if (refs.target === "openApi3") { return schema3; } if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => key === "type" ? acc : { ...acc, [key]: value }, {}); return { ...schema3, propertyNames: keyType }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { return { ...schema3, propertyNames: { enum: def.keyType._def.values } }; } return schema3; } var init_record = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() { init_lib(); init_parseDef(); init_string(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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 } }; } var init_map = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/map.js"() { init_parseDef(); init_record(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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 }; } var init_nativeEnum = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/never.js function parseNeverDef() { return { not: {} }; } var init_never = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/never.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/null.js function parseNullDef(refs) { return refs.target === "openApi3" ? { enum: ["null"], nullable: true } : { type: "null" }; } var init_null = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/null.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/union.js 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((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) { const types = options.reduce((types2, x2) => { const type2 = primitiveMappings[x2._def.typeName]; return type2 && !types2.includes(type2) ? [...types2, type2] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) { const types = options.reduce((acc, x2) => { const type2 = typeof x2._def.value; switch (type2) { case "string": case "number": case "boolean": return [...acc, type2]; case "bigint": return [...acc, "integer"]; case "object": if (x2._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, []); if (types.length === options.length) { const uniqueTypes = types.filter((x2, i2, a2) => a2.indexOf(x2) === i2); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce((acc, x2) => { return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value]; }, []) }; } } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce((acc, x2) => [ ...acc, ...x2._def.values.filter((x3) => !acc.includes(x3)) ], []) }; } return asAnyOf(def, refs); } var primitiveMappings, asAnyOf; var init_union = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/union.js"() { init_parseDef(); primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i2) => parseDef(x2._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i2}`] })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)); return anyOf.length ? { anyOf } : void 0; }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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" }] }; } var init_nullable = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"() { init_parseDef(); init_union(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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; } var init_number = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/number.js"() { init_errorMessages(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/object.js function parseObjectDef(def, refs) { const result = { type: "object", ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { if (propDef === void 0 || propDef._def === void 0) return acc; const parsedDef = parseDef(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) return acc; return { properties: { ...acc.properties, [propName]: parsedDef }, required: propDef.isOptional() ? acc.required : [...acc.required, propName] }; }, { properties: {}, required: [] }), additionalProperties: def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? true }; if (!result.required.length) delete result.required; return result; } var init_object = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/object.js"() { init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js var parseOptionalDef; var init_optional = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"() { init_parseDef(); 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/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js var parsePipelineDef; var init_pipeline = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"() { init_parseDef(); 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 a2 = parseDef(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b2 = parseDef(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a2 ? "1" : "0"] }); return { allOf: [a2, b2].filter((x2) => x2 !== void 0) }; }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } var init_promise = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"() { init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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 schema3 = { type: "array", uniqueItems: true, items }; if (def.minSize) { setResponseValueAndErrors(schema3, "minItems", def.minSize.value, def.minSize.message, refs); } if (def.maxSize) { setResponseValueAndErrors(schema3, "maxItems", def.maxSize.value, def.maxSize.message, refs); } return schema3; } var init_set = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/set.js"() { init_errorMessages(); init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/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((x2, i2) => parseDef(x2._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i2}`] })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []), 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((x2, i2) => parseDef(x2._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i2}`] })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []) }; } } var init_tuple = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"() { init_parseDef(); } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js function parseUndefinedDef() { return { not: {} }; } var init_undefined = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js function parseUnknownDef() { return {}; } var init_unknown = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"() { } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js var parseReadonlyDef; var init_readonly = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"() { init_parseDef(); parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parseDef.js function parseDef(def, refs, forceResolution = false) { const seenItem = refs.seen.get(def); if (seenItem && !forceResolution) { const seenSchema = get$ref(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchema = selectParser(def, def.typeName, refs); if (jsonSchema) { addMeta(def, refs, jsonSchema); } newItem.jsonSchema = jsonSchema; return jsonSchema; } var get$ref, getRelativePath, selectParser, addMeta; var init_parseDef = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/parseDef.js"() { init_lib(); init_any(); init_array(); init_bigint(); init_boolean(); init_branded(); init_catch(); init_date(); init_default(); init_effects(); init_enum(); init_intersection(); init_literal(); init_map(); init_nativeEnum(); init_never(); init_null(); init_nullable(); init_number(); init_object(); init_optional(); init_pipeline(); init_promise(); init_record(); init_set(); init_string(); init_tuple(); init_undefined(); init_union(); init_unknown(); init_readonly(); 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, index2) => refs.currentPath[index2] === value)) { console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); return {}; } return refs.$refStrategy === "seen" ? {} : void 0; } } }; getRelativePath = (pathA, pathB) => { let i2 = 0; for (; i2 < pathA.length && i2 < pathB.length; i2++) { if (pathA[i2] !== pathB[i2]) break; } return [(pathA.length - i2).toString(), ...pathB.slice(i2)].join("/"); }; 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 parseDef(def.getter()._def, refs); 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 void 0; default: return ((_2) => void 0)(typeName); } }; addMeta = (def, refs, jsonSchema) => { if (def.description) { jsonSchema.description = def.description; if (refs.markdownDescription) { jsonSchema.markdownDescription = def.description; } } return jsonSchema; }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/Refs.js var getRefs; var init_Refs = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/Refs.js"() { init_Options(); getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: void 0, seen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name2], jsonSchema: void 0 } ])) }; }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js var zodToJsonSchema; var init_zodToJsonSchema = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"() { init_parseDef(); init_Refs(); zodToJsonSchema = (schema3, options) => { const refs = getRefs(options); const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema4]) => ({ ...acc, [name3]: parseDef(schema4._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name3] }, true) ?? {} }), {}) : void 0; const name2 = typeof options === "string" ? options : options?.name; const main2 = parseDef(schema3._def, name2 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name2] }, false) ?? {}; const combined = name2 === void 0 ? definitions ? { ...main2, [refs.definitionPath]: definitions } : main2 : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name2 ].join("/"), [refs.definitionPath]: { ...definitions, [name2]: main2 } }; if (refs.target === "jsonSchema7") { combined.$schema = "http://json-schema.org/draft-07/schema#"; } else if (refs.target === "jsonSchema2019-09") { combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; } return combined; }; } }); // node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/index.js var init_esm = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.22.4_zod@3.22.4/node_modules/zod-to-json-schema/dist/esm/index.js"() { init_errorMessages(); init_Options(); init_parseDef(); init_any(); init_array(); init_bigint(); init_boolean(); init_branded(); init_catch(); init_date(); init_default(); init_effects(); init_enum(); init_intersection(); init_literal(); init_map(); init_nativeEnum(); init_never(); init_null(); init_nullable(); init_number(); init_object(); init_optional(); init_pipeline(); init_promise(); init_readonly(); init_record(); init_set(); init_string(); init_tuple(); init_undefined(); init_union(); init_unknown(); init_Refs(); init_zodToJsonSchema(); init_zodToJsonSchema(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/graph.js function nodeDataJson(node) { if (isRunnableInterface(node.data)) { return { type: "runnable", data: { id: node.data.lc_id, name: node.data.getName() } }; } else { return { type: "schema", data: { ...zodToJsonSchema(node.data.schema), title: node.data.name } }; } } var Graph; var init_graph = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/graph.js"() { init_esm(); init_esm_browser(); init_utils(); Graph = class { constructor() { Object.defineProperty(this, "nodes", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "edges", { enumerable: true, configurable: true, writable: true, value: [] }); } toJSON() { const stableNodeIds = {}; Object.values(this.nodes).forEach((node, i2) => { stableNodeIds[node.id] = validate_default(node.id) ? i2 : node.id; }); return { nodes: Object.values(this.nodes).map((node) => ({ id: stableNodeIds[node.id], ...nodeDataJson(node) })), edges: this.edges.map((edge) => edge.data ? { source: stableNodeIds[edge.source], target: stableNodeIds[edge.target], data: edge.data } : { source: stableNodeIds[edge.source], target: stableNodeIds[edge.target] }) }; } addNode(data, id2) { if (id2 !== void 0 && this.nodes[id2] !== void 0) { throw new Error(`Node with id ${id2} already exists`); } const nodeId = id2 || v4_default(); const node = { id: nodeId, data }; this.nodes[nodeId] = node; return node; } removeNode(node) { delete this.nodes[node.id]; this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); } addEdge(source, target, data) { if (this.nodes[source.id] === void 0) { throw new Error(`Source node ${source.id} not in graph`); } if (this.nodes[target.id] === void 0) { throw new Error(`Target node ${target.id} not in graph`); } const edge = { source: source.id, target: target.id, data }; this.edges.push(edge); return edge; } firstNode() { const targets = new Set(this.edges.map((edge) => edge.target)); const found = []; Object.values(this.nodes).forEach((node) => { if (!targets.has(node.id)) { found.push(node); } }); return found[0]; } lastNode() { const sources = new Set(this.edges.map((edge) => edge.source)); const found = []; Object.values(this.nodes).forEach((node) => { if (!sources.has(node.id)) { found.push(node); } }); return found[0]; } extend(graph) { Object.entries(graph.nodes).forEach(([key, value]) => { this.nodes[key] = value; }); this.edges = [...this.edges, ...graph.edges]; } trimFirstNode() { const firstNode = this.firstNode(); if (firstNode) { const outgoingEdges = this.edges.filter((edge) => edge.source === firstNode.id); if (Object.keys(this.nodes).length === 1 || outgoingEdges.length === 1) { this.removeNode(firstNode); } } } trimLastNode() { const lastNode = this.lastNode(); if (lastNode) { const incomingEdges = this.edges.filter((edge) => edge.target === lastNode.id); if (Object.keys(this.nodes).length === 1 || incomingEdges.length === 1) { this.removeNode(lastNode); } } } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/base.js function _coerceToDict3(value, defaultKey) { return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; } function _coerceToRunnable(coerceable) { if (typeof coerceable === "function") { return new RunnableLambda({ func: coerceable }); } else if (Runnable.isRunnable(coerceable)) { return coerceable; } else if (!Array.isArray(coerceable) && typeof coerceable === "object") { const runnables = {}; for (const [key, value] of Object.entries(coerceable)) { runnables[key] = _coerceToRunnable(value); } return new RunnableMap({ steps: runnables }); } else { throw new Error(`Expected a Runnable, function or object. Instead got an unsupported type.`); } } var import_p_retry3, Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableLambda, RunnableParallel, RunnableWithFallbacks, RunnableAssign, RunnablePick; var init_base3 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/base.js"() { init_lib(); import_p_retry3 = __toModule(require_p_retry()); init_manager(); init_log_stream(); init_serializable(); init_stream(); init_config(); init_async_caller2(); init_root_listener(); init_utils(); init_singletons(); init_graph(); Runnable = class extends Serializable { constructor() { super(...arguments); Object.defineProperty(this, "lc_runnable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); } getName(suffix) { const name2 = this.name ?? this.constructor.lc_name() ?? this.constructor.name; return suffix ? `${name2}${suffix}` : name2; } bind(kwargs) { return new RunnableBinding({ bound: this, kwargs, config: {} }); } map() { return new RunnableEach({ bound: this }); } withRetry(fields2) { return new RunnableRetry({ bound: this, kwargs: {}, config: {}, maxAttemptNumber: fields2?.stopAfterAttempt, ...fields2 }); } withConfig(config) { return new RunnableBinding({ bound: this, config, kwargs: {} }); } withFallbacks(fields2) { return new RunnableWithFallbacks({ runnable: this, fallbacks: fields2.fallbacks }); } _getOptionsList(options, length = 0) { if (Array.isArray(options)) { if (options.length !== length) { throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); } return options.map(ensureConfig); } return Array.from({ length }, () => ensureConfig(options)); } async batch(inputs, options, batchOptions) { const configList = this._getOptionsList(options ?? {}, inputs.length); const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; const caller2 = new AsyncCaller2({ maxConcurrency, onFailedAttempt: (e2) => { throw e2; } }); const batchCalls = inputs.map((input, i2) => caller2.call(async () => { try { const result = await this.invoke(input, configList[i2]); return result; } catch (e2) { if (batchOptions?.returnExceptions) { return e2; } throw e2; } })); return Promise.all(batchCalls); } async *_streamIterator(input, options) { yield this.invoke(input, options); } async stream(input, options) { const wrappedGenerator = new AsyncGeneratorWithSetup(this._streamIterator(input, ensureConfig(options))); await wrappedGenerator.setup; return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } _separateRunnableConfigFromCallOptions(options = {}) { const runnableConfig = ensureConfig({ callbacks: options.callbacks, tags: options.tags, metadata: options.metadata, runName: options.runName, configurable: options.configurable, recursionLimit: options.recursionLimit, maxConcurrency: options.maxConcurrency }); const callOptions = { ...options }; delete callOptions.callbacks; delete callOptions.tags; delete callOptions.metadata; delete callOptions.runName; delete callOptions.configurable; delete callOptions.recursionLimit; delete callOptions.maxConcurrency; return [runnableConfig, callOptions]; } async _callWithConfig(func, input, options) { const config = ensureConfig(options); const callbackManager_ = await getCallbackManagerForConfig(config); const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), void 0, config?.runType, void 0, void 0, config?.runName ?? this.getName()); let output; try { output = await func.call(this, input, config, runManager); } catch (e2) { await runManager?.handleChainError(e2); throw e2; } await runManager?.handleChainEnd(_coerceToDict3(output, "output")); return output; } async _batchWithConfig(func, inputs, options, batchOptions) { const optionsList2 = this._getOptionsList(options ?? {}, inputs.length); const callbackManagers = await Promise.all(optionsList2.map(getCallbackManagerForConfig)); const runManagers = await Promise.all(callbackManagers.map((callbackManager, i2) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict3(inputs[i2], "input"), void 0, optionsList2[i2].runType, void 0, void 0, optionsList2[i2].runName ?? this.getName()))); let outputs; try { outputs = await func.call(this, inputs, optionsList2, runManagers, batchOptions); } catch (e2) { await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e2))); throw e2; } await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict3(outputs, "output")))); return outputs; } async *_transformStreamWithConfig(inputGenerator, transformer, options) { let finalInput; let finalInputSupported = true; let finalOutput; let finalOutputSupported = true; const config = ensureConfig(options); const callbackManager_ = await getCallbackManagerForConfig(config); async function* wrapInputForTracing() { for await (const chunk of inputGenerator) { if (finalInputSupported) { if (finalInput === void 0) { finalInput = chunk; } else { try { finalInput = concat(finalInput, chunk); } catch { finalInput = void 0; finalInputSupported = false; } } } yield chunk; } } let runManager; try { const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, void 0, config?.runType, void 0, void 0, config?.runName ?? this.getName()), config); runManager = pipe.setup; const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); let iterator = pipe.output; if (streamLogHandler !== void 0 && runManager !== void 0) { iterator = await streamLogHandler.tapOutputIterable(runManager.runId, pipe.output); } for await (const chunk of iterator) { yield chunk; if (finalOutputSupported) { if (finalOutput === void 0) { finalOutput = chunk; } else { try { finalOutput = concat(finalOutput, chunk); } catch { finalOutput = void 0; finalOutputSupported = false; } } } } } catch (e2) { await runManager?.handleChainError(e2, void 0, void 0, void 0, { inputs: _coerceToDict3(finalInput, "input") }); throw e2; } await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: _coerceToDict3(finalInput, "input") }); } getGraph(_2) { const graph = new Graph(); const inputNode = graph.addNode({ name: `${this.getName()}Input`, schema: z.any() }); const runnableNode = graph.addNode(this); const outputNode = graph.addNode({ name: `${this.getName()}Output`, schema: z.any() }); graph.addEdge(inputNode, runnableNode); graph.addEdge(runnableNode, outputNode); return graph; } pipe(coerceable) { return new RunnableSequence({ first: this, last: _coerceToRunnable(coerceable) }); } pick(keys) { return this.pipe(new RunnablePick(keys)); } assign(mapping) { return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping }))); } async *transform(generator, options) { let finalChunk; for await (const chunk of generator) { if (finalChunk === void 0) { finalChunk = chunk; } else { finalChunk = concat(finalChunk, chunk); } } yield* this._streamIterator(finalChunk, ensureConfig(options)); } async *streamLog(input, options, streamOptions) { const logStreamCallbackHandler = new LogStreamCallbackHandler({ ...streamOptions, autoClose: false, _schemaFormat: "original" }); const config = ensureConfig(options); yield* this._streamLog(input, logStreamCallbackHandler, config); } async *_streamLog(input, logStreamCallbackHandler, config) { const { callbacks } = config; if (callbacks === void 0) { config.callbacks = [logStreamCallbackHandler]; } else if (Array.isArray(callbacks)) { config.callbacks = callbacks.concat([logStreamCallbackHandler]); } else { const copiedCallbacks = callbacks.copy(); copiedCallbacks.inheritableHandlers.push(logStreamCallbackHandler); config.callbacks = copiedCallbacks; } const runnableStreamPromise = this.stream(input, config); async function consumeRunnableStream() { try { const runnableStream = await runnableStreamPromise; for await (const chunk of runnableStream) { const patch = new RunLogPatch({ ops: [ { op: "add", path: "/streamed_output/-", value: chunk } ] }); await logStreamCallbackHandler.writer.write(patch); } } finally { await logStreamCallbackHandler.writer.close(); } } const runnableStreamConsumePromise = consumeRunnableStream(); try { for await (const log of logStreamCallbackHandler) { yield log; } } finally { await runnableStreamConsumePromise; } } async *streamEvents(input, options, streamOptions) { if (options.version !== "v1") { throw new Error(`Only version "v1" of the events schema is currently supported.`); } let runLog; let hasEncounteredStartEvent = false; const config = ensureConfig(options); const rootTags = config.tags ?? []; const rootMetadata = config.metadata ?? {}; const rootName = config.runName ?? this.getName(); const logStreamCallbackHandler = new LogStreamCallbackHandler({ ...streamOptions, autoClose: false, _schemaFormat: "streaming_events" }); const rootEventFilter = new _RootEventFilter({ ...streamOptions }); const logStream = this._streamLog(input, logStreamCallbackHandler, config); for await (const log of logStream) { if (!runLog) { runLog = RunLog.fromRunLogPatch(log); } else { runLog = runLog.concat(log); } if (runLog.state === void 0) { throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); } if (!hasEncounteredStartEvent) { hasEncounteredStartEvent = true; const state3 = { ...runLog.state }; const event2 = { run_id: state3.id, event: `on_${state3.type}_start`, name: rootName, tags: rootTags, metadata: rootMetadata, data: { input } }; if (rootEventFilter.includeEvent(event2, state3.type)) { yield event2; } } const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); const dedupedPaths = [...new Set(paths)]; for (const path of dedupedPaths) { let eventType; let data = {}; const logEntry = runLog.state.logs[path]; if (logEntry.end_time === void 0) { if (logEntry.streamed_output.length > 0) { eventType = "stream"; } else { eventType = "start"; } } else { eventType = "end"; } if (eventType === "start") { if (logEntry.inputs !== void 0) { data.input = logEntry.inputs; } } else if (eventType === "end") { if (logEntry.inputs !== void 0) { data.input = logEntry.inputs; } data.output = logEntry.final_output; } else if (eventType === "stream") { const chunkCount = logEntry.streamed_output.length; if (chunkCount !== 1) { throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); } data = { chunk: logEntry.streamed_output[0] }; logEntry.streamed_output = []; } yield { event: `on_${logEntry.type}_${eventType}`, name: logEntry.name, run_id: logEntry.id, tags: logEntry.tags, metadata: logEntry.metadata, data }; } const { state: state2 } = runLog; if (state2.streamed_output.length > 0) { const chunkCount = state2.streamed_output.length; if (chunkCount !== 1) { throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state2.name}"`); } const data = { chunk: state2.streamed_output[0] }; state2.streamed_output = []; const event2 = { event: `on_${state2.type}_stream`, run_id: state2.id, tags: rootTags, metadata: rootMetadata, name: rootName, data }; if (rootEventFilter.includeEvent(event2, state2.type)) { yield event2; } } } const state = runLog?.state; if (state !== void 0) { const event2 = { event: `on_${state.type}_end`, name: rootName, run_id: state.id, tags: rootTags, metadata: rootMetadata, data: { output: state.final_output } }; if (rootEventFilter.includeEvent(event2, state.type)) yield event2; } } static isRunnable(thing) { return isRunnableInterface(thing); } withListeners({ onStart, onEnd, onError }) { return new RunnableBinding({ bound: this, config: {}, configFactories: [ (config) => ({ callbacks: [ new RootListenersTracer({ config, onStart, onEnd, onError }) ] }) ] }); } }; RunnableBinding = class extends Runnable { static lc_name() { return "RunnableBinding"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "bound", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "config", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "configFactories", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.bound = fields2.bound; this.kwargs = fields2.kwargs; this.config = fields2.config; this.configFactories = fields2.configFactories; } getName(suffix) { return this.bound.getName(suffix); } async _mergeConfig(...options) { const config = mergeConfigs(this.config, ...options); return mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []); } bind(kwargs) { return new this.constructor({ bound: this.bound, kwargs: { ...this.kwargs, ...kwargs }, config: this.config }); } withConfig(config) { return new this.constructor({ bound: this.bound, kwargs: this.kwargs, config: { ...this.config, ...config } }); } withRetry(fields2) { return new this.constructor({ bound: this.bound.withRetry(fields2), kwargs: this.kwargs, config: this.config }); } async invoke(input, options) { return this.bound.invoke(input, await this._mergeConfig(options, this.kwargs)); } async batch(inputs, options, batchOptions) { const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(individualOption, this.kwargs))) : await this._mergeConfig(options, this.kwargs); return this.bound.batch(inputs, mergedOptions, batchOptions); } async *_streamIterator(input, options) { yield* this.bound._streamIterator(input, await this._mergeConfig(options, this.kwargs)); } async stream(input, options) { return this.bound.stream(input, await this._mergeConfig(options, this.kwargs)); } async *transform(generator, options) { yield* this.bound.transform(generator, await this._mergeConfig(options, this.kwargs)); } async *streamEvents(input, options, streamOptions) { yield* this.bound.streamEvents(input, { ...await this._mergeConfig(options, this.kwargs), version: options.version }, streamOptions); } static isRunnableBinding(thing) { return thing.bound && Runnable.isRunnable(thing.bound); } withListeners({ onStart, onEnd, onError }) { return new RunnableBinding({ bound: this.bound, kwargs: this.kwargs, config: this.config, configFactories: [ (config) => ({ callbacks: [ new RootListenersTracer({ config, onStart, onEnd, onError }) ] }) ] }); } }; RunnableEach = class extends Runnable { static lc_name() { return "RunnableEach"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "bound", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.bound = fields2.bound; } bind(kwargs) { return new RunnableEach({ bound: this.bound.bind(kwargs) }); } async invoke(inputs, config) { return this._callWithConfig(this._invoke, inputs, config); } async _invoke(inputs, config, runManager) { return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() })); } withListeners({ onStart, onEnd, onError }) { return new RunnableEach({ bound: this.bound.withListeners({ onStart, onEnd, onError }) }); } }; RunnableRetry = class extends RunnableBinding { static lc_name() { return "RunnableRetry"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "maxAttemptNumber", { enumerable: true, configurable: true, writable: true, value: 3 }); Object.defineProperty(this, "onFailedAttempt", { enumerable: true, configurable: true, writable: true, value: () => { } }); this.maxAttemptNumber = fields2.maxAttemptNumber ?? this.maxAttemptNumber; this.onFailedAttempt = fields2.onFailedAttempt ?? this.onFailedAttempt; } _patchConfigForRetry(attempt, config, runManager) { const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0; return patchConfig(config, { callbacks: runManager?.getChild(tag) }); } async _invoke(input, config, runManager) { return (0, import_p_retry3.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { onFailedAttempt: this.onFailedAttempt, retries: Math.max(this.maxAttemptNumber - 1, 0), randomize: true }); } async invoke(input, config) { return this._callWithConfig(this._invoke, input, config); } async _batch(inputs, configs, runManagers, batchOptions) { const resultsMap = {}; try { await (0, import_p_retry3.default)(async (attemptNumber) => { const remainingIndexes = inputs.map((_2, i2) => i2).filter((i2) => resultsMap[i2.toString()] === void 0 || resultsMap[i2.toString()] instanceof Error); const remainingInputs = remainingIndexes.map((i2) => inputs[i2]); const patchedConfigs = remainingIndexes.map((i2) => this._patchConfigForRetry(attemptNumber, configs?.[i2], runManagers?.[i2])); const results = await super.batch(remainingInputs, patchedConfigs, { ...batchOptions, returnExceptions: true }); let firstException; for (let i2 = 0; i2 < results.length; i2 += 1) { const result = results[i2]; const resultMapIndex = remainingIndexes[i2]; if (result instanceof Error) { if (firstException === void 0) { firstException = result; } } resultsMap[resultMapIndex.toString()] = result; } if (firstException) { throw firstException; } return results; }, { onFailedAttempt: this.onFailedAttempt, retries: Math.max(this.maxAttemptNumber - 1, 0), randomize: true }); } catch (e2) { if (batchOptions?.returnExceptions !== true) { throw e2; } } return Object.keys(resultsMap).sort((a2, b2) => parseInt(a2, 10) - parseInt(b2, 10)).map((key) => resultsMap[parseInt(key, 10)]); } async batch(inputs, options, batchOptions) { return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); } }; RunnableSequence = class extends Runnable { static lc_name() { return "RunnableSequence"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "first", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "middle", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "last", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); this.first = fields2.first; this.middle = fields2.middle ?? this.middle; this.last = fields2.last; this.name = fields2.name; } get steps() { return [this.first, ...this.middle, this.last]; } async invoke(input, options) { const config = ensureConfig(options); const callbackManager_ = await getCallbackManagerForConfig(config); const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), void 0, void 0, void 0, void 0, config?.runName); let nextStepInput = input; let finalOutput; try { const initialSteps = [this.first, ...this.middle]; for (let i2 = 0; i2 < initialSteps.length; i2 += 1) { const step = initialSteps[i2]; nextStepInput = await step.invoke(nextStepInput, patchConfig(config, { callbacks: runManager?.getChild(`seq:step:${i2 + 1}`) })); } finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { callbacks: runManager?.getChild(`seq:step:${this.steps.length}`) })); } catch (e2) { await runManager?.handleChainError(e2); throw e2; } await runManager?.handleChainEnd(_coerceToDict3(finalOutput, "output")); return finalOutput; } async batch(inputs, options, batchOptions) { const configList = this._getOptionsList(options ?? {}, inputs.length); const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); const runManagers = await Promise.all(callbackManagers.map((callbackManager, i2) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict3(inputs[i2], "input"), void 0, void 0, void 0, void 0, configList[i2].runName))); let nextStepInputs = inputs; try { for (let i2 = 0; i2 < this.steps.length; i2 += 1) { const step = this.steps[i2]; nextStepInputs = await step.batch(nextStepInputs, runManagers.map((runManager, j2) => { const childRunManager = runManager?.getChild(`seq:step:${i2 + 1}`); return patchConfig(configList[j2], { callbacks: childRunManager }); }), batchOptions); } } catch (e2) { await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e2))); throw e2; } await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict3(nextStepInputs, "output")))); return nextStepInputs; } async *_streamIterator(input, options) { const callbackManager_ = await getCallbackManagerForConfig(options); const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), void 0, void 0, void 0, void 0, options?.runName); const steps = [this.first, ...this.middle, this.last]; let concatSupported = true; let finalOutput; async function* inputGenerator() { yield input; } try { let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(options, { callbacks: runManager?.getChild(`seq:step:1`) })); for (let i2 = 1; i2 < steps.length; i2 += 1) { const step = steps[i2]; finalGenerator = await step.transform(finalGenerator, patchConfig(options, { callbacks: runManager?.getChild(`seq:step:${i2 + 1}`) })); } for await (const chunk of finalGenerator) { yield chunk; if (concatSupported) { if (finalOutput === void 0) { finalOutput = chunk; } else { try { finalOutput = concat(finalOutput, chunk); } catch (e2) { finalOutput = void 0; concatSupported = false; } } } } } catch (e2) { await runManager?.handleChainError(e2); throw e2; } await runManager?.handleChainEnd(_coerceToDict3(finalOutput, "output")); } getGraph(config) { const graph = new Graph(); let currentLastNode = null; this.steps.forEach((step, index2) => { const stepGraph = step.getGraph(config); if (index2 !== 0) { stepGraph.trimFirstNode(); } if (index2 !== this.steps.length - 1) { stepGraph.trimLastNode(); } graph.extend(stepGraph); const stepFirstNode = stepGraph.firstNode(); if (!stepFirstNode) { throw new Error(`Runnable ${step} has no first node`); } if (currentLastNode) { graph.addEdge(currentLastNode, stepFirstNode); } currentLastNode = stepGraph.lastNode(); }); return graph; } pipe(coerceable) { if (RunnableSequence.isRunnableSequence(coerceable)) { return new RunnableSequence({ first: this.first, middle: this.middle.concat([ this.last, coerceable.first, ...coerceable.middle ]), last: coerceable.last, name: this.name ?? coerceable.name }); } else { return new RunnableSequence({ first: this.first, middle: [...this.middle, this.last], last: _coerceToRunnable(coerceable), name: this.name }); } } static isRunnableSequence(thing) { return Array.isArray(thing.middle) && Runnable.isRunnable(thing); } static from([first, ...runnables], name2) { return new RunnableSequence({ first: _coerceToRunnable(first), middle: runnables.slice(0, -1).map(_coerceToRunnable), last: _coerceToRunnable(runnables[runnables.length - 1]), name: name2 }); } }; RunnableMap = class extends Runnable { static lc_name() { return "RunnableMap"; } getStepsKeys() { return Object.keys(this.steps); } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "steps", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.steps = {}; for (const [key, value] of Object.entries(fields2.steps)) { this.steps[key] = _coerceToRunnable(value); } } static from(steps) { return new RunnableMap({ steps }); } async invoke(input, options) { const config = ensureConfig(options); const callbackManager_ = await getCallbackManagerForConfig(config); const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input }, void 0, void 0, void 0, void 0, config?.runName); const output = {}; try { await Promise.all(Object.entries(this.steps).map(async ([key, runnable]) => { output[key] = await runnable.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`map:key:${key}`) })); })); } catch (e2) { await runManager?.handleChainError(e2); throw e2; } await runManager?.handleChainEnd(output); return output; } async *_transform(generator, runManager, options) { const steps = { ...this.steps }; const inputCopies = atee(generator, Object.keys(steps).length); const tasks2 = new Map(Object.entries(steps).map(([key, runnable], i2) => { const gen = runnable.transform(inputCopies[i2], patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) })); return [key, gen.next().then((result) => ({ key, gen, result }))]; })); while (tasks2.size) { const { key, result, gen } = await Promise.race(tasks2.values()); tasks2.delete(key); if (!result.done) { yield { [key]: result.value }; tasks2.set(key, gen.next().then((result2) => ({ key, gen, result: result2 }))); } } } transform(generator, options) { return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } async stream(input, options) { async function* generator() { yield input; } const wrappedGenerator = new AsyncGeneratorWithSetup(this.transform(generator(), options)); await wrappedGenerator.setup; return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } }; RunnableLambda = class extends Runnable { static lc_name() { return "RunnableLambda"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.func = fields2.func; } static from(func) { return new RunnableLambda({ func }); } async _invoke(input, config, runManager) { return new Promise((resolve, reject) => { const childConfig = patchConfig(config, { callbacks: runManager?.getChild(), recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 }); void AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => { try { let output = await this.func(input, { ...childConfig, config: childConfig }); if (output && Runnable.isRunnable(output)) { if (config?.recursionLimit === 0) { throw new Error("Recursion limit reached."); } output = await output.invoke(input, { ...childConfig, recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 }); } resolve(output); } catch (e2) { reject(e2); } }); }); } async invoke(input, options) { return this._callWithConfig(this._invoke, input, options); } async *_transform(generator, runManager, config) { let finalChunk; for await (const chunk of generator) { if (finalChunk === void 0) { finalChunk = chunk; } else { try { finalChunk = concat(finalChunk, chunk); } catch (e2) { finalChunk = chunk; } } } const output = await new Promise((resolve, reject) => { void AsyncLocalStorageProviderSingleton.getInstance().run(config, async () => { try { const res = await this.func(finalChunk, { ...config, config }); resolve(res); } catch (e2) { reject(e2); } }); }); if (output && Runnable.isRunnable(output)) { if (config?.recursionLimit === 0) { throw new Error("Recursion limit reached."); } const stream = await output.stream(finalChunk, patchConfig(config, { callbacks: runManager?.getChild(), recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 })); for await (const chunk of stream) { yield chunk; } } else { yield output; } } transform(generator, options) { return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } async stream(input, options) { async function* generator() { yield input; } const wrappedGenerator = new AsyncGeneratorWithSetup(this.transform(generator(), options)); await wrappedGenerator.setup; return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } }; RunnableParallel = class extends RunnableMap { }; RunnableWithFallbacks = class extends Runnable { static lc_name() { return "RunnableWithFallbacks"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "runnable", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "fallbacks", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.runnable = fields2.runnable; this.fallbacks = fields2.fallbacks; } *runnables() { yield this.runnable; for (const fallback of this.fallbacks) { yield fallback; } } async invoke(input, options) { const callbackManager_ = await CallbackManager.configure(options?.callbacks, void 0, options?.tags, void 0, options?.metadata); const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), void 0, void 0, void 0, void 0, options?.runName); let firstError; for (const runnable of this.runnables()) { try { const output = await runnable.invoke(input, patchConfig(options, { callbacks: runManager?.getChild() })); await runManager?.handleChainEnd(_coerceToDict3(output, "output")); return output; } catch (e2) { if (firstError === void 0) { firstError = e2; } } } if (firstError === void 0) { throw new Error("No error stored at end of fallback."); } await runManager?.handleChainError(firstError); throw firstError; } async batch(inputs, options, batchOptions) { if (batchOptions?.returnExceptions) { throw new Error("Not implemented."); } const configList = this._getOptionsList(options ?? {}, inputs.length); const callbackManagers = await Promise.all(configList.map((config) => CallbackManager.configure(config?.callbacks, void 0, config?.tags, void 0, config?.metadata))); const runManagers = await Promise.all(callbackManagers.map((callbackManager, i2) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict3(inputs[i2], "input"), void 0, void 0, void 0, void 0, configList[i2].runName))); let firstError; for (const runnable of this.runnables()) { try { const outputs = await runnable.batch(inputs, runManagers.map((runManager, j2) => patchConfig(configList[j2], { callbacks: runManager?.getChild() })), batchOptions); await Promise.all(runManagers.map((runManager, i2) => runManager?.handleChainEnd(_coerceToDict3(outputs[i2], "output")))); return outputs; } catch (e2) { if (firstError === void 0) { firstError = e2; } } } if (!firstError) { throw new Error("No error stored at end of fallbacks."); } await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); throw firstError; } }; RunnableAssign = class extends Runnable { static lc_name() { return "RunnableAssign"; } constructor(fields2) { if (fields2 instanceof RunnableMap) { fields2 = { mapper: fields2 }; } super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "mapper", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.mapper = fields2.mapper; } async invoke(input, options) { const mapperResult = await this.mapper.invoke(input, options); return { ...input, ...mapperResult }; } async *_transform(generator, runManager, options) { const mapperKeys = this.mapper.getStepsKeys(); const [forPassthrough, forMapper] = atee(generator); const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); const firstMapperChunkPromise = mapperOutput.next(); for await (const chunk of forPassthrough) { if (typeof chunk !== "object" || Array.isArray(chunk)) { throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); } const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); if (Object.keys(filtered).length > 0) { yield filtered; } } yield (await firstMapperChunkPromise).value; for await (const chunk of mapperOutput) { yield chunk; } } transform(generator, options) { return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } async stream(input, options) { async function* generator() { yield input; } const wrappedGenerator = new AsyncGeneratorWithSetup(this.transform(generator(), options)); await wrappedGenerator.setup; return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } }; RunnablePick = class extends Runnable { static lc_name() { return "RunnablePick"; } constructor(fields2) { if (typeof fields2 === "string" || Array.isArray(fields2)) { fields2 = { keys: fields2 }; } super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "keys", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.keys = fields2.keys; } async _pick(input) { if (typeof this.keys === "string") { return input[this.keys]; } else { const picked = this.keys.map((key) => [key, input[key]]).filter((v2) => v2[1] !== void 0); return picked.length === 0 ? void 0 : Object.fromEntries(picked); } } async invoke(input, options) { return this._callWithConfig(this._pick.bind(this), input, options); } async *_transform(generator) { for await (const chunk of generator) { const picked = await this._pick(chunk); if (picked !== void 0) { yield picked; } } } transform(generator, options) { return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } async stream(input, options) { async function* generator() { yield input; } const wrappedGenerator = new AsyncGeneratorWithSetup(this.transform(generator(), options)); await wrappedGenerator.setup; return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompt_values.js var prompt_values_exports = {}; __export(prompt_values_exports, { BasePromptValue: () => BasePromptValue, ChatPromptValue: () => ChatPromptValue, ImagePromptValue: () => ImagePromptValue, StringPromptValue: () => StringPromptValue }); var BasePromptValue, StringPromptValue, ChatPromptValue, ImagePromptValue; var init_prompt_values = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompt_values.js"() { init_serializable(); init_messages(); BasePromptValue = class extends Serializable { }; StringPromptValue = class extends BasePromptValue { static lc_name() { return "StringPromptValue"; } constructor(value) { super({ value }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "prompt_values"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "value", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.value = value; } toString() { return this.value; } toChatMessages() { return [new HumanMessage(this.value)]; } }; ChatPromptValue = class extends BasePromptValue { static lc_name() { return "ChatPromptValue"; } constructor(fields2) { if (Array.isArray(fields2)) { fields2 = { messages: fields2 }; } super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "prompt_values"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "messages", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.messages = fields2.messages; } toString() { return getBufferString(this.messages); } toChatMessages() { return this.messages; } }; ImagePromptValue = class extends BasePromptValue { static lc_name() { return "ImagePromptValue"; } constructor(fields2) { if (!("imageUrl" in fields2)) { fields2 = { imageUrl: fields2 }; } super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "prompt_values"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "imageUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "value", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.imageUrl = fields2.imageUrl; } toString() { return this.imageUrl.url; } toChatMessages() { return [ new HumanMessage({ content: [ { type: "image_url", image_url: { detail: this.imageUrl.detail, url: this.imageUrl.url } } ] }) ]; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/string.js var BaseStringPromptTemplate; var init_string2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/string.js"() { init_prompt_values(); init_base4(); BaseStringPromptTemplate = class extends BasePromptTemplate { async formatPromptValue(values) { const formattedPrompt = await this.format(values); return new StringPromptValue(formattedPrompt); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/template.js var parseFString, interpolateFString, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, renderTemplate, parseTemplate, checkValidTemplate; var init_template = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/template.js"() { parseFString = (template4) => { const chars = template4.split(""); const nodes = []; const nextBracket = (bracket, start) => { for (let i3 = start; i3 < chars.length; i3 += 1) { if (bracket.includes(chars[i3])) { return i3; } } return -1; }; let i2 = 0; while (i2 < chars.length) { if (chars[i2] === "{" && i2 + 1 < chars.length && chars[i2 + 1] === "{") { nodes.push({ type: "literal", text: "{" }); i2 += 2; } else if (chars[i2] === "}" && i2 + 1 < chars.length && chars[i2 + 1] === "}") { nodes.push({ type: "literal", text: "}" }); i2 += 2; } else if (chars[i2] === "{") { const j2 = nextBracket("}", i2); if (j2 < 0) { throw new Error("Unclosed '{' in template."); } nodes.push({ type: "variable", name: chars.slice(i2 + 1, j2).join("") }); i2 = j2 + 1; } else if (chars[i2] === "}") { throw new Error("Single '}' in template."); } else { const next2 = nextBracket("{}", i2); const text = (next2 < 0 ? chars.slice(i2) : chars.slice(i2, next2)).join(""); nodes.push({ type: "literal", text }); i2 = next2 < 0 ? chars.length : next2; } } return nodes; }; interpolateFString = (template4, values) => parseFString(template4).reduce((res, node) => { if (node.type === "variable") { if (node.name in values) { return res + values[node.name]; } throw new Error(`Missing value for input ${node.name}`); } return res + node.text; }, ""); DEFAULT_FORMATTER_MAPPING = { "f-string": interpolateFString }; DEFAULT_PARSER_MAPPING = { "f-string": parseFString }; renderTemplate = (template4, templateFormat, inputValues) => DEFAULT_FORMATTER_MAPPING[templateFormat](template4, inputValues); parseTemplate = (template4, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template4); checkValidTemplate = (template4, templateFormat, inputVariables) => { if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); throw new Error(`Invalid template format. Got \`${templateFormat}\`; should be one of ${validFormats}`); } try { const dummyInputs = inputVariables.reduce((acc, v2) => { acc[v2] = "foo"; return acc; }, {}); if (Array.isArray(template4)) { template4.forEach((message) => { if (message.type === "text") { renderTemplate(message.text, templateFormat, dummyInputs); } else if (message.type === "image_url") { if (typeof message.image_url === "string") { renderTemplate(message.image_url, templateFormat, dummyInputs); } else { const imageUrl = message.image_url.url; renderTemplate(imageUrl, templateFormat, dummyInputs); } } else { throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); } }); } else { renderTemplate(template4, templateFormat, dummyInputs); } } catch (e2) { throw new Error(`Invalid prompt schema: ${e2.message}`); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/prompt.js var prompt_exports = {}; __export(prompt_exports, { PromptTemplate: () => PromptTemplate }); var PromptTemplate; var init_prompt = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/prompt.js"() { init_string2(); init_template(); PromptTemplate = class extends BaseStringPromptTemplate { static lc_name() { return "PromptTemplate"; } constructor(input) { super(input); Object.defineProperty(this, "template", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "templateFormat", { enumerable: true, configurable: true, writable: true, value: "f-string" }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); Object.assign(this, input); if (this.validateTemplate) { let totalInputVariables = this.inputVariables; if (this.partialVariables) { totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); } checkValidTemplate(this.template, this.templateFormat, totalInputVariables); } } _getPromptType() { return "prompt"; } async format(values) { const allValues = await this.mergePartialAndUserVariables(values); return renderTemplate(this.template, this.templateFormat, allValues); } static fromExamples(examples2, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { const template4 = [prefix, ...examples2, suffix].join(exampleSeparator); return new PromptTemplate({ inputVariables, template: template4 }); } static fromTemplate(template4, { templateFormat = "f-string", ...rest } = {}) { const names = new Set(); parseTemplate(template4, templateFormat).forEach((node) => { if (node.type === "variable") { names.add(node.name); } }); return new PromptTemplate({ inputVariables: [...names], templateFormat, template: template4, ...rest }); } async partial(values) { const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); const newPartialVariables = { ...this.partialVariables ?? {}, ...values }; const promptDict = { ...this, inputVariables: newInputVariables, partialVariables: newPartialVariables }; return new PromptTemplate(promptDict); } serialize() { if (this.outputParser !== void 0) { throw new Error("Cannot serialize a prompt template with an output parser"); } return { _type: this._getPromptType(), input_variables: this.inputVariables, template: this.template, template_format: this.templateFormat }; } static async deserialize(data) { if (!data.template) { throw new Error("Prompt template must have a template"); } const res = new PromptTemplate({ inputVariables: data.input_variables, template: data.template, templateFormat: data.template_format }); return res; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/image.js var ImagePromptTemplate; var init_image = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/image.js"() { init_prompt_values(); init_base4(); init_template(); ImagePromptTemplate = class extends BasePromptTemplate { static lc_name() { return "ImagePromptTemplate"; } constructor(input) { super(input); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "prompts", "image"] }); Object.defineProperty(this, "template", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "templateFormat", { enumerable: true, configurable: true, writable: true, value: "f-string" }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); this.template = input.template; this.templateFormat = input.templateFormat ?? this.templateFormat; this.validateTemplate = input.validateTemplate ?? this.validateTemplate; if (this.validateTemplate) { let totalInputVariables = this.inputVariables; if (this.partialVariables) { totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); } checkValidTemplate([ { type: "image_url", image_url: this.template } ], this.templateFormat, totalInputVariables); } } _getPromptType() { return "prompt"; } async partial(values) { const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); const newPartialVariables = { ...this.partialVariables ?? {}, ...values }; const promptDict = { ...this, inputVariables: newInputVariables, partialVariables: newPartialVariables }; return new ImagePromptTemplate(promptDict); } async format(values) { const formatted = {}; for (const [key, value] of Object.entries(this.template)) { if (typeof value === "string") { formatted[key] = value.replace(/{([^{}]*)}/g, (match, group) => { const replacement = values[group]; return typeof replacement === "string" || typeof replacement === "number" ? String(replacement) : match; }); } else { formatted[key] = value; } } const url = values.url || formatted.url; const detail = values.detail || formatted.detail; if (!url) { throw new Error("Must provide either an image URL."); } if (typeof url !== "string") { throw new Error("url must be a string."); } const output = { url }; if (detail) { output.detail = detail; } return output; } async formatPromptValue(values) { const formattedPrompt = await this.format(values); return new ImagePromptValue(formattedPrompt); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/chat.js function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { return typeof baseMessagePromptTemplateLike.formatMessages === "function"; } function _coerceMessagePromptTemplateLike(messagePromptTemplateLike) { if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) { return messagePromptTemplateLike; } const message = coerceMessageLikeToMessage(messagePromptTemplateLike); if (message._getType() === "human") { return HumanMessagePromptTemplate.fromTemplate(message.content); } else if (message._getType() === "ai") { return AIMessagePromptTemplate.fromTemplate(message.content); } else if (message._getType() === "system") { return SystemMessagePromptTemplate.fromTemplate(message.content); } else if (ChatMessage.isInstance(message)) { return ChatMessagePromptTemplate.fromTemplate(message.content, message.role); } else { throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); } } function isMessagesPlaceholder(x2) { return x2.constructor.lc_name() === "MessagesPlaceholder"; } var BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate, _StringImageMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate; var init_chat = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/chat.js"() { init_messages(); init_prompt_values(); init_base3(); init_string2(); init_base4(); init_prompt(); init_image(); init_template(); BaseMessagePromptTemplate = class extends Runnable { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "prompts", "chat"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); } async invoke(input, options) { return this._callWithConfig((input2) => this.formatMessages(input2), input, { ...options, runType: "prompt" }); } }; MessagesPlaceholder = class extends BaseMessagePromptTemplate { static lc_name() { return "MessagesPlaceholder"; } constructor(fields2) { if (typeof fields2 === "string") { fields2 = { variableName: fields2 }; } super(fields2); Object.defineProperty(this, "variableName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "optional", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.variableName = fields2.variableName; this.optional = fields2.optional ?? false; } get inputVariables() { return [this.variableName]; } validateInputOrThrow(input, variableName) { if (this.optional && !input) { return false; } else if (!input) { const error = new Error(`Error: Field "${variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); error.name = "InputFormatError"; throw error; } let isInputBaseMessage = false; if (Array.isArray(input)) { isInputBaseMessage = input.every((message) => isBaseMessage(message)); } else { isInputBaseMessage = isBaseMessage(input); } if (!isInputBaseMessage) { const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); const error = new Error(`Error: Field "${variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: ${readableInput}`); error.name = "InputFormatError"; throw error; } return true; } async formatMessages(values) { this.validateInputOrThrow(values[this.variableName], this.variableName); return values[this.variableName] ?? []; } }; BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { constructor(fields2) { if (!("prompt" in fields2)) { fields2 = { prompt: fields2 }; } super(fields2); Object.defineProperty(this, "prompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.prompt = fields2.prompt; } get inputVariables() { return this.prompt.inputVariables; } async formatMessages(values) { return [await this.format(values)]; } }; BaseChatPromptTemplate = class extends BasePromptTemplate { constructor(input) { super(input); } async format(values) { return (await this.formatPromptValue(values)).toString(); } async formatPromptValue(values) { const resultMessages = await this.formatMessages(values); return new ChatPromptValue(resultMessages); } }; ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { static lc_name() { return "ChatMessagePromptTemplate"; } constructor(fields2, role) { if (!("prompt" in fields2)) { fields2 = { prompt: fields2, role }; } super(fields2); Object.defineProperty(this, "role", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.role = fields2.role; } async format(values) { return new ChatMessage(await this.prompt.format(values), this.role); } static fromTemplate(template4, role) { return new this(PromptTemplate.fromTemplate(template4), role); } }; _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { static _messageClass() { throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); } constructor(fields2, additionalOptions) { if (!("prompt" in fields2)) { fields2 = { prompt: fields2 }; } super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "prompts", "chat"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "inputVariables", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "additionalOptions", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "prompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "messageClass", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "chatMessageClass", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.prompt = fields2.prompt; if (Array.isArray(this.prompt)) { let inputVariables = []; this.prompt.forEach((prompt) => { if ("inputVariables" in prompt) { inputVariables = inputVariables.concat(prompt.inputVariables); } }); this.inputVariables = inputVariables; } else { this.inputVariables = this.prompt.inputVariables; } this.additionalOptions = additionalOptions ?? this.additionalOptions; } createMessage(content) { const constructor = this.constructor; if (constructor._messageClass()) { const MsgClass = constructor._messageClass(); return new MsgClass({ content }); } else if (constructor.chatMessageClass) { const MsgClass = constructor.chatMessageClass(); return new MsgClass({ content, role: this.getRoleFromMessageClass(MsgClass.lc_name()) }); } else { throw new Error("No message class defined"); } } getRoleFromMessageClass(name2) { switch (name2) { case "HumanMessage": return "human"; case "AIMessage": return "ai"; case "SystemMessage": return "system"; case "ChatMessage": return "chat"; default: throw new Error("Invalid message class name"); } } static fromTemplate(template4, additionalOptions) { if (typeof template4 === "string") { return new this(PromptTemplate.fromTemplate(template4)); } const prompt = []; for (const item of template4) { if (typeof item === "string" || typeof item === "object" && "text" in item) { let text = ""; if (typeof item === "string") { text = item; } else if (typeof item.text === "string") { text = item.text ?? ""; } prompt.push(PromptTemplate.fromTemplate(text)); } else if (typeof item === "object" && "image_url" in item) { let imgTemplate = item.image_url ?? ""; let imgTemplateObject; let inputVariables = []; if (typeof imgTemplate === "string") { const parsedTemplate = parseFString(imgTemplate); const variables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); if ((variables?.length ?? 0) > 0) { if (variables.length > 1) { throw new Error(`Only one format variable allowed per image template. Got: ${variables} From: ${imgTemplate}`); } inputVariables = [variables[0]]; } else { inputVariables = []; } imgTemplate = { url: imgTemplate }; imgTemplateObject = new ImagePromptTemplate({ template: imgTemplate, inputVariables }); } else if (typeof imgTemplate === "object") { if ("url" in imgTemplate) { const parsedTemplate = parseFString(imgTemplate.url); inputVariables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); } else { inputVariables = []; } imgTemplateObject = new ImagePromptTemplate({ template: imgTemplate, inputVariables }); } else { throw new Error("Invalid image template"); } prompt.push(imgTemplateObject); } } return new this({ prompt, additionalOptions }); } async format(input) { if (this.prompt instanceof BaseStringPromptTemplate) { const text = await this.prompt.format(input); return this.createMessage(text); } else { const content = []; for (const prompt of this.prompt) { let inputs = {}; if (!("inputVariables" in prompt)) { throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); } for (const item of prompt.inputVariables) { if (!inputs) { inputs = { [item]: input[item] }; } inputs = { ...inputs, [item]: input[item] }; } if (prompt instanceof BaseStringPromptTemplate) { const formatted = await prompt.format(inputs); content.push({ type: "text", text: formatted }); } else if (prompt instanceof ImagePromptTemplate) { const formatted = await prompt.format(inputs); content.push({ type: "image_url", image_url: formatted }); } } return this.createMessage(content); } } async formatMessages(values) { return [await this.format(values)]; } }; HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { static _messageClass() { return HumanMessage; } static lc_name() { return "HumanMessagePromptTemplate"; } }; AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { static _messageClass() { return AIMessage; } static lc_name() { return "AIMessagePromptTemplate"; } }; SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { static _messageClass() { return SystemMessage; } static lc_name() { return "SystemMessagePromptTemplate"; } }; ChatPromptTemplate = class extends BaseChatPromptTemplate { static lc_name() { return "ChatPromptTemplate"; } get lc_aliases() { return { promptMessages: "messages" }; } constructor(input) { super(input); Object.defineProperty(this, "promptMessages", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); Object.assign(this, input); if (this.validateTemplate) { const inputVariablesMessages = new Set(); for (const promptMessage of this.promptMessages) { if (promptMessage instanceof BaseMessage) continue; for (const inputVariable of promptMessage.inputVariables) { inputVariablesMessages.add(inputVariable); } } const totalInputVariables = this.inputVariables; const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); const difference2 = new Set([...inputVariablesInstance].filter((x2) => !inputVariablesMessages.has(x2))); if (difference2.size > 0) { throw new Error(`Input variables \`${[ ...difference2 ]}\` are not used in any of the prompt messages.`); } const otherDifference = new Set([...inputVariablesMessages].filter((x2) => !inputVariablesInstance.has(x2))); if (otherDifference.size > 0) { throw new Error(`Input variables \`${[ ...otherDifference ]}\` are used in prompt messages but not in the prompt template.`); } } } _getPromptType() { return "chat"; } async _parseImagePrompts(message, inputValues) { if (typeof message.content === "string") { return message; } const formattedMessageContent = await Promise.all(message.content.map(async (item) => { if (item.type !== "image_url") { return item; } let imageUrl = ""; if (typeof item.image_url === "string") { imageUrl = item.image_url; } else { imageUrl = item.image_url.url; } const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl); const formattedUrl = await promptTemplatePlaceholder.format(inputValues); if (typeof item.image_url !== "string" && "url" in item.image_url) { item.image_url.url = formattedUrl; } else { item.image_url = formattedUrl; } return item; })); message.content = formattedMessageContent; return message; } async formatMessages(values) { const allValues = await this.mergePartialAndUserVariables(values); let resultMessages = []; for (const promptMessage of this.promptMessages) { if (promptMessage instanceof BaseMessage) { resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); } else { const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) { throw new Error(`Missing value for input variable \`${inputVariable.toString()}\``); } acc[inputVariable] = allValues[inputVariable]; return acc; }, {}); const message = await promptMessage.formatMessages(inputValues); resultMessages = resultMessages.concat(message); } } return resultMessages; } async partial(values) { const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); const newPartialVariables = { ...this.partialVariables ?? {}, ...values }; const promptDict = { ...this, inputVariables: newInputVariables, partialVariables: newPartialVariables }; return new ChatPromptTemplate(promptDict); } static fromTemplate(template4) { const prompt = PromptTemplate.fromTemplate(template4); const humanTemplate = new HumanMessagePromptTemplate({ prompt }); return this.fromMessages([humanTemplate]); } static fromMessages(promptMessages, extra) { const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage)]), []); const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null)); const inputVariables = new Set(); for (const promptMessage of flattenedMessages) { if (promptMessage instanceof BaseMessage) continue; for (const inputVariable of promptMessage.inputVariables) { if (inputVariable in flattenedPartialVariables) { continue; } inputVariables.add(inputVariable); } } return new this({ ...extra, inputVariables: [...inputVariables], promptMessages: flattenedMessages, partialVariables: flattenedPartialVariables }); } static fromPromptMessages(promptMessages) { return this.fromMessages(promptMessages); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/few_shot.js var few_shot_exports = {}; __export(few_shot_exports, { FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, FewShotPromptTemplate: () => FewShotPromptTemplate }); var FewShotPromptTemplate, FewShotChatMessagePromptTemplate; var init_few_shot = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/few_shot.js"() { init_string2(); init_template(); init_prompt(); init_chat(); FewShotPromptTemplate = class extends BaseStringPromptTemplate { constructor(input) { super(input); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "examples", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "exampleSelector", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "examplePrompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "suffix", { enumerable: true, configurable: true, writable: true, value: "" }); Object.defineProperty(this, "exampleSeparator", { enumerable: true, configurable: true, writable: true, value: "\n\n" }); Object.defineProperty(this, "prefix", { enumerable: true, configurable: true, writable: true, value: "" }); Object.defineProperty(this, "templateFormat", { enumerable: true, configurable: true, writable: true, value: "f-string" }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); Object.assign(this, input); if (this.examples !== void 0 && this.exampleSelector !== void 0) { throw new Error("Only one of 'examples' and 'example_selector' should be provided"); } if (this.examples === void 0 && this.exampleSelector === void 0) { throw new Error("One of 'examples' and 'example_selector' should be provided"); } if (this.validateTemplate) { let totalInputVariables = this.inputVariables; if (this.partialVariables) { totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); } checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); } } _getPromptType() { return "few_shot"; } static lc_name() { return "FewShotPromptTemplate"; } async getExamples(inputVariables) { if (this.examples !== void 0) { return this.examples; } if (this.exampleSelector !== void 0) { return this.exampleSelector.selectExamples(inputVariables); } throw new Error("One of 'examples' and 'example_selector' should be provided"); } async partial(values) { const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); const newPartialVariables = { ...this.partialVariables ?? {}, ...values }; const promptDict = { ...this, inputVariables: newInputVariables, partialVariables: newPartialVariables }; return new FewShotPromptTemplate(promptDict); } async format(values) { const allValues = await this.mergePartialAndUserVariables(values); const examples2 = await this.getExamples(allValues); const exampleStrings = await Promise.all(examples2.map((example) => this.examplePrompt.format(example))); const template4 = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); return renderTemplate(template4, this.templateFormat, allValues); } serialize() { if (this.exampleSelector || !this.examples) { throw new Error("Serializing an example selector is not currently supported"); } if (this.outputParser !== void 0) { throw new Error("Serializing an output parser is not currently supported"); } return { _type: this._getPromptType(), input_variables: this.inputVariables, example_prompt: this.examplePrompt.serialize(), example_separator: this.exampleSeparator, suffix: this.suffix, prefix: this.prefix, template_format: this.templateFormat, examples: this.examples }; } static async deserialize(data) { const { example_prompt } = data; if (!example_prompt) { throw new Error("Missing example prompt"); } const examplePrompt = await PromptTemplate.deserialize(example_prompt); let examples2; if (Array.isArray(data.examples)) { examples2 = data.examples; } else { throw new Error("Invalid examples format. Only list or string are supported."); } return new FewShotPromptTemplate({ inputVariables: data.input_variables, examplePrompt, examples: examples2, exampleSeparator: data.example_separator, prefix: data.prefix, suffix: data.suffix, templateFormat: data.template_format }); } }; FewShotChatMessagePromptTemplate = class extends BaseChatPromptTemplate { _getPromptType() { return "few_shot_chat"; } static lc_name() { return "FewShotChatMessagePromptTemplate"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "examples", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "exampleSelector", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "examplePrompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "suffix", { enumerable: true, configurable: true, writable: true, value: "" }); Object.defineProperty(this, "exampleSeparator", { enumerable: true, configurable: true, writable: true, value: "\n\n" }); Object.defineProperty(this, "prefix", { enumerable: true, configurable: true, writable: true, value: "" }); Object.defineProperty(this, "templateFormat", { enumerable: true, configurable: true, writable: true, value: "f-string" }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); this.examples = fields2.examples; this.examplePrompt = fields2.examplePrompt; this.exampleSeparator = fields2.exampleSeparator ?? "\n\n"; this.exampleSelector = fields2.exampleSelector; this.prefix = fields2.prefix ?? ""; this.suffix = fields2.suffix ?? ""; this.templateFormat = fields2.templateFormat ?? "f-string"; this.validateTemplate = fields2.validateTemplate ?? true; if (this.examples !== void 0 && this.exampleSelector !== void 0) { throw new Error("Only one of 'examples' and 'example_selector' should be provided"); } if (this.examples === void 0 && this.exampleSelector === void 0) { throw new Error("One of 'examples' and 'example_selector' should be provided"); } if (this.validateTemplate) { let totalInputVariables = this.inputVariables; if (this.partialVariables) { totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); } checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); } } async getExamples(inputVariables) { if (this.examples !== void 0) { return this.examples; } if (this.exampleSelector !== void 0) { return this.exampleSelector.selectExamples(inputVariables); } throw new Error("One of 'examples' and 'example_selector' should be provided"); } async formatMessages(values) { const allValues = await this.mergePartialAndUserVariables(values); let examples2 = await this.getExamples(allValues); examples2 = examples2.map((example) => { const result = {}; this.examplePrompt.inputVariables.forEach((inputVariable) => { result[inputVariable] = example[inputVariable]; }); return result; }); const messages4 = []; for (const example of examples2) { const exampleMessages = await this.examplePrompt.formatMessages(example); messages4.push(...exampleMessages); } return messages4; } async format(values) { const allValues = await this.mergePartialAndUserVariables(values); const examples2 = await this.getExamples(allValues); const exampleMessages = await Promise.all(examples2.map((example) => this.examplePrompt.formatMessages(example))); const exampleStrings = exampleMessages.flat().map((message) => message.content); const template4 = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); return renderTemplate(template4, this.templateFormat, allValues); } async partial(values) { const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); const newPartialVariables = { ...this.partialVariables ?? {}, ...values }; const promptDict = { ...this, inputVariables: newInputVariables, partialVariables: newPartialVariables }; return new FewShotChatMessagePromptTemplate(promptDict); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/base.js var BasePromptTemplate; var init_base4 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/base.js"() { init_base3(); BasePromptTemplate = class extends Runnable { get lc_attributes() { return { partialVariables: void 0 }; } constructor(input) { super(input); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "prompts", this._getPromptType()] }); Object.defineProperty(this, "inputVariables", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "partialVariables", { enumerable: true, configurable: true, writable: true, value: void 0 }); const { inputVariables } = input; if (inputVariables.includes("stop")) { throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); } Object.assign(this, input); } async mergePartialAndUserVariables(userVariables) { const partialVariables = this.partialVariables ?? {}; const partialValues = {}; for (const [key, value] of Object.entries(partialVariables)) { if (typeof value === "string") { partialValues[key] = value; } else { partialValues[key] = await value(); } } const allKwargs = { ...partialValues, ...userVariables }; return allKwargs; } async invoke(input, options) { return this._callWithConfig((input2) => this.formatPromptValue(input2), input, { ...options, runType: "prompt" }); } serialize() { throw new Error("Use .toJSON() instead"); } static async deserialize(data) { switch (data._type) { case "prompt": { const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); return PromptTemplate2.deserialize(data); } case void 0: { const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); return PromptTemplate2.deserialize({ ...data, _type: "prompt" }); } case "few_shot": { const { FewShotPromptTemplate: FewShotPromptTemplate2 } = await Promise.resolve().then(() => (init_few_shot(), few_shot_exports)); return FewShotPromptTemplate2.deserialize(data); } default: throw new Error(`Invalid prompt type in config: ${data._type}`); } } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/pipeline.js var PipelinePromptTemplate; var init_pipeline2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/pipeline.js"() { init_base4(); init_chat(); PipelinePromptTemplate = class extends BasePromptTemplate { static lc_name() { return "PipelinePromptTemplate"; } constructor(input) { super({ ...input, inputVariables: [] }); Object.defineProperty(this, "pipelinePrompts", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "finalPrompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.pipelinePrompts = input.pipelinePrompts; this.finalPrompt = input.finalPrompt; this.inputVariables = this.computeInputValues(); } computeInputValues() { const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); const inputValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))).flat(); return [...new Set(inputValues)]; } static extractRequiredInputValues(allValues, requiredValueNames) { return requiredValueNames.reduce((requiredValues, valueName) => { requiredValues[valueName] = allValues[valueName]; return requiredValues; }, {}); } async formatPipelinePrompts(values) { const allValues = await this.mergePartialAndUserVariables(values); for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this.pipelinePrompts) { const pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); if (pipelinePrompt instanceof ChatPromptTemplate) { allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); } else { allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); } } return PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); } async formatPromptValue(values) { return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); } async format(values) { return this.finalPrompt.format(await this.formatPipelinePrompts(values)); } async partial(values) { const promptDict = { ...this }; promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); promptDict.partialVariables = { ...this.partialVariables ?? {}, ...values }; return new PipelinePromptTemplate(promptDict); } serialize() { throw new Error("Not implemented."); } _getPromptType() { return "pipeline"; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/serde.js var init_serde = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/serde.js"() { } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/structured.js var StructuredPrompt; var init_structured = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/structured.js"() { init_chat(); StructuredPrompt = class extends ChatPromptTemplate { get lc_aliases() { return { ...super.lc_aliases, schema: "schema_" }; } constructor(input) { super(input); Object.defineProperty(this, "schema", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.schema = input.schema; } pipe(coerceable) { if (typeof coerceable === "object" && "withStructuredOutput" in coerceable && typeof coerceable.withStructuredOutput === "function") { return super.pipe(coerceable.withStructuredOutput(this.schema)); } else { throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`); } } static fromMessagesAndSchema(promptMessages, schema3) { return StructuredPrompt.fromMessages(promptMessages, { schema: schema3 }); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/index.js var prompts_exports = {}; __export(prompts_exports, { AIMessagePromptTemplate: () => AIMessagePromptTemplate, BaseChatPromptTemplate: () => BaseChatPromptTemplate, BaseMessagePromptTemplate: () => BaseMessagePromptTemplate, BaseMessageStringPromptTemplate: () => BaseMessageStringPromptTemplate, BasePromptTemplate: () => BasePromptTemplate, BaseStringPromptTemplate: () => BaseStringPromptTemplate, ChatMessagePromptTemplate: () => ChatMessagePromptTemplate, ChatPromptTemplate: () => ChatPromptTemplate, DEFAULT_FORMATTER_MAPPING: () => DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING: () => DEFAULT_PARSER_MAPPING, FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, FewShotPromptTemplate: () => FewShotPromptTemplate, HumanMessagePromptTemplate: () => HumanMessagePromptTemplate, ImagePromptTemplate: () => ImagePromptTemplate, MessagesPlaceholder: () => MessagesPlaceholder, PipelinePromptTemplate: () => PipelinePromptTemplate, PromptTemplate: () => PromptTemplate, StructuredPrompt: () => StructuredPrompt, SystemMessagePromptTemplate: () => SystemMessagePromptTemplate, checkValidTemplate: () => checkValidTemplate, interpolateFString: () => interpolateFString, parseFString: () => parseFString, parseTemplate: () => parseTemplate, renderTemplate: () => renderTemplate }); var init_prompts = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/prompts/index.js"() { init_base4(); init_chat(); init_few_shot(); init_pipeline2(); init_prompt(); init_serde(); init_string2(); init_template(); init_image(); init_structured(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/prompts.js var init_prompts2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/prompts.js"() { init_prompts(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/base.js var BaseExampleSelector; var init_base5 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/base.js"() { init_serializable(); BaseExampleSelector = class extends Serializable { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "example_selectors", "base"] }); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/conditional.js function isLLM(llm) { return llm._modelType() === "base_llm"; } function isChatModel(llm) { return llm._modelType() === "base_chat_model"; } var BasePromptSelector, ConditionalPromptSelector; var init_conditional = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/conditional.js"() { BasePromptSelector = class { async getPromptAsync(llm, options) { const prompt = this.getPrompt(llm); return prompt.partial(options?.partialVariables ?? {}); } }; ConditionalPromptSelector = class extends BasePromptSelector { constructor(default_prompt, conditionals = []) { super(); Object.defineProperty(this, "defaultPrompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "conditionals", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.defaultPrompt = default_prompt; this.conditionals = conditionals; } getPrompt(llm) { for (const [condition, prompt] of this.conditionals) { if (condition(llm)) { return prompt; } } return this.defaultPrompt; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/length_based.js function getLengthBased(text) { return text.split(/\n| /).length; } var LengthBasedExampleSelector; var init_length_based = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/length_based.js"() { init_base5(); LengthBasedExampleSelector = class extends BaseExampleSelector { constructor(data) { super(data); Object.defineProperty(this, "examples", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "examplePrompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "getTextLength", { enumerable: true, configurable: true, writable: true, value: getLengthBased }); Object.defineProperty(this, "maxLength", { enumerable: true, configurable: true, writable: true, value: 2048 }); Object.defineProperty(this, "exampleTextLengths", { enumerable: true, configurable: true, writable: true, value: [] }); this.examplePrompt = data.examplePrompt; this.maxLength = data.maxLength ?? 2048; this.getTextLength = data.getTextLength ?? getLengthBased; } async addExample(example) { this.examples.push(example); const stringExample = await this.examplePrompt.format(example); this.exampleTextLengths.push(this.getTextLength(stringExample)); } async calculateExampleTextLengths(v2, values) { if (v2.length > 0) { return v2; } const { examples: examples2, examplePrompt } = values; const stringExamples = await Promise.all(examples2.map((eg) => examplePrompt.format(eg))); return stringExamples.map((eg) => this.getTextLength(eg)); } async selectExamples(inputVariables) { const inputs = Object.values(inputVariables).join(" "); let remainingLength = this.maxLength - this.getTextLength(inputs); let i2 = 0; const examples2 = []; while (remainingLength > 0 && i2 < this.examples.length) { const newLength = remainingLength - this.exampleTextLengths[i2]; if (newLength < 0) { break; } else { examples2.push(this.examples[i2]); remainingLength = newLength; } i2 += 1; } return examples2; } static async fromExamples(examples2, args) { const selector = new LengthBasedExampleSelector(args); await Promise.all(examples2.map((eg) => selector.addExample(eg))); return selector; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/documents/document.js var Document; var init_document = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/documents/document.js"() { Document = class { constructor(fields2) { Object.defineProperty(this, "pageContent", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.pageContent = fields2.pageContent ? fields2.pageContent.toString() : this.pageContent; this.metadata = fields2.metadata ?? {}; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js function sortedValues(values) { return Object.keys(values).sort().map((key) => values[key]); } var SemanticSimilarityExampleSelector; var init_semantic_similarity = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js"() { init_document(); init_base5(); SemanticSimilarityExampleSelector = class extends BaseExampleSelector { constructor(data) { super(data); Object.defineProperty(this, "vectorStoreRetriever", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "exampleKeys", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKeys", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.exampleKeys = data.exampleKeys; this.inputKeys = data.inputKeys; if (data.vectorStore !== void 0) { this.vectorStoreRetriever = data.vectorStore.asRetriever({ k: data.k ?? 4, filter: data.filter }); } else if (data.vectorStoreRetriever) { this.vectorStoreRetriever = data.vectorStoreRetriever; } else { throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`); } } async addExample(example) { const inputKeys = this.inputKeys ?? Object.keys(example); const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})).join(" "); await this.vectorStoreRetriever.addDocuments([ new Document({ pageContent: stringExample, metadata: example }) ]); } async selectExamples(inputVariables) { const inputKeys = this.inputKeys ?? Object.keys(inputVariables); const query = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: inputVariables[key] }), {})).join(" "); const exampleDocs = await this.vectorStoreRetriever.invoke(query); const examples2 = exampleDocs.map((doc) => doc.metadata); if (this.exampleKeys) { return examples2.map((example) => this.exampleKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})); } return examples2; } static async fromExamples(examples2, embeddings, vectorStoreCls, options = {}) { const inputKeys = options.inputKeys ?? null; const stringExamples = examples2.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {}) : example).join(" ")); const vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples2, embeddings, options); return new SemanticSimilarityExampleSelector({ vectorStore, k: options.k ?? 4, exampleKeys: options.exampleKeys, inputKeys: options.inputKeys }); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/index.js var example_selectors_exports = {}; __export(example_selectors_exports, { BaseExampleSelector: () => BaseExampleSelector, BasePromptSelector: () => BasePromptSelector, ConditionalPromptSelector: () => ConditionalPromptSelector, LengthBasedExampleSelector: () => LengthBasedExampleSelector, SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, isChatModel: () => isChatModel, isLLM: () => isLLM }); var init_example_selectors = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/example_selectors/index.js"() { init_base5(); init_conditional(); init_length_based(); init_semantic_similarity(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/example_selectors.js var init_example_selectors2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/example_selectors.js"() { init_example_selectors(); } }); // node_modules/.pnpm/lodash.get@4.4.2/node_modules/lodash.get/index.js var require_lodash = __commonJS({ "node_modules/.pnpm/lodash.get@4.4.2/node_modules/lodash.get/index.js"(exports2, module2) { var FUNC_ERROR_TEXT = "Expected a function"; var HASH_UNDEFINED = "__lodash_hash_undefined__"; var INFINITY = 1 / 0; var funcTag = "[object Function]"; var genTag = "[object GeneratorFunction]"; var symbolTag = "[object Symbol]"; var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; var reIsPlainProp = /^\w*$/; var reLeadingDot = /^\./; var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var reEscapeChar = /\\(\\)?/g; var reIsHostCtor = /^\[object .+?Constructor\]$/; var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root3 = freeGlobal || freeSelf || Function("return this")(); function getValue3(object, key) { return object == null ? void 0 : object[key]; } function isHostObject(value) { var result = false; if (value != null && typeof value.toString != "function") { try { result = !!(value + ""); } catch (e2) { } } return result; } var arrayProto = Array.prototype; var funcProto = Function.prototype; var objectProto = Object.prototype; var coreJsData = root3["__core-js_shared__"]; var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : ""; }(); var funcToString = funcProto.toString; var hasOwnProperty2 = objectProto.hasOwnProperty; var objectToString = objectProto.toString; var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); var Symbol2 = root3.Symbol; var splice = arrayProto.splice; var Map2 = getNative(root3, "Map"); var nativeCreate = getNative(Object, "create"); var symbolProto = Symbol2 ? Symbol2.prototype : void 0; var symbolToString = symbolProto ? symbolProto.toString : void 0; function Hash(entries) { var index2 = -1, length = entries ? entries.length : 0; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? void 0 : result; } return hasOwnProperty2.call(data, key) ? data[key] : void 0; } function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== void 0 : hasOwnProperty2.call(data, key); } function hashSet(key, value) { var data = this.__data__; data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; return this; } Hash.prototype.clear = hashClear; Hash.prototype["delete"] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; function ListCache(entries) { var index2 = -1, length = entries ? entries.length : 0; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function listCacheClear() { this.__data__ = []; } function listCacheDelete(key) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { return false; } var lastIndex = data.length - 1; if (index2 == lastIndex) { data.pop(); } else { splice.call(data, index2, 1); } return true; } function listCacheGet(key) { var data = this.__data__, index2 = assocIndexOf(data, key); return index2 < 0 ? void 0 : data[index2][1]; } function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } function listCacheSet(key, value) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { data.push([key, value]); } else { data[index2][1] = value; } return this; } ListCache.prototype.clear = listCacheClear; ListCache.prototype["delete"] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; function MapCache(entries) { var index2 = -1, length = entries ? entries.length : 0; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function mapCacheClear() { this.__data__ = { "hash": new Hash(), "map": new (Map2 || ListCache)(), "string": new Hash() }; } function mapCacheDelete(key) { return getMapData(this, key)["delete"](key); } function mapCacheGet(key) { return getMapData(this, key).get(key); } function mapCacheHas(key) { return getMapData(this, key).has(key); } function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } MapCache.prototype.clear = mapCacheClear; MapCache.prototype["delete"] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } function baseGet(object, path) { path = isKey(path, object) ? [path] : castPath(path); var index2 = 0, length = path.length; while (object != null && index2 < length) { object = object[toKey(path[index2++])]; } return index2 && index2 == length ? object : void 0; } function baseIsNative(value) { if (!isObject10(value) || isMasked(value)) { return false; } var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } function baseToString(value) { if (typeof value == "string") { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ""; } var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result; } function castPath(value) { return isArray(value) ? value : stringToPath(value); } function getMapData(map2, key) { var data = map2.__data__; return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; } function getNative(object, key) { var value = getValue3(object, key); return baseIsNative(value) ? value : void 0; } function isKey(value, object) { if (isArray(value)) { return false; } var type2 = typeof value; if (type2 == "number" || type2 == "symbol" || type2 == "boolean" || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); } function isKeyable(value) { var type2 = typeof value; return type2 == "string" || type2 == "number" || type2 == "symbol" || type2 == "boolean" ? value !== "__proto__" : value === null; } function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } var stringToPath = memoize(function(string) { string = toString3(string); var result = []; if (reLeadingDot.test(string)) { result.push(""); } string.replace(rePropName, function(match, number, quote, string2) { result.push(quote ? string2.replace(reEscapeChar, "$1") : number || match); }); return result; }); function toKey(value) { if (typeof value == "string" || isSymbol(value)) { return value; } var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result; } function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e2) { } try { return func + ""; } catch (e2) { } } return ""; } function memoize(func, resolver) { if (typeof func != "function" || resolver && typeof resolver != "function") { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache2 = memoized.cache; if (cache2.has(key)) { return cache2.get(key); } var result = func.apply(this, args); memoized.cache = cache2.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache)(); return memoized; } memoize.Cache = MapCache; function eq(value, other) { return value === other || value !== value && other !== other; } var isArray = Array.isArray; function isFunction(value) { var tag = isObject10(value) ? objectToString.call(value) : ""; return tag == funcTag || tag == genTag; } function isObject10(value) { var type2 = typeof value; return !!value && (type2 == "object" || type2 == "function"); } function isObjectLike(value) { return !!value && typeof value == "object"; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; } function toString3(value) { return value == null ? "" : baseToString(value); } function get22(object, path, defaultValue) { var result = object == null ? void 0 : baseGet(object, path); return result === void 0 ? defaultValue : result; } module2.exports = get22; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/utils.js var require_utils = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/utils.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.extend = extend4; exports2.indexOf = indexOf; exports2.escapeExpression = escapeExpression; exports2.isEmpty = isEmpty6; exports2.createFrame = createFrame2; exports2.blockParams = blockParams; exports2.appendContextPath = appendContextPath; var escape = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", "`": "`", "=": "=" }; var badChars = /[&<>"'`=]/g; var possible = /[&<>"'`=]/; function escapeChar(chr) { return escape[chr]; } function extend4(obj) { for (var i2 = 1; i2 < arguments.length; i2++) { for (var key in arguments[i2]) { if (Object.prototype.hasOwnProperty.call(arguments[i2], key)) { obj[key] = arguments[i2][key]; } } } return obj; } var toString3 = Object.prototype.toString; exports2.toString = toString3; var isFunction = function isFunction2(value) { return typeof value === "function"; }; if (isFunction(/x/)) { exports2.isFunction = isFunction = function(value) { return typeof value === "function" && toString3.call(value) === "[object Function]"; }; } exports2.isFunction = isFunction; var isArray = Array.isArray || function(value) { return value && typeof value === "object" ? toString3.call(value) === "[object Array]" : false; }; exports2.isArray = isArray; function indexOf(array, value) { for (var i2 = 0, len = array.length; i2 < len; i2++) { if (array[i2] === value) { return i2; } } return -1; } function escapeExpression(string) { if (typeof string !== "string") { if (string && string.toHTML) { return string.toHTML(); } else if (string == null) { return ""; } else if (!string) { return string + ""; } string = "" + string; } if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } function isEmpty6(value) { if (!value && value !== 0) { return true; } else if (isArray(value) && value.length === 0) { return true; } else { return false; } } function createFrame2(object) { var frame = extend4({}, object); frame._parent = object; return frame; } function blockParams(params, ids) { params.path = ids; return params; } function appendContextPath(contextPath, id2) { return (contextPath ? contextPath + "." : "") + id2; } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/exception.js var require_exception = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/exception.js"(exports2, module2) { "use strict"; exports2.__esModule = true; var errorProps = ["description", "fileName", "lineNumber", "endLineNumber", "message", "name", "number", "stack"]; function Exception2(message, node) { var loc = node && node.loc, line = void 0, endLineNumber = void 0, column = void 0, endColumn = void 0; if (loc) { line = loc.start.line; endLineNumber = loc.end.line; column = loc.start.column; endColumn = loc.end.column; message += " - " + line + ":" + column; } var tmp = Error.prototype.constructor.call(this, message); for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } if (Error.captureStackTrace) { Error.captureStackTrace(this, Exception2); } try { if (loc) { this.lineNumber = line; this.endLineNumber = endLineNumber; if (Object.defineProperty) { Object.defineProperty(this, "column", { value: column, enumerable: true }); Object.defineProperty(this, "endColumn", { value: endColumn, enumerable: true }); } else { this.column = column; this.endColumn = endColumn; } } } catch (nop) { } } Exception2.prototype = new Error(); exports2["default"] = Exception2; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/block-helper-missing.js var require_block_helper_missing = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/block-helper-missing.js"(exports2, module2) { "use strict"; exports2.__esModule = true; var _utils = require_utils(); exports2["default"] = function(instance) { instance.registerHelper("blockHelperMissing", function(context, options) { var inverse = options.inverse, fn = options.fn; if (context === true) { return fn(this); } else if (context === false || context == null) { return inverse(this); } else if (_utils.isArray(context)) { if (context.length > 0) { if (options.ids) { options.ids = [options.name]; } return instance.helpers.each(context, options); } else { return inverse(this); } } else { if (options.data && options.ids) { var data = _utils.createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name); options = { data }; } return fn(context, options); } }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/each.js var require_each = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/each.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports2["default"] = function(instance) { instance.registerHelper("each", function(context, options) { if (!options) { throw new _exception2["default"]("Must pass iterator to #each"); } var fn = options.fn, inverse = options.inverse, i2 = 0, ret = "", data = void 0, contextPath = void 0; if (options.data && options.ids) { contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + "."; } if (_utils.isFunction(context)) { context = context.call(this); } if (options.data) { data = _utils.createFrame(options.data); } function execIteration(field, index2, last) { if (data) { data.key = field; data.index = index2; data.first = index2 === 0; data.last = !!last; if (contextPath) { data.contextPath = contextPath + field; } } ret = ret + fn(context[field], { data, blockParams: _utils.blockParams([context[field], field], [contextPath + field, null]) }); } if (context && typeof context === "object") { if (_utils.isArray(context)) { for (var j2 = context.length; i2 < j2; i2++) { if (i2 in context) { execIteration(i2, i2, i2 === context.length - 1); } } } else if (typeof Symbol === "function" && context[Symbol.iterator]) { var newContext = []; var iterator = context[Symbol.iterator](); for (var it = iterator.next(); !it.done; it = iterator.next()) { newContext.push(it.value); } context = newContext; for (var j2 = context.length; i2 < j2; i2++) { execIteration(i2, i2, i2 === context.length - 1); } } else { (function() { var priorKey = void 0; Object.keys(context).forEach(function(key) { if (priorKey !== void 0) { execIteration(priorKey, i2 - 1); } priorKey = key; i2++; }); if (priorKey !== void 0) { execIteration(priorKey, i2 - 1, true); } })(); } } if (i2 === 0) { ret = inverse(this); } return ret; }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js var require_helper_missing = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports2["default"] = function(instance) { instance.registerHelper("helperMissing", function() { if (arguments.length === 1) { return void 0; } else { throw new _exception2["default"]('Missing helper: "' + arguments[arguments.length - 1].name + '"'); } }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/if.js var require_if = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/if.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports2["default"] = function(instance) { instance.registerHelper("if", function(conditional, options) { if (arguments.length != 2) { throw new _exception2["default"]("#if requires exactly one argument"); } if (_utils.isFunction(conditional)) { conditional = conditional.call(this); } if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); instance.registerHelper("unless", function(conditional, options) { if (arguments.length != 2) { throw new _exception2["default"]("#unless requires exactly one argument"); } return instance.helpers["if"].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash }); }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/log.js var require_log = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/log.js"(exports2, module2) { "use strict"; exports2.__esModule = true; exports2["default"] = function(instance) { instance.registerHelper("log", function() { var args = [void 0], options = arguments[arguments.length - 1]; for (var i2 = 0; i2 < arguments.length - 1; i2++) { args.push(arguments[i2]); } var level = 1; if (options.hash.level != null) { level = options.hash.level; } else if (options.data && options.data.level != null) { level = options.data.level; } args[0] = level; instance.log.apply(instance, args); }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/lookup.js var require_lookup = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/lookup.js"(exports2, module2) { "use strict"; exports2.__esModule = true; exports2["default"] = function(instance) { instance.registerHelper("lookup", function(obj, field, options) { if (!obj) { return obj; } return options.lookupProperty(obj, field); }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/with.js var require_with = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers/with.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports2["default"] = function(instance) { instance.registerHelper("with", function(context, options) { if (arguments.length != 2) { throw new _exception2["default"]("#with requires exactly one argument"); } if (_utils.isFunction(context)) { context = context.call(this); } var fn = options.fn; if (!_utils.isEmpty(context)) { var data = options.data; if (options.data && options.ids) { data = _utils.createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]); } return fn(context, { data, blockParams: _utils.blockParams([context], [data && data.contextPath]) }); } else { return options.inverse(this); } }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers.js var require_helpers = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/helpers.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.registerDefaultHelpers = registerDefaultHelpers; exports2.moveHelperToHooks = moveHelperToHooks; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _helpersBlockHelperMissing = require_block_helper_missing(); var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing); var _helpersEach = require_each(); var _helpersEach2 = _interopRequireDefault(_helpersEach); var _helpersHelperMissing = require_helper_missing(); var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing); var _helpersIf = require_if(); var _helpersIf2 = _interopRequireDefault(_helpersIf); var _helpersLog = require_log(); var _helpersLog2 = _interopRequireDefault(_helpersLog); var _helpersLookup = require_lookup(); var _helpersLookup2 = _interopRequireDefault(_helpersLookup); var _helpersWith = require_with(); var _helpersWith2 = _interopRequireDefault(_helpersWith); function registerDefaultHelpers(instance) { _helpersBlockHelperMissing2["default"](instance); _helpersEach2["default"](instance); _helpersHelperMissing2["default"](instance); _helpersIf2["default"](instance); _helpersLog2["default"](instance); _helpersLookup2["default"](instance); _helpersWith2["default"](instance); } function moveHelperToHooks(instance, helperName, keepHelper) { if (instance.helpers[helperName]) { instance.hooks[helperName] = instance.helpers[helperName]; if (!keepHelper) { delete instance.helpers[helperName]; } } } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/decorators/inline.js var require_inline = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/decorators/inline.js"(exports2, module2) { "use strict"; exports2.__esModule = true; var _utils = require_utils(); exports2["default"] = function(instance) { instance.registerDecorator("inline", function(fn, props, container, options) { var ret = fn; if (!props.partials) { props.partials = {}; ret = function(context, options2) { var original = container.partials; container.partials = _utils.extend({}, original, props.partials); var ret2 = fn(context, options2); container.partials = original; return ret2; }; } props.partials[options.args[0]] = options.fn; return ret; }); }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/decorators.js var require_decorators = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/decorators.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.registerDefaultDecorators = registerDefaultDecorators; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _decoratorsInline = require_inline(); var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline); function registerDefaultDecorators(instance) { _decoratorsInline2["default"](instance); } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/logger.js var require_logger = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/logger.js"(exports2, module2) { "use strict"; exports2.__esModule = true; var _utils = require_utils(); var logger41 = { methodMap: ["debug", "info", "warn", "error"], level: "info", lookupLevel: function lookupLevel(level) { if (typeof level === "string") { var levelMap = _utils.indexOf(logger41.methodMap, level.toLowerCase()); if (levelMap >= 0) { level = levelMap; } else { level = parseInt(level, 10); } } return level; }, log: function log(level) { level = logger41.lookupLevel(level); if (typeof console !== "undefined" && logger41.lookupLevel(logger41.level) <= level) { var method = logger41.methodMap[level]; if (!console[method]) { method = "log"; } for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { message[_key - 1] = arguments[_key]; } console[method].apply(console, message); } } }; exports2["default"] = logger41; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/internal/create-new-lookup-object.js var require_create_new_lookup_object = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/internal/create-new-lookup-object.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.createNewLookupObject = createNewLookupObject; var _utils = require_utils(); function createNewLookupObject() { for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) { sources[_key] = arguments[_key]; } return _utils.extend.apply(void 0, [Object.create(null)].concat(sources)); } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/internal/proto-access.js var require_proto_access = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/internal/proto-access.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.createProtoAccessControl = createProtoAccessControl; exports2.resultIsAllowed = resultIsAllowed; exports2.resetLoggedProperties = resetLoggedProperties; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _createNewLookupObject = require_create_new_lookup_object(); var _logger = require_logger(); var _logger2 = _interopRequireDefault(_logger); var loggedProperties = Object.create(null); function createProtoAccessControl(runtimeOptions) { var defaultMethodWhiteList = Object.create(null); defaultMethodWhiteList["constructor"] = false; defaultMethodWhiteList["__defineGetter__"] = false; defaultMethodWhiteList["__defineSetter__"] = false; defaultMethodWhiteList["__lookupGetter__"] = false; var defaultPropertyWhiteList = Object.create(null); defaultPropertyWhiteList["__proto__"] = false; return { properties: { whitelist: _createNewLookupObject.createNewLookupObject(defaultPropertyWhiteList, runtimeOptions.allowedProtoProperties), defaultValue: runtimeOptions.allowProtoPropertiesByDefault }, methods: { whitelist: _createNewLookupObject.createNewLookupObject(defaultMethodWhiteList, runtimeOptions.allowedProtoMethods), defaultValue: runtimeOptions.allowProtoMethodsByDefault } }; } function resultIsAllowed(result, protoAccessControl, propertyName) { if (typeof result === "function") { return checkWhiteList(protoAccessControl.methods, propertyName); } else { return checkWhiteList(protoAccessControl.properties, propertyName); } } function checkWhiteList(protoAccessControlForType, propertyName) { if (protoAccessControlForType.whitelist[propertyName] !== void 0) { return protoAccessControlForType.whitelist[propertyName] === true; } if (protoAccessControlForType.defaultValue !== void 0) { return protoAccessControlForType.defaultValue; } logUnexpecedPropertyAccessOnce(propertyName); return false; } function logUnexpecedPropertyAccessOnce(propertyName) { if (loggedProperties[propertyName] !== true) { loggedProperties[propertyName] = true; _logger2["default"].log("error", 'Handlebars: Access has been denied to resolve the property "' + propertyName + '" because it is not an "own property" of its parent.\nYou can add a runtime option to disable the check or this warning:\nSee https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details'); } } function resetLoggedProperties() { Object.keys(loggedProperties).forEach(function(propertyName) { delete loggedProperties[propertyName]; }); } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/base.js var require_base = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/base.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.HandlebarsEnvironment = HandlebarsEnvironment; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _helpers = require_helpers(); var _decorators = require_decorators(); var _logger = require_logger(); var _logger2 = _interopRequireDefault(_logger); var _internalProtoAccess = require_proto_access(); var VERSION4 = "4.7.8"; exports2.VERSION = VERSION4; var COMPILER_REVISION = 8; exports2.COMPILER_REVISION = COMPILER_REVISION; var LAST_COMPATIBLE_COMPILER_REVISION = 7; exports2.LAST_COMPATIBLE_COMPILER_REVISION = LAST_COMPATIBLE_COMPILER_REVISION; var REVISION_CHANGES = { 1: "<= 1.0.rc.2", 2: "== 1.0.0-rc.3", 3: "== 1.0.0-rc.4", 4: "== 1.x.x", 5: "== 2.0.0-alpha.x", 6: ">= 2.0.0-beta.1", 7: ">= 4.0.0 <4.3.0", 8: ">= 4.3.0" }; exports2.REVISION_CHANGES = REVISION_CHANGES; var objectType2 = "[object Object]"; function HandlebarsEnvironment(helpers2, partials, decorators) { this.helpers = helpers2 || {}; this.partials = partials || {}; this.decorators = decorators || {}; _helpers.registerDefaultHelpers(this); _decorators.registerDefaultDecorators(this); } HandlebarsEnvironment.prototype = { constructor: HandlebarsEnvironment, logger: _logger2["default"], log: _logger2["default"].log, registerHelper: function registerHelper(name2, fn) { if (_utils.toString.call(name2) === objectType2) { if (fn) { throw new _exception2["default"]("Arg not supported with multiple helpers"); } _utils.extend(this.helpers, name2); } else { this.helpers[name2] = fn; } }, unregisterHelper: function unregisterHelper(name2) { delete this.helpers[name2]; }, registerPartial: function registerPartial(name2, partial) { if (_utils.toString.call(name2) === objectType2) { _utils.extend(this.partials, name2); } else { if (typeof partial === "undefined") { throw new _exception2["default"]('Attempting to register a partial called "' + name2 + '" as undefined'); } this.partials[name2] = partial; } }, unregisterPartial: function unregisterPartial(name2) { delete this.partials[name2]; }, registerDecorator: function registerDecorator(name2, fn) { if (_utils.toString.call(name2) === objectType2) { if (fn) { throw new _exception2["default"]("Arg not supported with multiple decorators"); } _utils.extend(this.decorators, name2); } else { this.decorators[name2] = fn; } }, unregisterDecorator: function unregisterDecorator(name2) { delete this.decorators[name2]; }, resetLoggedPropertyAccesses: function resetLoggedPropertyAccesses() { _internalProtoAccess.resetLoggedProperties(); } }; var log = _logger2["default"].log; exports2.log = log; exports2.createFrame = _utils.createFrame; exports2.logger = _logger2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/safe-string.js var require_safe_string = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/safe-string.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function SafeString(string) { this.string = string; } SafeString.prototype.toString = SafeString.prototype.toHTML = function() { return "" + this.string; }; exports2["default"] = SafeString; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/internal/wrapHelper.js var require_wrapHelper = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/internal/wrapHelper.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.wrapHelper = wrapHelper; function wrapHelper(helper, transformOptionsFn) { if (typeof helper !== "function") { return helper; } var wrapper = function wrapper2() { var options = arguments[arguments.length - 1]; arguments[arguments.length - 1] = transformOptionsFn(options); return helper.apply(this, arguments); }; return wrapper; } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/runtime.js var require_runtime = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/runtime.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.checkRevision = checkRevision; exports2.template = template4; exports2.wrapProgram = wrapProgram; exports2.resolvePartial = resolvePartial; exports2.invokePartial = invokePartial; exports2.noop = noop; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _utils = require_utils(); var Utils = _interopRequireWildcard(_utils); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _base = require_base(); var _helpers = require_helpers(); var _internalWrapHelper = require_wrapHelper(); var _internalProtoAccess = require_proto_access(); function checkRevision(compilerInfo) { var compilerRevision = compilerInfo && compilerInfo[0] || 1, currentRevision = _base.COMPILER_REVISION; if (compilerRevision >= _base.LAST_COMPATIBLE_COMPILER_REVISION && compilerRevision <= _base.COMPILER_REVISION) { return; } if (compilerRevision < _base.LAST_COMPATIBLE_COMPILER_REVISION) { var runtimeVersions = _base.REVISION_CHANGES[currentRevision], compilerVersions = _base.REVISION_CHANGES[compilerRevision]; throw new _exception2["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (" + runtimeVersions + ") or downgrade your runtime to an older version (" + compilerVersions + ")."); } else { throw new _exception2["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version (" + compilerInfo[1] + ")."); } } function template4(templateSpec, env) { if (!env) { throw new _exception2["default"]("No environment passed to template"); } if (!templateSpec || !templateSpec.main) { throw new _exception2["default"]("Unknown template object: " + typeof templateSpec); } templateSpec.main.decorator = templateSpec.main_d; env.VM.checkRevision(templateSpec.compiler); var templateWasPrecompiledWithCompilerV7 = templateSpec.compiler && templateSpec.compiler[0] === 7; function invokePartialWrapper(partial, context, options) { if (options.hash) { context = Utils.extend({}, context, options.hash); if (options.ids) { options.ids[0] = true; } } partial = env.VM.resolvePartial.call(this, partial, context, options); var extendedOptions = Utils.extend({}, options, { hooks: this.hooks, protoAccessControl: this.protoAccessControl }); var result = env.VM.invokePartial.call(this, partial, context, extendedOptions); if (result == null && env.compile) { options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env); result = options.partials[options.name](context, extendedOptions); } if (result != null) { if (options.indent) { var lines = result.split("\n"); for (var i2 = 0, l2 = lines.length; i2 < l2; i2++) { if (!lines[i2] && i2 + 1 === l2) { break; } lines[i2] = options.indent + lines[i2]; } result = lines.join("\n"); } return result; } else { throw new _exception2["default"]("The partial " + options.name + " could not be compiled when running in runtime-only mode"); } } var container = { strict: function strict(obj, name2, loc) { if (!obj || !(name2 in obj)) { throw new _exception2["default"]('"' + name2 + '" not defined in ' + obj, { loc }); } return container.lookupProperty(obj, name2); }, lookupProperty: function lookupProperty(parent, propertyName) { var result = parent[propertyName]; if (result == null) { return result; } if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { return result; } if (_internalProtoAccess.resultIsAllowed(result, container.protoAccessControl, propertyName)) { return result; } return void 0; }, lookup: function lookup(depths, name2) { var len = depths.length; for (var i2 = 0; i2 < len; i2++) { var result = depths[i2] && container.lookupProperty(depths[i2], name2); if (result != null) { return depths[i2][name2]; } } }, lambda: function lambda(current, context) { return typeof current === "function" ? current.call(context) : current; }, escapeExpression: Utils.escapeExpression, invokePartial: invokePartialWrapper, fn: function fn(i2) { var ret2 = templateSpec[i2]; ret2.decorator = templateSpec[i2 + "_d"]; return ret2; }, programs: [], program: function program(i2, data, declaredBlockParams, blockParams, depths) { var programWrapper = this.programs[i2], fn = this.fn(i2); if (data || depths || blockParams || declaredBlockParams) { programWrapper = wrapProgram(this, i2, fn, data, declaredBlockParams, blockParams, depths); } else if (!programWrapper) { programWrapper = this.programs[i2] = wrapProgram(this, i2, fn); } return programWrapper; }, data: function data(value, depth) { while (value && depth--) { value = value._parent; } return value; }, mergeIfNeeded: function mergeIfNeeded(param, common2) { var obj = param || common2; if (param && common2 && param !== common2) { obj = Utils.extend({}, common2, param); } return obj; }, nullContext: Object.seal({}), noop: env.VM.noop, compilerInfo: templateSpec.compiler }; function ret(context) { var options = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1]; var data = options.data; ret._setup(options); if (!options.partial && templateSpec.useData) { data = initData(context, data); } var depths = void 0, blockParams = templateSpec.useBlockParams ? [] : void 0; if (templateSpec.useDepths) { if (options.depths) { depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths; } else { depths = [context]; } } function main2(context2) { return "" + templateSpec.main(container, context2, container.helpers, container.partials, data, blockParams, depths); } main2 = executeDecorators(templateSpec.main, main2, container, options.depths || [], data, blockParams); return main2(context, options); } ret.isTop = true; ret._setup = function(options) { if (!options.partial) { var mergedHelpers = Utils.extend({}, env.helpers, options.helpers); wrapHelpersToPassLookupProperty(mergedHelpers, container); container.helpers = mergedHelpers; if (templateSpec.usePartial) { container.partials = container.mergeIfNeeded(options.partials, env.partials); } if (templateSpec.usePartial || templateSpec.useDecorators) { container.decorators = Utils.extend({}, env.decorators, options.decorators); } container.hooks = {}; container.protoAccessControl = _internalProtoAccess.createProtoAccessControl(options); var keepHelperInHelpers = options.allowCallsToHelperMissing || templateWasPrecompiledWithCompilerV7; _helpers.moveHelperToHooks(container, "helperMissing", keepHelperInHelpers); _helpers.moveHelperToHooks(container, "blockHelperMissing", keepHelperInHelpers); } else { container.protoAccessControl = options.protoAccessControl; container.helpers = options.helpers; container.partials = options.partials; container.decorators = options.decorators; container.hooks = options.hooks; } }; ret._child = function(i2, data, blockParams, depths) { if (templateSpec.useBlockParams && !blockParams) { throw new _exception2["default"]("must pass block params"); } if (templateSpec.useDepths && !depths) { throw new _exception2["default"]("must pass parent depths"); } return wrapProgram(container, i2, templateSpec[i2], data, 0, blockParams, depths); }; return ret; } function wrapProgram(container, i2, fn, data, declaredBlockParams, blockParams, depths) { function prog(context) { var options = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1]; var currentDepths = depths; if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) { currentDepths = [context].concat(depths); } return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths); } prog = executeDecorators(fn, prog, container, depths, data, blockParams); prog.program = i2; prog.depth = depths ? depths.length : 0; prog.blockParams = declaredBlockParams || 0; return prog; } function resolvePartial(partial, context, options) { if (!partial) { if (options.name === "@partial-block") { partial = options.data["partial-block"]; } else { partial = options.partials[options.name]; } } else if (!partial.call && !options.name) { options.name = partial; partial = options.partials[partial]; } return partial; } function invokePartial(partial, context, options) { var currentPartialBlock = options.data && options.data["partial-block"]; options.partial = true; if (options.ids) { options.data.contextPath = options.ids[0] || options.data.contextPath; } var partialBlock = void 0; if (options.fn && options.fn !== noop) { (function() { options.data = _base.createFrame(options.data); var fn = options.fn; partialBlock = options.data["partial-block"] = function partialBlockWrapper(context2) { var options2 = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1]; options2.data = _base.createFrame(options2.data); options2.data["partial-block"] = currentPartialBlock; return fn(context2, options2); }; if (fn.partials) { options.partials = Utils.extend({}, options.partials, fn.partials); } })(); } if (partial === void 0 && partialBlock) { partial = partialBlock; } if (partial === void 0) { throw new _exception2["default"]("The partial " + options.name + " could not be found"); } else if (partial instanceof Function) { return partial(context, options); } } function noop() { return ""; } function initData(context, data) { if (!data || !("root" in data)) { data = data ? _base.createFrame(data) : {}; data.root = context; } return data; } function executeDecorators(fn, prog, container, depths, data, blockParams) { if (fn.decorator) { var props = {}; prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths); Utils.extend(prog, props); } return prog; } function wrapHelpersToPassLookupProperty(mergedHelpers, container) { Object.keys(mergedHelpers).forEach(function(helperName) { var helper = mergedHelpers[helperName]; mergedHelpers[helperName] = passLookupPropertyOption(helper, container); }); } function passLookupPropertyOption(helper, container) { var lookupProperty = container.lookupProperty; return _internalWrapHelper.wrapHelper(helper, function(options) { return Utils.extend({ lookupProperty }, options); }); } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/no-conflict.js var require_no_conflict = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/no-conflict.js"(exports2, module2) { "use strict"; exports2.__esModule = true; exports2["default"] = function(Handlebars3) { (function() { if (typeof globalThis === "object") return; Object.prototype.__defineGetter__("__magic__", function() { return this; }); __magic__.globalThis = __magic__; delete Object.prototype.__magic__; })(); var $Handlebars = globalThis.Handlebars; Handlebars3.noConflict = function() { if (globalThis.Handlebars === Handlebars3) { globalThis.Handlebars = $Handlebars; } return Handlebars3; }; }; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars.runtime.js var require_handlebars_runtime = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars.runtime.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _handlebarsBase = require_base(); var base = _interopRequireWildcard(_handlebarsBase); var _handlebarsSafeString = require_safe_string(); var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString); var _handlebarsException = require_exception(); var _handlebarsException2 = _interopRequireDefault(_handlebarsException); var _handlebarsUtils = require_utils(); var Utils = _interopRequireWildcard(_handlebarsUtils); var _handlebarsRuntime = require_runtime(); var runtime = _interopRequireWildcard(_handlebarsRuntime); var _handlebarsNoConflict = require_no_conflict(); var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); function create() { var hb = new base.HandlebarsEnvironment(); Utils.extend(hb, base); hb.SafeString = _handlebarsSafeString2["default"]; hb.Exception = _handlebarsException2["default"]; hb.Utils = Utils; hb.escapeExpression = Utils.escapeExpression; hb.VM = runtime; hb.template = function(spec) { return runtime.template(spec, hb); }; return hb; } var inst = create(); inst.create = create; _handlebarsNoConflict2["default"](inst); inst["default"] = inst; exports2["default"] = inst; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/ast.js var require_ast = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/ast.js"(exports2, module2) { "use strict"; exports2.__esModule = true; var AST = { helpers: { helperExpression: function helperExpression(node) { return node.type === "SubExpression" || (node.type === "MustacheStatement" || node.type === "BlockStatement") && !!(node.params && node.params.length || node.hash); }, scopedId: function scopedId(path) { return /^\.|this\b/.test(path.original); }, simpleId: function simpleId(path) { return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth; } } }; exports2["default"] = AST; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js var require_parser = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js"(exports2, module2) { "use strict"; exports2.__esModule = true; var handlebars3 = function() { var parser = { trace: function trace() { }, yy: {}, symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 }, terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" }, productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 0], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]], performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) { var $0 = $$.length - 1; switch (yystate) { case 1: return $$[$0 - 1]; break; case 2: this.$ = yy.prepareProgram($$[$0]); break; case 3: this.$ = $$[$0]; break; case 4: this.$ = $$[$0]; break; case 5: this.$ = $$[$0]; break; case 6: this.$ = $$[$0]; break; case 7: this.$ = $$[$0]; break; case 8: this.$ = $$[$0]; break; case 9: this.$ = { type: "CommentStatement", value: yy.stripComment($$[$0]), strip: yy.stripFlags($$[$0], $$[$0]), loc: yy.locInfo(this._$) }; break; case 10: this.$ = { type: "ContentStatement", original: $$[$0], value: $$[$0], loc: yy.locInfo(this._$) }; break; case 11: this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); break; case 12: this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] }; break; case 13: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$); break; case 14: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$); break; case 15: this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 16: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 17: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 18: this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] }; break; case 19: var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$), program = yy.prepareProgram([inverse], $$[$0 - 1].loc); program.chained = true; this.$ = { strip: $$[$0 - 2].strip, program, chain: true }; break; case 20: this.$ = $$[$0]; break; case 21: this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) }; break; case 22: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 23: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 24: this.$ = { type: "PartialStatement", name: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], indent: "", strip: yy.stripFlags($$[$0 - 4], $$[$0]), loc: yy.locInfo(this._$) }; break; case 25: this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); break; case 26: this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) }; break; case 27: this.$ = $$[$0]; break; case 28: this.$ = $$[$0]; break; case 29: this.$ = { type: "SubExpression", path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], loc: yy.locInfo(this._$) }; break; case 30: this.$ = { type: "Hash", pairs: $$[$0], loc: yy.locInfo(this._$) }; break; case 31: this.$ = { type: "HashPair", key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) }; break; case 32: this.$ = yy.id($$[$0 - 1]); break; case 33: this.$ = $$[$0]; break; case 34: this.$ = $$[$0]; break; case 35: this.$ = { type: "StringLiteral", value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) }; break; case 36: this.$ = { type: "NumberLiteral", value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) }; break; case 37: this.$ = { type: "BooleanLiteral", value: $$[$0] === "true", original: $$[$0] === "true", loc: yy.locInfo(this._$) }; break; case 38: this.$ = { type: "UndefinedLiteral", original: void 0, value: void 0, loc: yy.locInfo(this._$) }; break; case 39: this.$ = { type: "NullLiteral", original: null, value: null, loc: yy.locInfo(this._$) }; break; case 40: this.$ = $$[$0]; break; case 41: this.$ = $$[$0]; break; case 42: this.$ = yy.preparePath(true, $$[$0], this._$); break; case 43: this.$ = yy.preparePath(false, $$[$0], this._$); break; case 44: $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] }); this.$ = $$[$0 - 2]; break; case 45: this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }]; break; case 46: this.$ = []; break; case 47: $$[$0 - 1].push($$[$0]); break; case 48: this.$ = []; break; case 49: $$[$0 - 1].push($$[$0]); break; case 50: this.$ = []; break; case 51: $$[$0 - 1].push($$[$0]); break; case 58: this.$ = []; break; case 59: $$[$0 - 1].push($$[$0]); break; case 64: this.$ = []; break; case 65: $$[$0 - 1].push($$[$0]); break; case 70: this.$ = []; break; case 71: $$[$0 - 1].push($$[$0]); break; case 78: this.$ = []; break; case 79: $$[$0 - 1].push($$[$0]); break; case 82: this.$ = []; break; case 83: $$[$0 - 1].push($$[$0]); break; case 86: this.$ = []; break; case 87: $$[$0 - 1].push($$[$0]); break; case 90: this.$ = []; break; case 91: $$[$0 - 1].push($$[$0]); break; case 94: this.$ = []; break; case 95: $$[$0 - 1].push($$[$0]); break; case 98: this.$ = [$$[$0]]; break; case 99: $$[$0 - 1].push($$[$0]); break; case 100: this.$ = [$$[$0]]; break; case 101: $$[$0 - 1].push($$[$0]); break; } }, table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 15: [2, 48], 17: 39, 18: [2, 48] }, { 20: 41, 56: 40, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 44, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 45, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 41, 56: 48, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 49, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 50] }, { 72: [1, 35], 86: 51 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 52, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 53, 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 54, 47: [2, 54] }, { 28: 59, 43: 60, 44: [1, 58], 47: [2, 56] }, { 13: 62, 15: [1, 20], 18: [1, 61] }, { 33: [2, 86], 57: 63, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 64, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 65, 47: [1, 66] }, { 30: 67, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 68, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 69, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 70, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 74, 33: [2, 80], 50: 71, 63: 72, 64: 75, 65: [1, 43], 69: 73, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 79] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 50] }, { 20: 74, 53: 80, 54: [2, 84], 63: 81, 64: 75, 65: [1, 43], 69: 82, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 83, 47: [1, 66] }, { 47: [2, 55] }, { 4: 84, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 85, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 86, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 87, 47: [1, 66] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 74, 33: [2, 88], 58: 88, 63: 89, 64: 75, 65: [1, 43], 69: 90, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 91, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 92, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 31: 93, 33: [2, 60], 63: 94, 64: 75, 65: [1, 43], 69: 95, 70: 76, 71: 77, 72: [1, 78], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 66], 36: 96, 63: 97, 64: 75, 65: [1, 43], 69: 98, 70: 76, 71: 77, 72: [1, 78], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 22: 99, 23: [2, 52], 63: 100, 64: 75, 65: [1, 43], 69: 101, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 92], 62: 102, 63: 103, 64: 75, 65: [1, 43], 69: 104, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 105] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 106, 72: [1, 107], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 108], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 109] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 111, 46: 110, 47: [2, 76] }, { 33: [2, 70], 40: 112, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 113] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 74, 63: 115, 64: 75, 65: [1, 43], 67: 114, 68: [2, 96], 69: 116, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 117] }, { 32: 118, 33: [2, 62], 74: 119, 75: [1, 120] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 121, 74: 122, 75: [1, 120] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 123] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 124] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 108] }, { 20: 74, 63: 125, 64: 75, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 74, 33: [2, 72], 41: 126, 63: 127, 64: 75, 65: [1, 43], 69: 128, 70: 76, 71: 77, 72: [1, 78], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 129] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 130] }, { 33: [2, 63] }, { 72: [1, 132], 76: 131 }, { 33: [1, 133] }, { 33: [2, 69] }, { 15: [2, 12], 18: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 134, 74: 135, 75: [1, 120] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 137], 77: [1, 136] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 138] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }], defaultActions: { 4: [2, 1], 54: [2, 55], 56: [2, 20], 60: [2, 57], 73: [2, 81], 82: [2, 85], 86: [2, 18], 90: [2, 89], 101: [2, 53], 104: [2, 93], 110: [2, 19], 111: [2, 77], 116: [2, 97], 119: [2, 63], 122: [2, 69], 135: [2, 75], 136: [2, 32] }, parseError: function parseError(str3, hash) { throw new Error(str3); }, parse: function parse3(input) { var self2 = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; this.yy.parser = this; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); var ranges = this.lexer.options && this.lexer.options.ranges; if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n2) { stack.length = stack.length - 2 * n2; vstack.length = vstack.length - n2; lstack.length = lstack.length - n2; } function lex() { var token; token = self2.lexer.lex() || 1; if (typeof token !== "number") { token = self2.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a2, r3, yyval = {}, p2, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol === null || typeof symbol == "undefined") { symbol = lex(); } action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { var errStr = ""; if (!recovering) { expected = []; for (p2 in table[state]) if (this.terminals_[p2] && p2 > 2) { expected.push("'" + this.terminals_[p2] + "'"); } if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected }); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column }; if (ranges) { yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; } r3 = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r3 !== "undefined") { return r3; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; var lexer = function() { var lexer2 = { EOF: 1, parseError: function parseError(str3, hash) { if (this.yy.parser) { this.yy.parser.parseError(str3, hash); } else { throw new Error(str3); } }, setInput: function setInput(input) { this._input = input; this._more = this._less = this.done = false; this.yylineno = this.yyleng = 0; this.yytext = this.matched = this.match = ""; this.conditionStack = ["INITIAL"]; this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 }; if (this.options.ranges) this.yylloc.range = [0, 0]; this.offset = 0; return this; }, input: function input() { var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; var lines = ch.match(/(?:\r\n?|\n).*/g); if (lines) { this.yylineno++; this.yylloc.last_line++; } else { this.yylloc.last_column++; } if (this.options.ranges) this.yylloc.range[1]++; this._input = this._input.slice(1); return ch; }, unput: function unput(ch) { var len = ch.length; var lines = ch.split(/(?:\r\n?|\n)/g); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length - len - 1); this.offset -= len; var oldLines = this.match.split(/(?:\r\n?|\n)/g); this.match = this.match.substr(0, this.match.length - 1); this.matched = this.matched.substr(0, this.matched.length - 1); if (lines.length - 1) this.yylineno -= lines.length - 1; var r3 = this.yylloc.range; this.yylloc = { first_line: this.yylloc.first_line, last_line: this.yylineno + 1, first_column: this.yylloc.first_column, last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len }; if (this.options.ranges) { this.yylloc.range = [r3[0], r3[0] + this.yyleng - len]; } return this; }, more: function more() { this._more = true; return this; }, less: function less(n2) { this.unput(this.match.slice(n2)); }, pastInput: function pastInput() { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, ""); }, upcomingInput: function upcomingInput() { var next2 = this.match; if (next2.length < 20) { next2 += this._input.substr(0, 20 - next2.length); } return (next2.substr(0, 20) + (next2.length > 20 ? "..." : "")).replace(/\n/g, ""); }, showPosition: function showPosition() { var pre = this.pastInput(); var c2 = new Array(pre.length + 1).join("-"); return pre + this.upcomingInput() + "\n" + c2 + "^"; }, next: function next2() { if (this.done) { return this.EOF; } if (!this._input) this.done = true; var token, match, tempMatch, index2, col, lines; if (!this._more) { this.yytext = ""; this.match = ""; } var rules2 = this._currentRules(); for (var i2 = 0; i2 < rules2.length; i2++) { tempMatch = this._input.match(this.rules[rules2[i2]]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index2 = i2; if (!this.options.flex) break; } } if (match) { lines = match[0].match(/(?:\r\n?|\n).*/g); if (lines) this.yylineno += lines.length; this.yylloc = { first_line: this.yylloc.last_line, last_line: this.yylineno + 1, first_column: this.yylloc.last_column, last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length }; this.yytext += match[0]; this.match += match[0]; this.matches = match; this.yyleng = this.yytext.length; if (this.options.ranges) { this.yylloc.range = [this.offset, this.offset += this.yyleng]; } this._more = false; this._input = this._input.slice(match[0].length); this.matched += match[0]; token = this.performAction.call(this, this.yy, this, rules2[index2], this.conditionStack[this.conditionStack.length - 1]); if (this.done && this._input) this.done = false; if (token) return token; else return; } if (this._input === "") { return this.EOF; } else { return this.parseError("Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition(), { text: "", token: null, line: this.yylineno }); } }, lex: function lex() { var r3 = this.next(); if (typeof r3 !== "undefined") { return r3; } else { return this.lex(); } }, begin: function begin(condition) { this.conditionStack.push(condition); }, popState: function popState() { return this.conditionStack.pop(); }, _currentRules: function _currentRules() { return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; }, topState: function topState() { return this.conditionStack[this.conditionStack.length - 2]; }, pushState: function begin(condition) { this.begin(condition); } }; lexer2.options = {}; lexer2.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) { function strip2(start, end) { return yy_.yytext = yy_.yytext.substring(start, yy_.yyleng - end + start); } var YYSTATE = YY_START; switch ($avoiding_name_collisions) { case 0: if (yy_.yytext.slice(-2) === "\\\\") { strip2(0, 1); this.begin("mu"); } else if (yy_.yytext.slice(-1) === "\\") { strip2(0, 1); this.begin("emu"); } else { this.begin("mu"); } if (yy_.yytext) return 15; break; case 1: return 15; break; case 2: this.popState(); return 15; break; case 3: this.begin("raw"); return 15; break; case 4: this.popState(); if (this.conditionStack[this.conditionStack.length - 1] === "raw") { return 15; } else { strip2(5, 9); return "END_RAW_BLOCK"; } break; case 5: return 15; break; case 6: this.popState(); return 14; break; case 7: return 65; break; case 8: return 68; break; case 9: return 19; break; case 10: this.popState(); this.begin("raw"); return 23; break; case 11: return 55; break; case 12: return 60; break; case 13: return 29; break; case 14: return 47; break; case 15: this.popState(); return 44; break; case 16: this.popState(); return 44; break; case 17: return 34; break; case 18: return 39; break; case 19: return 51; break; case 20: return 48; break; case 21: this.unput(yy_.yytext); this.popState(); this.begin("com"); break; case 22: this.popState(); return 14; break; case 23: return 48; break; case 24: return 73; break; case 25: return 72; break; case 26: return 72; break; case 27: return 87; break; case 28: break; case 29: this.popState(); return 54; break; case 30: this.popState(); return 33; break; case 31: yy_.yytext = strip2(1, 2).replace(/\\"/g, '"'); return 80; break; case 32: yy_.yytext = strip2(1, 2).replace(/\\'/g, "'"); return 80; break; case 33: return 85; break; case 34: return 82; break; case 35: return 82; break; case 36: return 83; break; case 37: return 84; break; case 38: return 81; break; case 39: return 75; break; case 40: return 77; break; case 41: return 72; break; case 42: yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, "$1"); return 72; break; case 43: return "INVALID"; break; case 44: return 5; break; } }; lexer2.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]+?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/]; lexer2.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } }; return lexer2; }(); parser.lexer = lexer; function Parser2() { this.yy = {}; } Parser2.prototype = parser; parser.Parser = Parser2; return new Parser2(); }(); exports2["default"] = handlebars3; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js var require_visitor = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); function Visitor() { this.parents = []; } Visitor.prototype = { constructor: Visitor, mutating: false, acceptKey: function acceptKey(node, name2) { var value = this.accept(node[name2]); if (this.mutating) { if (value && !Visitor.prototype[value.type]) { throw new _exception2["default"]('Unexpected node type "' + value.type + '" found when accepting ' + name2 + " on " + node.type); } node[name2] = value; } }, acceptRequired: function acceptRequired(node, name2) { this.acceptKey(node, name2); if (!node[name2]) { throw new _exception2["default"](node.type + " requires " + name2); } }, acceptArray: function acceptArray(array) { for (var i2 = 0, l2 = array.length; i2 < l2; i2++) { this.acceptKey(array, i2); if (!array[i2]) { array.splice(i2, 1); i2--; l2--; } } }, accept: function accept(object) { if (!object) { return; } if (!this[object.type]) { throw new _exception2["default"]("Unknown type: " + object.type, object); } if (this.current) { this.parents.unshift(this.current); } this.current = object; var ret = this[object.type](object); this.current = this.parents.shift(); if (!this.mutating || ret) { return ret; } else if (ret !== false) { return object; } }, Program: function Program(program) { this.acceptArray(program.body); }, MustacheStatement: visitSubExpression, Decorator: visitSubExpression, BlockStatement: visitBlock, DecoratorBlock: visitBlock, PartialStatement: visitPartial, PartialBlockStatement: function PartialBlockStatement(partial) { visitPartial.call(this, partial); this.acceptKey(partial, "program"); }, ContentStatement: function ContentStatement() { }, CommentStatement: function CommentStatement() { }, SubExpression: visitSubExpression, PathExpression: function PathExpression() { }, StringLiteral: function StringLiteral() { }, NumberLiteral: function NumberLiteral() { }, BooleanLiteral: function BooleanLiteral() { }, UndefinedLiteral: function UndefinedLiteral() { }, NullLiteral: function NullLiteral() { }, Hash: function Hash(hash) { this.acceptArray(hash.pairs); }, HashPair: function HashPair(pair) { this.acceptRequired(pair, "value"); } }; function visitSubExpression(mustache) { this.acceptRequired(mustache, "path"); this.acceptArray(mustache.params); this.acceptKey(mustache, "hash"); } function visitBlock(block) { visitSubExpression.call(this, block); this.acceptKey(block, "program"); this.acceptKey(block, "inverse"); } function visitPartial(partial) { this.acceptRequired(partial, "name"); this.acceptArray(partial.params); this.acceptKey(partial, "hash"); } exports2["default"] = Visitor; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/whitespace-control.js var require_whitespace_control = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/whitespace-control.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _visitor = require_visitor(); var _visitor2 = _interopRequireDefault(_visitor); function WhitespaceControl() { var options = arguments.length <= 0 || arguments[0] === void 0 ? {} : arguments[0]; this.options = options; } WhitespaceControl.prototype = new _visitor2["default"](); WhitespaceControl.prototype.Program = function(program) { var doStandalone = !this.options.ignoreStandalone; var isRoot = !this.isRootSeen; this.isRootSeen = true; var body = program.body; for (var i2 = 0, l2 = body.length; i2 < l2; i2++) { var current = body[i2], strip2 = this.accept(current); if (!strip2) { continue; } var _isPrevWhitespace = isPrevWhitespace(body, i2, isRoot), _isNextWhitespace = isNextWhitespace(body, i2, isRoot), openStandalone = strip2.openStandalone && _isPrevWhitespace, closeStandalone = strip2.closeStandalone && _isNextWhitespace, inlineStandalone = strip2.inlineStandalone && _isPrevWhitespace && _isNextWhitespace; if (strip2.close) { omitRight(body, i2, true); } if (strip2.open) { omitLeft(body, i2, true); } if (doStandalone && inlineStandalone) { omitRight(body, i2); if (omitLeft(body, i2)) { if (current.type === "PartialStatement") { current.indent = /([ \t]+$)/.exec(body[i2 - 1].original)[1]; } } } if (doStandalone && openStandalone) { omitRight((current.program || current.inverse).body); omitLeft(body, i2); } if (doStandalone && closeStandalone) { omitRight(body, i2); omitLeft((current.inverse || current.program).body); } } return program; }; WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function(block) { this.accept(block.program); this.accept(block.inverse); var program = block.program || block.inverse, inverse = block.program && block.inverse, firstInverse = inverse, lastInverse = inverse; if (inverse && inverse.chained) { firstInverse = inverse.body[0].program; while (lastInverse.chained) { lastInverse = lastInverse.body[lastInverse.body.length - 1].program; } } var strip2 = { open: block.openStrip.open, close: block.closeStrip.close, openStandalone: isNextWhitespace(program.body), closeStandalone: isPrevWhitespace((firstInverse || program).body) }; if (block.openStrip.close) { omitRight(program.body, null, true); } if (inverse) { var inverseStrip = block.inverseStrip; if (inverseStrip.open) { omitLeft(program.body, null, true); } if (inverseStrip.close) { omitRight(firstInverse.body, null, true); } if (block.closeStrip.open) { omitLeft(lastInverse.body, null, true); } if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) { omitLeft(program.body); omitRight(firstInverse.body); } } else if (block.closeStrip.open) { omitLeft(program.body, null, true); } return strip2; }; WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function(mustache) { return mustache.strip; }; WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function(node) { var strip2 = node.strip || {}; return { inlineStandalone: true, open: strip2.open, close: strip2.close }; }; function isPrevWhitespace(body, i2, isRoot) { if (i2 === void 0) { i2 = body.length; } var prev = body[i2 - 1], sibling = body[i2 - 2]; if (!prev) { return isRoot; } if (prev.type === "ContentStatement") { return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original); } } function isNextWhitespace(body, i2, isRoot) { if (i2 === void 0) { i2 = -1; } var next2 = body[i2 + 1], sibling = body[i2 + 2]; if (!next2) { return isRoot; } if (next2.type === "ContentStatement") { return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next2.original); } } function omitRight(body, i2, multiple) { var current = body[i2 == null ? 0 : i2 + 1]; if (!current || current.type !== "ContentStatement" || !multiple && current.rightStripped) { return; } var original = current.value; current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, ""); current.rightStripped = current.value !== original; } function omitLeft(body, i2, multiple) { var current = body[i2 == null ? body.length - 1 : i2 - 1]; if (!current || current.type !== "ContentStatement" || !multiple && current.leftStripped) { return; } var original = current.value; current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, ""); current.leftStripped = current.value !== original; return current.leftStripped; } exports2["default"] = WhitespaceControl; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/helpers.js var require_helpers2 = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/helpers.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.SourceLocation = SourceLocation; exports2.id = id2; exports2.stripFlags = stripFlags; exports2.stripComment = stripComment; exports2.preparePath = preparePath; exports2.prepareMustache = prepareMustache; exports2.prepareRawBlock = prepareRawBlock; exports2.prepareBlock = prepareBlock; exports2.prepareProgram = prepareProgram; exports2.preparePartialBlock = preparePartialBlock; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); function validateClose(open, close) { close = close.path ? close.path.original : close; if (open.path.original !== close) { var errorNode = { loc: open.path.loc }; throw new _exception2["default"](open.path.original + " doesn't match " + close, errorNode); } } function SourceLocation(source, locInfo) { this.source = source; this.start = { line: locInfo.first_line, column: locInfo.first_column }; this.end = { line: locInfo.last_line, column: locInfo.last_column }; } function id2(token) { if (/^\[.*\]$/.test(token)) { return token.substring(1, token.length - 1); } else { return token; } } function stripFlags(open, close) { return { open: open.charAt(2) === "~", close: close.charAt(close.length - 3) === "~" }; } function stripComment(comment) { return comment.replace(/^\{\{~?!-?-?/, "").replace(/-?-?~?\}\}$/, ""); } function preparePath(data, parts, loc) { loc = this.locInfo(loc); var original = data ? "@" : "", dig = [], depth = 0; for (var i2 = 0, l2 = parts.length; i2 < l2; i2++) { var part = parts[i2].part, isLiteral = parts[i2].original !== part; original += (parts[i2].separator || "") + part; if (!isLiteral && (part === ".." || part === "." || part === "this")) { if (dig.length > 0) { throw new _exception2["default"]("Invalid path: " + original, { loc }); } else if (part === "..") { depth++; } } else { dig.push(part); } } return { type: "PathExpression", data, depth, parts: dig, original, loc }; } function prepareMustache(path, params, hash, open, strip2, locInfo) { var escapeFlag = open.charAt(3) || open.charAt(2), escaped = escapeFlag !== "{" && escapeFlag !== "&"; var decorator = /\*/.test(open); return { type: decorator ? "Decorator" : "MustacheStatement", path, params, hash, escaped, strip: strip2, loc: this.locInfo(locInfo) }; } function prepareRawBlock(openRawBlock, contents, close, locInfo) { validateClose(openRawBlock, close); locInfo = this.locInfo(locInfo); var program = { type: "Program", body: contents, strip: {}, loc: locInfo }; return { type: "BlockStatement", path: openRawBlock.path, params: openRawBlock.params, hash: openRawBlock.hash, program, openStrip: {}, inverseStrip: {}, closeStrip: {}, loc: locInfo }; } function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) { if (close && close.path) { validateClose(openBlock, close); } var decorator = /\*/.test(openBlock.open); program.blockParams = openBlock.blockParams; var inverse = void 0, inverseStrip = void 0; if (inverseAndProgram) { if (decorator) { throw new _exception2["default"]("Unexpected inverse block on decorator", inverseAndProgram); } if (inverseAndProgram.chain) { inverseAndProgram.program.body[0].closeStrip = close.strip; } inverseStrip = inverseAndProgram.strip; inverse = inverseAndProgram.program; } if (inverted) { inverted = inverse; inverse = program; program = inverted; } return { type: decorator ? "DecoratorBlock" : "BlockStatement", path: openBlock.path, params: openBlock.params, hash: openBlock.hash, program, inverse, openStrip: openBlock.strip, inverseStrip, closeStrip: close && close.strip, loc: this.locInfo(locInfo) }; } function prepareProgram(statements, loc) { if (!loc && statements.length) { var firstLoc = statements[0].loc, lastLoc = statements[statements.length - 1].loc; if (firstLoc && lastLoc) { loc = { source: firstLoc.source, start: { line: firstLoc.start.line, column: firstLoc.start.column }, end: { line: lastLoc.end.line, column: lastLoc.end.column } }; } } return { type: "Program", body: statements, strip: {}, loc }; } function preparePartialBlock(open, program, close, locInfo) { validateClose(open, close); return { type: "PartialBlockStatement", name: open.path, params: open.params, hash: open.hash, program, openStrip: open.strip, closeStrip: close && close.strip, loc: this.locInfo(locInfo) }; } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js var require_base2 = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.parseWithoutProcessing = parseWithoutProcessing; exports2.parse = parse3; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _parser = require_parser(); var _parser2 = _interopRequireDefault(_parser); var _whitespaceControl = require_whitespace_control(); var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl); var _helpers = require_helpers2(); var Helpers = _interopRequireWildcard(_helpers); var _utils = require_utils(); exports2.parser = _parser2["default"]; var yy = {}; _utils.extend(yy, Helpers); function parseWithoutProcessing(input, options) { if (input.type === "Program") { return input; } _parser2["default"].yy = yy; yy.locInfo = function(locInfo) { return new yy.SourceLocation(options && options.srcName, locInfo); }; var ast = _parser2["default"].parse(input); return ast; } function parse3(input, options) { var ast = parseWithoutProcessing(input, options); var strip2 = new _whitespaceControl2["default"](options); return strip2.accept(ast); } } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js var require_compiler = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js"(exports2) { "use strict"; exports2.__esModule = true; exports2.Compiler = Compiler; exports2.precompile = precompile; exports2.compile = compile; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _utils = require_utils(); var _ast = require_ast(); var _ast2 = _interopRequireDefault(_ast); var slice = [].slice; function Compiler() { } Compiler.prototype = { compiler: Compiler, equals: function equals(other) { var len = this.opcodes.length; if (other.opcodes.length !== len) { return false; } for (var i2 = 0; i2 < len; i2++) { var opcode = this.opcodes[i2], otherOpcode = other.opcodes[i2]; if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) { return false; } } len = this.children.length; for (var i2 = 0; i2 < len; i2++) { if (!this.children[i2].equals(other.children[i2])) { return false; } } return true; }, guid: 0, compile: function compile2(program, options) { this.sourceNode = []; this.opcodes = []; this.children = []; this.options = options; this.stringParams = options.stringParams; this.trackIds = options.trackIds; options.blockParams = options.blockParams || []; options.knownHelpers = _utils.extend(Object.create(null), { helperMissing: true, blockHelperMissing: true, each: true, "if": true, unless: true, "with": true, log: true, lookup: true }, options.knownHelpers); return this.accept(program); }, compileProgram: function compileProgram(program) { var childCompiler = new this.compiler(), result = childCompiler.compile(program, this.options), guid = this.guid++; this.usePartial = this.usePartial || result.usePartial; this.children[guid] = result; this.useDepths = this.useDepths || result.useDepths; return guid; }, accept: function accept(node) { if (!this[node.type]) { throw new _exception2["default"]("Unknown type: " + node.type, node); } this.sourceNode.unshift(node); var ret = this[node.type](node); this.sourceNode.shift(); return ret; }, Program: function Program(program) { this.options.blockParams.unshift(program.blockParams); var body = program.body, bodyLength = body.length; for (var i2 = 0; i2 < bodyLength; i2++) { this.accept(body[i2]); } this.options.blockParams.shift(); this.isSimple = bodyLength === 1; this.blockParams = program.blockParams ? program.blockParams.length : 0; return this; }, BlockStatement: function BlockStatement(block) { transformLiteralToPath(block); var program = block.program, inverse = block.inverse; program = program && this.compileProgram(program); inverse = inverse && this.compileProgram(inverse); var type2 = this.classifySexpr(block); if (type2 === "helper") { this.helperSexpr(block, program, inverse); } else if (type2 === "simple") { this.simpleSexpr(block); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); this.opcode("emptyHash"); this.opcode("blockValue", block.path.original); } else { this.ambiguousSexpr(block, program, inverse); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); this.opcode("emptyHash"); this.opcode("ambiguousBlockValue"); } this.opcode("append"); }, DecoratorBlock: function DecoratorBlock(decorator) { var program = decorator.program && this.compileProgram(decorator.program); var params = this.setupFullMustacheParams(decorator, program, void 0), path = decorator.path; this.useDecorators = true; this.opcode("registerDecorator", params.length, path.original); }, PartialStatement: function PartialStatement(partial) { this.usePartial = true; var program = partial.program; if (program) { program = this.compileProgram(partial.program); } var params = partial.params; if (params.length > 1) { throw new _exception2["default"]("Unsupported number of partial arguments: " + params.length, partial); } else if (!params.length) { if (this.options.explicitPartialContext) { this.opcode("pushLiteral", "undefined"); } else { params.push({ type: "PathExpression", parts: [], depth: 0 }); } } var partialName = partial.name.original, isDynamic = partial.name.type === "SubExpression"; if (isDynamic) { this.accept(partial.name); } this.setupFullMustacheParams(partial, program, void 0, true); var indent = partial.indent || ""; if (this.options.preventIndent && indent) { this.opcode("appendContent", indent); indent = ""; } this.opcode("invokePartial", isDynamic, partialName, indent); this.opcode("append"); }, PartialBlockStatement: function PartialBlockStatement(partialBlock) { this.PartialStatement(partialBlock); }, MustacheStatement: function MustacheStatement(mustache) { this.SubExpression(mustache); if (mustache.escaped && !this.options.noEscape) { this.opcode("appendEscaped"); } else { this.opcode("append"); } }, Decorator: function Decorator(decorator) { this.DecoratorBlock(decorator); }, ContentStatement: function ContentStatement(content) { if (content.value) { this.opcode("appendContent", content.value); } }, CommentStatement: function CommentStatement() { }, SubExpression: function SubExpression(sexpr) { transformLiteralToPath(sexpr); var type2 = this.classifySexpr(sexpr); if (type2 === "simple") { this.simpleSexpr(sexpr); } else if (type2 === "helper") { this.helperSexpr(sexpr); } else { this.ambiguousSexpr(sexpr); } }, ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) { var path = sexpr.path, name2 = path.parts[0], isBlock2 = program != null || inverse != null; this.opcode("getContext", path.depth); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); path.strict = true; this.accept(path); this.opcode("invokeAmbiguous", name2, isBlock2); }, simpleSexpr: function simpleSexpr(sexpr) { var path = sexpr.path; path.strict = true; this.accept(path); this.opcode("resolvePossibleLambda"); }, helperSexpr: function helperSexpr(sexpr, program, inverse) { var params = this.setupFullMustacheParams(sexpr, program, inverse), path = sexpr.path, name2 = path.parts[0]; if (this.options.knownHelpers[name2]) { this.opcode("invokeKnownHelper", params.length, name2); } else if (this.options.knownHelpersOnly) { throw new _exception2["default"]("You specified knownHelpersOnly, but used the unknown helper " + name2, sexpr); } else { path.strict = true; path.falsy = true; this.accept(path); this.opcode("invokeHelper", params.length, path.original, _ast2["default"].helpers.simpleId(path)); } }, PathExpression: function PathExpression(path) { this.addDepth(path.depth); this.opcode("getContext", path.depth); var name2 = path.parts[0], scoped = _ast2["default"].helpers.scopedId(path), blockParamId = !path.depth && !scoped && this.blockParamIndex(name2); if (blockParamId) { this.opcode("lookupBlockParam", blockParamId, path.parts); } else if (!name2) { this.opcode("pushContext"); } else if (path.data) { this.options.data = true; this.opcode("lookupData", path.depth, path.parts, path.strict); } else { this.opcode("lookupOnContext", path.parts, path.falsy, path.strict, scoped); } }, StringLiteral: function StringLiteral(string) { this.opcode("pushString", string.value); }, NumberLiteral: function NumberLiteral(number) { this.opcode("pushLiteral", number.value); }, BooleanLiteral: function BooleanLiteral(bool2) { this.opcode("pushLiteral", bool2.value); }, UndefinedLiteral: function UndefinedLiteral() { this.opcode("pushLiteral", "undefined"); }, NullLiteral: function NullLiteral() { this.opcode("pushLiteral", "null"); }, Hash: function Hash(hash) { var pairs2 = hash.pairs, i2 = 0, l2 = pairs2.length; this.opcode("pushHash"); for (; i2 < l2; i2++) { this.pushParam(pairs2[i2].value); } while (i2--) { this.opcode("assignToHash", pairs2[i2].key); } this.opcode("popHash"); }, opcode: function opcode(name2) { this.opcodes.push({ opcode: name2, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc }); }, addDepth: function addDepth(depth) { if (!depth) { return; } this.useDepths = true; }, classifySexpr: function classifySexpr(sexpr) { var isSimple = _ast2["default"].helpers.simpleId(sexpr.path); var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]); var isHelper = !isBlockParam && _ast2["default"].helpers.helperExpression(sexpr); var isEligible = !isBlockParam && (isHelper || isSimple); if (isEligible && !isHelper) { var _name = sexpr.path.parts[0], options = this.options; if (options.knownHelpers[_name]) { isHelper = true; } else if (options.knownHelpersOnly) { isEligible = false; } } if (isHelper) { return "helper"; } else if (isEligible) { return "ambiguous"; } else { return "simple"; } }, pushParams: function pushParams(params) { for (var i2 = 0, l2 = params.length; i2 < l2; i2++) { this.pushParam(params[i2]); } }, pushParam: function pushParam(val) { var value = val.value != null ? val.value : val.original || ""; if (this.stringParams) { if (value.replace) { value = value.replace(/^(\.?\.\/)*/g, "").replace(/\//g, "."); } if (val.depth) { this.addDepth(val.depth); } this.opcode("getContext", val.depth || 0); this.opcode("pushStringParam", value, val.type); if (val.type === "SubExpression") { this.accept(val); } } else { if (this.trackIds) { var blockParamIndex = void 0; if (val.parts && !_ast2["default"].helpers.scopedId(val) && !val.depth) { blockParamIndex = this.blockParamIndex(val.parts[0]); } if (blockParamIndex) { var blockParamChild = val.parts.slice(1).join("."); this.opcode("pushId", "BlockParam", blockParamIndex, blockParamChild); } else { value = val.original || value; if (value.replace) { value = value.replace(/^this(?:\.|$)/, "").replace(/^\.\//, "").replace(/^\.$/, ""); } this.opcode("pushId", val.type, value); } } this.accept(val); } }, setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) { var params = sexpr.params; this.pushParams(params); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); if (sexpr.hash) { this.accept(sexpr.hash); } else { this.opcode("emptyHash", omitEmpty); } return params; }, blockParamIndex: function blockParamIndex(name2) { for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) { var blockParams = this.options.blockParams[depth], param = blockParams && _utils.indexOf(blockParams, name2); if (blockParams && param >= 0) { return [depth, param]; } } } }; function precompile(input, options, env) { if (input == null || typeof input !== "string" && input.type !== "Program") { throw new _exception2["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed " + input); } options = options || {}; if (!("data" in options)) { options.data = true; } if (options.compat) { options.useDepths = true; } var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options); return new env.JavaScriptCompiler().compile(environment, options); } function compile(input, options, env) { if (options === void 0) options = {}; if (input == null || typeof input !== "string" && input.type !== "Program") { throw new _exception2["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed " + input); } options = _utils.extend({}, options); if (!("data" in options)) { options.data = true; } if (options.compat) { options.useDepths = true; } var compiled = void 0; function compileInput() { var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options), templateSpec = new env.JavaScriptCompiler().compile(environment, options, void 0, true); return env.template(templateSpec); } function ret(context, execOptions) { if (!compiled) { compiled = compileInput(); } return compiled.call(this, context, execOptions); } ret._setup = function(setupOptions) { if (!compiled) { compiled = compileInput(); } return compiled._setup(setupOptions); }; ret._child = function(i2, data, blockParams, depths) { if (!compiled) { compiled = compileInput(); } return compiled._child(i2, data, blockParams, depths); }; return ret; } function argEquals(a2, b2) { if (a2 === b2) { return true; } if (_utils.isArray(a2) && _utils.isArray(b2) && a2.length === b2.length) { for (var i2 = 0; i2 < a2.length; i2++) { if (!argEquals(a2[i2], b2[i2])) { return false; } } return true; } } function transformLiteralToPath(sexpr) { if (!sexpr.path.parts) { var literal = sexpr.path; sexpr.path = { type: "PathExpression", data: false, depth: 0, parts: [literal.original + ""], original: literal.original + "", loc: literal.loc }; } } } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64.js var require_base64 = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64.js"(exports2) { var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); exports2.encode = function(number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; exports2.decode = function(charCode) { var bigA = 65; var bigZ = 90; var littleA = 97; var littleZ = 122; var zero = 48; var nine = 57; var plus = 43; var slash = 47; var littleOffset = 26; var numberOffset = 52; if (bigA <= charCode && charCode <= bigZ) { return charCode - bigA; } if (littleA <= charCode && charCode <= littleZ) { return charCode - littleA + littleOffset; } if (zero <= charCode && charCode <= nine) { return charCode - zero + numberOffset; } if (charCode == plus) { return 62; } if (charCode == slash) { return 63; } return -1; }; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64-vlq.js var require_base64_vlq = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64-vlq.js"(exports2) { var base642 = require_base64(); var VLQ_BASE_SHIFT = 5; var VLQ_BASE = 1 << VLQ_BASE_SHIFT; var VLQ_BASE_MASK = VLQ_BASE - 1; var VLQ_CONTINUATION_BIT = VLQ_BASE; function toVLQSigned(aValue) { return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; } function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } exports2.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { digit |= VLQ_CONTINUATION_BIT; } encoded += base642.encode(digit); } while (vlq > 0); return encoded; }; exports2.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base642.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/util.js var require_util = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/util.js"(exports2) { function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports2.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports2.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ""; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ":"; } url += "//"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@"; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port; } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports2.urlGenerate = urlGenerate; function normalize2(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports2.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i2 = parts.length - 1; i2 >= 0; i2--) { part = parts[i2]; if (part === ".") { parts.splice(i2, 1); } else if (part === "..") { up++; } else if (up > 0) { if (part === "") { parts.splice(i2 + 1, up); up = 0; } else { parts.splice(i2, 2); up--; } } } path = parts.join("/"); if (path === "") { path = isAbsolute ? "/" : "."; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports2.normalize = normalize2; function join2(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || "/"; } if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === "/" ? aPath : normalize2(aRoot.replace(/\/+$/, "") + "/" + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports2.join = join2; exports2.isAbsolute = function(aPath) { return aPath.charAt(0) === "/" || urlRegexp.test(aPath); }; function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ""); var level = 0; while (aPath.indexOf(aRoot + "/") !== 0) { var index2 = aRoot.lastIndexOf("/"); if (index2 < 0) { return aPath; } aRoot = aRoot.slice(0, index2); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports2.relative = relative; var supportsNullProto = function() { var obj = Object.create(null); return !("__proto__" in obj); }(); function identity(s2) { return s2; } function toSetString(aStr) { if (isProtoString(aStr)) { return "$" + aStr; } return aStr; } exports2.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports2.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s2) { if (!s2) { return false; } var length = s2.length; if (length < 9) { return false; } if (s2.charCodeAt(length - 1) !== 95 || s2.charCodeAt(length - 2) !== 95 || s2.charCodeAt(length - 3) !== 111 || s2.charCodeAt(length - 4) !== 116 || s2.charCodeAt(length - 5) !== 111 || s2.charCodeAt(length - 6) !== 114 || s2.charCodeAt(length - 7) !== 112 || s2.charCodeAt(length - 8) !== 95 || s2.charCodeAt(length - 9) !== 95) { return false; } for (var i2 = length - 10; i2 >= 0; i2--) { if (s2.charCodeAt(i2) !== 36) { return false; } } return true; } function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports2.compareByOriginalPositions = compareByOriginalPositions; function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports2.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; } if (aStr2 === null) { return -1; } if (aStr1 > aStr2) { return 1; } return -1; } function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports2.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; function parseSourceMapInput(str3) { return JSON.parse(str3.replace(/^\)]}'[^\n]*\n/, "")); } exports2.parseSourceMapInput = parseSourceMapInput; function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ""; if (sourceRoot) { if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { sourceRoot += "/"; } sourceURL = sourceRoot + sourceURL; } if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { var index2 = parsed.path.lastIndexOf("/"); if (index2 >= 0) { parsed.path = parsed.path.substring(0, index2 + 1); } } sourceURL = join2(urlGenerate(parsed), sourceURL); } return normalize2(sourceURL); } exports2.computeSourceURL = computeSourceURL; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/array-set.js var require_array_set = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/array-set.js"(exports2) { var util3 = require_util(); var has6 = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; function ArraySet() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set13 = new ArraySet(); for (var i2 = 0, len = aArray.length; i2 < len; i2++) { set13.add(aArray[i2], aAllowDuplicates); } return set13; }; ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util3.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has6.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util3.toSetString(aStr); return has6.call(this._set, sStr); } }; ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util3.toSetString(aStr); if (has6.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error("No element indexed by " + aIdx); }; ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports2.ArraySet = ArraySet; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/mapping-list.js var require_mapping_list = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/mapping-list.js"(exports2) { var util3 = require_util(); function generatedPositionAfter(mappingA, mappingB) { var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } function MappingList() { this._array = []; this._sorted = true; this._last = { generatedLine: -1, generatedColumn: 0 }; } MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util3.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports2.MappingList = MappingList; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-generator.js var require_source_map_generator = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-generator.js"(exports2) { var base64VLQ = require_base64_vlq(); var util3 = require_util(); var ArraySet = require_array_set().ArraySet; var MappingList = require_mapping_list().MappingList; function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util3.getArg(aArgs, "file", null); this._sourceRoot = util3.getArg(aArgs, "sourceRoot", null); this._skipValidation = util3.getArg(aArgs, "skipValidation", false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot }); aSourceMapConsumer.eachMapping(function(mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util3.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function(sourceFile) { var sourceRelative = sourceFile; if (sourceRoot !== null) { sourceRelative = util3.relative(sourceRoot, sourceFile); } if (!generator._sources.has(sourceRelative)) { generator._sources.add(sourceRelative); } var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util3.getArg(aArgs, "generated"); var original = util3.getArg(aArgs, "original", null); var source = util3.getArg(aArgs, "source", null); var name2 = util3.getArg(aArgs, "name", null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name2); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name2 != null) { name2 = String(name2); if (!this._names.has(name2)) { this._names.add(name2); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source, name: name2 }); }; SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util3.relative(this._sourceRoot, source); } if (aSourceContent != null) { if (!this._sourcesContents) { this._sourcesContents = Object.create(null); } this._sourcesContents[util3.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { delete this._sourcesContents[util3.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; if (sourceRoot != null) { sourceFile = util3.relative(sourceRoot, sourceFile); } var newSources = new ArraySet(); var newNames = new ArraySet(); this._mappings.unsortedForEach(function(mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util3.join(aSourceMapPath, mapping.source); } if (sourceRoot != null) { mapping.source = util3.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name2 = mapping.name; if (name2 != null && !newNames.has(name2)) { newNames.add(name2); } }, this); this._sources = newSources; this._names = newNames; aSourceMapConsumer.sources.forEach(function(sourceFile2) { var content = aSourceMapConsumer.sourceContentFor(sourceFile2); if (content != null) { if (aSourceMapPath != null) { sourceFile2 = util3.join(aSourceMapPath, sourceFile2); } if (sourceRoot != null) { sourceFile2 = util3.relative(sourceRoot, sourceFile2); } this.setSourceContent(sourceFile2, content); } }, this); }; SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values."); } if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { return; } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { return; } else { throw new Error("Invalid mapping: " + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ""; var next2; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i2 = 0, len = mappings.length; i2 < len; i2++) { mapping = mappings[i2]; next2 = ""; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next2 += ";"; previousGeneratedLine++; } } else { if (i2 > 0) { if (!util3.compareByGeneratedPositionsInflated(mapping, mappings[i2 - 1])) { continue; } next2 += ","; } } next2 += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next2 += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; next2 += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next2 += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next2 += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next2; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function(source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util3.relative(aSourceRoot, source); } var key = util3.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map2 = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map2.file = this._file; } if (this._sourceRoot != null) { map2.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot); } return map2; }; SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports2.SourceMapGenerator = SourceMapGenerator; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/binary-search.js var require_binary_search = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/binary-search.js"(exports2) { exports2.GREATEST_LOWER_BOUND = 1; exports2.LEAST_UPPER_BOUND = 2; function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { return mid; } else if (cmp > 0) { if (aHigh - mid > 1) { return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } if (aBias == exports2.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { if (mid - aLow > 1) { return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } if (aBias == exports2.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } exports2.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index2 = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports2.GREATEST_LOWER_BOUND); if (index2 < 0) { return -1; } while (index2 - 1 >= 0) { if (aCompare(aHaystack[index2], aHaystack[index2 - 1], true) !== 0) { break; } --index2; } return index2; }; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/quick-sort.js var require_quick_sort = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/quick-sort.js"(exports2) { function swap(ary, x2, y2) { var temp = ary[x2]; ary[x2] = ary[y2]; ary[y2] = temp; } function randomIntInRange(low, high) { return Math.round(low + Math.random() * (high - low)); } function doQuickSort(ary, comparator, p2, r3) { if (p2 < r3) { var pivotIndex = randomIntInRange(p2, r3); var i2 = p2 - 1; swap(ary, pivotIndex, r3); var pivot = ary[r3]; for (var j2 = p2; j2 < r3; j2++) { if (comparator(ary[j2], pivot) <= 0) { i2 += 1; swap(ary, i2, j2); } } swap(ary, i2 + 1, j2); var q3 = i2 + 1; doQuickSort(ary, comparator, p2, q3 - 1); doQuickSort(ary, comparator, q3 + 1, r3); } } exports2.quickSort = function(ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-consumer.js var require_source_map_consumer = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-consumer.js"(exports2) { var util3 = require_util(); var binarySearch2 = require_binary_search(); var ArraySet = require_array_set().ArraySet; var base64VLQ = require_base64_vlq(); var quickSort = require_quick_sort().quickSort; function SourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util3.parseSourceMapInput(aSourceMap); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); } SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); }; SourceMapConsumer.prototype._version = 3; SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", { configurable: true, enumerable: true, get: function() { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", { configurable: true, enumerable: true, get: function() { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index2) { var c2 = aStr.charAt(index2); return c2 === ";" || c2 === ","; }; SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function(mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); source = util3.computeSourceURL(sourceRoot, source, this._sourceMapURL); return { source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util3.getArg(aArgs, "line"); var needle = { source: util3.getArg(aArgs, "source"), originalLine: line, originalColumn: util3.getArg(aArgs, "column", 0) }; needle.source = this._findSourceIndex(needle.source); if (needle.source < 0) { return []; } var mappings = []; var index2 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util3.compareByOriginalPositions, binarySearch2.LEAST_UPPER_BOUND); if (index2 >= 0) { var mapping = this._originalMappings[index2]; if (aArgs.column === void 0) { var originalLine = mapping.originalLine; while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util3.getArg(mapping, "generatedLine", null), column: util3.getArg(mapping, "generatedColumn", null), lastColumn: util3.getArg(mapping, "lastGeneratedColumn", null) }); mapping = this._originalMappings[++index2]; } } else { var originalColumn = mapping.originalColumn; while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util3.getArg(mapping, "generatedLine", null), column: util3.getArg(mapping, "generatedColumn", null), lastColumn: util3.getArg(mapping, "lastGeneratedColumn", null) }); mapping = this._originalMappings[++index2]; } } } return mappings; }; exports2.SourceMapConsumer = SourceMapConsumer; function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util3.parseSourceMapInput(aSourceMap); } var version3 = util3.getArg(sourceMap, "version"); var sources = util3.getArg(sourceMap, "sources"); var names = util3.getArg(sourceMap, "names", []); var sourceRoot = util3.getArg(sourceMap, "sourceRoot", null); var sourcesContent = util3.getArg(sourceMap, "sourcesContent", null); var mappings = util3.getArg(sourceMap, "mappings"); var file = util3.getArg(sourceMap, "file", null); if (version3 != this._version) { throw new Error("Unsupported version: " + version3); } if (sourceRoot) { sourceRoot = util3.normalize(sourceRoot); } sources = sources.map(String).map(util3.normalize).map(function(source) { return sourceRoot && util3.isAbsolute(sourceRoot) && util3.isAbsolute(source) ? util3.relative(sourceRoot, source) : source; }); this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this._absoluteSources = this._sources.toArray().map(function(s2) { return util3.computeSourceURL(sourceRoot, s2, aSourceMapURL); }); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this._sourceMapURL = aSourceMapURL; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util3.relative(this.sourceRoot, relativeSource); } if (this._sources.has(relativeSource)) { return this._sources.indexOf(relativeSource); } var i2; for (i2 = 0; i2 < this._absoluteSources.length; ++i2) { if (this._absoluteSources[i2] == aSource) { return i2; } } return -1; }; BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc._sourceMapURL = aSourceMapURL; smc._absoluteSources = smc._sources.toArray().map(function(s2) { return util3.computeSourceURL(smc.sourceRoot, s2, aSourceMapURL); }); var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i2 = 0, length = generatedMappings.length; i2 < length; i2++) { var srcMapping = generatedMappings[i2]; var destMapping = new Mapping(); destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util3.compareByOriginalPositions); return smc; }; BasicSourceMapConsumer.prototype._version = 3; Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", { get: function() { return this._absoluteSources.slice(); } }); function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index2 = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str3, segment, end, value; while (index2 < length) { if (aStr.charAt(index2) === ";") { generatedLine++; index2++; previousGeneratedColumn = 0; } else if (aStr.charAt(index2) === ",") { index2++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; for (end = index2; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str3 = aStr.slice(index2, end); segment = cachedSegments[str3]; if (segment) { index2 += str3.length; } else { segment = []; while (index2 < end) { base64VLQ.decode(aStr, index2, temp); value = temp.value; index2 = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error("Found a source, but no line and column"); } if (segment.length === 3) { throw new Error("Found a source and line, but no column"); } cachedSegments[str3] = segment; } mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { mapping.source = previousSource + segment[1]; previousSource += segment[1]; mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; mapping.originalLine += 1; mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === "number") { originalMappings.push(mapping); } } } quickSort(generatedMappings, util3.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util3.compareByOriginalPositions); this.__originalMappings = originalMappings; }; BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { if (aNeedle[aLineName] <= 0) { throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]); } return binarySearch2.search(aNeedle, aMappings, aComparator, aBias); }; BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index2 = 0; index2 < this._generatedMappings.length; ++index2) { var mapping = this._generatedMappings[index2]; if (index2 + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index2 + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } mapping.lastGeneratedColumn = Infinity; } }; BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util3.getArg(aArgs, "line"), generatedColumn: util3.getArg(aArgs, "column") }; var index2 = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util3.compareByGeneratedPositionsDeflated, util3.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)); if (index2 >= 0) { var mapping = this._generatedMappings[index2]; if (mapping.generatedLine === needle.generatedLine) { var source = util3.getArg(mapping, "source", null); if (source !== null) { source = this._sources.at(source); source = util3.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); } var name2 = util3.getArg(mapping, "name", null); if (name2 !== null) { name2 = this._names.at(name2); } return { source, line: util3.getArg(mapping, "originalLine", null), column: util3.getArg(mapping, "originalColumn", null), name: name2 }; } } return { source: null, line: null, column: null, name: null }; }; BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) { return sc == null; }); }; BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } var index2 = this._findSourceIndex(aSource); if (index2 >= 0) { return this.sourcesContent[index2]; } var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util3.relative(this.sourceRoot, relativeSource); } var url; if (this.sourceRoot != null && (url = util3.urlParse(this.sourceRoot))) { var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; } if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) { return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; } } if (nullOnMissing) { return null; } else { throw new Error('"' + relativeSource + '" is not in the SourceMap.'); } }; BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util3.getArg(aArgs, "source"); source = this._findSourceIndex(source); if (source < 0) { return { line: null, column: null, lastColumn: null }; } var needle = { source, originalLine: util3.getArg(aArgs, "line"), originalColumn: util3.getArg(aArgs, "column") }; var index2 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util3.compareByOriginalPositions, util3.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)); if (index2 >= 0) { var mapping = this._originalMappings[index2]; if (mapping.source === needle.source) { return { line: util3.getArg(mapping, "generatedLine", null), column: util3.getArg(mapping, "generatedColumn", null), lastColumn: util3.getArg(mapping, "lastGeneratedColumn", null) }; } } return { line: null, column: null, lastColumn: null }; }; exports2.BasicSourceMapConsumer = BasicSourceMapConsumer; function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util3.parseSourceMapInput(aSourceMap); } var version3 = util3.getArg(sourceMap, "version"); var sections = util3.getArg(sourceMap, "sections"); if (version3 != this._version) { throw new Error("Unsupported version: " + version3); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function(s2) { if (s2.url) { throw new Error("Support for url field in sections not implemented."); } var offset = util3.getArg(s2, "offset"); var offsetLine = util3.getArg(offset, "line"); var offsetColumn = util3.getArg(offset, "column"); if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) { throw new Error("Section offsets must be ordered and non-overlapping."); } lastOffset = offset; return { generatedOffset: { generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util3.getArg(s2, "map"), aSourceMapURL) }; }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; IndexedSourceMapConsumer.prototype._version = 3; Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", { get: function() { var sources = []; for (var i2 = 0; i2 < this._sections.length; i2++) { for (var j2 = 0; j2 < this._sections[i2].consumer.sources.length; j2++) { sources.push(this._sections[i2].consumer.sources[j2]); } } return sources; } }); IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util3.getArg(aArgs, "line"), generatedColumn: util3.getArg(aArgs, "column") }; var sectionIndex = binarySearch2.search(needle, this._sections, function(needle2, section2) { var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine; if (cmp) { return cmp; } return needle2.generatedColumn - section2.generatedOffset.generatedColumn; }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function(s2) { return s2.consumer.hasContentsOfAllSources(); }); }; IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i2 = 0; i2 < this._sections.length; i2++) { var section = this._sections[i2]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i2 = 0; i2 < this._sections.length; i2++) { var section = this._sections[i2]; if (section.consumer._findSourceIndex(util3.getArg(aArgs, "source")) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i2 = 0; i2 < this._sections.length; i2++) { var section = this._sections[i2]; var sectionMappings = section.consumer._generatedMappings; for (var j2 = 0; j2 < sectionMappings.length; j2++) { var mapping = sectionMappings[j2]; var source = section.consumer._sources.at(mapping.source); source = util3.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); this._sources.add(source); source = this._sources.indexOf(source); var name2 = null; if (mapping.name) { name2 = section.consumer._names.at(mapping.name); this._names.add(name2); name2 = this._names.indexOf(name2); } var adjustedMapping = { source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name2 }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === "number") { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util3.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util3.compareByOriginalPositions); }; exports2.IndexedSourceMapConsumer = IndexedSourceMapConsumer; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-node.js var require_source_node = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-node.js"(exports2) { var SourceMapGenerator = require_source_map_generator().SourceMapGenerator; var util3 = require_util(); var REGEX_NEWLINE = /(\r?\n)/; var NEWLINE_CODE = 10; var isSourceNode = "$$$isSourceNode$$$"; function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { var node = new SourceNode(); var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0; } }; var lastGeneratedLine = 1, lastGeneratedColumn = 0; var lastMapping = null; aSourceMapConsumer.eachMapping(function(mapping) { if (lastMapping !== null) { if (lastGeneratedLine < mapping.generatedLine) { addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; } else { var nextLine = remainingLines[remainingLinesIndex] || ""; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); lastMapping = mapping; return; } } while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex] || ""; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { addMappingWithCode(lastMapping, shiftNextLine()); } node.add(remainingLines.splice(remainingLinesIndex).join("")); } aSourceMapConsumer.sources.forEach(function(sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util3.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === void 0) { node.add(code); } else { var source = aRelativePath ? util3.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function(chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk); } return this; }; SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i2 = aChunk.length - 1; i2 >= 0; i2--) { this.prepend(aChunk[i2]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk); } return this; }; SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i2 = 0, len = this.children.length; i2 < len; i2++) { chunk = this.children[i2]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== "") { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i2; var len = this.children.length; if (len > 0) { newChildren = []; for (i2 = 0; i2 < len - 1; i2++) { newChildren.push(this.children[i2]); newChildren.push(aSep); } newChildren.push(this.children[i2]); this.children = newChildren; } return this; }; SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === "string") { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push("".replace(aPattern, aReplacement)); } return this; }; SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util3.toSetString(aSourceFile)] = aSourceContent; }; SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i2 = 0, len = this.children.length; i2 < len; i2++) { if (this.children[i2][isSourceNode]) { this.children[i2].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i2 = 0, len = sources.length; i2 < len; i2++) { aFn(util3.fromSetString(sources[i2]), this.sourceContents[sources[i2]]); } }; SourceNode.prototype.toString = function SourceNode_toString() { var str3 = ""; this.walk(function(chunk) { str3 += chunk; }); return str3; }; SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map2 = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function(chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map2.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map2.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map2.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function(sourceFile, sourceContent) { map2.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map2 }; }; exports2.SourceNode = SourceNode; } }); // node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/source-map.js var require_source_map = __commonJS({ "node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/source-map.js"(exports2) { exports2.SourceMapGenerator = require_source_map_generator().SourceMapGenerator; exports2.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer; exports2.SourceNode = require_source_node().SourceNode; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/code-gen.js var require_code_gen = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/code-gen.js"(exports2, module2) { "use strict"; exports2.__esModule = true; var _utils = require_utils(); var SourceNode = void 0; try { if (typeof define !== "function" || !define.amd) { SourceMap = require_source_map(); SourceNode = SourceMap.SourceNode; } } catch (err) { } var SourceMap; if (!SourceNode) { SourceNode = function(line, column, srcFile, chunks) { this.src = ""; if (chunks) { this.add(chunks); } }; SourceNode.prototype = { add: function add(chunks) { if (_utils.isArray(chunks)) { chunks = chunks.join(""); } this.src += chunks; }, prepend: function prepend(chunks) { if (_utils.isArray(chunks)) { chunks = chunks.join(""); } this.src = chunks + this.src; }, toStringWithSourceMap: function toStringWithSourceMap() { return { code: this.toString() }; }, toString: function toString3() { return this.src; } }; } function castChunk(chunk, codeGen, loc) { if (_utils.isArray(chunk)) { var ret = []; for (var i2 = 0, len = chunk.length; i2 < len; i2++) { ret.push(codeGen.wrap(chunk[i2], loc)); } return ret; } else if (typeof chunk === "boolean" || typeof chunk === "number") { return chunk + ""; } return chunk; } function CodeGen(srcFile) { this.srcFile = srcFile; this.source = []; } CodeGen.prototype = { isEmpty: function isEmpty6() { return !this.source.length; }, prepend: function prepend(source, loc) { this.source.unshift(this.wrap(source, loc)); }, push: function push(source, loc) { this.source.push(this.wrap(source, loc)); }, merge: function merge5() { var source = this.empty(); this.each(function(line) { source.add([" ", line, "\n"]); }); return source; }, each: function each(iter) { for (var i2 = 0, len = this.source.length; i2 < len; i2++) { iter(this.source[i2]); } }, empty: function empty() { var loc = this.currentLocation || { start: {} }; return new SourceNode(loc.start.line, loc.start.column, this.srcFile); }, wrap: function wrap2(chunk) { var loc = arguments.length <= 1 || arguments[1] === void 0 ? this.currentLocation || { start: {} } : arguments[1]; if (chunk instanceof SourceNode) { return chunk; } chunk = castChunk(chunk, this, loc); return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk); }, functionCall: function functionCall(fn, type2, params) { params = this.generateList(params); return this.wrap([fn, type2 ? "." + type2 + "(" : "(", params, ")"]); }, quotedString: function quotedString(str3) { return '"' + (str3 + "").replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029") + '"'; }, objectLiteral: function objectLiteral(obj) { var _this = this; var pairs2 = []; Object.keys(obj).forEach(function(key) { var value = castChunk(obj[key], _this); if (value !== "undefined") { pairs2.push([_this.quotedString(key), ":", value]); } }); var ret = this.generateList(pairs2); ret.prepend("{"); ret.add("}"); return ret; }, generateList: function generateList(entries) { var ret = this.empty(); for (var i2 = 0, len = entries.length; i2 < len; i2++) { if (i2) { ret.add(","); } ret.add(castChunk(entries[i2], this)); } return ret; }, generateArray: function generateArray(entries) { var ret = this.generateList(entries); ret.prepend("["); ret.add("]"); return ret; } }; exports2["default"] = CodeGen; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js var require_javascript_compiler = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _base = require_base(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _utils = require_utils(); var _codeGen = require_code_gen(); var _codeGen2 = _interopRequireDefault(_codeGen); function Literal(value) { this.value = value; } function JavaScriptCompiler() { } JavaScriptCompiler.prototype = { nameLookup: function nameLookup(parent, name2) { return this.internalNameLookup(parent, name2); }, depthedLookup: function depthedLookup(name2) { return [this.aliasable("container.lookup"), "(depths, ", JSON.stringify(name2), ")"]; }, compilerInfo: function compilerInfo() { var revision = _base.COMPILER_REVISION, versions = _base.REVISION_CHANGES[revision]; return [revision, versions]; }, appendToBuffer: function appendToBuffer(source, location2, explicit) { if (!_utils.isArray(source)) { source = [source]; } source = this.source.wrap(source, location2); if (this.environment.isSimple) { return ["return ", source, ";"]; } else if (explicit) { return ["buffer += ", source, ";"]; } else { source.appendToBuffer = true; return source; } }, initializeBuffer: function initializeBuffer() { return this.quotedString(""); }, internalNameLookup: function internalNameLookup(parent, name2) { this.lookupPropertyFunctionIsUsed = true; return ["lookupProperty(", parent, ",", JSON.stringify(name2), ")"]; }, lookupPropertyFunctionIsUsed: false, compile: function compile(environment, options, context, asObject) { this.environment = environment; this.options = options; this.stringParams = this.options.stringParams; this.trackIds = this.options.trackIds; this.precompile = !asObject; this.name = this.environment.name; this.isChild = !!context; this.context = context || { decorators: [], programs: [], environments: [] }; this.preamble(); this.stackSlot = 0; this.stackVars = []; this.aliases = {}; this.registers = { list: [] }; this.hashes = []; this.compileStack = []; this.inlineStack = []; this.blockParams = []; this.compileChildren(environment, options); this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat; this.useBlockParams = this.useBlockParams || environment.useBlockParams; var opcodes = environment.opcodes, opcode = void 0, firstLoc = void 0, i2 = void 0, l2 = void 0; for (i2 = 0, l2 = opcodes.length; i2 < l2; i2++) { opcode = opcodes[i2]; this.source.currentLocation = opcode.loc; firstLoc = firstLoc || opcode.loc; this[opcode.opcode].apply(this, opcode.args); } this.source.currentLocation = firstLoc; this.pushSource(""); if (this.stackSlot || this.inlineStack.length || this.compileStack.length) { throw new _exception2["default"]("Compile completed with content left on stack"); } if (!this.decorators.isEmpty()) { this.useDecorators = true; this.decorators.prepend(["var decorators = container.decorators, ", this.lookupPropertyFunctionVarDeclaration(), ";\n"]); this.decorators.push("return fn;"); if (asObject) { this.decorators = Function.apply(this, ["fn", "props", "container", "depth0", "data", "blockParams", "depths", this.decorators.merge()]); } else { this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"); this.decorators.push("}\n"); this.decorators = this.decorators.merge(); } } else { this.decorators = void 0; } var fn = this.createFunctionContext(asObject); if (!this.isChild) { var ret = { compiler: this.compilerInfo(), main: fn }; if (this.decorators) { ret.main_d = this.decorators; ret.useDecorators = true; } var _context = this.context; var programs = _context.programs; var decorators = _context.decorators; for (i2 = 0, l2 = programs.length; i2 < l2; i2++) { if (programs[i2]) { ret[i2] = programs[i2]; if (decorators[i2]) { ret[i2 + "_d"] = decorators[i2]; ret.useDecorators = true; } } } if (this.environment.usePartial) { ret.usePartial = true; } if (this.options.data) { ret.useData = true; } if (this.useDepths) { ret.useDepths = true; } if (this.useBlockParams) { ret.useBlockParams = true; } if (this.options.compat) { ret.compat = true; } if (!asObject) { ret.compiler = JSON.stringify(ret.compiler); this.source.currentLocation = { start: { line: 1, column: 0 } }; ret = this.objectLiteral(ret); if (options.srcName) { ret = ret.toStringWithSourceMap({ file: options.destName }); ret.map = ret.map && ret.map.toString(); } else { ret = ret.toString(); } } else { ret.compilerOptions = this.options; } return ret; } else { return fn; } }, preamble: function preamble() { this.lastContext = 0; this.source = new _codeGen2["default"](this.options.srcName); this.decorators = new _codeGen2["default"](this.options.srcName); }, createFunctionContext: function createFunctionContext(asObject) { var _this = this; var varDeclarations = ""; var locals = this.stackVars.concat(this.registers.list); if (locals.length > 0) { varDeclarations += ", " + locals.join(", "); } var aliasCount = 0; Object.keys(this.aliases).forEach(function(alias) { var node = _this.aliases[alias]; if (node.children && node.referenceCount > 1) { varDeclarations += ", alias" + ++aliasCount + "=" + alias; node.children[0] = "alias" + aliasCount; } }); if (this.lookupPropertyFunctionIsUsed) { varDeclarations += ", " + this.lookupPropertyFunctionVarDeclaration(); } var params = ["container", "depth0", "helpers", "partials", "data"]; if (this.useBlockParams || this.useDepths) { params.push("blockParams"); } if (this.useDepths) { params.push("depths"); } var source = this.mergeSource(varDeclarations); if (asObject) { params.push(source); return Function.apply(this, params); } else { return this.source.wrap(["function(", params.join(","), ") {\n ", source, "}"]); } }, mergeSource: function mergeSource(varDeclarations) { var isSimple = this.environment.isSimple, appendOnly = !this.forceBuffer, appendFirst = void 0, sourceSeen = void 0, bufferStart = void 0, bufferEnd = void 0; this.source.each(function(line) { if (line.appendToBuffer) { if (bufferStart) { line.prepend(" + "); } else { bufferStart = line; } bufferEnd = line; } else { if (bufferStart) { if (!sourceSeen) { appendFirst = true; } else { bufferStart.prepend("buffer += "); } bufferEnd.add(";"); bufferStart = bufferEnd = void 0; } sourceSeen = true; if (!isSimple) { appendOnly = false; } } }); if (appendOnly) { if (bufferStart) { bufferStart.prepend("return "); bufferEnd.add(";"); } else if (!sourceSeen) { this.source.push('return "";'); } } else { varDeclarations += ", buffer = " + (appendFirst ? "" : this.initializeBuffer()); if (bufferStart) { bufferStart.prepend("return buffer + "); bufferEnd.add(";"); } else { this.source.push("return buffer;"); } } if (varDeclarations) { this.source.prepend("var " + varDeclarations.substring(2) + (appendFirst ? "" : ";\n")); } return this.source.merge(); }, lookupPropertyFunctionVarDeclaration: function lookupPropertyFunctionVarDeclaration() { return "\n lookupProperty = container.lookupProperty || function(parent, propertyName) {\n if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n return parent[propertyName];\n }\n return undefined\n }\n ".trim(); }, blockValue: function blockValue(name2) { var blockHelperMissing = this.aliasable("container.hooks.blockHelperMissing"), params = [this.contextName(0)]; this.setupHelperArgs(name2, 0, params); var blockName = this.popStack(); params.splice(1, 0, blockName); this.push(this.source.functionCall(blockHelperMissing, "call", params)); }, ambiguousBlockValue: function ambiguousBlockValue() { var blockHelperMissing = this.aliasable("container.hooks.blockHelperMissing"), params = [this.contextName(0)]; this.setupHelperArgs("", 0, params, true); this.flushInline(); var current = this.topStack(); params.splice(1, 0, current); this.pushSource(["if (!", this.lastHelper, ") { ", current, " = ", this.source.functionCall(blockHelperMissing, "call", params), "}"]); }, appendContent: function appendContent(content) { if (this.pendingContent) { content = this.pendingContent + content; } else { this.pendingLocation = this.source.currentLocation; } this.pendingContent = content; }, append: function append() { if (this.isInline()) { this.replaceStack(function(current) { return [" != null ? ", current, ' : ""']; }); this.pushSource(this.appendToBuffer(this.popStack())); } else { var local = this.popStack(); this.pushSource(["if (", local, " != null) { ", this.appendToBuffer(local, void 0, true), " }"]); if (this.environment.isSimple) { this.pushSource(["else { ", this.appendToBuffer("''", void 0, true), " }"]); } } }, appendEscaped: function appendEscaped() { this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"), "(", this.popStack(), ")"])); }, getContext: function getContext(depth) { this.lastContext = depth; }, pushContext: function pushContext() { this.pushStackLiteral(this.contextName(this.lastContext)); }, lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) { var i2 = 0; if (!scoped && this.options.compat && !this.lastContext) { this.push(this.depthedLookup(parts[i2++])); } else { this.pushContext(); } this.resolvePath("context", parts, i2, falsy, strict); }, lookupBlockParam: function lookupBlockParam(blockParamId, parts) { this.useBlockParams = true; this.push(["blockParams[", blockParamId[0], "][", blockParamId[1], "]"]); this.resolvePath("context", parts, 1); }, lookupData: function lookupData(depth, parts, strict) { if (!depth) { this.pushStackLiteral("data"); } else { this.pushStackLiteral("container.data(data, " + depth + ")"); } this.resolvePath("data", parts, 0, true, strict); }, resolvePath: function resolvePath(type2, parts, i2, falsy, strict) { var _this2 = this; if (this.options.strict || this.options.assumeObjects) { this.push(strictLookup(this.options.strict && strict, this, parts, i2, type2)); return; } var len = parts.length; for (; i2 < len; i2++) { this.replaceStack(function(current) { var lookup = _this2.nameLookup(current, parts[i2], type2); if (!falsy) { return [" != null ? ", lookup, " : ", current]; } else { return [" && ", lookup]; } }); } }, resolvePossibleLambda: function resolvePossibleLambda() { this.push([this.aliasable("container.lambda"), "(", this.popStack(), ", ", this.contextName(0), ")"]); }, pushStringParam: function pushStringParam(string, type2) { this.pushContext(); this.pushString(type2); if (type2 !== "SubExpression") { if (typeof string === "string") { this.pushString(string); } else { this.pushStackLiteral(string); } } }, emptyHash: function emptyHash(omitEmpty) { if (this.trackIds) { this.push("{}"); } if (this.stringParams) { this.push("{}"); this.push("{}"); } this.pushStackLiteral(omitEmpty ? "undefined" : "{}"); }, pushHash: function pushHash() { if (this.hash) { this.hashes.push(this.hash); } this.hash = { values: {}, types: [], contexts: [], ids: [] }; }, popHash: function popHash() { var hash = this.hash; this.hash = this.hashes.pop(); if (this.trackIds) { this.push(this.objectLiteral(hash.ids)); } if (this.stringParams) { this.push(this.objectLiteral(hash.contexts)); this.push(this.objectLiteral(hash.types)); } this.push(this.objectLiteral(hash.values)); }, pushString: function pushString(string) { this.pushStackLiteral(this.quotedString(string)); }, pushLiteral: function pushLiteral(value) { this.pushStackLiteral(value); }, pushProgram: function pushProgram(guid) { if (guid != null) { this.pushStackLiteral(this.programExpression(guid)); } else { this.pushStackLiteral(null); } }, registerDecorator: function registerDecorator(paramSize, name2) { var foundDecorator = this.nameLookup("decorators", name2, "decorator"), options = this.setupHelperArgs(name2, paramSize); this.decorators.push(["fn = ", this.decorators.functionCall(foundDecorator, "", ["fn", "props", "container", options]), " || fn;"]); }, invokeHelper: function invokeHelper(paramSize, name2, isSimple) { var nonHelper = this.popStack(), helper = this.setupHelper(paramSize, name2); var possibleFunctionCalls = []; if (isSimple) { possibleFunctionCalls.push(helper.name); } possibleFunctionCalls.push(nonHelper); if (!this.options.strict) { possibleFunctionCalls.push(this.aliasable("container.hooks.helperMissing")); } var functionLookupCode = ["(", this.itemsSeparatedBy(possibleFunctionCalls, "||"), ")"]; var functionCall = this.source.functionCall(functionLookupCode, "call", helper.callParams); this.push(functionCall); }, itemsSeparatedBy: function itemsSeparatedBy(items, separator) { var result = []; result.push(items[0]); for (var i2 = 1; i2 < items.length; i2++) { result.push(separator, items[i2]); } return result; }, invokeKnownHelper: function invokeKnownHelper(paramSize, name2) { var helper = this.setupHelper(paramSize, name2); this.push(this.source.functionCall(helper.name, "call", helper.callParams)); }, invokeAmbiguous: function invokeAmbiguous(name2, helperCall) { this.useRegister("helper"); var nonHelper = this.popStack(); this.emptyHash(); var helper = this.setupHelper(0, name2, helperCall); var helperName = this.lastHelper = this.nameLookup("helpers", name2, "helper"); var lookup = ["(", "(helper = ", helperName, " || ", nonHelper, ")"]; if (!this.options.strict) { lookup[0] = "(helper = "; lookup.push(" != null ? helper : ", this.aliasable("container.hooks.helperMissing")); } this.push(["(", lookup, helper.paramsInit ? ["),(", helper.paramsInit] : [], "),", "(typeof helper === ", this.aliasable('"function"'), " ? ", this.source.functionCall("helper", "call", helper.callParams), " : helper))"]); }, invokePartial: function invokePartial(isDynamic, name2, indent) { var params = [], options = this.setupParams(name2, 1, params); if (isDynamic) { name2 = this.popStack(); delete options.name; } if (indent) { options.indent = JSON.stringify(indent); } options.helpers = "helpers"; options.partials = "partials"; options.decorators = "container.decorators"; if (!isDynamic) { params.unshift(this.nameLookup("partials", name2, "partial")); } else { params.unshift(name2); } if (this.options.compat) { options.depths = "depths"; } options = this.objectLiteral(options); params.push(options); this.push(this.source.functionCall("container.invokePartial", "", params)); }, assignToHash: function assignToHash(key) { var value = this.popStack(), context = void 0, type2 = void 0, id2 = void 0; if (this.trackIds) { id2 = this.popStack(); } if (this.stringParams) { type2 = this.popStack(); context = this.popStack(); } var hash = this.hash; if (context) { hash.contexts[key] = context; } if (type2) { hash.types[key] = type2; } if (id2) { hash.ids[key] = id2; } hash.values[key] = value; }, pushId: function pushId(type2, name2, child) { if (type2 === "BlockParam") { this.pushStackLiteral("blockParams[" + name2[0] + "].path[" + name2[1] + "]" + (child ? " + " + JSON.stringify("." + child) : "")); } else if (type2 === "PathExpression") { this.pushString(name2); } else if (type2 === "SubExpression") { this.pushStackLiteral("true"); } else { this.pushStackLiteral("null"); } }, compiler: JavaScriptCompiler, compileChildren: function compileChildren(environment, options) { var children2 = environment.children, child = void 0, compiler = void 0; for (var i2 = 0, l2 = children2.length; i2 < l2; i2++) { child = children2[i2]; compiler = new this.compiler(); var existing = this.matchExistingProgram(child); if (existing == null) { this.context.programs.push(""); var index2 = this.context.programs.length; child.index = index2; child.name = "program" + index2; this.context.programs[index2] = compiler.compile(child, options, this.context, !this.precompile); this.context.decorators[index2] = compiler.decorators; this.context.environments[index2] = child; this.useDepths = this.useDepths || compiler.useDepths; this.useBlockParams = this.useBlockParams || compiler.useBlockParams; child.useDepths = this.useDepths; child.useBlockParams = this.useBlockParams; } else { child.index = existing.index; child.name = "program" + existing.index; this.useDepths = this.useDepths || existing.useDepths; this.useBlockParams = this.useBlockParams || existing.useBlockParams; } } }, matchExistingProgram: function matchExistingProgram(child) { for (var i2 = 0, len = this.context.environments.length; i2 < len; i2++) { var environment = this.context.environments[i2]; if (environment && environment.equals(child)) { return environment; } } }, programExpression: function programExpression(guid) { var child = this.environment.children[guid], programParams = [child.index, "data", child.blockParams]; if (this.useBlockParams || this.useDepths) { programParams.push("blockParams"); } if (this.useDepths) { programParams.push("depths"); } return "container.program(" + programParams.join(", ") + ")"; }, useRegister: function useRegister(name2) { if (!this.registers[name2]) { this.registers[name2] = true; this.registers.list.push(name2); } }, push: function push(expr) { if (!(expr instanceof Literal)) { expr = this.source.wrap(expr); } this.inlineStack.push(expr); return expr; }, pushStackLiteral: function pushStackLiteral(item) { this.push(new Literal(item)); }, pushSource: function pushSource(source) { if (this.pendingContent) { this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation)); this.pendingContent = void 0; } if (source) { this.source.push(source); } }, replaceStack: function replaceStack(callback) { var prefix = ["("], stack = void 0, createdStack = void 0, usedLiteral = void 0; if (!this.isInline()) { throw new _exception2["default"]("replaceStack on non-inline"); } var top = this.popStack(true); if (top instanceof Literal) { stack = [top.value]; prefix = ["(", stack]; usedLiteral = true; } else { createdStack = true; var _name = this.incrStack(); prefix = ["((", this.push(_name), " = ", top, ")"]; stack = this.topStack(); } var item = callback.call(this, stack); if (!usedLiteral) { this.popStack(); } if (createdStack) { this.stackSlot--; } this.push(prefix.concat(item, ")")); }, incrStack: function incrStack() { this.stackSlot++; if (this.stackSlot > this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } return this.topStackName(); }, topStackName: function topStackName() { return "stack" + this.stackSlot; }, flushInline: function flushInline() { var inlineStack = this.inlineStack; this.inlineStack = []; for (var i2 = 0, len = inlineStack.length; i2 < len; i2++) { var entry = inlineStack[i2]; if (entry instanceof Literal) { this.compileStack.push(entry); } else { var stack = this.incrStack(); this.pushSource([stack, " = ", entry, ";"]); this.compileStack.push(stack); } } }, isInline: function isInline() { return this.inlineStack.length; }, popStack: function popStack(wrapped) { var inline = this.isInline(), item = (inline ? this.inlineStack : this.compileStack).pop(); if (!wrapped && item instanceof Literal) { return item.value; } else { if (!inline) { if (!this.stackSlot) { throw new _exception2["default"]("Invalid stack pop"); } this.stackSlot--; } return item; } }, topStack: function topStack() { var stack = this.isInline() ? this.inlineStack : this.compileStack, item = stack[stack.length - 1]; if (item instanceof Literal) { return item.value; } else { return item; } }, contextName: function contextName(context) { if (this.useDepths && context) { return "depths[" + context + "]"; } else { return "depth" + context; } }, quotedString: function quotedString(str3) { return this.source.quotedString(str3); }, objectLiteral: function objectLiteral(obj) { return this.source.objectLiteral(obj); }, aliasable: function aliasable(name2) { var ret = this.aliases[name2]; if (ret) { ret.referenceCount++; return ret; } ret = this.aliases[name2] = this.source.wrap(name2); ret.aliasable = true; ret.referenceCount = 1; return ret; }, setupHelper: function setupHelper(paramSize, name2, blockHelper) { var params = [], paramsInit = this.setupHelperArgs(name2, paramSize, params, blockHelper); var foundHelper = this.nameLookup("helpers", name2, "helper"), callContext = this.aliasable(this.contextName(0) + " != null ? " + this.contextName(0) + " : (container.nullContext || {})"); return { params, paramsInit, name: foundHelper, callParams: [callContext].concat(params) }; }, setupParams: function setupParams(helper, paramSize, params) { var options = {}, contexts = [], types = [], ids = [], objectArgs = !params, param = void 0; if (objectArgs) { params = []; } options.name = this.quotedString(helper); options.hash = this.popStack(); if (this.trackIds) { options.hashIds = this.popStack(); } if (this.stringParams) { options.hashTypes = this.popStack(); options.hashContexts = this.popStack(); } var inverse = this.popStack(), program = this.popStack(); if (program || inverse) { options.fn = program || "container.noop"; options.inverse = inverse || "container.noop"; } var i2 = paramSize; while (i2--) { param = this.popStack(); params[i2] = param; if (this.trackIds) { ids[i2] = this.popStack(); } if (this.stringParams) { types[i2] = this.popStack(); contexts[i2] = this.popStack(); } } if (objectArgs) { options.args = this.source.generateArray(params); } if (this.trackIds) { options.ids = this.source.generateArray(ids); } if (this.stringParams) { options.types = this.source.generateArray(types); options.contexts = this.source.generateArray(contexts); } if (this.options.data) { options.data = "data"; } if (this.useBlockParams) { options.blockParams = "blockParams"; } return options; }, setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) { var options = this.setupParams(helper, paramSize, params); options.loc = JSON.stringify(this.source.currentLocation); options = this.objectLiteral(options); if (useRegister) { this.useRegister("options"); params.push("options"); return ["options=", options]; } else if (params) { params.push(options); return ""; } else { return options; } } }; (function() { var reservedWords = "break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "); var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; for (var i2 = 0, l2 = reservedWords.length; i2 < l2; i2++) { compilerWords[reservedWords[i2]] = true; } })(); JavaScriptCompiler.isValidJavaScriptVariableName = function(name2) { return !JavaScriptCompiler.RESERVED_WORDS[name2] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name2); }; function strictLookup(requireTerminal, compiler, parts, i2, type2) { var stack = compiler.popStack(), len = parts.length; if (requireTerminal) { len--; } for (; i2 < len; i2++) { stack = compiler.nameLookup(stack, parts[i2], type2); } if (requireTerminal) { return [compiler.aliasable("container.strict"), "(", stack, ", ", compiler.quotedString(parts[i2]), ", ", JSON.stringify(compiler.source.currentLocation), " )"]; } else { return stack; } } exports2["default"] = JavaScriptCompiler; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars.js var require_handlebars = __commonJS({ "node_modules/.pnpm/handlebars@4.7.8/node_modules/handlebars/dist/cjs/handlebars.js"(exports2, module2) { "use strict"; exports2.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _handlebarsRuntime = require_handlebars_runtime(); var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime); var _handlebarsCompilerAst = require_ast(); var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst); var _handlebarsCompilerBase = require_base2(); var _handlebarsCompilerCompiler = require_compiler(); var _handlebarsCompilerJavascriptCompiler = require_javascript_compiler(); var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler); var _handlebarsCompilerVisitor = require_visitor(); var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor); var _handlebarsNoConflict = require_no_conflict(); var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); var _create = _handlebarsRuntime2["default"].create; function create() { var hb = _create(); hb.compile = function(input, options) { return _handlebarsCompilerCompiler.compile(input, options, hb); }; hb.precompile = function(input, options) { return _handlebarsCompilerCompiler.precompile(input, options, hb); }; hb.AST = _handlebarsCompilerAst2["default"]; hb.Compiler = _handlebarsCompilerCompiler.Compiler; hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2["default"]; hb.Parser = _handlebarsCompilerBase.parser; hb.parse = _handlebarsCompilerBase.parse; hb.parseWithoutProcessing = _handlebarsCompilerBase.parseWithoutProcessing; return hb; } var inst = create(); inst.create = create; _handlebarsNoConflict2["default"](inst); inst.Visitor = _handlebarsCompilerVisitor2["default"]; inst["default"] = inst; exports2["default"] = inst; module2.exports = exports2["default"]; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/js-sha1/hash.js function Sha1(sharedMemory) { if (sharedMemory) { blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; this.blocks = blocks; } else { this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } this.h0 = 1732584193; this.h1 = 4023233417; this.h2 = 2562383102; this.h3 = 271733878; this.h4 = 3285377520; this.block = this.start = this.bytes = this.hBytes = 0; this.finalized = this.hashed = false; this.first = true; } var root, HEX_CHARS, EXTRA, SHIFT, blocks, insecureHash; var init_hash = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/js-sha1/hash.js"() { "use strict"; root = typeof window === "object" ? window : {}; HEX_CHARS = "0123456789abcdef".split(""); EXTRA = [-2147483648, 8388608, 32768, 128]; SHIFT = [24, 16, 8, 0]; blocks = []; Sha1.prototype.update = function(message) { if (this.finalized) { return; } var notString = typeof message !== "string"; if (notString && message.constructor === root.ArrayBuffer) { message = new Uint8Array(message); } var code, index2 = 0, i2, length = message.length || 0, blocks2 = this.blocks; while (index2 < length) { if (this.hashed) { this.hashed = false; blocks2[0] = this.block; blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; } if (notString) { for (i2 = this.start; index2 < length && i2 < 64; ++index2) { blocks2[i2 >> 2] |= message[index2] << SHIFT[i2++ & 3]; } } else { for (i2 = this.start; index2 < length && i2 < 64; ++index2) { code = message.charCodeAt(index2); if (code < 128) { blocks2[i2 >> 2] |= code << SHIFT[i2++ & 3]; } else if (code < 2048) { blocks2[i2 >> 2] |= (192 | code >> 6) << SHIFT[i2++ & 3]; blocks2[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; } else if (code < 55296 || code >= 57344) { blocks2[i2 >> 2] |= (224 | code >> 12) << SHIFT[i2++ & 3]; blocks2[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; blocks2[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; } else { code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index2) & 1023); blocks2[i2 >> 2] |= (240 | code >> 18) << SHIFT[i2++ & 3]; blocks2[i2 >> 2] |= (128 | code >> 12 & 63) << SHIFT[i2++ & 3]; blocks2[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; blocks2[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; } } } this.lastByteIndex = i2; this.bytes += i2 - this.start; if (i2 >= 64) { this.block = blocks2[16]; this.start = i2 - 64; this.hash(); this.hashed = true; } else { this.start = i2; } } if (this.bytes > 4294967295) { this.hBytes += this.bytes / 4294967296 << 0; this.bytes = this.bytes % 4294967296; } return this; }; Sha1.prototype.finalize = function() { if (this.finalized) { return; } this.finalized = true; var blocks2 = this.blocks, i2 = this.lastByteIndex; blocks2[16] = this.block; blocks2[i2 >> 2] |= EXTRA[i2 & 3]; this.block = blocks2[16]; if (i2 >= 56) { if (!this.hashed) { this.hash(); } blocks2[0] = this.block; blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; } blocks2[14] = this.hBytes << 3 | this.bytes >>> 29; blocks2[15] = this.bytes << 3; this.hash(); }; Sha1.prototype.hash = function() { var a2 = this.h0, b2 = this.h1, c2 = this.h2, d2 = this.h3, e2 = this.h4; var f4, j2, t2, blocks2 = this.blocks; for (j2 = 16; j2 < 80; ++j2) { t2 = blocks2[j2 - 3] ^ blocks2[j2 - 8] ^ blocks2[j2 - 14] ^ blocks2[j2 - 16]; blocks2[j2] = t2 << 1 | t2 >>> 31; } for (j2 = 0; j2 < 20; j2 += 5) { f4 = b2 & c2 | ~b2 & d2; t2 = a2 << 5 | a2 >>> 27; e2 = t2 + f4 + e2 + 1518500249 + blocks2[j2] << 0; b2 = b2 << 30 | b2 >>> 2; f4 = a2 & b2 | ~a2 & c2; t2 = e2 << 5 | e2 >>> 27; d2 = t2 + f4 + d2 + 1518500249 + blocks2[j2 + 1] << 0; a2 = a2 << 30 | a2 >>> 2; f4 = e2 & a2 | ~e2 & b2; t2 = d2 << 5 | d2 >>> 27; c2 = t2 + f4 + c2 + 1518500249 + blocks2[j2 + 2] << 0; e2 = e2 << 30 | e2 >>> 2; f4 = d2 & e2 | ~d2 & a2; t2 = c2 << 5 | c2 >>> 27; b2 = t2 + f4 + b2 + 1518500249 + blocks2[j2 + 3] << 0; d2 = d2 << 30 | d2 >>> 2; f4 = c2 & d2 | ~c2 & e2; t2 = b2 << 5 | b2 >>> 27; a2 = t2 + f4 + a2 + 1518500249 + blocks2[j2 + 4] << 0; c2 = c2 << 30 | c2 >>> 2; } for (; j2 < 40; j2 += 5) { f4 = b2 ^ c2 ^ d2; t2 = a2 << 5 | a2 >>> 27; e2 = t2 + f4 + e2 + 1859775393 + blocks2[j2] << 0; b2 = b2 << 30 | b2 >>> 2; f4 = a2 ^ b2 ^ c2; t2 = e2 << 5 | e2 >>> 27; d2 = t2 + f4 + d2 + 1859775393 + blocks2[j2 + 1] << 0; a2 = a2 << 30 | a2 >>> 2; f4 = e2 ^ a2 ^ b2; t2 = d2 << 5 | d2 >>> 27; c2 = t2 + f4 + c2 + 1859775393 + blocks2[j2 + 2] << 0; e2 = e2 << 30 | e2 >>> 2; f4 = d2 ^ e2 ^ a2; t2 = c2 << 5 | c2 >>> 27; b2 = t2 + f4 + b2 + 1859775393 + blocks2[j2 + 3] << 0; d2 = d2 << 30 | d2 >>> 2; f4 = c2 ^ d2 ^ e2; t2 = b2 << 5 | b2 >>> 27; a2 = t2 + f4 + a2 + 1859775393 + blocks2[j2 + 4] << 0; c2 = c2 << 30 | c2 >>> 2; } for (; j2 < 60; j2 += 5) { f4 = b2 & c2 | b2 & d2 | c2 & d2; t2 = a2 << 5 | a2 >>> 27; e2 = t2 + f4 + e2 - 1894007588 + blocks2[j2] << 0; b2 = b2 << 30 | b2 >>> 2; f4 = a2 & b2 | a2 & c2 | b2 & c2; t2 = e2 << 5 | e2 >>> 27; d2 = t2 + f4 + d2 - 1894007588 + blocks2[j2 + 1] << 0; a2 = a2 << 30 | a2 >>> 2; f4 = e2 & a2 | e2 & b2 | a2 & b2; t2 = d2 << 5 | d2 >>> 27; c2 = t2 + f4 + c2 - 1894007588 + blocks2[j2 + 2] << 0; e2 = e2 << 30 | e2 >>> 2; f4 = d2 & e2 | d2 & a2 | e2 & a2; t2 = c2 << 5 | c2 >>> 27; b2 = t2 + f4 + b2 - 1894007588 + blocks2[j2 + 3] << 0; d2 = d2 << 30 | d2 >>> 2; f4 = c2 & d2 | c2 & e2 | d2 & e2; t2 = b2 << 5 | b2 >>> 27; a2 = t2 + f4 + a2 - 1894007588 + blocks2[j2 + 4] << 0; c2 = c2 << 30 | c2 >>> 2; } for (; j2 < 80; j2 += 5) { f4 = b2 ^ c2 ^ d2; t2 = a2 << 5 | a2 >>> 27; e2 = t2 + f4 + e2 - 899497514 + blocks2[j2] << 0; b2 = b2 << 30 | b2 >>> 2; f4 = a2 ^ b2 ^ c2; t2 = e2 << 5 | e2 >>> 27; d2 = t2 + f4 + d2 - 899497514 + blocks2[j2 + 1] << 0; a2 = a2 << 30 | a2 >>> 2; f4 = e2 ^ a2 ^ b2; t2 = d2 << 5 | d2 >>> 27; c2 = t2 + f4 + c2 - 899497514 + blocks2[j2 + 2] << 0; e2 = e2 << 30 | e2 >>> 2; f4 = d2 ^ e2 ^ a2; t2 = c2 << 5 | c2 >>> 27; b2 = t2 + f4 + b2 - 899497514 + blocks2[j2 + 3] << 0; d2 = d2 << 30 | d2 >>> 2; f4 = c2 ^ d2 ^ e2; t2 = b2 << 5 | b2 >>> 27; a2 = t2 + f4 + a2 - 899497514 + blocks2[j2 + 4] << 0; c2 = c2 << 30 | c2 >>> 2; } this.h0 = this.h0 + a2 << 0; this.h1 = this.h1 + b2 << 0; this.h2 = this.h2 + c2 << 0; this.h3 = this.h3 + d2 << 0; this.h4 = this.h4 + e2 << 0; }; Sha1.prototype.hex = function() { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; return HEX_CHARS[h0 >> 28 & 15] + HEX_CHARS[h0 >> 24 & 15] + HEX_CHARS[h0 >> 20 & 15] + HEX_CHARS[h0 >> 16 & 15] + HEX_CHARS[h0 >> 12 & 15] + HEX_CHARS[h0 >> 8 & 15] + HEX_CHARS[h0 >> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >> 28 & 15] + HEX_CHARS[h1 >> 24 & 15] + HEX_CHARS[h1 >> 20 & 15] + HEX_CHARS[h1 >> 16 & 15] + HEX_CHARS[h1 >> 12 & 15] + HEX_CHARS[h1 >> 8 & 15] + HEX_CHARS[h1 >> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >> 28 & 15] + HEX_CHARS[h2 >> 24 & 15] + HEX_CHARS[h2 >> 20 & 15] + HEX_CHARS[h2 >> 16 & 15] + HEX_CHARS[h2 >> 12 & 15] + HEX_CHARS[h2 >> 8 & 15] + HEX_CHARS[h2 >> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >> 28 & 15] + HEX_CHARS[h3 >> 24 & 15] + HEX_CHARS[h3 >> 20 & 15] + HEX_CHARS[h3 >> 16 & 15] + HEX_CHARS[h3 >> 12 & 15] + HEX_CHARS[h3 >> 8 & 15] + HEX_CHARS[h3 >> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >> 28 & 15] + HEX_CHARS[h4 >> 24 & 15] + HEX_CHARS[h4 >> 20 & 15] + HEX_CHARS[h4 >> 16 & 15] + HEX_CHARS[h4 >> 12 & 15] + HEX_CHARS[h4 >> 8 & 15] + HEX_CHARS[h4 >> 4 & 15] + HEX_CHARS[h4 & 15]; }; Sha1.prototype.toString = Sha1.prototype.hex; Sha1.prototype.digest = function() { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; return [ h0 >> 24 & 255, h0 >> 16 & 255, h0 >> 8 & 255, h0 & 255, h1 >> 24 & 255, h1 >> 16 & 255, h1 >> 8 & 255, h1 & 255, h2 >> 24 & 255, h2 >> 16 & 255, h2 >> 8 & 255, h2 & 255, h3 >> 24 & 255, h3 >> 16 & 255, h3 >> 8 & 255, h3 & 255, h4 >> 24 & 255, h4 >> 16 & 255, h4 >> 8 & 255, h4 & 255 ]; }; Sha1.prototype.array = Sha1.prototype.digest; Sha1.prototype.arrayBuffer = function() { this.finalize(); var buffer = new ArrayBuffer(20); var dataView = new DataView(buffer); dataView.setUint32(0, this.h0); dataView.setUint32(4, this.h1); dataView.setUint32(8, this.h2); dataView.setUint32(12, this.h3); dataView.setUint32(16, this.h4); return buffer; }; insecureHash = (message) => { return new Sha1(true).update(message)["hex"](); }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/hash.js var hash_exports = {}; __export(hash_exports, { insecureHash: () => insecureHash }); var init_hash2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/hash.js"() { init_hash(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/caches.js var caches_exports = {}; __export(caches_exports, { BaseCache: () => BaseCache, InMemoryCache: () => InMemoryCache, deserializeStoredGeneration: () => deserializeStoredGeneration, getCacheKey: () => getCacheKey, serializeGeneration: () => serializeGeneration }); function deserializeStoredGeneration(storedGeneration) { if (storedGeneration.message !== void 0) { return { text: storedGeneration.text, message: mapStoredMessageToChatMessage(storedGeneration.message) }; } else { return { text: storedGeneration.text }; } } function serializeGeneration(generation) { const serializedValue = { text: generation.text }; if (generation.message !== void 0) { serializedValue.message = generation.message.toDict(); } return serializedValue; } var getCacheKey, BaseCache, GLOBAL_MAP, InMemoryCache; var init_caches = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/caches.js"() { init_hash2(); init_messages(); getCacheKey = (...strings) => insecureHash(strings.join("_")); BaseCache = class { }; GLOBAL_MAP = new Map(); InMemoryCache = class extends BaseCache { constructor(map2) { super(); Object.defineProperty(this, "cache", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.cache = map2 ?? new Map(); } lookup(prompt, llmKey) { return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null); } async update(prompt, llmKey, value) { this.cache.set(getCacheKey(prompt, llmKey), value); } static global() { return new InMemoryCache(GLOBAL_MAP); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/embeddings.js var embeddings_exports = {}; __export(embeddings_exports, { Embeddings: () => Embeddings }); var Embeddings; var init_embeddings = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/embeddings.js"() { init_async_caller2(); Embeddings = class { constructor(params) { Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.caller = new AsyncCaller2(params ?? {}); } }; } }); // node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js var require_base64_js = __commonJS({ "node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js"(exports2) { "use strict"; exports2.byteLength = byteLength; exports2.toByteArray = toByteArray; exports2.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (i2 = 0, len = code.length; i2 < len; ++i2) { lookup[i2] = code[i2]; revLookup[code.charCodeAt(i2)] = i2; } var i2; var len; revLookup["-".charCodeAt(0)] = 62; revLookup["_".charCodeAt(0)] = 63; function getLens(b64) { var len2 = b64.length; if (len2 % 4 > 0) { throw new Error("Invalid string. Length must be a multiple of 4"); } var validLen = b64.indexOf("="); if (validLen === -1) validLen = len2; var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; } function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function toByteArray(b64) { var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0; var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; var i3; for (i3 = 0; i3 < len2; i3 += 4) { tmp = revLookup[b64.charCodeAt(i3)] << 18 | revLookup[b64.charCodeAt(i3 + 1)] << 12 | revLookup[b64.charCodeAt(i3 + 2)] << 6 | revLookup[b64.charCodeAt(i3 + 3)]; arr[curByte++] = tmp >> 16 & 255; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 2) { tmp = revLookup[b64.charCodeAt(i3)] << 2 | revLookup[b64.charCodeAt(i3 + 1)] >> 4; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 1) { tmp = revLookup[b64.charCodeAt(i3)] << 10 | revLookup[b64.charCodeAt(i3 + 1)] << 4 | revLookup[b64.charCodeAt(i3 + 2)] >> 2; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i3 = start; i3 < end; i3 += 3) { tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255); output.push(tripletToBase64(tmp)); } return output.join(""); } function fromByteArray(uint8) { var tmp; var len2 = uint8.length; var extraBytes = len2 % 3; var parts = []; var maxChunkLength = 16383; for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) { parts.push(encodeChunk(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength)); } if (extraBytes === 1) { tmp = uint8[len2 - 1]; parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); } else if (extraBytes === 2) { tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); } return parts.join(""); } } }); // node_modules/.pnpm/js-tiktoken@1.0.10/node_modules/js-tiktoken/dist/chunk-HXW345QN.js function bytePairMerge(piece, ranks) { let parts = Array.from({ length: piece.length }, (_2, i2) => ({ start: i2, end: i2 + 1 })); while (parts.length > 1) { let minRank = null; for (let i2 = 0; i2 < parts.length - 1; i2++) { const slice = piece.slice(parts[i2].start, parts[i2 + 1].end); const rank = ranks.get(slice.join(",")); if (rank == null) continue; if (minRank == null || rank < minRank[0]) { minRank = [rank, i2]; } } if (minRank != null) { const i2 = minRank[1]; parts[i2] = { start: parts[i2].start, end: parts[i2 + 1].end }; parts.splice(i2 + 1, 1); } else { break; } } return parts; } function bytePairEncode(piece, ranks) { if (piece.length === 1) return [ranks.get(piece.join(","))]; return bytePairMerge(piece, ranks).map((p2) => ranks.get(piece.slice(p2.start, p2.end).join(","))).filter((x2) => x2 != null); } function escapeRegex(str3) { return str3.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); } function getEncodingNameForModel(model) { switch (model) { case "gpt2": { return "gpt2"; } case "code-cushman-001": case "code-cushman-002": case "code-davinci-001": case "code-davinci-002": case "cushman-codex": case "davinci-codex": case "davinci-002": case "text-davinci-002": case "text-davinci-003": { return "p50k_base"; } case "code-davinci-edit-001": case "text-davinci-edit-001": { return "p50k_edit"; } case "ada": case "babbage": case "babbage-002": case "code-search-ada-code-001": case "code-search-babbage-code-001": case "curie": case "davinci": case "text-ada-001": case "text-babbage-001": case "text-curie-001": case "text-davinci-001": case "text-search-ada-doc-001": case "text-search-babbage-doc-001": case "text-search-curie-doc-001": case "text-search-davinci-doc-001": case "text-similarity-ada-001": case "text-similarity-babbage-001": case "text-similarity-curie-001": case "text-similarity-davinci-001": { return "r50k_base"; } case "gpt-3.5-turbo-instruct-0914": case "gpt-3.5-turbo-instruct": case "gpt-3.5-turbo-16k-0613": case "gpt-3.5-turbo-16k": case "gpt-3.5-turbo-0613": case "gpt-3.5-turbo-0301": case "gpt-3.5-turbo": case "gpt-4-32k-0613": case "gpt-4-32k-0314": case "gpt-4-32k": case "gpt-4-0613": case "gpt-4-0314": case "gpt-4": case "gpt-3.5-turbo-1106": case "gpt-35-turbo": case "gpt-4-1106-preview": case "gpt-4-vision-preview": case "gpt-3.5-turbo-0125": case "gpt-4-turbo-preview": case "gpt-4-0125-preview": case "text-embedding-ada-002": { return "cl100k_base"; } default: throw new Error("Unknown model"); } } var import_base64_js, __defProp2, __defNormalProp2, __publicField2, _Tiktoken, Tiktoken; var init_chunk_HXW345QN = __esm({ "node_modules/.pnpm/js-tiktoken@1.0.10/node_modules/js-tiktoken/dist/chunk-HXW345QN.js"() { import_base64_js = __toModule(require_base64_js()); __defProp2 = Object.defineProperty; __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; __publicField2 = (obj, key, value) => { __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; _Tiktoken = class { constructor(ranks, extendedSpecialTokens) { __publicField(this, "specialTokens"); __publicField(this, "inverseSpecialTokens"); __publicField(this, "patStr"); __publicField(this, "textEncoder", new TextEncoder()); __publicField(this, "textDecoder", new TextDecoder("utf-8")); __publicField(this, "rankMap", /* @__PURE__ */ new Map()); __publicField(this, "textMap", /* @__PURE__ */ new Map()); this.patStr = ranks.pat_str; const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x2) => { const [_2, offsetStr, ...tokens] = x2.split(" "); const offset = Number.parseInt(offsetStr, 10); tokens.forEach((token, i2) => memo[token] = offset + i2); return memo; }, {}); for (const [token, rank] of Object.entries(uncompressed)) { const bytes = import_base64_js.default.toByteArray(token); this.rankMap.set(bytes.join(","), rank); this.textMap.set(rank, bytes); } this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { memo[rank] = this.textEncoder.encode(text); return memo; }, {}); } encode(text, allowedSpecial = [], disallowedSpecial = "all") { const regexes = new RegExp(this.patStr, "ug"); const specialRegex = _Tiktoken.specialTokenRegex(Object.keys(this.specialTokens)); const ret = []; const allowedSpecialSet = new Set(allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial); const disallowedSpecialSet = new Set(disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter((x2) => !allowedSpecialSet.has(x2)) : disallowedSpecial); if (disallowedSpecialSet.size > 0) { const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ ...disallowedSpecialSet ]); const specialMatch = text.match(disallowedSpecialRegex); if (specialMatch != null) { throw new Error(`The text contains a special token that is not allowed: ${specialMatch[0]}`); } } let start = 0; while (true) { let nextSpecial = null; let startFind = start; while (true) { specialRegex.lastIndex = startFind; nextSpecial = specialRegex.exec(text); if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) break; startFind = nextSpecial.index + 1; } const end = nextSpecial?.index ?? text.length; for (const match of text.substring(start, end).matchAll(regexes)) { const piece = this.textEncoder.encode(match[0]); const token2 = this.rankMap.get(piece.join(",")); if (token2 != null) { ret.push(token2); continue; } ret.push(...bytePairEncode(piece, this.rankMap)); } if (nextSpecial == null) break; let token = this.specialTokens[nextSpecial[0]]; ret.push(token); start = nextSpecial.index + nextSpecial[0].length; } return ret; } decode(tokens) { const res = []; let length = 0; for (let i22 = 0; i22 < tokens.length; ++i22) { const token = tokens[i22]; const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; if (bytes != null) { res.push(bytes); length += bytes.length; } } const mergedArray = new Uint8Array(length); let i2 = 0; for (const bytes of res) { mergedArray.set(bytes, i2); i2 += bytes.length; } return this.textDecoder.decode(mergedArray); } }; Tiktoken = _Tiktoken; __publicField2(Tiktoken, "specialTokenRegex", (tokens) => { return new RegExp(tokens.map((i2) => escapeRegex(i2)).join("|"), "g"); }); } }); // node_modules/.pnpm/js-tiktoken@1.0.10/node_modules/js-tiktoken/dist/lite.js var init_lite = __esm({ "node_modules/.pnpm/js-tiktoken@1.0.10/node_modules/js-tiktoken/dist/lite.js"() { init_chunk_HXW345QN(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/tiktoken.js var tiktoken_exports = {}; __export(tiktoken_exports, { encodingForModel: () => encodingForModel, getEncoding: () => getEncoding }); async function getEncoding(encoding) { if (!(encoding in cache)) { cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e2) => { delete cache[encoding]; throw e2; }); } return await cache[encoding]; } async function encodingForModel(model) { return getEncoding(getEncodingNameForModel(model)); } var cache, caller; var init_tiktoken = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/tiktoken.js"() { init_lite(); init_async_caller2(); cache = {}; caller = /* @__PURE__ */ new AsyncCaller2({}); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/language_models/base.js var base_exports3 = {}; __export(base_exports3, { BaseLangChain: () => BaseLangChain, BaseLanguageModel: () => BaseLanguageModel, calculateMaxTokens: () => calculateMaxTokens, getEmbeddingContextSize: () => getEmbeddingContextSize, getModelContextSize: () => getModelContextSize, getModelNameForTiktoken: () => getModelNameForTiktoken }); var getModelNameForTiktoken, getEmbeddingContextSize, getModelContextSize, calculateMaxTokens, getVerbosity, BaseLangChain, BaseLanguageModel; var init_base6 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/language_models/base.js"() { init_caches(); init_prompt_values(); init_messages(); init_async_caller2(); init_tiktoken(); init_base3(); getModelNameForTiktoken = (modelName) => { if (modelName.startsWith("gpt-3.5-turbo-16k")) { return "gpt-3.5-turbo-16k"; } if (modelName.startsWith("gpt-3.5-turbo-")) { return "gpt-3.5-turbo"; } if (modelName.startsWith("gpt-4-32k")) { return "gpt-4-32k"; } if (modelName.startsWith("gpt-4-")) { return "gpt-4"; } return modelName; }; getEmbeddingContextSize = (modelName) => { switch (modelName) { case "text-embedding-ada-002": return 8191; default: return 2046; } }; getModelContextSize = (modelName) => { switch (getModelNameForTiktoken(modelName)) { case "gpt-3.5-turbo-16k": return 16384; case "gpt-3.5-turbo": return 4096; case "gpt-4-32k": return 32768; case "gpt-4": return 8192; case "text-davinci-003": return 4097; case "text-curie-001": return 2048; case "text-babbage-001": return 2048; case "text-ada-001": return 2048; case "code-davinci-002": return 8e3; case "code-cushman-001": return 2048; default: return 4097; } }; calculateMaxTokens = async ({ prompt, modelName }) => { let numTokens; try { numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; } catch (error) { console.warn("Failed to calculate number of tokens, falling back to approximate count"); numTokens = Math.ceil(prompt.length / 4); } const maxTokens = getModelContextSize(modelName); return maxTokens - numTokens; }; getVerbosity = () => false; BaseLangChain = class extends Runnable { get lc_attributes() { return { callbacks: void 0, verbose: void 0 }; } constructor(params) { super(params); Object.defineProperty(this, "verbose", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "callbacks", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.verbose = params.verbose ?? getVerbosity(); this.callbacks = params.callbacks; this.tags = params.tags ?? []; this.metadata = params.metadata ?? {}; } }; BaseLanguageModel = class extends BaseLangChain { get callKeys() { return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; } constructor({ callbacks, callbackManager, ...params }) { super({ callbacks: callbacks ?? callbackManager, ...params }); Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "cache", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "_encoding", { enumerable: true, configurable: true, writable: true, value: void 0 }); if (typeof params.cache === "object") { this.cache = params.cache; } else if (params.cache) { this.cache = InMemoryCache.global(); } else { this.cache = void 0; } this.caller = new AsyncCaller2(params ?? {}); } async getNumTokens(content) { if (typeof content !== "string") { return 0; } let numTokens = Math.ceil(content.length / 4); if (!this._encoding) { try { this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); } catch (error) { console.warn("Failed to calculate number of tokens, falling back to approximate count", error); } } if (this._encoding) { try { numTokens = this._encoding.encode(content).length; } catch (error) { console.warn("Failed to calculate number of tokens, falling back to approximate count", error); } } return numTokens; } static _convertInputToPromptValue(input) { if (typeof input === "string") { return new StringPromptValue(input); } else if (Array.isArray(input)) { return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); } else { return input; } } _identifyingParams() { return {}; } _getSerializedCacheKeyParametersForCall(callOptions) { const params = { ...this._identifyingParams(), ...callOptions, _type: this._llmType(), _model: this._modelType() }; const filteredEntries = Object.entries(params).filter(([_2, value]) => value !== void 0); const serializedEntries = filteredEntries.map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); return serializedEntries; } serialize() { return { ...this._identifyingParams(), _type: this._llmType(), _model: this._modelType() }; } static async deserialize(_data) { throw new Error("Use .toJSON() instead"); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/outputs.js var outputs_exports = {}; __export(outputs_exports, { ChatGenerationChunk: () => ChatGenerationChunk, GenerationChunk: () => GenerationChunk, RUN_KEY: () => RUN_KEY }); var RUN_KEY, GenerationChunk, ChatGenerationChunk; var init_outputs = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/outputs.js"() { RUN_KEY = "__run"; GenerationChunk = class { constructor(fields2) { Object.defineProperty(this, "text", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "generationInfo", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.text = fields2.text; this.generationInfo = fields2.generationInfo; } concat(chunk) { return new GenerationChunk({ text: this.text + chunk.text, generationInfo: { ...this.generationInfo, ...chunk.generationInfo } }); } }; ChatGenerationChunk = class extends GenerationChunk { constructor(fields2) { super(fields2); Object.defineProperty(this, "message", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.message = fields2.message; } concat(chunk) { return new ChatGenerationChunk({ text: this.text + chunk.text, generationInfo: { ...this.generationInfo, ...chunk.generationInfo }, message: this.message.concat(chunk.message) }); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/language_models/chat_models.js var chat_models_exports = {}; __export(chat_models_exports, { BaseChatModel: () => BaseChatModel, SimpleChatModel: () => SimpleChatModel, createChatMessageChunkEncoderStream: () => createChatMessageChunkEncoderStream }); function createChatMessageChunkEncoderStream() { const textEncoder = new TextEncoder(); return new TransformStream({ transform(chunk, controller) { controller.enqueue(textEncoder.encode(typeof chunk.content === "string" ? chunk.content : JSON.stringify(chunk.content))); } }); } var BaseChatModel, SimpleChatModel; var init_chat_models = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/language_models/chat_models.js"() { init_messages(); init_outputs(); init_base6(); init_manager(); BaseChatModel = class extends BaseLanguageModel { constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "chat_models", this._llmType()] }); } _separateRunnableConfigFromCallOptions(options) { const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); if (callOptions?.timeout && !callOptions.signal) { callOptions.signal = AbortSignal.timeout(callOptions.timeout); } return [runnableConfig, callOptions]; } async invoke(input, options) { const promptValue = BaseChatModel._convertInputToPromptValue(input); const result = await this.generatePrompt([promptValue], options, options?.callbacks); const chatGeneration = result.generations[0][0]; return chatGeneration.message; } async *_streamResponseChunks(_messages, _options, _runManager) { throw new Error("Not implemented."); } async *_streamIterator(input, options) { if (this._streamResponseChunks === BaseChatModel.prototype._streamResponseChunks) { yield this.invoke(input, options); } else { const prompt = BaseChatModel._convertInputToPromptValue(input); const messages4 = prompt.toChatMessages(); const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); const extra = { options: callOptions, invocation_params: this?.invocationParams(callOptions), batch_size: 1 }; const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [messages4], void 0, void 0, extra, void 0, void 0, runnableConfig.runName); let generationChunk; try { for await (const chunk of this._streamResponseChunks(messages4, callOptions, runManagers?.[0])) { chunk.message.response_metadata = { ...chunk.generationInfo, ...chunk.message.response_metadata }; yield chunk.message; if (!generationChunk) { generationChunk = chunk; } else { generationChunk = generationChunk.concat(chunk); } } } catch (err) { await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); throw err; } await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generationChunk]] }))); } } async _generateUncached(messages4, parsedOptions, handledOptions) { const baseMessages = messages4.map((messageList) => messageList.map(coerceMessageLikeToMessage)); const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); const extra = { options: parsedOptions, invocation_params: this?.invocationParams(parsedOptions), batch_size: 1 }; const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, void 0, void 0, extra, void 0, void 0, handledOptions.runName); const results = await Promise.allSettled(baseMessages.map((messageList, i2) => this._generate(messageList, { ...parsedOptions, promptIndex: i2 }, runManagers?.[i2]))); const generations = []; const llmOutputs = []; await Promise.all(results.map(async (pResult, i2) => { if (pResult.status === "fulfilled") { const result = pResult.value; for (const generation of result.generations) { generation.message.response_metadata = { ...generation.generationInfo, ...generation.message.response_metadata }; } if (result.generations.length === 1) { result.generations[0].message.response_metadata = { ...result.llmOutput, ...result.generations[0].message.response_metadata }; } generations[i2] = result.generations; llmOutputs[i2] = result.llmOutput; return runManagers?.[i2]?.handleLLMEnd({ generations: [result.generations], llmOutput: result.llmOutput }); } else { await runManagers?.[i2]?.handleLLMError(pResult.reason); return Promise.reject(pResult.reason); } })); const output = { generations, llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : void 0 }; Object.defineProperty(output, RUN_KEY, { value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, configurable: true }); return output; } async _generateCached({ messages: messages4, cache: cache2, llmStringKey, parsedOptions, handledOptions }) { const baseMessages = messages4.map((messageList) => messageList.map(coerceMessageLikeToMessage)); const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); const extra = { options: parsedOptions, invocation_params: this?.invocationParams(parsedOptions), batch_size: 1, cached: true }; const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, void 0, void 0, extra, void 0, void 0, handledOptions.runName); const missingPromptIndices = []; const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index2) => { const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); const result = await cache2.lookup(prompt, llmStringKey); if (result == null) { missingPromptIndices.push(index2); } return result; })); const cachedResults = results.map((result, index2) => ({ result, runManager: runManagers?.[index2] })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); const generations = []; await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i2) => { if (promiseResult.status === "fulfilled") { const result = promiseResult.value; generations[i2] = result; if (result.length) { await runManager?.handleLLMNewToken(result[0].text); } return runManager?.handleLLMEnd({ generations: [result] }); } else { await runManager?.handleLLMError(promiseResult.reason); return Promise.reject(promiseResult.reason); } })); const output = { generations, missingPromptIndices }; Object.defineProperty(output, RUN_KEY, { value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, configurable: true }); return output; } async generate(messages4, options, callbacks) { let parsedOptions; if (Array.isArray(options)) { parsedOptions = { stop: options }; } else { parsedOptions = options; } const baseMessages = messages4.map((messageList) => messageList.map(coerceMessageLikeToMessage)); const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; if (!this.cache) { return this._generateUncached(baseMessages, callOptions, runnableConfig); } const { cache: cache2 } = this; const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); const { generations, missingPromptIndices } = await this._generateCached({ messages: baseMessages, cache: cache2, llmStringKey, parsedOptions: callOptions, handledOptions: runnableConfig }); let llmOutput = {}; if (missingPromptIndices.length > 0) { const results = await this._generateUncached(missingPromptIndices.map((i2) => baseMessages[i2]), callOptions, runnableConfig); await Promise.all(results.generations.map(async (generation, index2) => { const promptIndex = missingPromptIndices[index2]; generations[promptIndex] = generation; const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); return cache2.update(prompt, llmStringKey, generation); })); llmOutput = results.llmOutput ?? {}; } return { generations, llmOutput }; } invocationParams(_options) { return {}; } _modelType() { return "base_chat_model"; } serialize() { return { ...this.invocationParams(), _type: this._llmType(), _model: this._modelType() }; } async generatePrompt(promptValues, options, callbacks) { const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); return this.generate(promptMessages, options, callbacks); } async call(messages4, options, callbacks) { const result = await this.generate([messages4.map(coerceMessageLikeToMessage)], options, callbacks); const generations = result.generations; return generations[0][0].message; } async callPrompt(promptValue, options, callbacks) { const promptMessages = promptValue.toChatMessages(); return this.call(promptMessages, options, callbacks); } async predictMessages(messages4, options, callbacks) { return this.call(messages4, options, callbacks); } async predict(text, options, callbacks) { const message = new HumanMessage(text); const result = await this.call([message], options, callbacks); if (typeof result.content !== "string") { throw new Error("Cannot use predict when output is not a string."); } return result.content; } }; SimpleChatModel = class extends BaseChatModel { async _generate(messages4, options, runManager) { const text = await this._call(messages4, options, runManager); const message = new AIMessage(text); if (typeof message.content !== "string") { throw new Error("Cannot generate with a simple chat model when output is not a string."); } return { generations: [ { text: message.content, message } ] }; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/language_models/llms.js var llms_exports = {}; __export(llms_exports, { BaseLLM: () => BaseLLM, LLM: () => LLM }); var BaseLLM, LLM; var init_llms = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/language_models/llms.js"() { init_messages(); init_outputs(); init_manager(); init_base6(); BaseLLM = class extends BaseLanguageModel { constructor({ concurrency, ...rest }) { super(concurrency ? { maxConcurrency: concurrency, ...rest } : rest); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "llms", this._llmType()] }); } async invoke(input, options) { const promptValue = BaseLLM._convertInputToPromptValue(input); const result = await this.generatePrompt([promptValue], options, options?.callbacks); return result.generations[0][0].text; } async *_streamResponseChunks(_input, _options, _runManager) { throw new Error("Not implemented."); } _separateRunnableConfigFromCallOptions(options) { const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); if (callOptions?.timeout && !callOptions.signal) { callOptions.signal = AbortSignal.timeout(callOptions.timeout); } return [runnableConfig, callOptions]; } async *_streamIterator(input, options) { if (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) { yield this.invoke(input, options); } else { const prompt = BaseLLM._convertInputToPromptValue(input); const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); const extra = { options: callOptions, invocation_params: this?.invocationParams(callOptions), batch_size: 1 }; const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], void 0, void 0, extra, void 0, void 0, runnableConfig.runName); let generation = new GenerationChunk({ text: "" }); try { for await (const chunk of this._streamResponseChunks(input.toString(), callOptions, runManagers?.[0])) { if (!generation) { generation = chunk; } else { generation = generation.concat(chunk); } if (typeof chunk.text === "string") { yield chunk.text; } } } catch (err) { await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); throw err; } await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generation]] }))); } } async generatePrompt(promptValues, options, callbacks) { const prompts = promptValues.map((promptValue) => promptValue.toString()); return this.generate(prompts, options, callbacks); } invocationParams(_options) { return {}; } _flattenLLMResult(llmResult) { const llmResults = []; for (let i2 = 0; i2 < llmResult.generations.length; i2 += 1) { const genList = llmResult.generations[i2]; if (i2 === 0) { llmResults.push({ generations: [genList], llmOutput: llmResult.llmOutput }); } else { const llmOutput = llmResult.llmOutput ? { ...llmResult.llmOutput, tokenUsage: {} } : void 0; llmResults.push({ generations: [genList], llmOutput }); } } return llmResults; } async _generateUncached(prompts, parsedOptions, handledOptions) { const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); const extra = { options: parsedOptions, invocation_params: this?.invocationParams(parsedOptions), batch_size: prompts.length }; const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, void 0, void 0, extra, void 0, void 0, handledOptions?.runName); let output; try { output = await this._generate(prompts, parsedOptions, runManagers?.[0]); } catch (err) { await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); throw err; } const flattenedOutputs = this._flattenLLMResult(output); await Promise.all((runManagers ?? []).map((runManager, i2) => runManager?.handleLLMEnd(flattenedOutputs[i2]))); const runIds = runManagers?.map((manager) => manager.runId) || void 0; Object.defineProperty(output, RUN_KEY, { value: runIds ? { runIds } : void 0, configurable: true }); return output; } async _generateCached({ prompts, cache: cache2, llmStringKey, parsedOptions, handledOptions }) { const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); const extra = { options: parsedOptions, invocation_params: this?.invocationParams(parsedOptions), batch_size: prompts.length, cached: true }; const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, void 0, void 0, extra, void 0, void 0, handledOptions?.runName); const missingPromptIndices = []; const results = await Promise.allSettled(prompts.map(async (prompt, index2) => { const result = await cache2.lookup(prompt, llmStringKey); if (result == null) { missingPromptIndices.push(index2); } return result; })); const cachedResults = results.map((result, index2) => ({ result, runManager: runManagers?.[index2] })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); const generations = []; await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i2) => { if (promiseResult.status === "fulfilled") { const result = promiseResult.value; generations[i2] = result; if (result.length) { await runManager?.handleLLMNewToken(result[0].text); } return runManager?.handleLLMEnd({ generations: [result] }); } else { await runManager?.handleLLMError(promiseResult.reason); return Promise.reject(promiseResult.reason); } })); const output = { generations, missingPromptIndices }; Object.defineProperty(output, RUN_KEY, { value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, configurable: true }); return output; } async generate(prompts, options, callbacks) { if (!Array.isArray(prompts)) { throw new Error("Argument 'prompts' is expected to be a string[]"); } let parsedOptions; if (Array.isArray(options)) { parsedOptions = { stop: options }; } else { parsedOptions = options; } const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; if (!this.cache) { return this._generateUncached(prompts, callOptions, runnableConfig); } const { cache: cache2 } = this; const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); const { generations, missingPromptIndices } = await this._generateCached({ prompts, cache: cache2, llmStringKey, parsedOptions: callOptions, handledOptions: runnableConfig }); let llmOutput = {}; if (missingPromptIndices.length > 0) { const results = await this._generateUncached(missingPromptIndices.map((i2) => prompts[i2]), callOptions, runnableConfig); await Promise.all(results.generations.map(async (generation, index2) => { const promptIndex = missingPromptIndices[index2]; generations[promptIndex] = generation; return cache2.update(prompts[promptIndex], llmStringKey, generation); })); llmOutput = results.llmOutput ?? {}; } return { generations, llmOutput }; } async call(prompt, options, callbacks) { const { generations } = await this.generate([prompt], options, callbacks); return generations[0][0].text; } async predict(text, options, callbacks) { return this.call(text, options, callbacks); } async predictMessages(messages4, options, callbacks) { const text = getBufferString(messages4); const prediction = await this.call(text, options, callbacks); return new AIMessage(prediction); } _identifyingParams() { return {}; } serialize() { return { ...this._identifyingParams(), _type: this._llmType(), _model: this._modelType() }; } _modelType() { return "base_llm"; } }; LLM = class extends BaseLLM { async _generate(prompts, options, runManager) { const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { ...options, promptIndex }, runManager).then((text) => [{ text }]))); return { generations }; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/passthrough.js var RunnablePassthrough; var init_passthrough = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/passthrough.js"() { init_stream(); init_base3(); init_config(); RunnablePassthrough = class extends Runnable { static lc_name() { return "RunnablePassthrough"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); if (fields2) { this.func = fields2.func; } } async invoke(input, options) { const config = ensureConfig(options); if (this.func) { await this.func(input, config); } return this._callWithConfig((input2) => Promise.resolve(input2), input, config); } async *transform(generator, options) { const config = ensureConfig(options); let finalOutput; let finalOutputSupported = true; for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { yield chunk; if (finalOutputSupported) { if (finalOutput === void 0) { finalOutput = chunk; } else { try { finalOutput = concat(finalOutput, chunk); } catch { finalOutput = void 0; finalOutputSupported = false; } } } } if (this.func && finalOutput !== void 0) { await this.func(finalOutput, config); } } static assign(mapping) { return new RunnableAssign(new RunnableMap({ steps: mapping })); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/router.js var RouterRunnable; var init_router = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/router.js"() { init_base3(); init_config(); RouterRunnable = class extends Runnable { static lc_name() { return "RouterRunnable"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "runnables", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.runnables = fields2.runnables; } async invoke(input, options) { const { key, input: actualInput } = input; const runnable = this.runnables[key]; if (runnable === void 0) { throw new Error(`No runnable associated with key "${key}".`); } return runnable.invoke(actualInput, ensureConfig(options)); } async batch(inputs, options, batchOptions) { const keys = inputs.map((input) => input.key); const actualInputs = inputs.map((input) => input.input); const missingKey = keys.find((key) => this.runnables[key] === void 0); if (missingKey !== void 0) { throw new Error(`One or more keys do not have a corresponding runnable.`); } const runnables = keys.map((key) => this.runnables[key]); const optionsList2 = this._getOptionsList(options ?? {}, inputs.length); const maxConcurrency = optionsList2[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; const batchResults = []; for (let i2 = 0; i2 < actualInputs.length; i2 += batchSize) { const batchPromises = actualInputs.slice(i2, i2 + batchSize).map((actualInput, i3) => runnables[i3].invoke(actualInput, optionsList2[i3])); const batchResult = await Promise.all(batchPromises); batchResults.push(batchResult); } return batchResults.flat(); } async stream(input, options) { const { key, input: actualInput } = input; const runnable = this.runnables[key]; if (runnable === void 0) { throw new Error(`No runnable associated with key "${key}".`); } return runnable.stream(actualInput, options); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/branch.js var RunnableBranch; var init_branch = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/branch.js"() { init_base3(); init_config(); init_stream(); RunnableBranch = class extends Runnable { static lc_name() { return "RunnableBranch"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "default", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "branches", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.branches = fields2.branches; this.default = fields2.default; } static from(branches) { if (branches.length < 1) { throw new Error("RunnableBranch requires at least one branch"); } const branchLikes = branches.slice(0, -1); const coercedBranches = branchLikes.map(([condition, runnable]) => [ _coerceToRunnable(condition), _coerceToRunnable(runnable) ]); const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); return new this({ branches: coercedBranches, default: defaultBranch }); } async _invoke(input, config, runManager) { let result; for (let i2 = 0; i2 < this.branches.length; i2 += 1) { const [condition, branchRunnable] = this.branches[i2]; const conditionValue = await condition.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`condition:${i2 + 1}`) })); if (conditionValue) { result = await branchRunnable.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`branch:${i2 + 1}`) })); break; } } if (!result) { result = await this.default.invoke(input, patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); } return result; } async invoke(input, config = {}) { return this._callWithConfig(this._invoke, input, config); } async *_streamIterator(input, config) { const callbackManager_ = await getCallbackManagerForConfig(config); const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), void 0, void 0, void 0, void 0, config?.runName); let finalOutput; let finalOutputSupported = true; let stream; try { for (let i2 = 0; i2 < this.branches.length; i2 += 1) { const [condition, branchRunnable] = this.branches[i2]; const conditionValue = await condition.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`condition:${i2 + 1}`) })); if (conditionValue) { stream = await branchRunnable.stream(input, patchConfig(config, { callbacks: runManager?.getChild(`branch:${i2 + 1}`) })); for await (const chunk of stream) { yield chunk; if (finalOutputSupported) { if (finalOutput === void 0) { finalOutput = chunk; } else { try { finalOutput = concat(finalOutput, chunk); } catch (e2) { finalOutput = void 0; finalOutputSupported = false; } } } } break; } } if (stream === void 0) { stream = await this.default.stream(input, patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); for await (const chunk of stream) { yield chunk; if (finalOutputSupported) { if (finalOutput === void 0) { finalOutput = chunk; } else { try { finalOutput = concat(finalOutput, chunk); } catch (e2) { finalOutput = void 0; finalOutputSupported = false; } } } } } } catch (e2) { await runManager?.handleChainError(e2); throw e2; } await runManager?.handleChainEnd(finalOutput ?? {}); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/history.js var RunnableWithMessageHistory; var init_history = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/history.js"() { init_messages(); init_base3(); init_passthrough(); RunnableWithMessageHistory = class extends RunnableBinding { constructor(fields2) { let historyChain = new RunnableLambda({ func: (input, options) => this._enterHistory(input, options ?? {}) }).withConfig({ runName: "loadHistory" }); const messagesKey = fields2.historyMessagesKey ?? fields2.inputMessagesKey; if (messagesKey) { historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: "insertHistory" }); } const bound = historyChain.pipe(fields2.runnable.withListeners({ onEnd: (run, config2) => this._exitHistory(run, config2 ?? {}) })).withConfig({ runName: "RunnableWithMessageHistory" }); const config = fields2.config ?? {}; super({ ...fields2, config, bound }); Object.defineProperty(this, "runnable", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputMessagesKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputMessagesKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "historyMessagesKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "getMessageHistory", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.runnable = fields2.runnable; this.getMessageHistory = fields2.getMessageHistory; this.inputMessagesKey = fields2.inputMessagesKey; this.outputMessagesKey = fields2.outputMessagesKey; this.historyMessagesKey = fields2.historyMessagesKey; } _getInputMessages(inputValue) { if (typeof inputValue === "string") { return [new HumanMessage(inputValue)]; } else if (Array.isArray(inputValue)) { return inputValue; } else { return [inputValue]; } } _getOutputMessages(outputValue) { let newOutputValue = outputValue; if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { newOutputValue = outputValue[this.outputMessagesKey ?? "output"]; } if (typeof newOutputValue === "string") { return [new AIMessage(newOutputValue)]; } else if (Array.isArray(newOutputValue)) { return newOutputValue; } else if (isBaseMessage(newOutputValue)) { return [newOutputValue]; } throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(newOutputValue, null, 2)}`); } async _enterHistory(input, kwargs) { const history = kwargs?.config?.configurable?.messageHistory; if (this.historyMessagesKey) { return history.getMessages(); } const inputVal = input || (this.inputMessagesKey ? input[this.inputMessagesKey] : void 0); const historyMessages = history ? await history.getMessages() : []; const returnType = [ ...historyMessages, ...this._getInputMessages(inputVal) ]; return returnType; } async _exitHistory(run, config) { const history = config.configurable?.messageHistory; const { inputs } = run; const inputValue = inputs[this.inputMessagesKey ?? "input"]; const inputMessages = this._getInputMessages(inputValue); const outputValue = run.outputs; if (!outputValue) { throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); } const outputMessages = this._getOutputMessages(outputValue); for await (const message of [...inputMessages, ...outputMessages]) { await history.addMessage(message); } } async _mergeConfig(...configs) { const config = await super._mergeConfig(...configs); if (!config.configurable || !config.configurable.sessionId) { const exampleInput = { [this.inputMessagesKey ?? "input"]: "foo" }; const exampleConfig = { configurable: { sessionId: "123" } }; throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream() eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); } const { sessionId } = config.configurable; config.configurable.messageHistory = await this.getMessageHistory(sessionId); return config; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/index.js var runnables_exports = {}; __export(runnables_exports, { RouterRunnable: () => RouterRunnable, Runnable: () => Runnable, RunnableAssign: () => RunnableAssign, RunnableBinding: () => RunnableBinding, RunnableBranch: () => RunnableBranch, RunnableEach: () => RunnableEach, RunnableLambda: () => RunnableLambda, RunnableMap: () => RunnableMap, RunnableParallel: () => RunnableParallel, RunnablePassthrough: () => RunnablePassthrough, RunnablePick: () => RunnablePick, RunnableRetry: () => RunnableRetry, RunnableSequence: () => RunnableSequence, RunnableWithFallbacks: () => RunnableWithFallbacks, RunnableWithMessageHistory: () => RunnableWithMessageHistory, _coerceToRunnable: () => _coerceToRunnable, ensureConfig: () => ensureConfig, getCallbackManagerForConfig: () => getCallbackManagerForConfig, patchConfig: () => patchConfig }); var init_runnables = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/runnables/index.js"() { init_base3(); init_config(); init_passthrough(); init_router(); init_branch(); init_history(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/base.js var BaseLLMOutputParser, BaseOutputParser, OutputParserException; var init_base7 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/base.js"() { init_runnables(); BaseLLMOutputParser = class extends Runnable { parseResultWithPrompt(generations, _prompt, callbacks) { return this.parseResult(generations, callbacks); } _baseMessageToString(message) { return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); } _baseMessageContentToString(content) { return JSON.stringify(content); } async invoke(input, options) { if (typeof input === "string") { return this._callWithConfig(async (input2, options2) => this.parseResult([{ text: input2 }], options2?.callbacks), input, { ...options, runType: "parser" }); } else { return this._callWithConfig(async (input2, options2) => this.parseResult([ { message: input2, text: this._baseMessageToString(input2) } ], options2?.callbacks), input, { ...options, runType: "parser" }); } } }; BaseOutputParser = class extends BaseLLMOutputParser { parseResult(generations, callbacks) { return this.parse(generations[0].text, callbacks); } async parseWithPrompt(text, _prompt, callbacks) { return this.parse(text, callbacks); } _type() { throw new Error("_type not implemented"); } }; OutputParserException = class extends Error { constructor(message, llmOutput, observation, sendToLLM = false) { super(message); Object.defineProperty(this, "llmOutput", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "observation", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "sendToLLM", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.llmOutput = llmOutput; this.observation = observation; this.sendToLLM = sendToLLM; if (sendToLLM) { if (observation === void 0 || llmOutput === void 0) { throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); } } } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/deep-compare-strict.js function deepCompareStrict(a2, b2) { const typeofa = typeof a2; if (typeofa !== typeof b2) { return false; } if (Array.isArray(a2)) { if (!Array.isArray(b2)) { return false; } const length = a2.length; if (length !== b2.length) { return false; } for (let i2 = 0; i2 < length; i2++) { if (!deepCompareStrict(a2[i2], b2[i2])) { return false; } } return true; } if (typeofa === "object") { if (!a2 || !b2) { return a2 === b2; } const aKeys = Object.keys(a2); const bKeys = Object.keys(b2); const length = aKeys.length; if (length !== bKeys.length) { return false; } for (const k2 of aKeys) { if (!deepCompareStrict(a2[k2], b2[k2])) { return false; } } return true; } return a2 === b2; } var init_deep_compare_strict = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/deep-compare-strict.js"() { } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/pointer.js function encodePointer(p2) { return encodeURI(escapePointer(p2)); } function escapePointer(p2) { return p2.replace(/~/g, "~0").replace(/\//g, "~1"); } var init_pointer = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/pointer.js"() { } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/dereference.js function dereference(schema3, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = "") { if (schema3 && typeof schema3 === "object" && !Array.isArray(schema3)) { const id2 = schema3.$id || schema3.id; if (id2) { const url = new URL(id2, baseURI.href); if (url.hash.length > 1) { lookup[url.href] = schema3; } else { url.hash = ""; if (basePointer === "") { baseURI = url; } else { dereference(schema3, lookup, baseURI); } } } } else if (schema3 !== true && schema3 !== false) { return lookup; } const schemaURI = baseURI.href + (basePointer ? "#" + basePointer : ""); if (lookup[schemaURI] !== void 0) { throw new Error(`Duplicate schema URI "${schemaURI}".`); } lookup[schemaURI] = schema3; if (schema3 === true || schema3 === false) { return lookup; } if (schema3.__absolute_uri__ === void 0) { Object.defineProperty(schema3, "__absolute_uri__", { enumerable: false, value: schemaURI }); } if (schema3.$ref && schema3.__absolute_ref__ === void 0) { const url = new URL(schema3.$ref, baseURI.href); url.hash = url.hash; Object.defineProperty(schema3, "__absolute_ref__", { enumerable: false, value: url.href }); } if (schema3.$recursiveRef && schema3.__absolute_recursive_ref__ === void 0) { const url = new URL(schema3.$recursiveRef, baseURI.href); url.hash = url.hash; Object.defineProperty(schema3, "__absolute_recursive_ref__", { enumerable: false, value: url.href }); } if (schema3.$anchor) { const url = new URL("#" + schema3.$anchor, baseURI.href); lookup[url.href] = schema3; } for (let key in schema3) { if (ignoredKeyword[key]) { continue; } const keyBase = `${basePointer}/${encodePointer(key)}`; const subSchema = schema3[key]; if (Array.isArray(subSchema)) { if (schemaArrayKeyword[key]) { const length = subSchema.length; for (let i2 = 0; i2 < length; i2++) { dereference(subSchema[i2], lookup, baseURI, `${keyBase}/${i2}`); } } } else if (schemaMapKeyword[key]) { for (let subKey in subSchema) { dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); } } else { dereference(subSchema, lookup, baseURI, keyBase); } } return lookup; } var schemaArrayKeyword, schemaMapKeyword, ignoredKeyword, initialBaseURI; var init_dereference = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/dereference.js"() { init_pointer(); schemaArrayKeyword = { prefixItems: true, items: true, allOf: true, anyOf: true, oneOf: true }; schemaMapKeyword = { $defs: true, definitions: true, properties: true, patternProperties: true, dependentSchemas: true }; ignoredKeyword = { id: true, $id: true, $ref: true, $schema: true, $anchor: true, $vocabulary: true, $comment: true, default: true, enum: true, const: true, required: true, type: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? /* @__PURE__ */ new URL(self.location.origin + self.location.pathname + location.search) : /* @__PURE__ */ new URL("https://github.com/cfworker"); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/format.js function bind(r3) { return r3.test.bind(r3); } function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function date(str3) { const matches = str3.match(DATE); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); } function time(full, str3) { const matches = str3.match(TIME); if (!matches) return false; const hour = +matches[1]; const minute = +matches[2]; const second = +matches[3]; const timeZone = !!matches[5]; return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone); } function date_time(str3) { const dateTime = str3.split(DATE_TIME_SEPARATOR); return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); } function uri(str3) { return NOT_URI_FRAGMENT.test(str3) && URI_PATTERN.test(str3); } function regex(str3) { if (Z_ANCHOR.test(str3)) return false; try { new RegExp(str3); return true; } catch (e2) { return false; } } var DATE, DAYS, TIME, HOSTNAME, URIREF, URITEMPLATE, URL_, UUID, JSON_POINTER, JSON_POINTER_URI_FRAGMENT, RELATIVE_JSON_POINTER, FASTDATE, FASTTIME, FASTDATETIME, FASTURIREFERENCE, EMAIL, IPV4, IPV6, DURATION, fullFormat, fastFormat, DATE_TIME_SEPARATOR, NOT_URI_FRAGMENT, URI_PATTERN, Z_ANCHOR; var init_format = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/format.js"() { DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; FASTDATE = /^\d\d\d\d-[0-1]\d-[0-3]\d$/; FASTTIME = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i; FASTDATETIME = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i; FASTURIREFERENCE = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i; EMAIL = (input) => { if (input[0] === '"') return false; const [name2, host, ...rest] = input.split("@"); if (!name2 || !host || rest.length !== 0 || name2.length > 64 || host.length > 253) return false; if (name2[0] === "." || name2.endsWith(".") || name2.includes("..")) return false; if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name2)) return false; return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); }; IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input)); fullFormat = { date, time: /* @__PURE__ */ time.bind(void 0, false), "date-time": date_time, duration: DURATION, uri, "uri-reference": /* @__PURE__ */ bind(URIREF), "uri-template": /* @__PURE__ */ bind(URITEMPLATE), url: /* @__PURE__ */ bind(URL_), email: EMAIL, hostname: /* @__PURE__ */ bind(HOSTNAME), ipv4: /* @__PURE__ */ bind(IPV4), ipv6: /* @__PURE__ */ bind(IPV6), regex, uuid: /* @__PURE__ */ bind(UUID), "json-pointer": /* @__PURE__ */ bind(JSON_POINTER), "json-pointer-uri-fragment": /* @__PURE__ */ bind(JSON_POINTER_URI_FRAGMENT), "relative-json-pointer": /* @__PURE__ */ bind(RELATIVE_JSON_POINTER) }; fastFormat = { ...fullFormat, date: /* @__PURE__ */ bind(FASTDATE), time: /* @__PURE__ */ bind(FASTTIME), "date-time": /* @__PURE__ */ bind(FASTDATETIME), "uri-reference": /* @__PURE__ */ bind(FASTURIREFERENCE) }; DATE_TIME_SEPARATOR = /t|\s/i; NOT_URI_FRAGMENT = /\/|:/; URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; Z_ANCHOR = /[^\\]\\Z/; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/types.js var init_types = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/types.js"() { } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/ucs2-length.js function ucs2length(s2) { let result = 0; let length = s2.length; let index2 = 0; let charCode; while (index2 < length) { result++; charCode = s2.charCodeAt(index2++); if (charCode >= 55296 && charCode <= 56319 && index2 < length) { charCode = s2.charCodeAt(index2); if ((charCode & 64512) == 56320) { index2++; } } } return result; } var init_ucs2_length = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/ucs2-length.js"() { } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validate.js function validate3(instance, schema3, draft = "2019-09", lookup = dereference(schema3), shortCircuit = true, recursiveAnchor = null, instanceLocation = "#", schemaLocation = "#", evaluated = Object.create(null)) { if (schema3 === true) { return { valid: true, errors: [] }; } if (schema3 === false) { return { valid: false, errors: [ { instanceLocation, keyword: "false", keywordLocation: instanceLocation, error: "False boolean schema." } ] }; } const rawInstanceType = typeof instance; let instanceType; switch (rawInstanceType) { case "boolean": case "number": case "string": instanceType = rawInstanceType; break; case "object": if (instance === null) { instanceType = "null"; } else if (Array.isArray(instance)) { instanceType = "array"; } else { instanceType = "object"; } break; default: throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); } const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema3; const errors = []; if ($recursiveAnchor === true && recursiveAnchor === null) { recursiveAnchor = schema3; } if ($recursiveRef === "#") { const refSchema = recursiveAnchor === null ? lookup[__absolute_recursive_ref__] : recursiveAnchor; const keywordLocation = `${schemaLocation}/$recursiveRef`; const result = validate3(instance, recursiveAnchor === null ? schema3 : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); if (!result.valid) { errors.push({ instanceLocation, keyword: "$recursiveRef", keywordLocation, error: "A subschema had errors." }, ...result.errors); } } if ($ref !== void 0) { const uri2 = __absolute_ref__ || $ref; const refSchema = lookup[uri2]; if (refSchema === void 0) { let message = `Unresolved $ref "${$ref}".`; if (__absolute_ref__ && __absolute_ref__ !== $ref) { message += ` Absolute URI "${__absolute_ref__}".`; } message += ` Known schemas: - ${Object.keys(lookup).join("\n- ")}`; throw new Error(message); } const keywordLocation = `${schemaLocation}/$ref`; const result = validate3(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); if (!result.valid) { errors.push({ instanceLocation, keyword: "$ref", keywordLocation, error: "A subschema had errors." }, ...result.errors); } if (draft === "4" || draft === "7") { return { valid: errors.length === 0, errors }; } } if (Array.isArray($type)) { let length = $type.length; let valid = false; for (let i2 = 0; i2 < length; i2++) { if (instanceType === $type[i2] || $type[i2] === "integer" && instanceType === "number" && instance % 1 === 0 && instance === instance) { valid = true; break; } } if (!valid) { errors.push({ instanceLocation, keyword: "type", keywordLocation: `${schemaLocation}/type`, error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` }); } } else if ($type === "integer") { if (instanceType !== "number" || instance % 1 || instance !== instance) { errors.push({ instanceLocation, keyword: "type", keywordLocation: `${schemaLocation}/type`, error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` }); } } else if ($type !== void 0 && instanceType !== $type) { errors.push({ instanceLocation, keyword: "type", keywordLocation: `${schemaLocation}/type`, error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` }); } if ($const !== void 0) { if (instanceType === "object" || instanceType === "array") { if (!deepCompareStrict(instance, $const)) { errors.push({ instanceLocation, keyword: "const", keywordLocation: `${schemaLocation}/const`, error: `Instance does not match ${JSON.stringify($const)}.` }); } } else if (instance !== $const) { errors.push({ instanceLocation, keyword: "const", keywordLocation: `${schemaLocation}/const`, error: `Instance does not match ${JSON.stringify($const)}.` }); } } if ($enum !== void 0) { if (instanceType === "object" || instanceType === "array") { if (!$enum.some((value) => deepCompareStrict(instance, value))) { errors.push({ instanceLocation, keyword: "enum", keywordLocation: `${schemaLocation}/enum`, error: `Instance does not match any of ${JSON.stringify($enum)}.` }); } } else if (!$enum.some((value) => instance === value)) { errors.push({ instanceLocation, keyword: "enum", keywordLocation: `${schemaLocation}/enum`, error: `Instance does not match any of ${JSON.stringify($enum)}.` }); } } if ($not !== void 0) { const keywordLocation = `${schemaLocation}/not`; const result = validate3(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); if (result.valid) { errors.push({ instanceLocation, keyword: "not", keywordLocation, error: 'Instance matched "not" schema.' }); } } let subEvaluateds = []; if ($anyOf !== void 0) { const keywordLocation = `${schemaLocation}/anyOf`; const errorsLength = errors.length; let anyValid = false; for (let i2 = 0; i2 < $anyOf.length; i2++) { const subSchema = $anyOf[i2]; const subEvaluated = Object.create(evaluated); const result = validate3(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i2}`, subEvaluated); errors.push(...result.errors); anyValid = anyValid || result.valid; if (result.valid) { subEvaluateds.push(subEvaluated); } } if (anyValid) { errors.length = errorsLength; } else { errors.splice(errorsLength, 0, { instanceLocation, keyword: "anyOf", keywordLocation, error: "Instance does not match any subschemas." }); } } if ($allOf !== void 0) { const keywordLocation = `${schemaLocation}/allOf`; const errorsLength = errors.length; let allValid = true; for (let i2 = 0; i2 < $allOf.length; i2++) { const subSchema = $allOf[i2]; const subEvaluated = Object.create(evaluated); const result = validate3(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i2}`, subEvaluated); errors.push(...result.errors); allValid = allValid && result.valid; if (result.valid) { subEvaluateds.push(subEvaluated); } } if (allValid) { errors.length = errorsLength; } else { errors.splice(errorsLength, 0, { instanceLocation, keyword: "allOf", keywordLocation, error: `Instance does not match every subschema.` }); } } if ($oneOf !== void 0) { const keywordLocation = `${schemaLocation}/oneOf`; const errorsLength = errors.length; const matches = $oneOf.filter((subSchema, i2) => { const subEvaluated = Object.create(evaluated); const result = validate3(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i2}`, subEvaluated); errors.push(...result.errors); if (result.valid) { subEvaluateds.push(subEvaluated); } return result.valid; }).length; if (matches === 1) { errors.length = errorsLength; } else { errors.splice(errorsLength, 0, { instanceLocation, keyword: "oneOf", keywordLocation, error: `Instance does not match exactly one subschema (${matches} matches).` }); } } if (instanceType === "object" || instanceType === "array") { Object.assign(evaluated, ...subEvaluateds); } if ($if !== void 0) { const keywordLocation = `${schemaLocation}/if`; const conditionResult = validate3(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; if (conditionResult) { if ($then !== void 0) { const thenResult = validate3(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); if (!thenResult.valid) { errors.push({ instanceLocation, keyword: "if", keywordLocation, error: `Instance does not match "then" schema.` }, ...thenResult.errors); } } } else if ($else !== void 0) { const elseResult = validate3(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); if (!elseResult.valid) { errors.push({ instanceLocation, keyword: "if", keywordLocation, error: `Instance does not match "else" schema.` }, ...elseResult.errors); } } } if (instanceType === "object") { if ($required !== void 0) { for (const key of $required) { if (!(key in instance)) { errors.push({ instanceLocation, keyword: "required", keywordLocation: `${schemaLocation}/required`, error: `Instance does not have required property "${key}".` }); } } } const keys = Object.keys(instance); if ($minProperties !== void 0 && keys.length < $minProperties) { errors.push({ instanceLocation, keyword: "minProperties", keywordLocation: `${schemaLocation}/minProperties`, error: `Instance does not have at least ${$minProperties} properties.` }); } if ($maxProperties !== void 0 && keys.length > $maxProperties) { errors.push({ instanceLocation, keyword: "maxProperties", keywordLocation: `${schemaLocation}/maxProperties`, error: `Instance does not have at least ${$maxProperties} properties.` }); } if ($propertyNames !== void 0) { const keywordLocation = `${schemaLocation}/propertyNames`; for (const key in instance) { const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; const result = validate3(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); if (!result.valid) { errors.push({ instanceLocation, keyword: "propertyNames", keywordLocation, error: `Property name "${key}" does not match schema.` }, ...result.errors); } } } if ($dependentRequired !== void 0) { const keywordLocation = `${schemaLocation}/dependantRequired`; for (const key in $dependentRequired) { if (key in instance) { const required = $dependentRequired[key]; for (const dependantKey of required) { if (!(dependantKey in instance)) { errors.push({ instanceLocation, keyword: "dependentRequired", keywordLocation, error: `Instance has "${key}" but does not have "${dependantKey}".` }); } } } } } if ($dependentSchemas !== void 0) { for (const key in $dependentSchemas) { const keywordLocation = `${schemaLocation}/dependentSchemas`; if (key in instance) { const result = validate3(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); if (!result.valid) { errors.push({ instanceLocation, keyword: "dependentSchemas", keywordLocation, error: `Instance has "${key}" but does not match dependant schema.` }, ...result.errors); } } } } if ($dependencies !== void 0) { const keywordLocation = `${schemaLocation}/dependencies`; for (const key in $dependencies) { if (key in instance) { const propsOrSchema = $dependencies[key]; if (Array.isArray(propsOrSchema)) { for (const dependantKey of propsOrSchema) { if (!(dependantKey in instance)) { errors.push({ instanceLocation, keyword: "dependencies", keywordLocation, error: `Instance has "${key}" but does not have "${dependantKey}".` }); } } } else { const result = validate3(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); if (!result.valid) { errors.push({ instanceLocation, keyword: "dependencies", keywordLocation, error: `Instance has "${key}" but does not match dependant schema.` }, ...result.errors); } } } } } const thisEvaluated = Object.create(null); let stop = false; if ($properties !== void 0) { const keywordLocation = `${schemaLocation}/properties`; for (const key in $properties) { if (!(key in instance)) { continue; } const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; const result = validate3(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); if (result.valid) { evaluated[key] = thisEvaluated[key] = true; } else { stop = shortCircuit; errors.push({ instanceLocation, keyword: "properties", keywordLocation, error: `Property "${key}" does not match schema.` }, ...result.errors); if (stop) break; } } } if (!stop && $patternProperties !== void 0) { const keywordLocation = `${schemaLocation}/patternProperties`; for (const pattern in $patternProperties) { const regex2 = new RegExp(pattern); const subSchema = $patternProperties[pattern]; for (const key in instance) { if (!regex2.test(key)) { continue; } const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; const result = validate3(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); if (result.valid) { evaluated[key] = thisEvaluated[key] = true; } else { stop = shortCircuit; errors.push({ instanceLocation, keyword: "patternProperties", keywordLocation, error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` }, ...result.errors); } } } } if (!stop && $additionalProperties !== void 0) { const keywordLocation = `${schemaLocation}/additionalProperties`; for (const key in instance) { if (thisEvaluated[key]) { continue; } const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; const result = validate3(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); if (result.valid) { evaluated[key] = true; } else { stop = shortCircuit; errors.push({ instanceLocation, keyword: "additionalProperties", keywordLocation, error: `Property "${key}" does not match additional properties schema.` }, ...result.errors); } } } else if (!stop && $unevaluatedProperties !== void 0) { const keywordLocation = `${schemaLocation}/unevaluatedProperties`; for (const key in instance) { if (!evaluated[key]) { const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; const result = validate3(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); if (result.valid) { evaluated[key] = true; } else { errors.push({ instanceLocation, keyword: "unevaluatedProperties", keywordLocation, error: `Property "${key}" does not match unevaluated properties schema.` }, ...result.errors); } } } } } else if (instanceType === "array") { if ($maxItems !== void 0 && instance.length > $maxItems) { errors.push({ instanceLocation, keyword: "maxItems", keywordLocation: `${schemaLocation}/maxItems`, error: `Array has too many items (${instance.length} > ${$maxItems}).` }); } if ($minItems !== void 0 && instance.length < $minItems) { errors.push({ instanceLocation, keyword: "minItems", keywordLocation: `${schemaLocation}/minItems`, error: `Array has too few items (${instance.length} < ${$minItems}).` }); } const length = instance.length; let i2 = 0; let stop = false; if ($prefixItems !== void 0) { const keywordLocation = `${schemaLocation}/prefixItems`; const length2 = Math.min($prefixItems.length, length); for (; i2 < length2; i2++) { const result = validate3(instance[i2], $prefixItems[i2], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i2}`, `${keywordLocation}/${i2}`); evaluated[i2] = true; if (!result.valid) { stop = shortCircuit; errors.push({ instanceLocation, keyword: "prefixItems", keywordLocation, error: `Items did not match schema.` }, ...result.errors); if (stop) break; } } } if ($items !== void 0) { const keywordLocation = `${schemaLocation}/items`; if (Array.isArray($items)) { const length2 = Math.min($items.length, length); for (; i2 < length2; i2++) { const result = validate3(instance[i2], $items[i2], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i2}`, `${keywordLocation}/${i2}`); evaluated[i2] = true; if (!result.valid) { stop = shortCircuit; errors.push({ instanceLocation, keyword: "items", keywordLocation, error: `Items did not match schema.` }, ...result.errors); if (stop) break; } } } else { for (; i2 < length; i2++) { const result = validate3(instance[i2], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i2}`, keywordLocation); evaluated[i2] = true; if (!result.valid) { stop = shortCircuit; errors.push({ instanceLocation, keyword: "items", keywordLocation, error: `Items did not match schema.` }, ...result.errors); if (stop) break; } } } if (!stop && $additionalItems !== void 0) { const keywordLocation2 = `${schemaLocation}/additionalItems`; for (; i2 < length; i2++) { const result = validate3(instance[i2], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i2}`, keywordLocation2); evaluated[i2] = true; if (!result.valid) { stop = shortCircuit; errors.push({ instanceLocation, keyword: "additionalItems", keywordLocation: keywordLocation2, error: `Items did not match additional items schema.` }, ...result.errors); } } } } if ($contains !== void 0) { if (length === 0 && $minContains === void 0) { errors.push({ instanceLocation, keyword: "contains", keywordLocation: `${schemaLocation}/contains`, error: `Array is empty. It must contain at least one item matching the schema.` }); } else if ($minContains !== void 0 && length < $minContains) { errors.push({ instanceLocation, keyword: "minContains", keywordLocation: `${schemaLocation}/minContains`, error: `Array has less items (${length}) than minContains (${$minContains}).` }); } else { const keywordLocation = `${schemaLocation}/contains`; const errorsLength = errors.length; let contained = 0; for (let j2 = 0; j2 < length; j2++) { const result = validate3(instance[j2], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j2}`, keywordLocation); if (result.valid) { evaluated[j2] = true; contained++; } else { errors.push(...result.errors); } } if (contained >= ($minContains || 0)) { errors.length = errorsLength; } if ($minContains === void 0 && $maxContains === void 0 && contained === 0) { errors.splice(errorsLength, 0, { instanceLocation, keyword: "contains", keywordLocation, error: `Array does not contain item matching schema.` }); } else if ($minContains !== void 0 && contained < $minContains) { errors.push({ instanceLocation, keyword: "minContains", keywordLocation: `${schemaLocation}/minContains`, error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` }); } else if ($maxContains !== void 0 && contained > $maxContains) { errors.push({ instanceLocation, keyword: "maxContains", keywordLocation: `${schemaLocation}/maxContains`, error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` }); } } } if (!stop && $unevaluatedItems !== void 0) { const keywordLocation = `${schemaLocation}/unevaluatedItems`; for (i2; i2 < length; i2++) { if (evaluated[i2]) { continue; } const result = validate3(instance[i2], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i2}`, keywordLocation); evaluated[i2] = true; if (!result.valid) { errors.push({ instanceLocation, keyword: "unevaluatedItems", keywordLocation, error: `Items did not match unevaluated items schema.` }, ...result.errors); } } } if ($uniqueItems) { for (let j2 = 0; j2 < length; j2++) { const a2 = instance[j2]; const ao = typeof a2 === "object" && a2 !== null; for (let k2 = 0; k2 < length; k2++) { if (j2 === k2) { continue; } const b2 = instance[k2]; const bo = typeof b2 === "object" && b2 !== null; if (a2 === b2 || ao && bo && deepCompareStrict(a2, b2)) { errors.push({ instanceLocation, keyword: "uniqueItems", keywordLocation: `${schemaLocation}/uniqueItems`, error: `Duplicate items at indexes ${j2} and ${k2}.` }); j2 = Number.MAX_SAFE_INTEGER; k2 = Number.MAX_SAFE_INTEGER; } } } } } else if (instanceType === "number") { if (draft === "4") { if ($minimum !== void 0 && ($exclusiveMinimum === true && instance <= $minimum || instance < $minimum)) { errors.push({ instanceLocation, keyword: "minimum", keywordLocation: `${schemaLocation}/minimum`, error: `${instance} is less than ${$exclusiveMinimum ? "or equal to " : ""} ${$minimum}.` }); } if ($maximum !== void 0 && ($exclusiveMaximum === true && instance >= $maximum || instance > $maximum)) { errors.push({ instanceLocation, keyword: "maximum", keywordLocation: `${schemaLocation}/maximum`, error: `${instance} is greater than ${$exclusiveMaximum ? "or equal to " : ""} ${$maximum}.` }); } } else { if ($minimum !== void 0 && instance < $minimum) { errors.push({ instanceLocation, keyword: "minimum", keywordLocation: `${schemaLocation}/minimum`, error: `${instance} is less than ${$minimum}.` }); } if ($maximum !== void 0 && instance > $maximum) { errors.push({ instanceLocation, keyword: "maximum", keywordLocation: `${schemaLocation}/maximum`, error: `${instance} is greater than ${$maximum}.` }); } if ($exclusiveMinimum !== void 0 && instance <= $exclusiveMinimum) { errors.push({ instanceLocation, keyword: "exclusiveMinimum", keywordLocation: `${schemaLocation}/exclusiveMinimum`, error: `${instance} is less than ${$exclusiveMinimum}.` }); } if ($exclusiveMaximum !== void 0 && instance >= $exclusiveMaximum) { errors.push({ instanceLocation, keyword: "exclusiveMaximum", keywordLocation: `${schemaLocation}/exclusiveMaximum`, error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` }); } } if ($multipleOf !== void 0) { const remainder = instance % $multipleOf; if (Math.abs(0 - remainder) >= 11920929e-14 && Math.abs($multipleOf - remainder) >= 11920929e-14) { errors.push({ instanceLocation, keyword: "multipleOf", keywordLocation: `${schemaLocation}/multipleOf`, error: `${instance} is not a multiple of ${$multipleOf}.` }); } } } else if (instanceType === "string") { const length = $minLength === void 0 && $maxLength === void 0 ? 0 : ucs2length(instance); if ($minLength !== void 0 && length < $minLength) { errors.push({ instanceLocation, keyword: "minLength", keywordLocation: `${schemaLocation}/minLength`, error: `String is too short (${length} < ${$minLength}).` }); } if ($maxLength !== void 0 && length > $maxLength) { errors.push({ instanceLocation, keyword: "maxLength", keywordLocation: `${schemaLocation}/maxLength`, error: `String is too long (${length} > ${$maxLength}).` }); } if ($pattern !== void 0 && !new RegExp($pattern).test(instance)) { errors.push({ instanceLocation, keyword: "pattern", keywordLocation: `${schemaLocation}/pattern`, error: `String does not match pattern.` }); } if ($format !== void 0 && fastFormat[$format] && !fastFormat[$format](instance)) { errors.push({ instanceLocation, keyword: "format", keywordLocation: `${schemaLocation}/format`, error: `String does not match format "${$format}".` }); } } return { valid: errors.length === 0, errors }; } var init_validate2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validate.js"() { init_deep_compare_strict(); init_dereference(); init_format(); init_pointer(); init_ucs2_length(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validator.js var Validator; var init_validator = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validator.js"() { init_dereference(); init_validate2(); Validator = class { constructor(schema3, draft = "2019-09", shortCircuit = true) { Object.defineProperty(this, "schema", { enumerable: true, configurable: true, writable: true, value: schema3 }); Object.defineProperty(this, "draft", { enumerable: true, configurable: true, writable: true, value: draft }); Object.defineProperty(this, "shortCircuit", { enumerable: true, configurable: true, writable: true, value: shortCircuit }); Object.defineProperty(this, "lookup", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.lookup = dereference(schema3); } validate(instance) { return validate3(instance, this.schema, this.draft, this.lookup, this.shortCircuit); } addSchema(schema3, id2) { if (id2) { schema3 = { ...schema3, $id: id2 }; } dereference(schema3, this.lookup); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/index.js var init_src = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/index.js"() { init_deep_compare_strict(); init_dereference(); init_format(); init_pointer(); init_types(); init_ucs2_length(); init_validate2(); init_validator(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/index.js var init_json_schema = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/@cfworker/json-schema/index.js"() { init_src(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/transform.js var BaseTransformOutputParser, BaseCumulativeTransformOutputParser; var init_transform = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/transform.js"() { init_base7(); init_messages(); init_outputs(); init_json_schema(); BaseTransformOutputParser = class extends BaseOutputParser { async *_transform(inputGenerator) { for await (const chunk of inputGenerator) { if (typeof chunk === "string") { yield this.parseResult([{ text: chunk }]); } else { yield this.parseResult([ { message: chunk, text: this._baseMessageToString(chunk) } ]); } } } async *transform(inputGenerator, options) { yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { ...options, runType: "parser" }); } }; BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { constructor(fields2) { super(fields2); Object.defineProperty(this, "diff", { enumerable: true, configurable: true, writable: true, value: false }); this.diff = fields2?.diff ?? this.diff; } async *_transform(inputGenerator) { let prevParsed; let accGen; for await (const chunk of inputGenerator) { if (typeof chunk !== "string" && typeof chunk.content !== "string") { throw new Error("Cannot handle non-string output."); } let chunkGen; if (isBaseMessageChunk(chunk)) { if (typeof chunk.content !== "string") { throw new Error("Cannot handle non-string message output."); } chunkGen = new ChatGenerationChunk({ message: chunk, text: chunk.content }); } else if (isBaseMessage(chunk)) { if (typeof chunk.content !== "string") { throw new Error("Cannot handle non-string message output."); } chunkGen = new ChatGenerationChunk({ message: chunk.toChunk(), text: chunk.content }); } else { chunkGen = new GenerationChunk({ text: chunk }); } if (accGen === void 0) { accGen = chunkGen; } else { accGen = accGen.concat(chunkGen); } const parsed = await this.parsePartialResult([accGen]); if (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { if (this.diff) { yield this._diff(prevParsed, parsed); } else { yield parsed; } prevParsed = parsed; } } } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/bytes.js var BytesOutputParser; var init_bytes = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/bytes.js"() { init_transform(); BytesOutputParser = class extends BaseTransformOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers", "bytes"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "textEncoder", { enumerable: true, configurable: true, writable: true, value: new TextEncoder() }); } static lc_name() { return "BytesOutputParser"; } parse(text) { return Promise.resolve(this.textEncoder.encode(text)); } getFormatInstructions() { return ""; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/list.js var ListOutputParser, CommaSeparatedListOutputParser, CustomListOutputParser, NumberedListOutputParser, MarkdownListOutputParser; var init_list = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/list.js"() { init_base7(); init_transform(); ListOutputParser = class extends BaseTransformOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "re", { enumerable: true, configurable: true, writable: true, value: void 0 }); } async *_transform(inputGenerator) { let buffer = ""; for await (const input of inputGenerator) { if (typeof input === "string") { buffer += input; } else { buffer += input.content; } if (!this.re) { const parts = await this.parse(buffer); if (parts.length > 1) { for (const part of parts.slice(0, -1)) { yield [part]; } buffer = parts[parts.length - 1]; } } else { const matches = [...buffer.matchAll(this.re)]; if (matches.length > 1) { let doneIdx = 0; for (const match of matches.slice(0, -1)) { yield [match[1]]; doneIdx += (match.index ?? 0) + match[0].length; } buffer = buffer.slice(doneIdx); } } } for (const part of await this.parse(buffer)) { yield [part]; } } }; CommaSeparatedListOutputParser = class extends ListOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers", "list"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); } static lc_name() { return "CommaSeparatedListOutputParser"; } async parse(text) { try { return text.trim().split(",").map((s2) => s2.trim()); } catch (e2) { throw new OutputParserException(`Could not parse output: ${text}`, text); } } getFormatInstructions() { return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; } }; CustomListOutputParser = class extends ListOutputParser { constructor({ length, separator }) { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers", "list"] }); Object.defineProperty(this, "length", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "separator", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.length = length; this.separator = separator || ","; } async parse(text) { try { const items = text.trim().split(this.separator).map((s2) => s2.trim()); if (this.length !== void 0 && items.length !== this.length) { throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`); } return items; } catch (e2) { if (Object.getPrototypeOf(e2) === OutputParserException.prototype) { throw e2; } throw new OutputParserException(`Could not parse output: ${text}`); } } getFormatInstructions() { return `Your response should be a list of ${this.length === void 0 ? "" : `${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`; } }; NumberedListOutputParser = class extends ListOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers", "list"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "re", { enumerable: true, configurable: true, writable: true, value: /\d+\.\s([^\n]+)/g }); } static lc_name() { return "NumberedListOutputParser"; } getFormatInstructions() { return `Your response should be a numbered list with each item on a new line. For example: 1. foo 2. bar 3. baz`; } async parse(text) { return [...text.matchAll(this.re) ?? []].map((m2) => m2[1]); } }; MarkdownListOutputParser = class extends ListOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers", "list"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "re", { enumerable: true, configurable: true, writable: true, value: /^\s*[-*]\s([^\n]+)$/gm }); } static lc_name() { return "NumberedListOutputParser"; } getFormatInstructions() { return `Your response should be a numbered list with each item on a new line. For example: 1. foo 2. bar 3. baz`; } async parse(text) { return [...text.matchAll(this.re) ?? []].map((m2) => m2[1]); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/string.js var StringOutputParser; var init_string3 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/string.js"() { init_transform(); StringOutputParser = class extends BaseTransformOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers", "string"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); } static lc_name() { return "StrOutputParser"; } parse(text) { return Promise.resolve(text); } getFormatInstructions() { return ""; } _textContentToString(content) { return content.text; } _imageUrlContentToString(_content) { throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); } _messageContentComplexToString(content) { switch (content.type) { case "text": return this._textContentToString(content); case "image_url": return this._imageUrlContentToString(content); default: throw new Error(`Cannot coerce "${content.type}" message part into a string.`); } } _baseMessageContentToString(content) { return content.reduce((acc, item) => acc + this._messageContentComplexToString(item), ""); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/structured.js var StructuredOutputParser, JsonMarkdownStructuredOutputParser, AsymmetricStructuredOutputParser; var init_structured2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/structured.js"() { init_lib(); init_esm(); init_base7(); StructuredOutputParser = class extends BaseOutputParser { static lc_name() { return "StructuredOutputParser"; } toJSON() { return this.toJSONNotImplemented(); } constructor(schema3) { super(schema3); Object.defineProperty(this, "schema", { enumerable: true, configurable: true, writable: true, value: schema3 }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "output_parsers", "structured"] }); } static fromZodSchema(schema3) { return new this(schema3); } static fromNamesAndDescriptions(schemas) { const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name2, description2]) => [name2, z.string().describe(description2)]))); return new this(zodSchema); } getFormatInstructions() { return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}} would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: \`\`\`json ${JSON.stringify(zodToJsonSchema(this.schema))} \`\`\` `; } async parse(text) { try { const json2 = text.includes("```") ? text.trim().split(/```(?:json)?/)[1] : text.trim(); return await this.schema.parseAsync(JSON.parse(json2)); } catch (e2) { throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e2}`, text); } } }; JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser { static lc_name() { return "JsonMarkdownStructuredOutputParser"; } getFormatInstructions(options) { const interpolationDepth = options?.interpolationDepth ?? 1; if (interpolationDepth < 1) { throw new Error("f string interpolation depth must be at least 1"); } return `Return a markdown code snippet with a JSON object formatted to look like: \`\`\`json ${this._schemaToInstruction(zodToJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))} \`\`\``; } _schemaToInstruction(schemaInput, indent = 2) { const schema3 = schemaInput; if ("type" in schema3) { let nullable = false; let type2; if (Array.isArray(schema3.type)) { const nullIdx = schema3.type.findIndex((type3) => type3 === "null"); if (nullIdx !== -1) { nullable = true; schema3.type.splice(nullIdx, 1); } type2 = schema3.type.join(" | "); } else { type2 = schema3.type; } if (schema3.type === "object" && schema3.properties) { const description3 = schema3.description ? ` // ${schema3.description}` : ""; const properties = Object.entries(schema3.properties).map(([key, value]) => { const isOptional = schema3.required?.includes(key) ? "" : " (optional)"; return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; }).join("\n"); return `{ ${properties} ${" ".repeat(indent - 2)}}${description3}`; } if (schema3.type === "array" && schema3.items) { const description3 = schema3.description ? ` // ${schema3.description}` : ""; return `array[ ${" ".repeat(indent)}${this._schemaToInstruction(schema3.items, indent + 2)} ${" ".repeat(indent - 2)}] ${description3}`; } const isNullable = nullable ? " (nullable)" : ""; const description2 = schema3.description ? ` // ${schema3.description}` : ""; return `${type2}${description2}${isNullable}`; } if ("anyOf" in schema3) { return schema3.anyOf.map((s2) => this._schemaToInstruction(s2, indent)).join(` ${" ".repeat(indent - 2)}`); } throw new Error("unsupported schema type"); } static fromZodSchema(schema3) { return new this(schema3); } static fromNamesAndDescriptions(schemas) { const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name2, description2]) => [name2, z.string().describe(description2)]))); return new this(zodSchema); } }; AsymmetricStructuredOutputParser = class extends BaseOutputParser { constructor({ inputSchema }) { super(...arguments); Object.defineProperty(this, "structuredInputParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); } async parse(text) { let parsedInput; try { parsedInput = await this.structuredInputParser.parse(text); } catch (e2) { throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e2}`, text); } return this.outputProcessor(parsedInput); } getFormatInstructions() { return this.structuredInputParser.getFormatInstructions(); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/json_patch.js var json_patch_exports = {}; __export(json_patch_exports, { applyPatch: () => applyPatch, compare: () => compare }); var init_json_patch = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/json_patch.js"() { init_fast_json_patch(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/json.js function parseJsonMarkdown(s2, parser = parsePartialJson) { s2 = s2.trim(); const match = /```(json)?(.*)```/s.exec(s2); if (!match) { return parser(s2); } else { return parser(match[2]); } } function parsePartialJson(s2) { if (typeof s2 === "undefined") { return null; } try { return JSON.parse(s2); } catch (error) { } let new_s = ""; const stack = []; let isInsideString = false; let escaped = false; for (let char of s2) { if (isInsideString) { if (char === '"' && !escaped) { isInsideString = false; } else if (char === "\n" && !escaped) { char = "\\n"; } else if (char === "\\") { escaped = !escaped; } else { escaped = false; } } else { if (char === '"') { isInsideString = true; escaped = false; } else if (char === "{") { stack.push("}"); } else if (char === "[") { stack.push("]"); } else if (char === "}" || char === "]") { if (stack && stack[stack.length - 1] === char) { stack.pop(); } else { return null; } } } new_s += char; } if (isInsideString) { new_s += '"'; } for (let i2 = stack.length - 1; i2 >= 0; i2 -= 1) { new_s += stack[i2]; } try { return JSON.parse(new_s); } catch (error) { return null; } } var JsonOutputParser; var init_json = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/json.js"() { init_transform(); init_json_patch(); JsonOutputParser = class extends BaseCumulativeTransformOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); } static lc_name() { return "JsonOutputParser"; } _diff(prev, next2) { if (!next2) { return void 0; } if (!prev) { return [{ op: "replace", path: "", value: next2 }]; } return compare(prev, next2); } async parsePartialResult(generations) { return parseJsonMarkdown(generations[0].text); } async parse(text) { return parseJsonMarkdown(text, JSON.parse); } getFormatInstructions() { return ""; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/sax-js/sax.js var initializeSax, sax; var init_sax = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/sax-js/sax.js"() { initializeSax = function() { const sax2 = {}; sax2.parser = function(strict, opt) { return new SAXParser(strict, opt); }; sax2.SAXParser = SAXParser; sax2.SAXStream = SAXStream; sax2.createStream = createStream; sax2.MAX_BUFFER_LENGTH = 64 * 1024; const buffers = [ "comment", "sgmlDecl", "textNode", "tagName", "doctype", "procInstName", "procInstBody", "entity", "attribName", "attribValue", "cdata", "script" ]; sax2.EVENTS = [ "text", "processinginstruction", "sgmldeclaration", "doctype", "comment", "opentagstart", "attribute", "opentag", "closetag", "opencdata", "cdata", "closecdata", "error", "end", "ready", "script", "opennamespace", "closenamespace" ]; function SAXParser(strict, opt) { if (!(this instanceof SAXParser)) { return new SAXParser(strict, opt); } var parser = this; clearBuffers(parser); parser.q = parser.c = ""; parser.bufferCheckPosition = sax2.MAX_BUFFER_LENGTH; parser.opt = opt || {}; parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; parser.tags = []; parser.closed = parser.closedRoot = parser.sawRoot = false; parser.tag = parser.error = null; parser.strict = !!strict; parser.noscript = !!(strict || parser.opt.noscript); parser.state = S2.BEGIN; parser.strictEntities = parser.opt.strictEntities; parser.ENTITIES = parser.strictEntities ? Object.create(sax2.XML_ENTITIES) : Object.create(sax2.ENTITIES); parser.attribList = []; if (parser.opt.xmlns) { parser.ns = Object.create(rootNS); } parser.trackPosition = parser.opt.position !== false; if (parser.trackPosition) { parser.position = parser.line = parser.column = 0; } emit(parser, "onready"); } if (!Object.create) { Object.create = function(o2) { function F2() { } F2.prototype = o2; var newf = new F2(); return newf; }; } if (!Object.keys) { Object.keys = function(o2) { var a2 = []; for (var i2 in o2) if (o2.hasOwnProperty(i2)) a2.push(i2); return a2; }; } function checkBufferLength(parser) { var maxAllowed = Math.max(sax2.MAX_BUFFER_LENGTH, 10); var maxActual = 0; for (var i2 = 0, l2 = buffers.length; i2 < l2; i2++) { var len = parser[buffers[i2]].length; if (len > maxAllowed) { switch (buffers[i2]) { case "textNode": closeText(parser); break; case "cdata": emitNode(parser, "oncdata", parser.cdata); parser.cdata = ""; break; case "script": emitNode(parser, "onscript", parser.script); parser.script = ""; break; default: error(parser, "Max buffer length exceeded: " + buffers[i2]); } } maxActual = Math.max(maxActual, len); } var m2 = sax2.MAX_BUFFER_LENGTH - maxActual; parser.bufferCheckPosition = m2 + parser.position; } function clearBuffers(parser) { for (var i2 = 0, l2 = buffers.length; i2 < l2; i2++) { parser[buffers[i2]] = ""; } } function flushBuffers(parser) { closeText(parser); if (parser.cdata !== "") { emitNode(parser, "oncdata", parser.cdata); parser.cdata = ""; } if (parser.script !== "") { emitNode(parser, "onscript", parser.script); parser.script = ""; } } SAXParser.prototype = { end: function() { end(this); }, write, resume: function() { this.error = null; return this; }, close: function() { return this.write(null); }, flush: function() { flushBuffers(this); } }; var Stream4 = ReadableStream; if (!Stream4) Stream4 = function() { }; var streamWraps = sax2.EVENTS.filter(function(ev) { return ev !== "error" && ev !== "end"; }); function createStream(strict, opt) { return new SAXStream(strict, opt); } function SAXStream(strict, opt) { if (!(this instanceof SAXStream)) { return new SAXStream(strict, opt); } Stream4.apply(this); this._parser = new SAXParser(strict, opt); this.writable = true; this.readable = true; var me2 = this; this._parser.onend = function() { me2.emit("end"); }; this._parser.onerror = function(er) { me2.emit("error", er); me2._parser.error = null; }; this._decoder = null; streamWraps.forEach(function(ev) { Object.defineProperty(me2, "on" + ev, { get: function() { return me2._parser["on" + ev]; }, set: function(h2) { if (!h2) { me2.removeAllListeners(ev); me2._parser["on" + ev] = h2; return h2; } me2.on(ev, h2); }, enumerable: true, configurable: false }); }); } SAXStream.prototype = Object.create(Stream4.prototype, { constructor: { value: SAXStream } }); SAXStream.prototype.write = function(data) { this._parser.write(data.toString()); this.emit("data", data); return true; }; SAXStream.prototype.end = function(chunk) { if (chunk && chunk.length) { this.write(chunk); } this._parser.end(); return true; }; SAXStream.prototype.on = function(ev, handler) { var me2 = this; if (!me2._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) { me2._parser["on" + ev] = function() { var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); args.splice(0, 0, ev); me2.emit.apply(me2, args); }; } return Stream4.prototype.on.call(me2, ev, handler); }; var CDATA = "[CDATA["; var DOCTYPE = "DOCTYPE"; var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }; var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; function isWhitespace2(c2) { return c2 === " " || c2 === "\n" || c2 === "\r" || c2 === " "; } function isQuote(c2) { return c2 === '"' || c2 === "'"; } function isAttribEnd(c2) { return c2 === ">" || isWhitespace2(c2); } function isMatch(regex2, c2) { return regex2.test(c2); } function notMatch(regex2, c2) { return !isMatch(regex2, c2); } var S2 = 0; sax2.STATE = { BEGIN: S2++, BEGIN_WHITESPACE: S2++, TEXT: S2++, TEXT_ENTITY: S2++, OPEN_WAKA: S2++, SGML_DECL: S2++, SGML_DECL_QUOTED: S2++, DOCTYPE: S2++, DOCTYPE_QUOTED: S2++, DOCTYPE_DTD: S2++, DOCTYPE_DTD_QUOTED: S2++, COMMENT_STARTING: S2++, COMMENT: S2++, COMMENT_ENDING: S2++, COMMENT_ENDED: S2++, CDATA: S2++, CDATA_ENDING: S2++, CDATA_ENDING_2: S2++, PROC_INST: S2++, PROC_INST_BODY: S2++, PROC_INST_ENDING: S2++, OPEN_TAG: S2++, OPEN_TAG_SLASH: S2++, ATTRIB: S2++, ATTRIB_NAME: S2++, ATTRIB_NAME_SAW_WHITE: S2++, ATTRIB_VALUE: S2++, ATTRIB_VALUE_QUOTED: S2++, ATTRIB_VALUE_CLOSED: S2++, ATTRIB_VALUE_UNQUOTED: S2++, ATTRIB_VALUE_ENTITY_Q: S2++, ATTRIB_VALUE_ENTITY_U: S2++, CLOSE_TAG: S2++, CLOSE_TAG_SAW_WHITE: S2++, SCRIPT: S2++, SCRIPT_ENDING: S2++ }; sax2.XML_ENTITIES = { amp: "&", gt: ">", lt: "<", quot: '"', apos: "'" }; sax2.ENTITIES = { amp: "&", gt: ">", lt: "<", quot: '"', apos: "'", AElig: 198, Aacute: 193, Acirc: 194, Agrave: 192, Aring: 197, Atilde: 195, Auml: 196, Ccedil: 199, ETH: 208, Eacute: 201, Ecirc: 202, Egrave: 200, Euml: 203, Iacute: 205, Icirc: 206, Igrave: 204, Iuml: 207, Ntilde: 209, Oacute: 211, Ocirc: 212, Ograve: 210, Oslash: 216, Otilde: 213, Ouml: 214, THORN: 222, Uacute: 218, Ucirc: 219, Ugrave: 217, Uuml: 220, Yacute: 221, aacute: 225, acirc: 226, aelig: 230, agrave: 224, aring: 229, atilde: 227, auml: 228, ccedil: 231, eacute: 233, ecirc: 234, egrave: 232, eth: 240, euml: 235, iacute: 237, icirc: 238, igrave: 236, iuml: 239, ntilde: 241, oacute: 243, ocirc: 244, ograve: 242, oslash: 248, otilde: 245, ouml: 246, szlig: 223, thorn: 254, uacute: 250, ucirc: 251, ugrave: 249, uuml: 252, yacute: 253, yuml: 255, copy: 169, reg: 174, nbsp: 160, iexcl: 161, cent: 162, pound: 163, curren: 164, yen: 165, brvbar: 166, sect: 167, uml: 168, ordf: 170, laquo: 171, not: 172, shy: 173, macr: 175, deg: 176, plusmn: 177, sup1: 185, sup2: 178, sup3: 179, acute: 180, micro: 181, para: 182, middot: 183, cedil: 184, ordm: 186, raquo: 187, frac14: 188, frac12: 189, frac34: 190, iquest: 191, times: 215, divide: 247, OElig: 338, oelig: 339, Scaron: 352, scaron: 353, Yuml: 376, fnof: 402, circ: 710, tilde: 732, Alpha: 913, Beta: 914, Gamma: 915, Delta: 916, Epsilon: 917, Zeta: 918, Eta: 919, Theta: 920, Iota: 921, Kappa: 922, Lambda: 923, Mu: 924, Nu: 925, Xi: 926, Omicron: 927, Pi: 928, Rho: 929, Sigma: 931, Tau: 932, Upsilon: 933, Phi: 934, Chi: 935, Psi: 936, Omega: 937, alpha: 945, beta: 946, gamma: 947, delta: 948, epsilon: 949, zeta: 950, eta: 951, theta: 952, iota: 953, kappa: 954, lambda: 955, mu: 956, nu: 957, xi: 958, omicron: 959, pi: 960, rho: 961, sigmaf: 962, sigma: 963, tau: 964, upsilon: 965, phi: 966, chi: 967, psi: 968, omega: 969, thetasym: 977, upsih: 978, piv: 982, ensp: 8194, emsp: 8195, thinsp: 8201, zwnj: 8204, zwj: 8205, lrm: 8206, rlm: 8207, ndash: 8211, mdash: 8212, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221, bdquo: 8222, dagger: 8224, Dagger: 8225, bull: 8226, hellip: 8230, permil: 8240, prime: 8242, Prime: 8243, lsaquo: 8249, rsaquo: 8250, oline: 8254, frasl: 8260, euro: 8364, image: 8465, weierp: 8472, real: 8476, trade: 8482, alefsym: 8501, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595, harr: 8596, crarr: 8629, lArr: 8656, uArr: 8657, rArr: 8658, dArr: 8659, hArr: 8660, forall: 8704, part: 8706, exist: 8707, empty: 8709, nabla: 8711, isin: 8712, notin: 8713, ni: 8715, prod: 8719, sum: 8721, minus: 8722, lowast: 8727, radic: 8730, prop: 8733, infin: 8734, ang: 8736, and: 8743, or: 8744, cap: 8745, cup: 8746, int: 8747, there4: 8756, sim: 8764, cong: 8773, asymp: 8776, ne: 8800, equiv: 8801, le: 8804, ge: 8805, sub: 8834, sup: 8835, nsub: 8836, sube: 8838, supe: 8839, oplus: 8853, otimes: 8855, perp: 8869, sdot: 8901, lceil: 8968, rceil: 8969, lfloor: 8970, rfloor: 8971, lang: 9001, rang: 9002, loz: 9674, spades: 9824, clubs: 9827, hearts: 9829, diams: 9830 }; Object.keys(sax2.ENTITIES).forEach(function(key) { var e2 = sax2.ENTITIES[key]; var s3 = typeof e2 === "number" ? String.fromCharCode(e2) : e2; sax2.ENTITIES[key] = s3; }); for (var s2 in sax2.STATE) { sax2.STATE[sax2.STATE[s2]] = s2; } S2 = sax2.STATE; function emit(parser, event2, data) { parser[event2] && parser[event2](data); } function emitNode(parser, nodeType, data) { if (parser.textNode) closeText(parser); emit(parser, nodeType, data); } function closeText(parser) { parser.textNode = textopts(parser.opt, parser.textNode); if (parser.textNode) emit(parser, "ontext", parser.textNode); parser.textNode = ""; } function textopts(opt, text) { if (opt.trim) text = text.trim(); if (opt.normalize) text = text.replace(/\s+/g, " "); return text; } function error(parser, er) { closeText(parser); if (parser.trackPosition) { er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c; } er = new Error(er); parser.error = er; emit(parser, "onerror", er); return parser; } function end(parser) { if (parser.sawRoot && !parser.closedRoot) strictFail(parser, "Unclosed root tag"); if (parser.state !== S2.BEGIN && parser.state !== S2.BEGIN_WHITESPACE && parser.state !== S2.TEXT) { error(parser, "Unexpected end"); } closeText(parser); parser.c = ""; parser.closed = true; emit(parser, "onend"); SAXParser.call(parser, parser.strict, parser.opt); return parser; } function strictFail(parser, message) { if (typeof parser !== "object" || !(parser instanceof SAXParser)) { throw new Error("bad call to strictFail"); } if (parser.strict) { error(parser, message); } } function newTag(parser) { if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase](); var parent = parser.tags[parser.tags.length - 1] || parser; var tag = parser.tag = { name: parser.tagName, attributes: {} }; if (parser.opt.xmlns) { tag.ns = parent.ns; } parser.attribList.length = 0; emitNode(parser, "onopentagstart", tag); } function qname(name2, attribute) { var i2 = name2.indexOf(":"); var qualName = i2 < 0 ? ["", name2] : name2.split(":"); var prefix = qualName[0]; var local = qualName[1]; if (attribute && name2 === "xmlns") { prefix = "xmlns"; local = ""; } return { prefix, local }; } function attrib(parser) { if (!parser.strict) { parser.attribName = parser.attribName[parser.looseCase](); } if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) { parser.attribName = parser.attribValue = ""; return; } if (parser.opt.xmlns) { var qn = qname(parser.attribName, true); var prefix = qn.prefix; var local = qn.local; if (prefix === "xmlns") { if (local === "xml" && parser.attribValue !== XML_NAMESPACE) { strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + "\nActual: " + parser.attribValue); } else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) { strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + "\nActual: " + parser.attribValue); } else { var tag = parser.tag; var parent = parser.tags[parser.tags.length - 1] || parser; if (tag.ns === parent.ns) { tag.ns = Object.create(parent.ns); } tag.ns[local] = parser.attribValue; } } parser.attribList.push([parser.attribName, parser.attribValue]); } else { parser.tag.attributes[parser.attribName] = parser.attribValue; emitNode(parser, "onattribute", { name: parser.attribName, value: parser.attribValue }); } parser.attribName = parser.attribValue = ""; } function openTag(parser, selfClosing) { if (parser.opt.xmlns) { var tag = parser.tag; var qn = qname(parser.tagName); tag.prefix = qn.prefix; tag.local = qn.local; tag.uri = tag.ns[qn.prefix] || ""; if (tag.prefix && !tag.uri) { strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName)); tag.uri = qn.prefix; } var parent = parser.tags[parser.tags.length - 1] || parser; if (tag.ns && parent.ns !== tag.ns) { Object.keys(tag.ns).forEach(function(p2) { emitNode(parser, "onopennamespace", { prefix: p2, uri: tag.ns[p2] }); }); } for (var i2 = 0, l2 = parser.attribList.length; i2 < l2; i2++) { var nv = parser.attribList[i2]; var name2 = nv[0]; var value = nv[1]; var qualName = qname(name2, true); var prefix = qualName.prefix; var local = qualName.local; var uri2 = prefix === "" ? "" : tag.ns[prefix] || ""; var a2 = { name: name2, value, prefix, local, uri: uri2 }; if (prefix && prefix !== "xmlns" && !uri2) { strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); a2.uri = prefix; } parser.tag.attributes[name2] = a2; emitNode(parser, "onattribute", a2); } parser.attribList.length = 0; } parser.tag.isSelfClosing = !!selfClosing; parser.sawRoot = true; parser.tags.push(parser.tag); emitNode(parser, "onopentag", parser.tag); if (!selfClosing) { if (!parser.noscript && parser.tagName.toLowerCase() === "script") { parser.state = S2.SCRIPT; } else { parser.state = S2.TEXT; } parser.tag = null; parser.tagName = ""; } parser.attribName = parser.attribValue = ""; parser.attribList.length = 0; } function closeTag(parser) { if (!parser.tagName) { strictFail(parser, "Weird empty close tag."); parser.textNode += ""; parser.state = S2.TEXT; return; } if (parser.script) { if (parser.tagName !== "script") { parser.script += ""; parser.tagName = ""; parser.state = S2.SCRIPT; return; } emitNode(parser, "onscript", parser.script); parser.script = ""; } var t2 = parser.tags.length; var tagName = parser.tagName; if (!parser.strict) { tagName = tagName[parser.looseCase](); } var closeTo = tagName; while (t2--) { var close = parser.tags[t2]; if (close.name !== closeTo) { strictFail(parser, "Unexpected close tag"); } else { break; } } if (t2 < 0) { strictFail(parser, "Unmatched closing tag: " + parser.tagName); parser.textNode += ""; parser.state = S2.TEXT; return; } parser.tagName = tagName; var s3 = parser.tags.length; while (s3-- > t2) { var tag = parser.tag = parser.tags.pop(); parser.tagName = parser.tag.name; emitNode(parser, "onclosetag", parser.tagName); var x2 = {}; for (var i2 in tag.ns) { x2[i2] = tag.ns[i2]; } var parent = parser.tags[parser.tags.length - 1] || parser; if (parser.opt.xmlns && tag.ns !== parent.ns) { Object.keys(tag.ns).forEach(function(p2) { var n2 = tag.ns[p2]; emitNode(parser, "onclosenamespace", { prefix: p2, uri: n2 }); }); } } if (t2 === 0) parser.closedRoot = true; parser.tagName = parser.attribValue = parser.attribName = ""; parser.attribList.length = 0; parser.state = S2.TEXT; } function parseEntity(parser) { var entity = parser.entity; var entityLC = entity.toLowerCase(); var num; var numStr = ""; if (parser.ENTITIES[entity]) { return parser.ENTITIES[entity]; } if (parser.ENTITIES[entityLC]) { return parser.ENTITIES[entityLC]; } entity = entityLC; if (entity.charAt(0) === "#") { if (entity.charAt(1) === "x") { entity = entity.slice(2); num = parseInt(entity, 16); numStr = num.toString(16); } else { entity = entity.slice(1); num = parseInt(entity, 10); numStr = num.toString(10); } } entity = entity.replace(/^0+/, ""); if (isNaN(num) || numStr.toLowerCase() !== entity) { strictFail(parser, "Invalid character entity"); return "&" + parser.entity + ";"; } return String.fromCodePoint(num); } function beginWhiteSpace(parser, c2) { if (c2 === "<") { parser.state = S2.OPEN_WAKA; parser.startTagPosition = parser.position; } else if (!isWhitespace2(c2)) { strictFail(parser, "Non-whitespace before first tag."); parser.textNode = c2; parser.state = S2.TEXT; } } function charAt(chunk, i2) { var result = ""; if (i2 < chunk.length) { result = chunk.charAt(i2); } return result; } function write(chunk) { var parser = this; if (this.error) { throw this.error; } if (parser.closed) { return error(parser, "Cannot write after close. Assign an onready handler."); } if (chunk === null) { return end(parser); } if (typeof chunk === "object") { chunk = chunk.toString(); } var i2 = 0; var c2 = ""; while (true) { c2 = charAt(chunk, i2++); parser.c = c2; if (!c2) { break; } if (parser.trackPosition) { parser.position++; if (c2 === "\n") { parser.line++; parser.column = 0; } else { parser.column++; } } switch (parser.state) { case S2.BEGIN: parser.state = S2.BEGIN_WHITESPACE; if (c2 === "\uFEFF") { continue; } beginWhiteSpace(parser, c2); continue; case S2.BEGIN_WHITESPACE: beginWhiteSpace(parser, c2); continue; case S2.TEXT: if (parser.sawRoot && !parser.closedRoot) { var starti = i2 - 1; while (c2 && c2 !== "<" && c2 !== "&") { c2 = charAt(chunk, i2++); if (c2 && parser.trackPosition) { parser.position++; if (c2 === "\n") { parser.line++; parser.column = 0; } else { parser.column++; } } } parser.textNode += chunk.substring(starti, i2 - 1); } if (c2 === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { parser.state = S2.OPEN_WAKA; parser.startTagPosition = parser.position; } else { if (!isWhitespace2(c2) && (!parser.sawRoot || parser.closedRoot)) { strictFail(parser, "Text data outside of root node."); } if (c2 === "&") { parser.state = S2.TEXT_ENTITY; } else { parser.textNode += c2; } } continue; case S2.SCRIPT: if (c2 === "<") { parser.state = S2.SCRIPT_ENDING; } else { parser.script += c2; } continue; case S2.SCRIPT_ENDING: if (c2 === "/") { parser.state = S2.CLOSE_TAG; } else { parser.script += "<" + c2; parser.state = S2.SCRIPT; } continue; case S2.OPEN_WAKA: if (c2 === "!") { parser.state = S2.SGML_DECL; parser.sgmlDecl = ""; } else if (isWhitespace2(c2)) { } else if (isMatch(nameStart, c2)) { parser.state = S2.OPEN_TAG; parser.tagName = c2; } else if (c2 === "/") { parser.state = S2.CLOSE_TAG; parser.tagName = ""; } else if (c2 === "?") { parser.state = S2.PROC_INST; parser.procInstName = parser.procInstBody = ""; } else { strictFail(parser, "Unencoded <"); if (parser.startTagPosition + 1 < parser.position) { var pad2 = parser.position - parser.startTagPosition; c2 = new Array(pad2).join(" ") + c2; } parser.textNode += "<" + c2; parser.state = S2.TEXT; } continue; case S2.SGML_DECL: if ((parser.sgmlDecl + c2).toUpperCase() === CDATA) { emitNode(parser, "onopencdata"); parser.state = S2.CDATA; parser.sgmlDecl = ""; parser.cdata = ""; } else if (parser.sgmlDecl + c2 === "--") { parser.state = S2.COMMENT; parser.comment = ""; parser.sgmlDecl = ""; } else if ((parser.sgmlDecl + c2).toUpperCase() === DOCTYPE) { parser.state = S2.DOCTYPE; if (parser.doctype || parser.sawRoot) { strictFail(parser, "Inappropriately located doctype declaration"); } parser.doctype = ""; parser.sgmlDecl = ""; } else if (c2 === ">") { emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); parser.sgmlDecl = ""; parser.state = S2.TEXT; } else if (isQuote(c2)) { parser.state = S2.SGML_DECL_QUOTED; parser.sgmlDecl += c2; } else { parser.sgmlDecl += c2; } continue; case S2.SGML_DECL_QUOTED: if (c2 === parser.q) { parser.state = S2.SGML_DECL; parser.q = ""; } parser.sgmlDecl += c2; continue; case S2.DOCTYPE: if (c2 === ">") { parser.state = S2.TEXT; emitNode(parser, "ondoctype", parser.doctype); parser.doctype = true; } else { parser.doctype += c2; if (c2 === "[") { parser.state = S2.DOCTYPE_DTD; } else if (isQuote(c2)) { parser.state = S2.DOCTYPE_QUOTED; parser.q = c2; } } continue; case S2.DOCTYPE_QUOTED: parser.doctype += c2; if (c2 === parser.q) { parser.q = ""; parser.state = S2.DOCTYPE; } continue; case S2.DOCTYPE_DTD: parser.doctype += c2; if (c2 === "]") { parser.state = S2.DOCTYPE; } else if (isQuote(c2)) { parser.state = S2.DOCTYPE_DTD_QUOTED; parser.q = c2; } continue; case S2.DOCTYPE_DTD_QUOTED: parser.doctype += c2; if (c2 === parser.q) { parser.state = S2.DOCTYPE_DTD; parser.q = ""; } continue; case S2.COMMENT: if (c2 === "-") { parser.state = S2.COMMENT_ENDING; } else { parser.comment += c2; } continue; case S2.COMMENT_ENDING: if (c2 === "-") { parser.state = S2.COMMENT_ENDED; parser.comment = textopts(parser.opt, parser.comment); if (parser.comment) { emitNode(parser, "oncomment", parser.comment); } parser.comment = ""; } else { parser.comment += "-" + c2; parser.state = S2.COMMENT; } continue; case S2.COMMENT_ENDED: if (c2 !== ">") { strictFail(parser, "Malformed comment"); parser.comment += "--" + c2; parser.state = S2.COMMENT; } else { parser.state = S2.TEXT; } continue; case S2.CDATA: if (c2 === "]") { parser.state = S2.CDATA_ENDING; } else { parser.cdata += c2; } continue; case S2.CDATA_ENDING: if (c2 === "]") { parser.state = S2.CDATA_ENDING_2; } else { parser.cdata += "]" + c2; parser.state = S2.CDATA; } continue; case S2.CDATA_ENDING_2: if (c2 === ">") { if (parser.cdata) { emitNode(parser, "oncdata", parser.cdata); } emitNode(parser, "onclosecdata"); parser.cdata = ""; parser.state = S2.TEXT; } else if (c2 === "]") { parser.cdata += "]"; } else { parser.cdata += "]]" + c2; parser.state = S2.CDATA; } continue; case S2.PROC_INST: if (c2 === "?") { parser.state = S2.PROC_INST_ENDING; } else if (isWhitespace2(c2)) { parser.state = S2.PROC_INST_BODY; } else { parser.procInstName += c2; } continue; case S2.PROC_INST_BODY: if (!parser.procInstBody && isWhitespace2(c2)) { continue; } else if (c2 === "?") { parser.state = S2.PROC_INST_ENDING; } else { parser.procInstBody += c2; } continue; case S2.PROC_INST_ENDING: if (c2 === ">") { emitNode(parser, "onprocessinginstruction", { name: parser.procInstName, body: parser.procInstBody }); parser.procInstName = parser.procInstBody = ""; parser.state = S2.TEXT; } else { parser.procInstBody += "?" + c2; parser.state = S2.PROC_INST_BODY; } continue; case S2.OPEN_TAG: if (isMatch(nameBody, c2)) { parser.tagName += c2; } else { newTag(parser); if (c2 === ">") { openTag(parser); } else if (c2 === "/") { parser.state = S2.OPEN_TAG_SLASH; } else { if (!isWhitespace2(c2)) { strictFail(parser, "Invalid character in tag name"); } parser.state = S2.ATTRIB; } } continue; case S2.OPEN_TAG_SLASH: if (c2 === ">") { openTag(parser, true); closeTag(parser); } else { strictFail(parser, "Forward-slash in opening tag not followed by >"); parser.state = S2.ATTRIB; } continue; case S2.ATTRIB: if (isWhitespace2(c2)) { continue; } else if (c2 === ">") { openTag(parser); } else if (c2 === "/") { parser.state = S2.OPEN_TAG_SLASH; } else if (isMatch(nameStart, c2)) { parser.attribName = c2; parser.attribValue = ""; parser.state = S2.ATTRIB_NAME; } else { strictFail(parser, "Invalid attribute name"); } continue; case S2.ATTRIB_NAME: if (c2 === "=") { parser.state = S2.ATTRIB_VALUE; } else if (c2 === ">") { strictFail(parser, "Attribute without value"); parser.attribValue = parser.attribName; attrib(parser); openTag(parser); } else if (isWhitespace2(c2)) { parser.state = S2.ATTRIB_NAME_SAW_WHITE; } else if (isMatch(nameBody, c2)) { parser.attribName += c2; } else { strictFail(parser, "Invalid attribute name"); } continue; case S2.ATTRIB_NAME_SAW_WHITE: if (c2 === "=") { parser.state = S2.ATTRIB_VALUE; } else if (isWhitespace2(c2)) { continue; } else { strictFail(parser, "Attribute without value"); parser.tag.attributes[parser.attribName] = ""; parser.attribValue = ""; emitNode(parser, "onattribute", { name: parser.attribName, value: "" }); parser.attribName = ""; if (c2 === ">") { openTag(parser); } else if (isMatch(nameStart, c2)) { parser.attribName = c2; parser.state = S2.ATTRIB_NAME; } else { strictFail(parser, "Invalid attribute name"); parser.state = S2.ATTRIB; } } continue; case S2.ATTRIB_VALUE: if (isWhitespace2(c2)) { continue; } else if (isQuote(c2)) { parser.q = c2; parser.state = S2.ATTRIB_VALUE_QUOTED; } else { strictFail(parser, "Unquoted attribute value"); parser.state = S2.ATTRIB_VALUE_UNQUOTED; parser.attribValue = c2; } continue; case S2.ATTRIB_VALUE_QUOTED: if (c2 !== parser.q) { if (c2 === "&") { parser.state = S2.ATTRIB_VALUE_ENTITY_Q; } else { parser.attribValue += c2; } continue; } attrib(parser); parser.q = ""; parser.state = S2.ATTRIB_VALUE_CLOSED; continue; case S2.ATTRIB_VALUE_CLOSED: if (isWhitespace2(c2)) { parser.state = S2.ATTRIB; } else if (c2 === ">") { openTag(parser); } else if (c2 === "/") { parser.state = S2.OPEN_TAG_SLASH; } else if (isMatch(nameStart, c2)) { strictFail(parser, "No whitespace between attributes"); parser.attribName = c2; parser.attribValue = ""; parser.state = S2.ATTRIB_NAME; } else { strictFail(parser, "Invalid attribute name"); } continue; case S2.ATTRIB_VALUE_UNQUOTED: if (!isAttribEnd(c2)) { if (c2 === "&") { parser.state = S2.ATTRIB_VALUE_ENTITY_U; } else { parser.attribValue += c2; } continue; } attrib(parser); if (c2 === ">") { openTag(parser); } else { parser.state = S2.ATTRIB; } continue; case S2.CLOSE_TAG: if (!parser.tagName) { if (isWhitespace2(c2)) { continue; } else if (notMatch(nameStart, c2)) { if (parser.script) { parser.script += "") { closeTag(parser); } else if (isMatch(nameBody, c2)) { parser.tagName += c2; } else if (parser.script) { parser.script += "") { closeTag(parser); } else { strictFail(parser, "Invalid characters in closing tag"); } continue; case S2.TEXT_ENTITY: case S2.ATTRIB_VALUE_ENTITY_Q: case S2.ATTRIB_VALUE_ENTITY_U: var returnState; var buffer; switch (parser.state) { case S2.TEXT_ENTITY: returnState = S2.TEXT; buffer = "textNode"; break; case S2.ATTRIB_VALUE_ENTITY_Q: returnState = S2.ATTRIB_VALUE_QUOTED; buffer = "attribValue"; break; case S2.ATTRIB_VALUE_ENTITY_U: returnState = S2.ATTRIB_VALUE_UNQUOTED; buffer = "attribValue"; break; } if (c2 === ";") { if (parser.opt.unparsedEntities) { var parsedEntity = parseEntity(parser); parser.entity = ""; parser.state = returnState; parser.write(parsedEntity); } else { parser[buffer] += parseEntity(parser); parser.entity = ""; parser.state = returnState; } } else if (isMatch(parser.entity.length ? entityBody : entityStart, c2)) { parser.entity += c2; } else { strictFail(parser, "Invalid character in entity name"); parser[buffer] += "&" + parser.entity + c2; parser.entity = ""; parser.state = returnState; } continue; default: { throw new Error(parser, "Unknown state: " + parser.state); } } } if (parser.position >= parser.bufferCheckPosition) { checkBufferLength(parser); } return parser; } if (!String.fromCodePoint) { (function() { var stringFromCharCode = String.fromCharCode; var floor = Math.floor; var fromCodePoint = function() { var MAX_SIZE = 16384; var codeUnits = []; var highSurrogate; var lowSurrogate; var index2 = -1; var length = arguments.length; if (!length) { return ""; } var result = ""; while (++index2 < length) { var codePoint = Number(arguments[index2]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) { throw RangeError("Invalid code point: " + codePoint); } if (codePoint <= 65535) { codeUnits.push(codePoint); } else { codePoint -= 65536; highSurrogate = (codePoint >> 10) + 55296; lowSurrogate = codePoint % 1024 + 56320; codeUnits.push(highSurrogate, lowSurrogate); } if (index2 + 1 === length || codeUnits.length > MAX_SIZE) { result += stringFromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; }; if (Object.defineProperty) { Object.defineProperty(String, "fromCodePoint", { value: fromCodePoint, configurable: true, writable: true }); } else { String.fromCodePoint = fromCodePoint; } })(); } return sax2; }; sax = /* @__PURE__ */ initializeSax(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/xml.js function parseXMLMarkdown(s2) { const cleanedString = strip(s2); const parser = sax.parser(true); let parsedResult = {}; const elementStack = []; parser.onopentag = (node) => { const element = { name: node.name, attributes: node.attributes, children: [], text: "", isSelfClosing: node.isSelfClosing }; if (elementStack.length > 0) { const parentElement = elementStack[elementStack.length - 1]; parentElement.children.push(element); } else { parsedResult = element; } if (!node.isSelfClosing) { elementStack.push(element); } }; parser.onclosetag = () => { if (elementStack.length > 0) { const lastElement = elementStack.pop(); if (elementStack.length === 0 && lastElement) { parsedResult = lastElement; } } }; parser.ontext = (text) => { if (elementStack.length > 0) { const currentElement = elementStack[elementStack.length - 1]; currentElement.text += text; } }; parser.onattribute = (attr) => { if (elementStack.length > 0) { const currentElement = elementStack[elementStack.length - 1]; currentElement.attributes[attr.name] = attr.value; } }; const match = /```(xml)?(.*)```/s.exec(cleanedString); const xmlString = match ? match[2] : cleanedString; parser.write(xmlString).close(); if (parsedResult && parsedResult.name === "?xml") { parsedResult = parsedResult.children[0]; } return parseParsedResult(parsedResult); } var XML_FORMAT_INSTRUCTIONS, XMLOutputParser, strip, parseParsedResult; var init_xml = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/xml.js"() { init_transform(); init_json_patch(); init_sax(); XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file. 1. Output should conform to the tags below. 2. If tags are not given, make them on your own. 3. Remember to always open and close all the tags. As an example, for the tags ["foo", "bar", "baz"]: 1. String " " is a well-formatted instance of the schema. 2. String " " is a badly-formatted instance. 3. String " " is a badly-formatted instance. Here are the output tags: \`\`\` {tags} \`\`\``; XMLOutputParser = class extends BaseCumulativeTransformOutputParser { constructor(fields2) { super(fields2); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain_core", "output_parsers"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); this.tags = fields2?.tags; } static lc_name() { return "XMLOutputParser"; } _diff(prev, next2) { if (!next2) { return void 0; } if (!prev) { return [{ op: "replace", path: "", value: next2 }]; } return compare(prev, next2); } async parsePartialResult(generations) { return parseXMLMarkdown(generations[0].text); } async parse(text) { return parseXMLMarkdown(text); } getFormatInstructions() { const withTags = !!(this.tags && this.tags.length > 0); return withTags ? XML_FORMAT_INSTRUCTIONS.replace("{tags}", this.tags?.join(", ") ?? "") : XML_FORMAT_INSTRUCTIONS; } }; strip = (text) => text.split("\n").map((line) => line.replace(/^\s+/, "")).join("\n").trim(); parseParsedResult = (input) => { if (Object.keys(input).length === 0) { return {}; } const result = {}; if (input.children.length > 0) { result[input.name] = input.children.map(parseParsedResult); return result; } else { result[input.name] = input.text ?? void 0; return result; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/index.js var output_parsers_exports = {}; __export(output_parsers_exports, { AsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser, BaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser, BaseLLMOutputParser: () => BaseLLMOutputParser, BaseOutputParser: () => BaseOutputParser, BaseTransformOutputParser: () => BaseTransformOutputParser, BytesOutputParser: () => BytesOutputParser, CommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser, CustomListOutputParser: () => CustomListOutputParser, JsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser, JsonOutputParser: () => JsonOutputParser, ListOutputParser: () => ListOutputParser, MarkdownListOutputParser: () => MarkdownListOutputParser, NumberedListOutputParser: () => NumberedListOutputParser, OutputParserException: () => OutputParserException, StringOutputParser: () => StringOutputParser, StructuredOutputParser: () => StructuredOutputParser, XMLOutputParser: () => XMLOutputParser, XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, parseJsonMarkdown: () => parseJsonMarkdown, parsePartialJson: () => parsePartialJson, parseXMLMarkdown: () => parseXMLMarkdown }); var init_output_parsers = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/index.js"() { init_base7(); init_bytes(); init_list(); init_string3(); init_structured2(); init_transform(); init_json(); init_xml(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tools.js var tools_exports = {}; __export(tools_exports, { DynamicStructuredTool: () => DynamicStructuredTool, DynamicTool: () => DynamicTool, StructuredTool: () => StructuredTool, Tool: () => Tool, ToolInputParsingException: () => ToolInputParsingException }); var ToolInputParsingException, StructuredTool, Tool, DynamicTool, DynamicStructuredTool; var init_tools = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/tools.js"() { init_lib(); init_manager(); init_base6(); init_config(); ToolInputParsingException = class extends Error { constructor(message, output) { super(message); Object.defineProperty(this, "output", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.output = output; } }; StructuredTool = class extends BaseLangChain { get lc_namespace() { return ["langchain", "tools"]; } constructor(fields2) { super(fields2 ?? {}); Object.defineProperty(this, "returnDirect", { enumerable: true, configurable: true, writable: true, value: false }); } async invoke(input, config) { return this.call(input, ensureConfig(config)); } async call(arg, configArg, tags) { let parsed; try { parsed = await this.schema.parseAsync(arg); } catch (e2) { throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(arg)); } const config = parseCallbackConfigArg(configArg); const callbackManager_ = await CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose }); const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof parsed === "string" ? parsed : JSON.stringify(parsed), void 0, void 0, void 0, void 0, config.runName); let result; try { result = await this._call(parsed, runManager, config); } catch (e2) { await runManager?.handleToolError(e2); throw e2; } await runManager?.handleToolEnd(result); return result; } }; Tool = class extends StructuredTool { constructor(fields2) { super(fields2); Object.defineProperty(this, "schema", { enumerable: true, configurable: true, writable: true, value: z.object({ input: z.string().optional() }).transform((obj) => obj.input) }); } call(arg, callbacks) { return super.call(typeof arg === "string" || !arg ? { input: arg } : arg, callbacks); } }; DynamicTool = class extends Tool { static lc_name() { return "DynamicTool"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "description", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.name = fields2.name; this.description = fields2.description; this.func = fields2.func; this.returnDirect = fields2.returnDirect ?? this.returnDirect; } async call(arg, configArg) { const config = parseCallbackConfigArg(configArg); if (config.runName === void 0) { config.runName = this.name; } return super.call(arg, config); } async _call(input, runManager, config) { return this.func(input, runManager, config); } }; DynamicStructuredTool = class extends StructuredTool { static lc_name() { return "DynamicStructuredTool"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "description", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "schema", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.name = fields2.name; this.description = fields2.description; this.func = fields2.func; this.returnDirect = fields2.returnDirect ?? this.returnDirect; this.schema = fields2.schema; } async call(arg, configArg, tags) { const config = parseCallbackConfigArg(configArg); if (config.runName === void 0) { config.runName = this.name; } return super.call(arg, config, tags); } _call(arg, runManager, config) { return this.func(arg, runManager, config); } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/chunk_array.js var chunk_array_exports = {}; __export(chunk_array_exports, { chunkArray: () => chunkArray }); var chunkArray; var init_chunk_array = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/chunk_array.js"() { chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index2) => { const chunkIndex = Math.floor(index2 / chunkSize); const chunk = chunks[chunkIndex] || []; chunks[chunkIndex] = chunk.concat([elem]); return chunks; }, []); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/function_calling.js var function_calling_exports = {}; __export(function_calling_exports, { convertToOpenAIFunction: () => convertToOpenAIFunction, convertToOpenAITool: () => convertToOpenAITool }); function convertToOpenAIFunction(tool) { return { name: tool.name, description: tool.description, parameters: zodToJsonSchema(tool.schema) }; } function convertToOpenAITool(tool) { return { type: "function", function: convertToOpenAIFunction(tool) }; } var init_function_calling = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/utils/function_calling.js"() { init_esm(); } }); // node_modules/.pnpm/binary-search@1.3.6/node_modules/binary-search/index.js var require_binary_search2 = __commonJS({ "node_modules/.pnpm/binary-search@1.3.6/node_modules/binary-search/index.js"(exports2, module2) { module2.exports = function(haystack, needle, comparator, low, high) { var mid, cmp; if (low === void 0) low = 0; else { low = low | 0; if (low < 0 || low >= haystack.length) throw new RangeError("invalid lower bound"); } if (high === void 0) high = haystack.length - 1; else { high = high | 0; if (high < low || high >= haystack.length) throw new RangeError("invalid upper bound"); } while (low <= high) { mid = low + (high - low >>> 1); cmp = +comparator(haystack[mid], needle, mid, haystack); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; } return ~low; }; } }); // node_modules/.pnpm/num-sort@2.1.0/node_modules/num-sort/index.js var require_num_sort = __commonJS({ "node_modules/.pnpm/num-sort@2.1.0/node_modules/num-sort/index.js"(exports2) { "use strict"; function assertNumber(number) { if (typeof number !== "number") { throw new TypeError("Expected a number"); } } exports2.ascending = (left, right) => { assertNumber(left); assertNumber(right); if (Number.isNaN(left)) { return -1; } if (Number.isNaN(right)) { return 1; } return left - right; }; exports2.descending = (left, right) => { assertNumber(left); assertNumber(right); if (Number.isNaN(left)) { return 1; } if (Number.isNaN(right)) { return -1; } return right - left; }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/load/serializable.js var init_serializable2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/load/serializable.js"() { init_serializable(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/runnables.js var init_runnables2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/runnables.js"() { init_runnables(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/language_models/base.js var init_base8 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/language_models/base.js"() { init_base6(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/outputs.js var init_outputs2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/outputs.js"() { init_outputs(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/callbacks/manager.js var init_manager2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/callbacks/manager.js"() { init_manager(); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/util/set.js function intersection3(setA, setB) { const _intersection = new Set(); for (const elem of setB) { if (setA.has(elem)) { _intersection.add(elem); } } return _intersection; } function union(setA, setB) { const _union = new Set(setA); for (const elem of setB) { _union.add(elem); } return _union; } function difference(setA, setB) { const _difference = new Set(setA); for (const elem of setB) { _difference.delete(elem); } return _difference; } var init_set2 = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/util/set.js"() { } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/sequential_chain.js var sequential_chain_exports = {}; __export(sequential_chain_exports, { SequentialChain: () => SequentialChain, SimpleSequentialChain: () => SimpleSequentialChain }); function formatSet(input) { return Array.from(input).map((i2) => `"${i2}"`).join(", "); } var SequentialChain, SimpleSequentialChain; var init_sequential_chain = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/sequential_chain.js"() { init_base9(); init_set2(); SequentialChain = class extends BaseChain { static lc_name() { return "SequentialChain"; } get inputKeys() { return this.inputVariables; } get outputKeys() { return this.outputVariables; } constructor(fields2) { super(fields2); Object.defineProperty(this, "chains", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputVariables", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputVariables", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "returnAll", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.chains = fields2.chains; this.inputVariables = fields2.inputVariables; this.outputVariables = fields2.outputVariables ?? []; if (this.outputVariables.length > 0 && fields2.returnAll) { throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time."); } this.returnAll = fields2.returnAll ?? false; this._validateChains(); } _validateChains() { if (this.chains.length === 0) { throw new Error("Sequential chain must have at least one chain."); } const memoryKeys = this.memory?.memoryKeys ?? []; const inputKeysSet = new Set(this.inputKeys); const memoryKeysSet = new Set(memoryKeys); const keysIntersection = intersection3(inputKeysSet, memoryKeysSet); if (keysIntersection.size > 0) { throw new Error(`The following keys: ${formatSet(keysIntersection)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`); } const availableKeys = union(inputKeysSet, memoryKeysSet); for (const chain of this.chains) { let missingKeys = difference(new Set(chain.inputKeys), availableKeys); if (chain.memory) { missingKeys = difference(missingKeys, new Set(chain.memory.memoryKeys)); } if (missingKeys.size > 0) { throw new Error(`Missing variables for chain "${chain._chainType()}": ${formatSet(missingKeys)}. Only got the following variables: ${formatSet(availableKeys)}.`); } const outputKeysSet = new Set(chain.outputKeys); const overlappingOutputKeys = intersection3(availableKeys, outputKeysSet); if (overlappingOutputKeys.size > 0) { throw new Error(`The following output variables for chain "${chain._chainType()}" are overlapping: ${formatSet(overlappingOutputKeys)}. This can lead to unexpected behaviour.`); } for (const outputKey of outputKeysSet) { availableKeys.add(outputKey); } } if (this.outputVariables.length === 0) { if (this.returnAll) { const outputKeys = difference(availableKeys, inputKeysSet); this.outputVariables = Array.from(outputKeys); } else { this.outputVariables = this.chains[this.chains.length - 1].outputKeys; } } else { const missingKeys = difference(new Set(this.outputVariables), new Set(availableKeys)); if (missingKeys.size > 0) { throw new Error(`The following output variables were expected to be in the final chain output but were not found: ${formatSet(missingKeys)}.`); } } } async _call(values, runManager) { let input = {}; const allChainValues = values; let i2 = 0; for (const chain of this.chains) { i2 += 1; input = await chain.call(allChainValues, runManager?.getChild(`step_${i2}`)); for (const key of Object.keys(input)) { allChainValues[key] = input[key]; } } const output = {}; for (const key of this.outputVariables) { output[key] = allChainValues[key]; } return output; } _chainType() { return "sequential_chain"; } static async deserialize(data) { const chains = []; const inputVariables = data.input_variables; const outputVariables = data.output_variables; const serializedChains = data.chains; for (const serializedChain of serializedChains) { const deserializedChain = await BaseChain.deserialize(serializedChain); chains.push(deserializedChain); } return new SequentialChain({ chains, inputVariables, outputVariables }); } serialize() { const chains = []; for (const chain of this.chains) { chains.push(chain.serialize()); } return { _type: this._chainType(), input_variables: this.inputVariables, output_variables: this.outputVariables, chains }; } }; SimpleSequentialChain = class extends BaseChain { static lc_name() { return "SimpleSequentialChain"; } get inputKeys() { return [this.inputKey]; } get outputKeys() { return [this.outputKey]; } constructor(fields2) { super(fields2); Object.defineProperty(this, "chains", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input" }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "output" }); Object.defineProperty(this, "trimOutputs", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.chains = fields2.chains; this.trimOutputs = fields2.trimOutputs ?? false; this._validateChains(); } _validateChains() { for (const chain of this.chains) { if (chain.inputKeys.filter((k2) => !chain.memory?.memoryKeys.includes(k2)).length !== 1) { throw new Error(`Chains used in SimpleSequentialChain should all have one input, got ${chain.inputKeys.length} for ${chain._chainType()}.`); } if (chain.outputKeys.length !== 1) { throw new Error(`Chains used in SimpleSequentialChain should all have one output, got ${chain.outputKeys.length} for ${chain._chainType()}.`); } } } async _call(values, runManager) { let input = values[this.inputKey]; let i2 = 0; for (const chain of this.chains) { i2 += 1; input = (await chain.call({ [chain.inputKeys[0]]: input, signal: values.signal }, runManager?.getChild(`step_${i2}`)))[chain.outputKeys[0]]; if (this.trimOutputs) { input = input.trim(); } await runManager?.handleText(input); } return { [this.outputKey]: input }; } _chainType() { return "simple_sequential_chain"; } static async deserialize(data) { const chains = []; const serializedChains = data.chains; for (const serializedChain of serializedChains) { const deserializedChain = await BaseChain.deserialize(serializedChain); chains.push(deserializedChain); } return new SimpleSequentialChain({ chains }); } serialize() { const chains = []; for (const chain of this.chains) { chains.push(chain.serialize()); } return { _type: this._chainType(), chains }; } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/combine_docs_chain.js var combine_docs_chain_exports = {}; __export(combine_docs_chain_exports, { MapReduceDocumentsChain: () => MapReduceDocumentsChain, RefineDocumentsChain: () => RefineDocumentsChain, StuffDocumentsChain: () => StuffDocumentsChain }); var StuffDocumentsChain, MapReduceDocumentsChain, RefineDocumentsChain; var init_combine_docs_chain = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/combine_docs_chain.js"() { init_prompts2(); init_base9(); init_llm_chain(); StuffDocumentsChain = class extends BaseChain { static lc_name() { return "StuffDocumentsChain"; } get inputKeys() { return [this.inputKey, ...this.llmChain.inputKeys].filter((key) => key !== this.documentVariableName); } get outputKeys() { return this.llmChain.outputKeys; } constructor(fields2) { super(fields2); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input_documents" }); Object.defineProperty(this, "documentVariableName", { enumerable: true, configurable: true, writable: true, value: "context" }); this.llmChain = fields2.llmChain; this.documentVariableName = fields2.documentVariableName ?? this.documentVariableName; this.inputKey = fields2.inputKey ?? this.inputKey; } _prepInputs(values) { if (!(this.inputKey in values)) { throw new Error(`Document key ${this.inputKey} not found.`); } const { [this.inputKey]: docs, ...rest } = values; const texts = docs.map(({ pageContent }) => pageContent); const text = texts.join("\n\n"); return { ...rest, [this.documentVariableName]: text }; } async _call(values, runManager) { const result = await this.llmChain.call(this._prepInputs(values), runManager?.getChild("combine_documents")); return result; } _chainType() { return "stuff_documents_chain"; } static async deserialize(data) { if (!data.llm_chain) { throw new Error("Missing llm_chain"); } return new StuffDocumentsChain({ llmChain: await LLMChain.deserialize(data.llm_chain) }); } serialize() { return { _type: this._chainType(), llm_chain: this.llmChain.serialize() }; } }; MapReduceDocumentsChain = class extends BaseChain { static lc_name() { return "MapReduceDocumentsChain"; } get inputKeys() { return [this.inputKey, ...this.combineDocumentChain.inputKeys]; } get outputKeys() { return this.combineDocumentChain.outputKeys; } constructor(fields2) { super(fields2); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input_documents" }); Object.defineProperty(this, "documentVariableName", { enumerable: true, configurable: true, writable: true, value: "context" }); Object.defineProperty(this, "returnIntermediateSteps", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "maxTokens", { enumerable: true, configurable: true, writable: true, value: 3e3 }); Object.defineProperty(this, "maxIterations", { enumerable: true, configurable: true, writable: true, value: 10 }); Object.defineProperty(this, "ensureMapStep", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "combineDocumentChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.llmChain = fields2.llmChain; this.combineDocumentChain = fields2.combineDocumentChain; this.documentVariableName = fields2.documentVariableName ?? this.documentVariableName; this.ensureMapStep = fields2.ensureMapStep ?? this.ensureMapStep; this.inputKey = fields2.inputKey ?? this.inputKey; this.maxTokens = fields2.maxTokens ?? this.maxTokens; this.maxIterations = fields2.maxIterations ?? this.maxIterations; this.returnIntermediateSteps = fields2.returnIntermediateSteps ?? false; } async _call(values, runManager) { if (!(this.inputKey in values)) { throw new Error(`Document key ${this.inputKey} not found.`); } const { [this.inputKey]: docs, ...rest } = values; let currentDocs = docs; let intermediateSteps = []; for (let i2 = 0; i2 < this.maxIterations; i2 += 1) { const inputs = currentDocs.map((d2) => ({ [this.documentVariableName]: d2.pageContent, ...rest })); const canSkipMapStep = i2 !== 0 || !this.ensureMapStep; if (canSkipMapStep) { const formatted = await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({ [this.combineDocumentChain.inputKey]: currentDocs, ...rest })); const length = await this.combineDocumentChain.llmChain._getNumTokens(formatted); const withinTokenLimit = length < this.maxTokens; if (withinTokenLimit) { break; } } const results = await this.llmChain.apply(inputs, runManager ? Array.from({ length: inputs.length }, (_2, i3) => runManager.getChild(`map_${i3 + 1}`)) : void 0); const { outputKey } = this.llmChain; if (this.returnIntermediateSteps) { intermediateSteps = intermediateSteps.concat(results.map((r3) => r3[outputKey])); } currentDocs = results.map((r3) => ({ pageContent: r3[outputKey], metadata: {} })); } const newInputs = { [this.combineDocumentChain.inputKey]: currentDocs, ...rest }; const result = await this.combineDocumentChain.call(newInputs, runManager?.getChild("combine_documents")); if (this.returnIntermediateSteps) { return { ...result, intermediateSteps }; } return result; } _chainType() { return "map_reduce_documents_chain"; } static async deserialize(data) { if (!data.llm_chain) { throw new Error("Missing llm_chain"); } if (!data.combine_document_chain) { throw new Error("Missing combine_document_chain"); } return new MapReduceDocumentsChain({ llmChain: await LLMChain.deserialize(data.llm_chain), combineDocumentChain: await StuffDocumentsChain.deserialize(data.combine_document_chain) }); } serialize() { return { _type: this._chainType(), llm_chain: this.llmChain.serialize(), combine_document_chain: this.combineDocumentChain.serialize() }; } }; RefineDocumentsChain = class extends BaseChain { static lc_name() { return "RefineDocumentsChain"; } get defaultDocumentPrompt() { return new PromptTemplate({ inputVariables: ["page_content"], template: "{page_content}" }); } get inputKeys() { return [ ...new Set([ this.inputKey, ...this.llmChain.inputKeys, ...this.refineLLMChain.inputKeys ]) ].filter((key) => key !== this.documentVariableName && key !== this.initialResponseName); } get outputKeys() { return [this.outputKey]; } constructor(fields2) { super(fields2); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input_documents" }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "output_text" }); Object.defineProperty(this, "documentVariableName", { enumerable: true, configurable: true, writable: true, value: "context" }); Object.defineProperty(this, "initialResponseName", { enumerable: true, configurable: true, writable: true, value: "existing_answer" }); Object.defineProperty(this, "refineLLMChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "documentPrompt", { enumerable: true, configurable: true, writable: true, value: this.defaultDocumentPrompt }); this.llmChain = fields2.llmChain; this.refineLLMChain = fields2.refineLLMChain; this.documentVariableName = fields2.documentVariableName ?? this.documentVariableName; this.inputKey = fields2.inputKey ?? this.inputKey; this.outputKey = fields2.outputKey ?? this.outputKey; this.documentPrompt = fields2.documentPrompt ?? this.documentPrompt; this.initialResponseName = fields2.initialResponseName ?? this.initialResponseName; } async _constructInitialInputs(doc, rest) { const baseInfo = { page_content: doc.pageContent, ...doc.metadata }; const documentInfo = {}; this.documentPrompt.inputVariables.forEach((value) => { documentInfo[value] = baseInfo[value]; }); const baseInputs = { [this.documentVariableName]: await this.documentPrompt.format({ ...documentInfo }) }; const inputs = { ...baseInputs, ...rest }; return inputs; } async _constructRefineInputs(doc, res) { const baseInfo = { page_content: doc.pageContent, ...doc.metadata }; const documentInfo = {}; this.documentPrompt.inputVariables.forEach((value) => { documentInfo[value] = baseInfo[value]; }); const baseInputs = { [this.documentVariableName]: await this.documentPrompt.format({ ...documentInfo }) }; const inputs = { [this.initialResponseName]: res, ...baseInputs }; return inputs; } async _call(values, runManager) { if (!(this.inputKey in values)) { throw new Error(`Document key ${this.inputKey} not found.`); } const { [this.inputKey]: docs, ...rest } = values; const currentDocs = docs; const initialInputs = await this._constructInitialInputs(currentDocs[0], rest); let res = await this.llmChain.predict({ ...initialInputs }, runManager?.getChild("answer")); const refineSteps = [res]; for (let i2 = 1; i2 < currentDocs.length; i2 += 1) { const refineInputs = await this._constructRefineInputs(currentDocs[i2], res); const inputs = { ...refineInputs, ...rest }; res = await this.refineLLMChain.predict({ ...inputs }, runManager?.getChild("refine")); refineSteps.push(res); } return { [this.outputKey]: res }; } _chainType() { return "refine_documents_chain"; } static async deserialize(data) { const SerializedLLMChain = data.llm_chain; if (!SerializedLLMChain) { throw new Error("Missing llm_chain"); } const SerializedRefineDocumentChain = data.refine_llm_chain; if (!SerializedRefineDocumentChain) { throw new Error("Missing refine_llm_chain"); } return new RefineDocumentsChain({ llmChain: await LLMChain.deserialize(SerializedLLMChain), refineLLMChain: await LLMChain.deserialize(SerializedRefineDocumentChain) }); } serialize() { return { _type: this._chainType(), llm_chain: this.llmChain.serialize(), refine_llm_chain: this.refineLLMChain.serialize() }; } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/stuff_prompts.js var DEFAULT_QA_PROMPT, system_template, messages, CHAT_PROMPT, QA_PROMPT_SELECTOR; var init_stuff_prompts = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/stuff_prompts.js"() { init_prompts2(); init_example_selectors2(); DEFAULT_QA_PROMPT = /* @__PURE__ */ new PromptTemplate({ template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", inputVariables: ["context", "question"] }); system_template = `Use the following pieces of context to answer the users question. If you don't know the answer, just say that you don't know, don't try to make up an answer. ---------------- {context}`; messages = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(system_template), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromMessages(messages); QA_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_QA_PROMPT, [[isChatModel, CHAT_PROMPT]]); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/map_reduce_prompts.js var qa_template, DEFAULT_COMBINE_QA_PROMPT, system_template2, messages2, CHAT_QA_PROMPT, COMBINE_QA_PROMPT_SELECTOR, combine_prompt, COMBINE_PROMPT, system_combine_template, combine_messages, CHAT_COMBINE_PROMPT, COMBINE_PROMPT_SELECTOR; var init_map_reduce_prompts = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/map_reduce_prompts.js"() { init_prompts2(); init_example_selectors2(); qa_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. Return any relevant text verbatim. {context} Question: {question} Relevant text, if any:`; DEFAULT_COMBINE_QA_PROMPT = /* @__PURE__ */ PromptTemplate.fromTemplate(qa_template); system_template2 = `Use the following portion of a long document to see if any of the text is relevant to answer the question. Return any relevant text verbatim. ---------------- {context}`; messages2 = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(system_template2), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_QA_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromMessages(messages2); COMBINE_QA_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_COMBINE_QA_PROMPT, [ [isChatModel, CHAT_QA_PROMPT] ]); combine_prompt = `Given the following extracted parts of a long document and a question, create a final answer. If you don't know the answer, just say that you don't know. Don't try to make up an answer. QUESTION: Which state/country's law governs the interpretation of the contract? ========= Content: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an injunction or other relief to protect its Intellectual Property Rights. Content: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other) right or remedy. 11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation in force of the remainder of the term (if any) and this Agreement. 11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any kind between the parties. 11.9 No Third-Party Beneficiaries. Content: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as defined in Clause 8.5) or that such a violation is reasonably likely to occur, ========= FINAL ANSWER: This Agreement is governed by English law. QUESTION: What did the president say about Michael Jackson? ========= Content: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. Last year COVID-19 kept us apart. This year we are finally together again. Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. With a duty to one another to the American people to the Constitution. And with an unwavering resolve that freedom will always triumph over tyranny. Six days ago, Russia\u2019s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. He thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. He met the Ukrainian people. From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. Content: And we won\u2019t stop. We have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. Let\u2019s use this moment to reset. Let\u2019s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. Let\u2019s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. We can\u2019t change how divided we\u2019ve been. But we can change how we move forward\u2014on COVID-19 and other issues we must face together. I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. Officer Mora was 27 years old. Officer Rivera was 22. Both Dominican Americans who\u2019d grown up on the same streets they later chose to patrol as police officers. I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. Content: And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. To all Americans, I will be honest with you, as I\u2019ve always promised. A Russian dictator, invading a foreign country, has costs around the world. And I\u2019m taking robust action to make sure the pain of our sanctions is targeted at Russia\u2019s economy. And I will use every tool at our disposal to protect American businesses and consumers. Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. These steps will help blunt gas prices here at home. And I know the news about what\u2019s happening can seem alarming. But I want you to know that we are going to be okay. Content: More support for patients and families. To get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. It\u2019s based on DARPA\u2014the Defense Department project that led to the Internet, GPS, and so much more. ARPA-H will have a singular purpose\u2014to drive breakthroughs in cancer, Alzheimer\u2019s, diabetes, and more. A unity agenda for the nation. We can do this. My fellow Americans\u2014tonight , we have gathered in a sacred space\u2014the citadel of our democracy. In this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. We have fought for freedom, expanded liberty, defeated totalitarianism and terror. And built the strongest, freest, and most prosperous nation the world has ever known. Now is the hour. Our moment of responsibility. Our test of resolve and conscience, of history itself. It is in this moment that our character is formed. Our purpose is found. Our future is forged. Well I know this nation. ========= FINAL ANSWER: The president did not mention Michael Jackson. QUESTION: {question} ========= {summaries} ========= FINAL ANSWER:`; COMBINE_PROMPT = /* @__PURE__ */ PromptTemplate.fromTemplate(combine_prompt); system_combine_template = `Given the following extracted parts of a long document and a question, create a final answer. If you don't know the answer, just say that you don't know. Don't try to make up an answer. ---------------- {summaries}`; combine_messages = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(system_combine_template), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_COMBINE_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromMessages(combine_messages); COMBINE_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(COMBINE_PROMPT, [ [isChatModel, CHAT_COMBINE_PROMPT] ]); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/refine_prompts.js var DEFAULT_REFINE_PROMPT_TMPL, DEFAULT_REFINE_PROMPT, refineTemplate, messages3, CHAT_REFINE_PROMPT, REFINE_PROMPT_SELECTOR, DEFAULT_TEXT_QA_PROMPT_TMPL, DEFAULT_TEXT_QA_PROMPT, chat_qa_prompt_template, chat_messages, CHAT_QUESTION_PROMPT, QUESTION_PROMPT_SELECTOR; var init_refine_prompts = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/refine_prompts.js"() { init_prompts2(); init_example_selectors2(); DEFAULT_REFINE_PROMPT_TMPL = `The original question is as follows: {question} We have provided an existing answer: {existing_answer} We have the opportunity to refine the existing answer (only if needed) with some more context below. ------------ {context} ------------ Given the new context, refine the original answer to better answer the question. If the context isn't useful, return the original answer.`; DEFAULT_REFINE_PROMPT = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["question", "existing_answer", "context"], template: DEFAULT_REFINE_PROMPT_TMPL }); refineTemplate = `The original question is as follows: {question} We have provided an existing answer: {existing_answer} We have the opportunity to refine the existing answer (only if needed) with some more context below. ------------ {context} ------------ Given the new context, refine the original answer to better answer the question. If the context isn't useful, return the original answer.`; messages3 = [ /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}"), /* @__PURE__ */ AIMessagePromptTemplate.fromTemplate("{existing_answer}"), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate(refineTemplate) ]; CHAT_REFINE_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromMessages(messages3); REFINE_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_REFINE_PROMPT, [ [isChatModel, CHAT_REFINE_PROMPT] ]); DEFAULT_TEXT_QA_PROMPT_TMPL = `Context information is below. --------------------- {context} --------------------- Given the context information and no prior knowledge, answer the question: {question}`; DEFAULT_TEXT_QA_PROMPT = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["context", "question"], template: DEFAULT_TEXT_QA_PROMPT_TMPL }); chat_qa_prompt_template = `Context information is below. --------------------- {context} --------------------- Given the context information and no prior knowledge, answer any questions`; chat_messages = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(chat_qa_prompt_template), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_QUESTION_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromMessages(chat_messages); QUESTION_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_TEXT_QA_PROMPT, [ [isChatModel, CHAT_QUESTION_PROMPT] ]); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/load.js function loadQAStuffChain(llm, params = {}) { const { prompt = QA_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; const llmChain = new LLMChain({ prompt, llm, verbose }); const chain = new StuffDocumentsChain({ llmChain, verbose }); return chain; } function loadQAMapReduceChain(llm, params = {}) { const { combineMapPrompt = COMBINE_QA_PROMPT_SELECTOR.getPrompt(llm), combinePrompt = COMBINE_PROMPT_SELECTOR.getPrompt(llm), verbose, combineLLM, returnIntermediateSteps } = params; const llmChain = new LLMChain({ prompt: combineMapPrompt, llm, verbose }); const combineLLMChain = new LLMChain({ prompt: combinePrompt, llm: combineLLM ?? llm, verbose }); const combineDocumentChain = new StuffDocumentsChain({ llmChain: combineLLMChain, documentVariableName: "summaries", verbose }); const chain = new MapReduceDocumentsChain({ llmChain, combineDocumentChain, returnIntermediateSteps, verbose }); return chain; } function loadQARefineChain(llm, params = {}) { const { questionPrompt = QUESTION_PROMPT_SELECTOR.getPrompt(llm), refinePrompt = REFINE_PROMPT_SELECTOR.getPrompt(llm), refineLLM, verbose } = params; const llmChain = new LLMChain({ prompt: questionPrompt, llm, verbose }); const refineLLMChain = new LLMChain({ prompt: refinePrompt, llm: refineLLM ?? llm, verbose }); const chain = new RefineDocumentsChain({ llmChain, refineLLMChain, verbose }); return chain; } var loadQAChain; var init_load = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/question_answering/load.js"() { init_llm_chain(); init_combine_docs_chain(); init_stuff_prompts(); init_map_reduce_prompts(); init_refine_prompts(); loadQAChain = (llm, params = { type: "stuff" }) => { const { type: type2 } = params; if (type2 === "stuff") { return loadQAStuffChain(llm, params); } if (type2 === "map_reduce") { return loadQAMapReduceChain(llm, params); } if (type2 === "refine") { return loadQARefineChain(llm, params); } throw new Error(`Invalid _type: ${type2}`); }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/vector_db_qa.js var vector_db_qa_exports = {}; __export(vector_db_qa_exports, { VectorDBQAChain: () => VectorDBQAChain }); var VectorDBQAChain; var init_vector_db_qa = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/vector_db_qa.js"() { init_base9(); init_load(); VectorDBQAChain = class extends BaseChain { static lc_name() { return "VectorDBQAChain"; } get inputKeys() { return [this.inputKey]; } get outputKeys() { return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); } constructor(fields2) { super(fields2); Object.defineProperty(this, "k", { enumerable: true, configurable: true, writable: true, value: 4 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "query" }); Object.defineProperty(this, "vectorstore", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "combineDocumentsChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "returnSourceDocuments", { enumerable: true, configurable: true, writable: true, value: false }); this.vectorstore = fields2.vectorstore; this.combineDocumentsChain = fields2.combineDocumentsChain; this.inputKey = fields2.inputKey ?? this.inputKey; this.k = fields2.k ?? this.k; this.returnSourceDocuments = fields2.returnSourceDocuments ?? this.returnSourceDocuments; } async _call(values, runManager) { if (!(this.inputKey in values)) { throw new Error(`Question key ${this.inputKey} not found.`); } const question = values[this.inputKey]; const docs = await this.vectorstore.similaritySearch(question, this.k, values.filter, runManager?.getChild("vectorstore")); const inputs = { question, input_documents: docs }; const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); if (this.returnSourceDocuments) { return { ...result, sourceDocuments: docs }; } return result; } _chainType() { return "vector_db_qa"; } static async deserialize(data, values) { if (!("vectorstore" in values)) { throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); } const { vectorstore } = values; if (!data.combine_documents_chain) { throw new Error(`VectorDBQAChain must have combine_documents_chain in serialized data`); } return new VectorDBQAChain({ combineDocumentsChain: await BaseChain.deserialize(data.combine_documents_chain), k: data.k, vectorstore }); } serialize() { return { _type: this._chainType(), combine_documents_chain: this.combineDocumentsChain.serialize(), k: this.k }; } static fromLLM(llm, vectorstore, options) { const qaChain = loadQAStuffChain(llm); return new this({ vectorstore, combineDocumentsChain: qaChain, ...options }); } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/api/prompts.js var API_URL_RAW_PROMPT_TEMPLATE, API_URL_PROMPT_TEMPLATE, API_RESPONSE_RAW_PROMPT_TEMPLATE, API_RESPONSE_PROMPT_TEMPLATE; var init_prompts3 = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/api/prompts.js"() { init_prompts2(); API_URL_RAW_PROMPT_TEMPLATE = `You are given the below API Documentation: {api_docs} Using this documentation, generate the full API url to call for answering the user question. You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call. Question:{question} API url:`; API_URL_PROMPT_TEMPLATE = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["api_docs", "question"], template: API_URL_RAW_PROMPT_TEMPLATE }); API_RESPONSE_RAW_PROMPT_TEMPLATE = `${API_URL_RAW_PROMPT_TEMPLATE} {api_url} Here is the response from the API: {api_response} Summarize this response to answer the original question. Summary:`; API_RESPONSE_PROMPT_TEMPLATE = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["api_docs", "question", "api_url", "api_response"], template: API_RESPONSE_RAW_PROMPT_TEMPLATE }); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/api/api_chain.js var api_chain_exports = {}; __export(api_chain_exports, { APIChain: () => APIChain }); var APIChain; var init_api_chain = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/api/api_chain.js"() { init_base9(); init_llm_chain(); init_prompts3(); APIChain = class extends BaseChain { get inputKeys() { return [this.inputKey]; } get outputKeys() { return [this.outputKey]; } constructor(fields2) { super(fields2); Object.defineProperty(this, "apiAnswerChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "apiRequestChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "apiDocs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "headers", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "question" }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "output" }); this.apiRequestChain = fields2.apiRequestChain; this.apiAnswerChain = fields2.apiAnswerChain; this.apiDocs = fields2.apiDocs; this.inputKey = fields2.inputKey ?? this.inputKey; this.outputKey = fields2.outputKey ?? this.outputKey; this.headers = fields2.headers ?? this.headers; } async _call(values, runManager) { const question = values[this.inputKey]; const api_url = await this.apiRequestChain.predict({ question, api_docs: this.apiDocs }, runManager?.getChild("request")); const res = await fetch(api_url, { headers: this.headers }); const api_response = await res.text(); const answer = await this.apiAnswerChain.predict({ question, api_docs: this.apiDocs, api_url, api_response }, runManager?.getChild("response")); return { [this.outputKey]: answer }; } _chainType() { return "api_chain"; } static async deserialize(data) { const { api_request_chain, api_answer_chain, api_docs } = data; if (!api_request_chain) { throw new Error("LLMChain must have api_request_chain"); } if (!api_answer_chain) { throw new Error("LLMChain must have api_answer_chain"); } if (!api_docs) { throw new Error("LLMChain must have api_docs"); } return new APIChain({ apiAnswerChain: await LLMChain.deserialize(api_answer_chain), apiRequestChain: await LLMChain.deserialize(api_request_chain), apiDocs: api_docs }); } serialize() { return { _type: this._chainType(), api_answer_chain: this.apiAnswerChain.serialize(), api_request_chain: this.apiRequestChain.serialize(), api_docs: this.apiDocs }; } static fromLLMAndAPIDocs(llm, apiDocs, options = {}) { const { apiUrlPrompt = API_URL_PROMPT_TEMPLATE, apiResponsePrompt = API_RESPONSE_PROMPT_TEMPLATE } = options; const apiRequestChain = new LLMChain({ prompt: apiUrlPrompt, llm }); const apiAnswerChain = new LLMChain({ prompt: apiResponsePrompt, llm }); return new this({ apiAnswerChain, apiRequestChain, apiDocs, ...options }); } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/base.js var BaseChain; var init_base9 = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/base.js"() { init_outputs2(); init_manager2(); init_runnables2(); init_base8(); BaseChain = class extends BaseLangChain { get lc_namespace() { return ["langchain", "chains", this._chainType()]; } constructor(fields2, verbose, callbacks) { if (arguments.length === 1 && typeof fields2 === "object" && !("saveContext" in fields2)) { const { memory, callbackManager, ...rest } = fields2; super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); this.memory = memory; } else { super({ verbose, callbacks }); this.memory = fields2; } } _selectMemoryInputs(values) { const valuesForMemory = { ...values }; if ("signal" in valuesForMemory) { delete valuesForMemory.signal; } if ("timeout" in valuesForMemory) { delete valuesForMemory.timeout; } return valuesForMemory; } async invoke(input, options) { const config = ensureConfig(options); const fullValues = await this._formatValues(input); const callbackManager_ = await CallbackManager.configure(config?.callbacks, this.callbacks, config?.tags, this.tags, config?.metadata, this.metadata, { verbose: this.verbose }); const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues, void 0, void 0, void 0, void 0, config?.runName); let outputValues; try { outputValues = await (fullValues.signal ? Promise.race([ this._call(fullValues, runManager, config), new Promise((_2, reject) => { fullValues.signal?.addEventListener("abort", () => { reject(new Error("AbortError")); }); }) ]) : this._call(fullValues, runManager, config)); } catch (e2) { await runManager?.handleChainError(e2); throw e2; } if (!(this.memory == null)) { await this.memory.saveContext(this._selectMemoryInputs(input), outputValues); } await runManager?.handleChainEnd(outputValues); Object.defineProperty(outputValues, RUN_KEY, { value: runManager ? { runId: runManager?.runId } : void 0, configurable: true }); return outputValues; } _validateOutputs(outputs) { const missingKeys = this.outputKeys.filter((k2) => !(k2 in outputs)); if (missingKeys.length) { throw new Error(`Missing output keys: ${missingKeys.join(", ")} from chain ${this._chainType()}`); } } async prepOutputs(inputs, outputs, returnOnlyOutputs = false) { this._validateOutputs(outputs); if (this.memory) { await this.memory.saveContext(inputs, outputs); } if (returnOnlyOutputs) { return outputs; } return { ...inputs, ...outputs }; } serialize() { throw new Error("Method not implemented."); } async run(input, config) { const inputKeys = this.inputKeys.filter((k2) => !this.memory?.memoryKeys.includes(k2)); const isKeylessInput = inputKeys.length <= 1; if (!isKeylessInput) { throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); } const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; const returnValues = await this.call(values, config); const keys = Object.keys(returnValues); if (keys.length === 1) { return returnValues[keys[0]]; } throw new Error("return values have multiple keys, `run` only supported when one key currently"); } async _formatValues(values) { const fullValues = { ...values }; if (fullValues.timeout && !fullValues.signal) { fullValues.signal = AbortSignal.timeout(fullValues.timeout); delete fullValues.timeout; } if (!(this.memory == null)) { const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); for (const [key, value] of Object.entries(newValues)) { fullValues[key] = value; } } return fullValues; } async call(values, config, tags) { const parsedConfig = { tags, ...parseCallbackConfigArg(config) }; return this.invoke(values, parsedConfig); } async apply(inputs, config) { return Promise.all(inputs.map(async (i2, idx) => this.call(i2, config?.[idx]))); } static async deserialize(data, values = {}) { switch (data._type) { case "llm_chain": { const { LLMChain: LLMChain2 } = await Promise.resolve().then(() => (init_llm_chain(), llm_chain_exports)); return LLMChain2.deserialize(data); } case "sequential_chain": { const { SequentialChain: SequentialChain2 } = await Promise.resolve().then(() => (init_sequential_chain(), sequential_chain_exports)); return SequentialChain2.deserialize(data); } case "simple_sequential_chain": { const { SimpleSequentialChain: SimpleSequentialChain2 } = await Promise.resolve().then(() => (init_sequential_chain(), sequential_chain_exports)); return SimpleSequentialChain2.deserialize(data); } case "stuff_documents_chain": { const { StuffDocumentsChain: StuffDocumentsChain2 } = await Promise.resolve().then(() => (init_combine_docs_chain(), combine_docs_chain_exports)); return StuffDocumentsChain2.deserialize(data); } case "map_reduce_documents_chain": { const { MapReduceDocumentsChain: MapReduceDocumentsChain2 } = await Promise.resolve().then(() => (init_combine_docs_chain(), combine_docs_chain_exports)); return MapReduceDocumentsChain2.deserialize(data); } case "refine_documents_chain": { const { RefineDocumentsChain: RefineDocumentsChain2 } = await Promise.resolve().then(() => (init_combine_docs_chain(), combine_docs_chain_exports)); return RefineDocumentsChain2.deserialize(data); } case "vector_db_qa": { const { VectorDBQAChain: VectorDBQAChain2 } = await Promise.resolve().then(() => (init_vector_db_qa(), vector_db_qa_exports)); return VectorDBQAChain2.deserialize(data, values); } case "api_chain": { const { APIChain: APIChain2 } = await Promise.resolve().then(() => (init_api_chain(), api_chain_exports)); return APIChain2.deserialize(data); } default: throw new Error(`Invalid prompt type in config: ${data._type}`); } } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/output_parsers.js var init_output_parsers2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/output_parsers.js"() { init_output_parsers(); } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/output_parsers/noop.js var NoOpOutputParser; var init_noop = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/output_parsers/noop.js"() { init_output_parsers2(); NoOpOutputParser = class extends BaseOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "output_parsers", "default"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); } static lc_name() { return "NoOpOutputParser"; } parse(text) { return Promise.resolve(text); } getFormatInstructions() { return ""; } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/llm_chain.js var llm_chain_exports = {}; __export(llm_chain_exports, { LLMChain: () => LLMChain }); function isBaseLanguageModel(llmLike) { return typeof llmLike._llmType === "function"; } function _getLanguageModel(llmLike) { if (isBaseLanguageModel(llmLike)) { return llmLike; } else if ("bound" in llmLike && Runnable.isRunnable(llmLike.bound)) { return _getLanguageModel(llmLike.bound); } else if ("runnable" in llmLike && "fallbacks" in llmLike && Runnable.isRunnable(llmLike.runnable)) { return _getLanguageModel(llmLike.runnable); } else if ("default" in llmLike && Runnable.isRunnable(llmLike.default)) { return _getLanguageModel(llmLike.default); } else { throw new Error("Unable to extract BaseLanguageModel from llmLike object."); } } var LLMChain; var init_llm_chain = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/chains/llm_chain.js"() { init_base8(); init_prompts2(); init_runnables2(); init_base9(); init_noop(); LLMChain = class extends BaseChain { static lc_name() { return "LLMChain"; } get inputKeys() { return this.prompt.inputVariables; } get outputKeys() { return [this.outputKey]; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "prompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "llm", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "llmKwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "text" }); Object.defineProperty(this, "outputParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.prompt = fields2.prompt; this.llm = fields2.llm; this.llmKwargs = fields2.llmKwargs; this.outputKey = fields2.outputKey ?? this.outputKey; this.outputParser = fields2.outputParser ?? new NoOpOutputParser(); if (this.prompt.outputParser) { if (fields2.outputParser) { throw new Error("Cannot set both outputParser and prompt.outputParser"); } this.outputParser = this.prompt.outputParser; } } getCallKeys() { const callKeys = "callKeys" in this.llm ? this.llm.callKeys : []; return callKeys; } _selectMemoryInputs(values) { const valuesForMemory = super._selectMemoryInputs(values); const callKeys = this.getCallKeys(); for (const key of callKeys) { if (key in values) { delete valuesForMemory[key]; } } return valuesForMemory; } async _getFinalOutput(generations, promptValue, runManager) { let finalCompletion; if (this.outputParser) { finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); } else { finalCompletion = generations[0].text; } return finalCompletion; } call(values, config) { return super.call(values, config); } async _call(values, runManager) { const valuesForPrompt = { ...values }; const valuesForLLM = { ...this.llmKwargs }; const callKeys = this.getCallKeys(); for (const key of callKeys) { if (key in values) { if (valuesForLLM) { valuesForLLM[key] = values[key]; delete valuesForPrompt[key]; } } } const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); if ("generatePrompt" in this.llm) { const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); return { [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager) }; } const modelWithParser = this.outputParser ? this.llm.pipe(this.outputParser) : this.llm; const response = await modelWithParser.invoke(promptValue, runManager?.getChild()); return { [this.outputKey]: response }; } async predict(values, callbackManager) { const output = await this.call(values, callbackManager); return output[this.outputKey]; } _chainType() { return "llm"; } static async deserialize(data) { const { llm, prompt } = data; if (!llm) { throw new Error("LLMChain must have llm"); } if (!prompt) { throw new Error("LLMChain must have prompt"); } return new LLMChain({ llm: await BaseLanguageModel.deserialize(llm), prompt: await BasePromptTemplate.deserialize(prompt) }); } serialize() { const serialize2 = "serialize" in this.llm ? this.llm.serialize() : void 0; return { _type: `${this._chainType()}_chain`, llm: serialize2, prompt: this.prompt.serialize() }; } _getNumTokens(text) { return _getLanguageModel(this.llm).getNumTokens(text); } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/helpers.js var deserializeHelper; var init_helpers2 = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/helpers.js"() { init_llm_chain(); deserializeHelper = async (llm, tools, data, fromLLMAndTools, fromConstructor) => { if (data.load_from_llm_and_tools) { if (!llm) { throw new Error("Loading from llm and tools, llm must be provided."); } if (!tools) { throw new Error("Loading from llm and tools, tools must be provided."); } return fromLLMAndTools(llm, tools, data); } if (!data.llm_chain) { throw new Error("Loading from constructor, llm_chain must be provided."); } const llmChain = await LLMChain.deserialize(data.llm_chain); return fromConstructor({ ...data, llmChain }); }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/types.js var AgentActionOutputParser, AgentMultiActionOutputParser; var init_types2 = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/types.js"() { init_output_parsers2(); AgentActionOutputParser = class extends BaseOutputParser { }; AgentMultiActionOutputParser = class extends BaseOutputParser { }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/mrkl/prompt.js var PREFIX, FORMAT_INSTRUCTIONS, SUFFIX; var init_prompt2 = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/mrkl/prompt.js"() { PREFIX = `Answer the following questions as best you can. You have access to the following tools:`; FORMAT_INSTRUCTIONS = `Use the following format in your response: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question`; SUFFIX = `Begin! Question: {input} Thought:{agent_scratchpad}`; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/mrkl/outputParser.js var FINAL_ANSWER_ACTION, ZeroShotAgentOutputParser; var init_outputParser = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/mrkl/outputParser.js"() { init_output_parsers2(); init_types2(); init_prompt2(); FINAL_ANSWER_ACTION = "Final Answer:"; ZeroShotAgentOutputParser = class extends AgentActionOutputParser { constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "agents", "mrkl"] }); Object.defineProperty(this, "finishToolName", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.finishToolName = fields2?.finishToolName || FINAL_ANSWER_ACTION; } async parse(text) { if (text.includes(this.finishToolName)) { const parts = text.split(this.finishToolName); const output = parts[parts.length - 1].trim(); return { returnValues: { output }, log: text }; } const match = /Action:([\s\S]*?)(?:\nAction Input:([\s\S]*?))?$/.exec(text); if (!match) { throw new OutputParserException(`Could not parse LLM output: ${text}`); } return { tool: match[1].trim(), toolInput: match[2] ? match[2].trim().replace(/^("+)(.*?)(\1)$/, "$2") : "", log: text }; } getFormatInstructions() { return FORMAT_INSTRUCTIONS; } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/mrkl/index.js var mrkl_exports = {}; __export(mrkl_exports, { ZeroShotAgent: () => ZeroShotAgent }); var ZeroShotAgent; var init_mrkl = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/mrkl/index.js"() { init_prompts2(); init_llm_chain(); init_agent(); init_helpers2(); init_outputParser(); init_prompt2(); ZeroShotAgent = class extends Agent { static lc_name() { return "ZeroShotAgent"; } constructor(input) { const outputParser = input?.outputParser ?? ZeroShotAgent.getDefaultOutputParser(); super({ ...input, outputParser }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "agents", "mrkl"] }); } _agentType() { return "zero-shot-react-description"; } observationPrefix() { return "Observation: "; } llmPrefix() { return "Thought:"; } static getDefaultOutputParser(fields2) { return new ZeroShotAgentOutputParser(fields2); } static validateTools(tools) { const descriptionlessTool = tools.find((tool) => !tool.description); if (descriptionlessTool) { const msg = `Got a tool ${descriptionlessTool.name} without a description. This agent requires descriptions for all tools.`; throw new Error(msg); } } static createPrompt(tools, args) { const { prefix = PREFIX, suffix = SUFFIX, inputVariables = ["input", "agent_scratchpad"] } = args ?? {}; const toolStrings = tools.map((tool) => `${tool.name}: ${tool.description}`).join("\n"); const toolNames = tools.map((tool) => tool.name); const formatInstructions = renderTemplate(FORMAT_INSTRUCTIONS, "f-string", { tool_names: toolNames }); const template4 = [prefix, toolStrings, formatInstructions, suffix].join("\n\n"); return new PromptTemplate({ template: template4, inputVariables }); } static fromLLMAndTools(llm, tools, args) { ZeroShotAgent.validateTools(tools); const prompt = ZeroShotAgent.createPrompt(tools, args); const outputParser = args?.outputParser ?? ZeroShotAgent.getDefaultOutputParser(); const chain = new LLMChain({ prompt, llm, callbacks: args?.callbacks ?? args?.callbackManager }); return new ZeroShotAgent({ llmChain: chain, allowedTools: tools.map((t2) => t2.name), outputParser }); } static async deserialize(data) { const { llm, tools, ...rest } = data; return deserializeHelper(llm, tools, rest, (llm2, tools2, args) => ZeroShotAgent.fromLLMAndTools(llm2, tools2, { prefix: args.prefix, suffix: args.suffix, inputVariables: args.input_variables }), (args) => new ZeroShotAgent(args)); } }; } }); // node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/agent.js function isAgentAction(input) { return !Array.isArray(input) && input?.tool !== void 0; } function isRunnableAgent(x2) { return x2.runnable !== void 0; } var ParseError, BaseAgent, BaseSingleActionAgent, BaseMultiActionAgent, RunnableSingleActionAgent, RunnableMultiActionAgent, RunnableAgent, LLMSingleActionAgent, Agent; var init_agent = __esm({ "node_modules/.pnpm/langchain@0.1.28_76397b2c2eef2e89170fe9f645871cc8/node_modules/langchain/dist/agents/agent.js"() { init_serializable2(); init_runnables2(); ParseError = class extends Error { constructor(msg, output) { super(msg); Object.defineProperty(this, "output", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.output = output; } }; BaseAgent = class extends Serializable { get returnValues() { return ["output"]; } get allowedTools() { return void 0; } _agentType() { throw new Error("Not implemented"); } returnStoppedResponse(earlyStoppingMethod, _steps, _inputs, _callbackManager) { if (earlyStoppingMethod === "force") { return Promise.resolve({ returnValues: { output: "Agent stopped due to max iterations." }, log: "" }); } throw new Error(`Invalid stopping method: ${earlyStoppingMethod}`); } async prepareForOutput(_returnValues, _steps) { return {}; } }; BaseSingleActionAgent = class extends BaseAgent { _agentActionType() { return "single"; } }; BaseMultiActionAgent = class extends BaseAgent { _agentActionType() { return "multi"; } }; RunnableSingleActionAgent = class extends BaseSingleActionAgent { get inputKeys() { return []; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "agents", "runnable"] }); Object.defineProperty(this, "runnable", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "streamRunnable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "defaultRunName", { enumerable: true, configurable: true, writable: true, value: "RunnableAgent" }); this.runnable = fields2.runnable; this.defaultRunName = fields2.defaultRunName ?? this.defaultRunName; this.streamRunnable = fields2.streamRunnable ?? this.streamRunnable; } async plan(steps, inputs, callbackManager, config) { const combinedInput = { ...inputs, steps }; const combinedConfig = patchConfig(config, { callbacks: callbackManager, runName: this.defaultRunName }); if (this.streamRunnable) { const stream = await this.runnable.stream(combinedInput, combinedConfig); let finalOutput; for await (const chunk of stream) { if (finalOutput === void 0) { finalOutput = chunk; } else { throw new Error([ `Multiple agent actions/finishes received in streamed agent output.`, `Set "streamRunnable: false" when initializing the agent to invoke this agent in non-streaming mode.` ].join("\n")); } } if (finalOutput === void 0) { throw new Error([ "No streaming output received from underlying runnable.", `Set "streamRunnable: false" when initializing the agent to invoke this agent in non-streaming mode.` ].join("\n")); } return finalOutput; } else { return this.runnable.invoke(combinedInput, combinedConfig); } } }; RunnableMultiActionAgent = class extends BaseMultiActionAgent { get inputKeys() { return []; } constructor(fields2) { super(fields2); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "agents", "runnable"] }); Object.defineProperty(this, "runnable", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "defaultRunName", { enumerable: true, configurable: true, writable: true, value: "RunnableAgent" }); Object.defineProperty(this, "stop", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "streamRunnable", { enumerable: true, configurable: true, writable: true, value: true }); this.runnable = fields2.runnable; this.stop = fields2.stop; this.defaultRunName = fields2.defaultRunName ?? this.defaultRunName; this.streamRunnable = fields2.streamRunnable ?? this.streamRunnable; } async plan(steps, inputs, callbackManager, config) { const combinedInput = { ...inputs, steps }; const combinedConfig = patchConfig(config, { callbacks: callbackManager, runName: this.defaultRunName }); let output; if (this.streamRunnable) { const stream = await this.runnable.stream(combinedInput, combinedConfig); let finalOutput; for await (const chunk of stream) { if (finalOutput === void 0) { finalOutput = chunk; } else { throw new Error([ `Multiple agent actions/finishes received in streamed agent output.`, `Set "streamRunnable: false" when initializing the agent to invoke this agent in non-streaming mode.` ].join("\n")); } } if (finalOutput === void 0) { throw new Error([ "No streaming output received from underlying runnable.", `Set "streamRunnable: false" when initializing the agent to invoke this agent in non-streaming mode.` ].join("\n")); } output = finalOutput; } else { output = await this.runnable.invoke(combinedInput, combinedConfig); } if (isAgentAction(output)) { return [output]; } return output; } }; RunnableAgent = class extends RunnableMultiActionAgent { }; LLMSingleActionAgent = class extends BaseSingleActionAgent { constructor(input) { super(input); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "agents"] }); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "stop", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.stop = input.stop; this.llmChain = input.llmChain; this.outputParser = input.outputParser; } get inputKeys() { return this.llmChain.inputKeys; } async plan(steps, inputs, callbackManager) { const output = await this.llmChain.call({ intermediate_steps: steps, stop: this.stop, ...inputs }, callbackManager); return this.outputParser.parse(output[this.llmChain.outputKey], callbackManager); } }; Agent = class extends BaseSingleActionAgent { get allowedTools() { return this._allowedTools; } get inputKeys() { return this.llmChain.inputKeys.filter((k2) => k2 !== "agent_scratchpad"); } constructor(input) { super(input); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "_allowedTools", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.llmChain = input.llmChain; this._allowedTools = input.allowedTools; this.outputParser = input.outputParser; } static getDefaultOutputParser(_fields) { throw new Error("Not implemented"); } static createPrompt(_tools, _fields) { throw new Error("Not implemented"); } static fromLLMAndTools(_llm, _tools, _args) { throw new Error("Not implemented"); } static validateTools(_tools) { } _stop() { return [` ${this.observationPrefix()}`]; } finishToolName() { return "Final Answer"; } async constructScratchPad(steps) { return steps.reduce((thoughts, { action, observation }) => thoughts + [ action.log, `${this.observationPrefix()}${observation}`, this.llmPrefix() ].join("\n"), ""); } async _plan(steps, inputs, suffix, callbackManager) { const thoughts = await this.constructScratchPad(steps); const newInputs = { ...inputs, agent_scratchpad: suffix ? `${thoughts}${suffix}` : thoughts }; if (this._stop().length !== 0) { newInputs.stop = this._stop(); } const output = await this.llmChain.predict(newInputs, callbackManager); if (!this.outputParser) { throw new Error("Output parser not set"); } return this.outputParser.parse(output, callbackManager); } plan(steps, inputs, callbackManager) { return this._plan(steps, inputs, void 0, callbackManager); } async returnStoppedResponse(earlyStoppingMethod, steps, inputs, callbackManager) { if (earlyStoppingMethod === "force") { return { returnValues: { output: "Agent stopped due to max iterations." }, log: "" }; } if (earlyStoppingMethod === "generate") { try { const action = await this._plan(steps, inputs, "\n\nI now need to return a final answer based on the previous steps:", callbackManager); if ("returnValues" in action) { return action; } return { returnValues: { output: action.log }, log: action.log }; } catch (err) { if (!(err instanceof ParseError)) { throw err; } return { returnValues: { output: err.output }, log: err.output }; } } throw new Error(`Invalid stopping method: ${earlyStoppingMethod}`); } static async deserialize(data) { switch (data._type) { case "zero-shot-react-description": { const { ZeroShotAgent: ZeroShotAgent2 } = await Promise.resolve().then(() => (init_mrkl(), mrkl_exports)); return ZeroShotAgent2.deserialize(data); } default: throw new Error("Unknown agent type"); } } }; } }); // node_modules/.pnpm/jsonpointer@5.0.1/node_modules/jsonpointer/jsonpointer.js var require_jsonpointer = __commonJS({ "node_modules/.pnpm/jsonpointer@5.0.1/node_modules/jsonpointer/jsonpointer.js"(exports2) { var hasExcape = /~/; var escapeMatcher = /~[01]/g; function escapeReplacer(m2) { switch (m2) { case "~1": return "/"; case "~0": return "~"; } throw new Error("Invalid tilde escape: " + m2); } function untilde(str3) { if (!hasExcape.test(str3)) return str3; return str3.replace(escapeMatcher, escapeReplacer); } function setter(obj, pointer, value) { var part; var hasNextPart; for (var p2 = 1, len = pointer.length; p2 < len; ) { if (pointer[p2] === "constructor" || pointer[p2] === "prototype" || pointer[p2] === "__proto__") return obj; part = untilde(pointer[p2++]); hasNextPart = len > p2; if (typeof obj[part] === "undefined") { if (Array.isArray(obj) && part === "-") { part = obj.length; } if (hasNextPart) { if (pointer[p2] !== "" && pointer[p2] < Infinity || pointer[p2] === "-") obj[part] = []; else obj[part] = {}; } } if (!hasNextPart) break; obj = obj[part]; } var oldValue = obj[part]; if (value === void 0) delete obj[part]; else obj[part] = value; return oldValue; } function compilePointer(pointer) { if (typeof pointer === "string") { pointer = pointer.split("/"); if (pointer[0] === "") return pointer; throw new Error("Invalid JSON pointer."); } else if (Array.isArray(pointer)) { for (const part of pointer) { if (typeof part !== "string" && typeof part !== "number") { throw new Error("Invalid JSON pointer. Must be of type string or number."); } } return pointer; } throw new Error("Invalid JSON pointer."); } function get22(obj, pointer) { if (typeof obj !== "object") throw new Error("Invalid input object."); pointer = compilePointer(pointer); var len = pointer.length; if (len === 1) return obj; for (var p2 = 1; p2 < len; ) { obj = obj[untilde(pointer[p2++])]; if (len === p2) return obj; if (typeof obj !== "object" || obj === null) return void 0; } } function set13(obj, pointer, value) { if (typeof obj !== "object") throw new Error("Invalid input object."); pointer = compilePointer(pointer); if (pointer.length === 0) throw new Error("Invalid JSON pointer for set."); return setter(obj, pointer, value); } function compile(pointer) { var compiled = compilePointer(pointer); return { get: function(object) { return get22(object, compiled); }, set: function(object, value) { return set13(object, compiled, value); } }; } exports2.get = get22; exports2.set = set13; exports2.compile = compile; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/tools.js var init_tools2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/tools.js"() { init_tools(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/utils/function_calling.js var init_function_calling2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/utils/function_calling.js"() { init_function_calling(); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/version.mjs var VERSION; var init_version = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/version.mjs"() { VERSION = "4.29.1"; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/registry.mjs function setShims(shims4, options = { auto: false }) { if (auto) { throw new Error(`you must \`import 'openai/shims/${shims4.kind}'\` before importing anything else from openai`); } if (kind) { throw new Error(`can't \`import 'openai/shims/${shims4.kind}'\` after \`import 'openai/shims/${kind}'\``); } auto = options.auto; kind = shims4.kind; fetch2 = shims4.fetch; Request2 = shims4.Request; Response2 = shims4.Response; Headers2 = shims4.Headers; FormData2 = shims4.FormData; Blob2 = shims4.Blob; File2 = shims4.File; ReadableStream2 = shims4.ReadableStream; getMultipartRequestOptions = shims4.getMultipartRequestOptions; getDefaultAgent = shims4.getDefaultAgent; fileFromPath = shims4.fileFromPath; isFsReadStream = shims4.isFsReadStream; } var auto, kind, fetch2, Request2, Response2, Headers2, FormData2, Blob2, File2, ReadableStream2, getMultipartRequestOptions, getDefaultAgent, fileFromPath, isFsReadStream; var init_registry = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/registry.mjs"() { auto = false; kind = void 0; fetch2 = void 0; Request2 = void 0; Response2 = void 0; Headers2 = void 0; FormData2 = void 0; Blob2 = void 0; File2 = void 0; ReadableStream2 = void 0; getMultipartRequestOptions = void 0; getDefaultAgent = void 0; fileFromPath = void 0; isFsReadStream = void 0; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/MultipartBody.mjs var MultipartBody; var init_MultipartBody = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/MultipartBody.mjs"() { MultipartBody = class { constructor(body) { this.body = body; } get [Symbol.toStringTag]() { return "MultipartBody"; } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/web-runtime.mjs function getRuntime({ manuallyImported } = {}) { const recommendation = manuallyImported ? `You may need to use polyfills` : `Add one of these imports before your first \`import \u2026 from 'openai'\`: - \`import 'openai/shims/node'\` (if you're running on Node) - \`import 'openai/shims/web'\` (otherwise) `; let _fetch, _Request, _Response, _Headers; try { _fetch = fetch; _Request = Request; _Response = Response; _Headers = Headers; } catch (error) { throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`); } return { kind: "web", fetch: _fetch, Request: _Request, Response: _Response, Headers: _Headers, FormData: typeof FormData !== "undefined" ? FormData : class FormData { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`); } }, Blob: typeof Blob !== "undefined" ? Blob : class Blob { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`); } }, File: typeof File !== "undefined" ? File : class File { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`); } }, ReadableStream: typeof ReadableStream !== "undefined" ? ReadableStream : class ReadableStream { constructor() { throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`); } }, getMultipartRequestOptions: async (form, opts) => ({ ...opts, body: new MultipartBody(form) }), getDefaultAgent: (url) => void 0, fileFromPath: () => { throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads"); }, isFsReadStream: (value) => false }; } var init_web_runtime = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/web-runtime.mjs"() { init_MultipartBody(); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/auto/runtime.mjs var init_runtime = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/auto/runtime.mjs"() { init_web_runtime(); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/index.mjs var init_shims = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/_shims/index.mjs"() { init_registry(); init_runtime(); init_registry(); if (!kind) setShims(getRuntime(), { auto: true }); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/error.mjs var error_exports = {}; __export(error_exports, { APIConnectionError: () => APIConnectionError, APIConnectionTimeoutError: () => APIConnectionTimeoutError, APIError: () => APIError, APIUserAbortError: () => APIUserAbortError, AuthenticationError: () => AuthenticationError, BadRequestError: () => BadRequestError, ConflictError: () => ConflictError, InternalServerError: () => InternalServerError, NotFoundError: () => NotFoundError, OpenAIError: () => OpenAIError, PermissionDeniedError: () => PermissionDeniedError, RateLimitError: () => RateLimitError, UnprocessableEntityError: () => UnprocessableEntityError }); var OpenAIError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError; var init_error = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/error.mjs"() { init_core2(); OpenAIError = class extends Error { }; APIError = class extends OpenAIError { constructor(status, error, message, headers) { super(`${APIError.makeMessage(status, error, message)}`); this.status = status; this.headers = headers; const data = error; this.error = data; this.code = data?.["code"]; this.param = data?.["param"]; this.type = data?.["type"]; } static makeMessage(status, error, message) { const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; if (status && msg) { return `${status} ${msg}`; } if (status) { return `${status} status code (no body)`; } if (msg) { return msg; } return "(no status code or body)"; } static generate(status, errorResponse, message, headers) { if (!status) { return new APIConnectionError({ cause: castToError(errorResponse) }); } const error = errorResponse?.["error"]; if (status === 400) { return new BadRequestError(status, error, message, headers); } if (status === 401) { return new AuthenticationError(status, error, message, headers); } if (status === 403) { return new PermissionDeniedError(status, error, message, headers); } if (status === 404) { return new NotFoundError(status, error, message, headers); } if (status === 409) { return new ConflictError(status, error, message, headers); } if (status === 422) { return new UnprocessableEntityError(status, error, message, headers); } if (status === 429) { return new RateLimitError(status, error, message, headers); } if (status >= 500) { return new InternalServerError(status, error, message, headers); } return new APIError(status, error, message, headers); } }; APIUserAbortError = class extends APIError { constructor({ message } = {}) { super(void 0, void 0, message || "Request was aborted.", void 0); this.status = void 0; } }; APIConnectionError = class extends APIError { constructor({ message, cause }) { super(void 0, void 0, message || "Connection error.", void 0); this.status = void 0; if (cause) this.cause = cause; } }; APIConnectionTimeoutError = class extends APIConnectionError { constructor({ message } = {}) { super({ message: message ?? "Request timed out." }); } }; BadRequestError = class extends APIError { constructor() { super(...arguments); this.status = 400; } }; AuthenticationError = class extends APIError { constructor() { super(...arguments); this.status = 401; } }; PermissionDeniedError = class extends APIError { constructor() { super(...arguments); this.status = 403; } }; NotFoundError = class extends APIError { constructor() { super(...arguments); this.status = 404; } }; ConflictError = class extends APIError { constructor() { super(...arguments); this.status = 409; } }; UnprocessableEntityError = class extends APIError { constructor() { super(...arguments); this.status = 422; } }; RateLimitError = class extends APIError { constructor() { super(...arguments); this.status = 429; } }; InternalServerError = class extends APIError { }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/streaming.mjs function partition(str3, delimiter) { const index2 = str3.indexOf(delimiter); if (index2 !== -1) { return [str3.substring(0, index2), delimiter, str3.substring(index2 + delimiter.length)]; } return [str3, "", ""]; } function readableStreamAsyncIterable(stream) { if (stream[Symbol.asyncIterator]) return stream; const reader = stream.getReader(); return { async next() { try { const result = await reader.read(); if (result?.done) reader.releaseLock(); return result; } catch (e2) { reader.releaseLock(); throw e2; } }, async return() { const cancelPromise = reader.cancel(); reader.releaseLock(); await cancelPromise; return { done: true, value: void 0 }; }, [Symbol.asyncIterator]() { return this; } }; } var Stream, SSEDecoder, LineDecoder; var init_streaming = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/streaming.mjs"() { init_shims(); init_error(); init_error(); Stream = class { constructor(iterator, controller) { this.iterator = iterator; this.controller = controller; } static fromSSEResponse(response, controller) { let consumed = false; const decoder = new SSEDecoder(); async function* iterMessages() { if (!response.body) { controller.abort(); throw new OpenAIError(`Attempted to iterate over a response with no body`); } const lineDecoder = new LineDecoder(); const iter = readableStreamAsyncIterable(response.body); for await (const chunk of iter) { for (const line of lineDecoder.decode(chunk)) { const sse = decoder.decode(line); if (sse) yield sse; } } for (const line of lineDecoder.flush()) { const sse = decoder.decode(line); if (sse) yield sse; } } async function* iterator() { if (consumed) { throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); } consumed = true; let done = false; try { for await (const sse of iterMessages()) { if (done) continue; if (sse.data.startsWith("[DONE]")) { done = true; continue; } if (sse.event === null) { let data; try { data = JSON.parse(sse.data); } catch (e2) { console.error(`Could not parse message into JSON:`, sse.data); console.error(`From chunk:`, sse.raw); throw e2; } if (data && data.error) { throw new APIError(void 0, data.error, void 0, void 0); } yield data; } else { let data; try { data = JSON.parse(sse.data); } catch (e2) { console.error(`Could not parse message into JSON:`, sse.data); console.error(`From chunk:`, sse.raw); throw e2; } if (sse.event == "error") { throw new APIError(void 0, data.error, data.message, void 0); } yield { event: sse.event, data }; } } done = true; } catch (e2) { if (e2 instanceof Error && e2.name === "AbortError") return; throw e2; } finally { if (!done) controller.abort(); } } return new Stream(iterator, controller); } static fromReadableStream(readableStream, controller) { let consumed = false; async function* iterLines() { const lineDecoder = new LineDecoder(); const iter = readableStreamAsyncIterable(readableStream); for await (const chunk of iter) { for (const line of lineDecoder.decode(chunk)) { yield line; } } for (const line of lineDecoder.flush()) { yield line; } } async function* iterator() { if (consumed) { throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); } consumed = true; let done = false; try { for await (const line of iterLines()) { if (done) continue; if (line) yield JSON.parse(line); } done = true; } catch (e2) { if (e2 instanceof Error && e2.name === "AbortError") return; throw e2; } finally { if (!done) controller.abort(); } } return new Stream(iterator, controller); } [Symbol.asyncIterator]() { return this.iterator(); } tee() { const left = []; const right = []; const iterator = this.iterator(); const teeIterator = (queue2) => { return { next: () => { if (queue2.length === 0) { const result = iterator.next(); left.push(result); right.push(result); } return queue2.shift(); } }; }; return [ new Stream(() => teeIterator(left), this.controller), new Stream(() => teeIterator(right), this.controller) ]; } toReadableStream() { const self2 = this; let iter; const encoder = new TextEncoder(); return new ReadableStream2({ async start() { iter = self2[Symbol.asyncIterator](); }, async pull(ctrl) { try { const { value, done } = await iter.next(); if (done) return ctrl.close(); const bytes = encoder.encode(JSON.stringify(value) + "\n"); ctrl.enqueue(bytes); } catch (err) { ctrl.error(err); } }, async cancel() { await iter.return?.(); } }); } }; SSEDecoder = class { constructor() { this.event = null; this.data = []; this.chunks = []; } decode(line) { if (line.endsWith("\r")) { line = line.substring(0, line.length - 1); } if (!line) { if (!this.event && !this.data.length) return null; const sse = { event: this.event, data: this.data.join("\n"), raw: this.chunks }; this.event = null; this.data = []; this.chunks = []; return sse; } this.chunks.push(line); if (line.startsWith(":")) { return null; } let [fieldname, _2, value] = partition(line, ":"); if (value.startsWith(" ")) { value = value.substring(1); } if (fieldname === "event") { this.event = value; } else if (fieldname === "data") { this.data.push(value); } return null; } }; LineDecoder = class { constructor() { this.buffer = []; this.trailingCR = false; } decode(chunk) { let text = this.decodeText(chunk); if (this.trailingCR) { text = "\r" + text; this.trailingCR = false; } if (text.endsWith("\r")) { this.trailingCR = true; text = text.slice(0, -1); } if (!text) { return []; } const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ""); let lines = text.split(LineDecoder.NEWLINE_REGEXP); if (trailingNewline) { lines.pop(); } if (lines.length === 1 && !trailingNewline) { this.buffer.push(lines[0]); return []; } if (this.buffer.length > 0) { lines = [this.buffer.join("") + lines[0], ...lines.slice(1)]; this.buffer = []; } if (!trailingNewline) { this.buffer = [lines.pop() || ""]; } return lines; } decodeText(bytes) { if (bytes == null) return ""; if (typeof bytes === "string") return bytes; if (typeof Buffer !== "undefined") { if (bytes instanceof Buffer) { return bytes.toString(); } if (bytes instanceof Uint8Array) { return Buffer.from(bytes).toString(); } throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`); } if (typeof TextDecoder !== "undefined") { if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8")); return this.textDecoder.decode(bytes); } throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`); } throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`); } flush() { if (!this.buffer.length && !this.trailingCR) { return []; } const lines = [this.buffer.join("")]; this.buffer = []; this.trailingCR = false; return lines; } }; LineDecoder.NEWLINE_CHARS = new Set(["\n", "\r", "\v", "\f", "", "", "", "\x85", "\u2028", "\u2029"]); LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/uploads.mjs async function toFile(value, name2, options = {}) { value = await value; if (isResponseLike(value)) { const blob = await value.blob(); name2 || (name2 = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file"); return new File2([blob], name2, options); } const bits = await getBytes(value); name2 || (name2 = getName(value) ?? "unknown_file"); if (!options.type) { const type2 = bits[0]?.type; if (typeof type2 === "string") { options = { ...options, type: type2 }; } } return new File2(bits, name2, options); } async function getBytes(value) { let parts = []; if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) { parts.push(value); } else if (isBlobLike(value)) { parts.push(await value.arrayBuffer()); } else if (isAsyncIterableIterator(value)) { for await (const chunk of value) { parts.push(chunk); } } else { throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`); } return parts; } function propsForError(value) { const props = Object.getOwnPropertyNames(value); return `[${props.map((p2) => `"${p2}"`).join(", ")}]`; } function getName(value) { return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop(); } var isResponseLike, isFileLike, isBlobLike, isUploadable, getStringFromMaybeBuffer, isAsyncIterableIterator, isMultipartBody, multipartFormRequestOptions, createForm, addFormValue; var init_uploads = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/uploads.mjs"() { init_shims(); init_shims(); isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; isUploadable = (value) => { return isFileLike(value) || isResponseLike(value) || isFsReadStream(value); }; getStringFromMaybeBuffer = (x2) => { if (typeof x2 === "string") return x2; if (typeof Buffer !== "undefined" && x2 instanceof Buffer) return String(x2); return void 0; }; isAsyncIterableIterator = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; isMultipartBody = (body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody"; multipartFormRequestOptions = async (opts) => { const form = await createForm(opts.body); return getMultipartRequestOptions(form, opts); }; createForm = async (body) => { const form = new FormData2(); await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); return form; }; addFormValue = async (form, key, value) => { if (value === void 0) return; if (value == null) { throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); } if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { form.append(key, String(value)); } else if (isUploadable(value)) { const file = await toFile(value); form.append(key, file); } else if (Array.isArray(value)) { await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry))); } else if (typeof value === "object") { await Promise.all(Object.entries(value).map(([name2, prop]) => addFormValue(form, `${key}[${name2}]`, prop))); } else { throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/core.mjs async function defaultParseResponse(props) { const { response } = props; if (props.options.stream) { debug("response", response.status, response.url, response.headers, response.body); if (props.options.__streamClass) { return props.options.__streamClass.fromSSEResponse(response, props.controller); } return Stream.fromSSEResponse(response, props.controller); } if (response.status === 204) { return null; } if (props.options.__binaryResponse) { return response; } const contentType = response.headers.get("content-type"); const isJSON = contentType?.includes("application/json") || contentType?.includes("application/vnd.api+json"); if (isJSON) { const json2 = await response.json(); debug("response", response.status, response.url, response.headers, json2); return json2; } const text = await response.text(); debug("response", response.status, response.url, response.headers, text); return text; } function getBrowserInfo() { if (typeof navigator === "undefined" || !navigator) { return null; } const browserPatterns = [ { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } ]; for (const { key, pattern } of browserPatterns) { const match = pattern.exec(navigator.userAgent); if (match) { const major = match[1] || 0; const minor = match[2] || 0; const patch = match[3] || 0; return { browser: key, version: `${major}.${minor}.${patch}` }; } } return null; } function isEmptyObj(obj) { if (!obj) return true; for (const _k in obj) return false; return true; } function hasOwn(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } function applyHeadersMut(targetHeaders, newHeaders) { for (const k2 in newHeaders) { if (!hasOwn(newHeaders, k2)) continue; const lowerKey = k2.toLowerCase(); if (!lowerKey) continue; const val = newHeaders[k2]; if (val === null) { delete targetHeaders[lowerKey]; } else if (val !== void 0) { targetHeaders[lowerKey] = val; } } } function debug(action, ...args) { if (typeof process !== "undefined" && process.env["DEBUG"] === "true") { console.log(`OpenAI:DEBUG:${action}`, ...args); } } function isObj(obj) { return obj != null && typeof obj === "object" && !Array.isArray(obj); } var __classPrivateFieldSet, __classPrivateFieldGet, _AbstractPage_client, APIPromise, APIClient, AbstractPage, PagePromise, createResponseHeaders, requestOptionsKeys, isRequestOptions, getPlatformProperties, normalizeArch, normalizePlatform, _platformHeaders, getPlatformHeaders, safeJSON, startsWithSchemeRegexp, isAbsoluteURL, sleep, validatePositiveInteger, castToError, readEnv, uuid4, isRunningInBrowser; var init_core2 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/core.mjs"() { init_version(); init_streaming(); init_error(); init_shims(); init_uploads(); init_uploads(); __classPrivateFieldSet = function(receiver, state, value, kind4, f4) { if (kind4 === "m") throw new TypeError("Private method is not writable"); if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; }; __classPrivateFieldGet = function(receiver, state, kind4, f4) { if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); }; APIPromise = class extends Promise { constructor(responsePromise, parseResponse = defaultParseResponse) { super((resolve) => { resolve(null); }); this.responsePromise = responsePromise; this.parseResponse = parseResponse; } _thenUnwrap(transform2) { return new APIPromise(this.responsePromise, async (props) => transform2(await this.parseResponse(props))); } asResponse() { return this.responsePromise.then((p2) => p2.response); } async withResponse() { const [data, response] = await Promise.all([this.parse(), this.asResponse()]); return { data, response }; } parse() { if (!this.parsedPromise) { this.parsedPromise = this.responsePromise.then(this.parseResponse); } return this.parsedPromise; } then(onfulfilled, onrejected) { return this.parse().then(onfulfilled, onrejected); } catch(onrejected) { return this.parse().catch(onrejected); } finally(onfinally) { return this.parse().finally(onfinally); } }; APIClient = class { constructor({ baseURL, maxRetries = 2, timeout = 6e5, httpAgent, fetch: overridenFetch }) { this.baseURL = baseURL; this.maxRetries = validatePositiveInteger("maxRetries", maxRetries); this.timeout = validatePositiveInteger("timeout", timeout); this.httpAgent = httpAgent; this.fetch = overridenFetch ?? fetch2; } authHeaders(opts) { return {}; } defaultHeaders(opts) { return { Accept: "application/json", "Content-Type": "application/json", "User-Agent": this.getUserAgent(), ...getPlatformHeaders(), ...this.authHeaders(opts) }; } validateHeaders(headers, customHeaders) { } defaultIdempotencyKey() { return `stainless-node-retry-${uuid4()}`; } get(path, opts) { return this.methodRequest("get", path, opts); } post(path, opts) { return this.methodRequest("post", path, opts); } patch(path, opts) { return this.methodRequest("patch", path, opts); } put(path, opts) { return this.methodRequest("put", path, opts); } delete(path, opts) { return this.methodRequest("delete", path, opts); } methodRequest(method, path, opts) { return this.request(Promise.resolve(opts).then((opts2) => ({ method, path, ...opts2 }))); } getAPIList(path, Page2, opts) { return this.requestAPIList(Page2, { method: "get", path, ...opts }); } calculateContentLength(body) { if (typeof body === "string") { if (typeof Buffer !== "undefined") { return Buffer.byteLength(body, "utf8").toString(); } if (typeof TextEncoder !== "undefined") { const encoder = new TextEncoder(); const encoded = encoder.encode(body); return encoded.length.toString(); } } return null; } buildRequest(options) { const { method, path, query, headers = {} } = options; const body = isMultipartBody(options.body) ? options.body.body : options.body ? JSON.stringify(options.body, null, 2) : null; const contentLength = this.calculateContentLength(body); const url = this.buildURL(path, query); if ("timeout" in options) validatePositiveInteger("timeout", options.timeout); const timeout = options.timeout ?? this.timeout; const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url); const minAgentTimeout = timeout + 1e3; if (typeof httpAgent?.options?.timeout === "number" && minAgentTimeout > (httpAgent.options.timeout ?? 0)) { httpAgent.options.timeout = minAgentTimeout; } if (this.idempotencyHeader && method !== "get") { if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); headers[this.idempotencyHeader] = options.idempotencyKey; } const reqHeaders = this.buildHeaders({ options, headers, contentLength }); const req = { method, ...body && { body }, headers: reqHeaders, ...httpAgent && { agent: httpAgent }, signal: options.signal ?? null }; return { req, url, timeout }; } buildHeaders({ options, headers, contentLength }) { const reqHeaders = {}; if (contentLength) { reqHeaders["content-length"] = contentLength; } const defaultHeaders = this.defaultHeaders(options); applyHeadersMut(reqHeaders, defaultHeaders); applyHeadersMut(reqHeaders, headers); if (isMultipartBody(options.body) && kind !== "node") { delete reqHeaders["content-type"]; } this.validateHeaders(reqHeaders, headers); return reqHeaders; } async prepareOptions(options) { } async prepareRequest(request7, { url, options }) { } parseHeaders(headers) { return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers }; } makeStatusError(status, error, message, headers) { return APIError.generate(status, error, message, headers); } request(options, remainingRetries = null) { return new APIPromise(this.makeRequest(options, remainingRetries)); } async makeRequest(optionsInput, retriesRemaining) { const options = await optionsInput; if (retriesRemaining == null) { retriesRemaining = options.maxRetries ?? this.maxRetries; } await this.prepareOptions(options); const { req, url, timeout } = this.buildRequest(options); await this.prepareRequest(req, { url, options }); debug("request", url, options, req.headers); if (options.signal?.aborted) { throw new APIUserAbortError(); } const controller = new AbortController(); const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); if (response instanceof Error) { if (options.signal?.aborted) { throw new APIUserAbortError(); } if (retriesRemaining) { return this.retryRequest(options, retriesRemaining); } if (response.name === "AbortError") { throw new APIConnectionTimeoutError(); } throw new APIConnectionError({ cause: response }); } const responseHeaders = createResponseHeaders(response.headers); if (!response.ok) { if (retriesRemaining && this.shouldRetry(response)) { const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; debug(`response (error; ${retryMessage2})`, response.status, url, responseHeaders); return this.retryRequest(options, retriesRemaining, responseHeaders); } const errText = await response.text().catch((e2) => castToError(e2).message); const errJSON = safeJSON(errText); const errMessage = errJSON ? void 0 : errText; const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); throw err; } return { response, options, controller }; } requestAPIList(Page2, options) { const request7 = this.makeRequest(options, null); return new PagePromise(this, request7, Page2); } buildURL(path, query) { const url = isAbsoluteURL(path) ? new URL(path) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path)); const defaultQuery = this.defaultQuery(); if (!isEmptyObj(defaultQuery)) { query = { ...defaultQuery, ...query }; } if (typeof query === "object" && query && !Array.isArray(query)) { url.search = this.stringifyQuery(query); } return url.toString(); } stringifyQuery(query) { return Object.entries(query).filter(([_2, value]) => typeof value !== "undefined").map(([key, value]) => { if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; } if (value === null) { return `${encodeURIComponent(key)}=`; } throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); }).join("&"); } async fetchWithTimeout(url, init2, ms, controller) { const { signal, ...options } = init2 || {}; if (signal) signal.addEventListener("abort", () => controller.abort()); const timeout = setTimeout(() => controller.abort(), ms); return this.getRequestClient().fetch.call(void 0, url, { signal: controller.signal, ...options }).finally(() => { clearTimeout(timeout); }); } getRequestClient() { return { fetch: this.fetch }; } shouldRetry(response) { const shouldRetryHeader = response.headers.get("x-should-retry"); if (shouldRetryHeader === "true") return true; if (shouldRetryHeader === "false") return false; if (response.status === 408) return true; if (response.status === 409) return true; if (response.status === 429) return true; if (response.status >= 500) return true; return false; } async retryRequest(options, retriesRemaining, responseHeaders) { let timeoutMillis; const retryAfterMillisHeader = responseHeaders?.["retry-after-ms"]; if (retryAfterMillisHeader) { const timeoutMs = parseFloat(retryAfterMillisHeader); if (!Number.isNaN(timeoutMs)) { timeoutMillis = timeoutMs; } } const retryAfterHeader = responseHeaders?.["retry-after"]; if (retryAfterHeader && !timeoutMillis) { const timeoutSeconds = parseFloat(retryAfterHeader); if (!Number.isNaN(timeoutSeconds)) { timeoutMillis = timeoutSeconds * 1e3; } else { timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } } if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { const maxRetries = options.maxRetries ?? this.maxRetries; timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } await sleep(timeoutMillis); return this.makeRequest(options, retriesRemaining - 1); } calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { const initialRetryDelay = 0.5; const maxRetryDelay = 8; const numRetries = maxRetries - retriesRemaining; const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); const jitter = 1 - Math.random() * 0.25; return sleepSeconds * jitter * 1e3; } getUserAgent() { return `${this.constructor.name}/JS ${VERSION}`; } }; AbstractPage = class { constructor(client, response, body, options) { _AbstractPage_client.set(this, void 0); __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); this.options = options; this.response = response; this.body = body; } hasNextPage() { const items = this.getPaginatedItems(); if (!items.length) return false; return this.nextPageInfo() != null; } async getNextPage() { const nextInfo = this.nextPageInfo(); if (!nextInfo) { throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); } const nextOptions = { ...this.options }; if ("params" in nextInfo && typeof nextOptions.query === "object") { nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; } else if ("url" in nextInfo) { const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; for (const [key, value] of params) { nextInfo.url.searchParams.set(key, value); } nextOptions.query = void 0; nextOptions.path = nextInfo.url.toString(); } return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); } async *iterPages() { let page = this; yield page; while (page.hasNextPage()) { page = await page.getNextPage(); yield page; } } async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { for await (const page of this.iterPages()) { for (const item of page.getPaginatedItems()) { yield item; } } } }; PagePromise = class extends APIPromise { constructor(client, request7, Page2) { super(request7, async (props) => new Page2(client, props.response, await defaultParseResponse(props), props.options)); } async *[Symbol.asyncIterator]() { const page = await this; for await (const item of page) { yield item; } } }; createResponseHeaders = (headers) => { return new Proxy(Object.fromEntries(headers.entries()), { get(target, name2) { const key = name2.toString(); return target[key.toLowerCase()] || target[key]; } }); }; requestOptionsKeys = { method: true, path: true, query: true, body: true, headers: true, maxRetries: true, stream: true, timeout: true, httpAgent: true, signal: true, idempotencyKey: true, __binaryResponse: true, __streamClass: true }; isRequestOptions = (obj) => { return typeof obj === "object" && obj !== null && !isEmptyObj(obj) && Object.keys(obj).every((k2) => hasOwn(requestOptionsKeys, k2)); }; getPlatformProperties = () => { if (typeof Deno !== "undefined" && Deno.build != null) { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": normalizePlatform(Deno.build.os), "X-Stainless-Arch": normalizeArch(Deno.build.arch), "X-Stainless-Runtime": "deno", "X-Stainless-Runtime-Version": Deno.version }; } if (typeof EdgeRuntime !== "undefined") { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": `other:${EdgeRuntime}`, "X-Stainless-Runtime": "edge", "X-Stainless-Runtime-Version": process.version }; } if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": normalizePlatform(process.platform), "X-Stainless-Arch": normalizeArch(process.arch), "X-Stainless-Runtime": "node", "X-Stainless-Runtime-Version": process.version }; } const browserInfo = getBrowserInfo(); if (browserInfo) { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": `browser:${browserInfo.browser}`, "X-Stainless-Runtime-Version": browserInfo.version }; } return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": "unknown", "X-Stainless-Runtime-Version": "unknown" }; }; normalizeArch = (arch) => { if (arch === "x32") return "x32"; if (arch === "x86_64" || arch === "x64") return "x64"; if (arch === "arm") return "arm"; if (arch === "aarch64" || arch === "arm64") return "arm64"; if (arch) return `other:${arch}`; return "unknown"; }; normalizePlatform = (platform) => { platform = platform.toLowerCase(); if (platform.includes("ios")) return "iOS"; if (platform === "android") return "Android"; if (platform === "darwin") return "MacOS"; if (platform === "win32") return "Windows"; if (platform === "freebsd") return "FreeBSD"; if (platform === "openbsd") return "OpenBSD"; if (platform === "linux") return "Linux"; if (platform) return `Other:${platform}`; return "Unknown"; }; getPlatformHeaders = () => { return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); }; safeJSON = (text) => { try { return JSON.parse(text); } catch (err) { return void 0; } }; startsWithSchemeRegexp = new RegExp("^(?:[a-z]+:)?//", "i"); isAbsoluteURL = (url) => { return startsWithSchemeRegexp.test(url); }; sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); validatePositiveInteger = (name2, n2) => { if (typeof n2 !== "number" || !Number.isInteger(n2)) { throw new OpenAIError(`${name2} must be an integer`); } if (n2 < 0) { throw new OpenAIError(`${name2} must be a positive integer`); } return n2; }; castToError = (err) => { if (err instanceof Error) return err; return new Error(err); }; readEnv = (env) => { if (typeof process !== "undefined") { return process.env?.[env]?.trim() ?? void 0; } if (typeof Deno !== "undefined") { return Deno.env?.get?.(env)?.trim(); } return void 0; }; uuid4 = () => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c2) => { const r3 = Math.random() * 16 | 0; const v2 = c2 === "x" ? r3 : r3 & 3 | 8; return v2.toString(16); }); }; isRunningInBrowser = () => { return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined"; }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/pagination.mjs var Page, CursorPage; var init_pagination = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/pagination.mjs"() { init_core2(); Page = class extends AbstractPage { constructor(client, response, body, options) { super(client, response, body, options); this.data = body.data || []; this.object = body.object; } getPaginatedItems() { return this.data ?? []; } nextPageParams() { return null; } nextPageInfo() { return null; } }; CursorPage = class extends AbstractPage { constructor(client, response, body, options) { super(client, response, body, options); this.data = body.data || []; } getPaginatedItems() { return this.data ?? []; } nextPageParams() { const info = this.nextPageInfo(); if (!info) return null; if ("params" in info) return info.params; const params = Object.fromEntries(info.url.searchParams); if (!Object.keys(params).length) return null; return params; } nextPageInfo() { const data = this.getPaginatedItems(); if (!data.length) { return null; } const id2 = data[data.length - 1]?.id; if (!id2) { return null; } return { params: { after: id2 } }; } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resource.mjs var APIResource; var init_resource = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resource.mjs"() { APIResource = class { constructor(client) { this._client = client; } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/chat/completions.mjs var Completions; var init_completions = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/chat/completions.mjs"() { init_resource(); Completions = class extends APIResource { create(body, options) { return this._client.post("/chat/completions", { body, ...options, stream: body.stream ?? false }); } }; (function(Completions6) { })(Completions || (Completions = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/chat/chat.mjs var Chat; var init_chat2 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/chat/chat.mjs"() { init_resource(); init_completions(); Chat = class extends APIResource { constructor() { super(...arguments); this.completions = new Completions(this._client); } }; (function(Chat3) { Chat3.Completions = Completions; })(Chat || (Chat = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/chat/index.mjs var init_chat3 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/chat/index.mjs"() { init_chat2(); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/shared.mjs var init_shared = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/shared.mjs"() { } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/speech.mjs var Speech; var init_speech = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/speech.mjs"() { init_resource(); Speech = class extends APIResource { create(body, options) { return this._client.post("/audio/speech", { body, ...options, __binaryResponse: true }); } }; (function(Speech2) { })(Speech || (Speech = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/transcriptions.mjs var Transcriptions; var init_transcriptions = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/transcriptions.mjs"() { init_resource(); init_core2(); Transcriptions = class extends APIResource { create(body, options) { return this._client.post("/audio/transcriptions", multipartFormRequestOptions({ body, ...options })); } }; (function(Transcriptions2) { })(Transcriptions || (Transcriptions = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/translations.mjs var Translations; var init_translations = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/translations.mjs"() { init_resource(); init_core2(); Translations = class extends APIResource { create(body, options) { return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options })); } }; (function(Translations2) { })(Translations || (Translations = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/audio.mjs var Audio; var init_audio = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/audio/audio.mjs"() { init_resource(); init_speech(); init_transcriptions(); init_translations(); Audio = class extends APIResource { constructor() { super(...arguments); this.transcriptions = new Transcriptions(this._client); this.translations = new Translations(this._client); this.speech = new Speech(this._client); } }; (function(Audio2) { Audio2.Transcriptions = Transcriptions; Audio2.Translations = Translations; Audio2.Speech = Speech; })(Audio || (Audio = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/assistants/files.mjs var Files, AssistantFilesPage; var init_files = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/assistants/files.mjs"() { init_resource(); init_core2(); init_files(); init_pagination(); Files = class extends APIResource { create(assistantId, body, options) { return this._client.post(`/assistants/${assistantId}/files`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } retrieve(assistantId, fileId, options) { return this._client.get(`/assistants/${assistantId}/files/${fileId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } list(assistantId, query = {}, options) { if (isRequestOptions(query)) { return this.list(assistantId, {}, query); } return this._client.getAPIList(`/assistants/${assistantId}/files`, AssistantFilesPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } del(assistantId, fileId, options) { return this._client.delete(`/assistants/${assistantId}/files/${fileId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } }; AssistantFilesPage = class extends CursorPage { }; (function(Files4) { Files4.AssistantFilesPage = AssistantFilesPage; })(Files || (Files = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/assistants/assistants.mjs var Assistants, AssistantsPage; var init_assistants = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/assistants/assistants.mjs"() { init_resource(); init_core2(); init_assistants(); init_files(); init_pagination(); Assistants = class extends APIResource { constructor() { super(...arguments); this.files = new Files(this._client); } create(body, options) { return this._client.post("/assistants", { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } retrieve(assistantId, options) { return this._client.get(`/assistants/${assistantId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } update(assistantId, body, options) { return this._client.post(`/assistants/${assistantId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } list(query = {}, options) { if (isRequestOptions(query)) { return this.list({}, query); } return this._client.getAPIList("/assistants", AssistantsPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } del(assistantId, options) { return this._client.delete(`/assistants/${assistantId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } }; AssistantsPage = class extends CursorPage { }; (function(Assistants2) { Assistants2.AssistantsPage = AssistantsPage; Assistants2.Files = Files; Assistants2.AssistantFilesPage = AssistantFilesPage; })(Assistants || (Assistants = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/RunnableFunction.mjs function isRunnableFunctionWithParse(fn) { return typeof fn.parse === "function"; } var init_RunnableFunction = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/RunnableFunction.mjs"() { } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/chatCompletionUtils.mjs var isAssistantMessage, isFunctionMessage, isToolMessage; var init_chatCompletionUtils = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/chatCompletionUtils.mjs"() { isAssistantMessage = (message) => { return message?.role === "assistant"; }; isFunctionMessage = (message) => { return message?.role === "function"; }; isToolMessage = (message) => { return message?.role === "tool"; }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/AbstractChatCompletionRunner.mjs var __classPrivateFieldSet2, __classPrivateFieldGet2, _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_connectedPromise, _AbstractChatCompletionRunner_resolveConnectedPromise, _AbstractChatCompletionRunner_rejectConnectedPromise, _AbstractChatCompletionRunner_endPromise, _AbstractChatCompletionRunner_resolveEndPromise, _AbstractChatCompletionRunner_rejectEndPromise, _AbstractChatCompletionRunner_listeners, _AbstractChatCompletionRunner_ended, _AbstractChatCompletionRunner_errored, _AbstractChatCompletionRunner_aborted, _AbstractChatCompletionRunner_catchingPromiseCreated, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_handleError, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult, DEFAULT_MAX_CHAT_COMPLETIONS, AbstractChatCompletionRunner; var init_AbstractChatCompletionRunner = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/AbstractChatCompletionRunner.mjs"() { init_error(); init_RunnableFunction(); init_chatCompletionUtils(); __classPrivateFieldSet2 = function(receiver, state, value, kind4, f4) { if (kind4 === "m") throw new TypeError("Private method is not writable"); if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; }; __classPrivateFieldGet2 = function(receiver, state, kind4, f4) { if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); }; DEFAULT_MAX_CHAT_COMPLETIONS = 10; AbstractChatCompletionRunner = class { constructor() { _AbstractChatCompletionRunner_instances.add(this); this.controller = new AbortController(); _AbstractChatCompletionRunner_connectedPromise.set(this, void 0); _AbstractChatCompletionRunner_resolveConnectedPromise.set(this, () => { }); _AbstractChatCompletionRunner_rejectConnectedPromise.set(this, () => { }); _AbstractChatCompletionRunner_endPromise.set(this, void 0); _AbstractChatCompletionRunner_resolveEndPromise.set(this, () => { }); _AbstractChatCompletionRunner_rejectEndPromise.set(this, () => { }); _AbstractChatCompletionRunner_listeners.set(this, {}); this._chatCompletions = []; this.messages = []; _AbstractChatCompletionRunner_ended.set(this, false); _AbstractChatCompletionRunner_errored.set(this, false); _AbstractChatCompletionRunner_aborted.set(this, false); _AbstractChatCompletionRunner_catchingPromiseCreated.set(this, false); _AbstractChatCompletionRunner_handleError.set(this, (error) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_errored, true, "f"); if (error instanceof Error && error.name === "AbortError") { error = new APIUserAbortError(); } if (error instanceof APIUserAbortError) { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_aborted, true, "f"); return this._emit("abort", error); } if (error instanceof OpenAIError) { return this._emit("error", error); } if (error instanceof Error) { const openAIError = new OpenAIError(error.message); openAIError.cause = error; return this._emit("error", openAIError); } return this._emit("error", new OpenAIError(String(error))); }); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_connectedPromise, new Promise((resolve, reject) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_resolveConnectedPromise, resolve, "f"); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_rejectConnectedPromise, reject, "f"); }), "f"); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_endPromise, new Promise((resolve, reject) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_resolveEndPromise, resolve, "f"); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_rejectEndPromise, reject, "f"); }), "f"); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_connectedPromise, "f").catch(() => { }); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_endPromise, "f").catch(() => { }); } _run(executor) { setTimeout(() => { executor().then(() => { this._emitFinal(); this._emit("end"); }, __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_handleError, "f")); }, 0); } _addChatCompletion(chatCompletion) { this._chatCompletions.push(chatCompletion); this._emit("chatCompletion", chatCompletion); const message = chatCompletion.choices[0]?.message; if (message) this._addMessage(message); return chatCompletion; } _addMessage(message, emit = true) { if (!("content" in message)) message.content = null; this.messages.push(message); if (emit) { this._emit("message", message); if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) { this._emit("functionCallResult", message.content); } else if (isAssistantMessage(message) && message.function_call) { this._emit("functionCall", message.function_call); } else if (isAssistantMessage(message) && message.tool_calls) { for (const tool_call of message.tool_calls) { if (tool_call.type === "function") { this._emit("functionCall", tool_call.function); } } } } } _connected() { if (this.ended) return; __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_resolveConnectedPromise, "f").call(this); this._emit("connect"); } get ended() { return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_ended, "f"); } get errored() { return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_errored, "f"); } get aborted() { return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_aborted, "f"); } abort() { this.controller.abort(); } on(event2, listener) { const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event2] || (__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event2] = []); listeners.push({ listener }); return this; } off(event2, listener) { const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event2]; if (!listeners) return this; const index2 = listeners.findIndex((l2) => l2.listener === listener); if (index2 >= 0) listeners.splice(index2, 1); return this; } once(event2, listener) { const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event2] || (__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event2] = []); listeners.push({ listener, once: true }); return this; } emitted(event2) { return new Promise((resolve, reject) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); if (event2 !== "error") this.once("error", reject); this.once(event2, resolve); }); } async done() { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); await __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_endPromise, "f"); } async finalChatCompletion() { await this.done(); const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (!completion) throw new OpenAIError("stream ended without producing a ChatCompletion"); return completion; } async finalContent() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); } async finalMessage() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); } async finalFunctionCall() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); } async finalFunctionCallResult() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); } async totalUsage() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); } allChatCompletions() { return [...this._chatCompletions]; } _emit(event2, ...args) { if (__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_ended, "f")) { return; } if (event2 === "end") { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_ended, true, "f"); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_resolveEndPromise, "f").call(this); } const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event2]; if (listeners) { __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event2] = listeners.filter((l2) => !l2.once); listeners.forEach(({ listener }) => listener(...args)); } if (event2 === "abort") { const error = args[0]; if (!__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { Promise.reject(error); } __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); this._emit("end"); return; } if (event2 === "error") { const error = args[0]; if (!__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { Promise.reject(error); } __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); this._emit("end"); } } _emitFinal() { const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (completion) this._emit("finalChatCompletion", completion); const finalMessage = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); if (finalMessage) this._emit("finalMessage", finalMessage); const finalContent = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); if (finalContent) this._emit("finalContent", finalContent); const finalFunctionCall = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); if (finalFunctionCall) this._emit("finalFunctionCall", finalFunctionCall); const finalFunctionCallResult = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); if (finalFunctionCallResult != null) this._emit("finalFunctionCallResult", finalFunctionCallResult); if (this._chatCompletions.some((c2) => c2.usage)) { this._emit("totalUsage", __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); } } async _createChatCompletion(completions, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); const chatCompletion = await completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); return this._addChatCompletion(chatCompletion); } async _runChatCompletion(completions, params, options) { for (const message of params.messages) { this._addMessage(message, false); } return await this._createChatCompletion(completions, params, options); } async _runFunctions(completions, params, options) { const role = "function"; const { function_call = "auto", stream, ...restParams } = params; const singleFunctionToCall = typeof function_call !== "string" && function_call?.name; const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; const functionsByName = {}; for (const f4 of params.functions) { functionsByName[f4.name || f4.function.name] = f4; } const functions = params.functions.map((f4) => ({ name: f4.name || f4.function.name, parameters: f4.parameters, description: f4.description })); for (const message of params.messages) { this._addMessage(message, false); } for (let i2 = 0; i2 < maxChatCompletions; ++i2) { const chatCompletion = await this._createChatCompletion(completions, { ...restParams, function_call, functions, messages: [...this.messages] }, options); const message = chatCompletion.choices[0]?.message; if (!message) { throw new OpenAIError(`missing message in ChatCompletion response`); } if (!message.function_call) return; const { name: name2, arguments: args } = message.function_call; const fn = functionsByName[name2]; if (!fn) { const content2 = `Invalid function_call: ${JSON.stringify(name2)}. Available options are: ${functions.map((f4) => JSON.stringify(f4.name)).join(", ")}. Please try again`; this._addMessage({ role, name: name2, content: content2 }); continue; } else if (singleFunctionToCall && singleFunctionToCall !== name2) { const content2 = `Invalid function_call: ${JSON.stringify(name2)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; this._addMessage({ role, name: name2, content: content2 }); continue; } let parsed; try { parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; } catch (error) { this._addMessage({ role, name: name2, content: error instanceof Error ? error.message : String(error) }); continue; } const rawContent = await fn.function(parsed, this); const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); this._addMessage({ role, name: name2, content }); if (singleFunctionToCall) return; } } async _runTools(completions, params, options) { const role = "tool"; const { tool_choice = "auto", stream, ...restParams } = params; const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice?.function?.name; const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; const functionsByName = {}; for (const f4 of params.tools) { if (f4.type === "function") { functionsByName[f4.function.name || f4.function.function.name] = f4.function; } } const tools = "tools" in params ? params.tools.map((t2) => t2.type === "function" ? { type: "function", function: { name: t2.function.name || t2.function.function.name, parameters: t2.function.parameters, description: t2.function.description } } : t2) : void 0; for (const message of params.messages) { this._addMessage(message, false); } for (let i2 = 0; i2 < maxChatCompletions; ++i2) { const chatCompletion = await this._createChatCompletion(completions, { ...restParams, tool_choice, tools, messages: [...this.messages] }, options); const message = chatCompletion.choices[0]?.message; if (!message) { throw new OpenAIError(`missing message in ChatCompletion response`); } if (!message.tool_calls) { return; } for (const tool_call of message.tool_calls) { if (tool_call.type !== "function") continue; const tool_call_id = tool_call.id; const { name: name2, arguments: args } = tool_call.function; const fn = functionsByName[name2]; if (!fn) { const content2 = `Invalid tool_call: ${JSON.stringify(name2)}. Available options are: ${tools.map((f4) => JSON.stringify(f4.function.name)).join(", ")}. Please try again`; this._addMessage({ role, tool_call_id, content: content2 }); continue; } else if (singleFunctionToCall && singleFunctionToCall !== name2) { const content2 = `Invalid tool_call: ${JSON.stringify(name2)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; this._addMessage({ role, tool_call_id, content: content2 }); continue; } let parsed; try { parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; } catch (error) { const content2 = error instanceof Error ? error.message : String(error); this._addMessage({ role, tool_call_id, content: content2 }); continue; } const rawContent = await fn.function(parsed, this); const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); this._addMessage({ role, tool_call_id, content }); if (singleFunctionToCall) { return; } } } return; } }; _AbstractChatCompletionRunner_connectedPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_endPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveEndPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectEndPromise = new WeakMap(), _AbstractChatCompletionRunner_listeners = new WeakMap(), _AbstractChatCompletionRunner_ended = new WeakMap(), _AbstractChatCompletionRunner_errored = new WeakMap(), _AbstractChatCompletionRunner_aborted = new WeakMap(), _AbstractChatCompletionRunner_catchingPromiseCreated = new WeakMap(), _AbstractChatCompletionRunner_handleError = new WeakMap(), _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() { return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() { let i2 = this.messages.length; while (i2-- > 0) { const message = this.messages[i2]; if (isAssistantMessage(message)) { return { ...message, content: message.content ?? null }; } } throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant"); }, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall2() { for (let i2 = this.messages.length - 1; i2 >= 0; i2--) { const message = this.messages[i2]; if (isAssistantMessage(message) && message?.function_call) { return message.function_call; } if (isAssistantMessage(message) && message?.tool_calls?.length) { return message.tool_calls.at(-1)?.function; } } return; }, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult2() { for (let i2 = this.messages.length - 1; i2 >= 0; i2--) { const message = this.messages[i2]; if (isFunctionMessage(message) && message.content != null) { return message.content; } if (isToolMessage(message) && message.content != null && this.messages.some((x2) => x2.role === "assistant" && x2.tool_calls?.some((y2) => y2.type === "function" && y2.id === message.tool_call_id))) { return message.content; } } return; }, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() { const total = { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0 }; for (const { usage } of this._chatCompletions) { if (usage) { total.completion_tokens += usage.completion_tokens; total.prompt_tokens += usage.prompt_tokens; total.total_tokens += usage.total_tokens; } } return total; }, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) { if (params.n != null && params.n > 1) { throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly."); } }, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) { return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent); }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/ChatCompletionRunner.mjs var ChatCompletionRunner; var init_ChatCompletionRunner = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/ChatCompletionRunner.mjs"() { init_AbstractChatCompletionRunner(); init_chatCompletionUtils(); ChatCompletionRunner = class extends AbstractChatCompletionRunner { static runFunctions(completions, params, options) { const runner = new ChatCompletionRunner(); const opts = { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions" } }; runner._run(() => runner._runFunctions(completions, params, opts)); return runner; } static runTools(completions, params, options) { const runner = new ChatCompletionRunner(); const opts = { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" } }; runner._run(() => runner._runTools(completions, params, opts)); return runner; } _addMessage(message) { super._addMessage(message); if (isAssistantMessage(message) && message.content) { this._emit("content", message.content); } } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/ChatCompletionStream.mjs function finalizeChatCompletion(snapshot) { const { id: id2, choices, created, model, system_fingerprint, ...rest } = snapshot; return { ...rest, id: id2, choices: choices.map(({ message, finish_reason, index: index2, logprobs, ...choiceRest }) => { if (!finish_reason) throw new OpenAIError(`missing finish_reason for choice ${index2}`); const { content = null, function_call, tool_calls, ...messageRest } = message; const role = message.role; if (!role) throw new OpenAIError(`missing role for choice ${index2}`); if (function_call) { const { arguments: args, name: name2 } = function_call; if (args == null) throw new OpenAIError(`missing function_call.arguments for choice ${index2}`); if (!name2) throw new OpenAIError(`missing function_call.name for choice ${index2}`); return { ...choiceRest, message: { content, function_call: { arguments: args, name: name2 }, role }, finish_reason, index: index2, logprobs }; } if (tool_calls) { return { ...choiceRest, index: index2, finish_reason, logprobs, message: { ...messageRest, role, content, tool_calls: tool_calls.map((tool_call, i2) => { const { function: fn, type: type2, id: id3, ...toolRest } = tool_call; const { arguments: args, name: name2, ...fnRest } = fn || {}; if (id3 == null) throw new OpenAIError(`missing choices[${index2}].tool_calls[${i2}].id ${str(snapshot)}`); if (type2 == null) throw new OpenAIError(`missing choices[${index2}].tool_calls[${i2}].type ${str(snapshot)}`); if (name2 == null) throw new OpenAIError(`missing choices[${index2}].tool_calls[${i2}].function.name ${str(snapshot)}`); if (args == null) throw new OpenAIError(`missing choices[${index2}].tool_calls[${i2}].function.arguments ${str(snapshot)}`); return { ...toolRest, id: id3, type: type2, function: { ...fnRest, name: name2, arguments: args } }; }) } }; } return { ...choiceRest, message: { ...messageRest, content, role }, finish_reason, index: index2, logprobs }; }), created, model, object: "chat.completion", ...system_fingerprint ? { system_fingerprint } : {} }; } function str(x2) { return JSON.stringify(x2); } var __classPrivateFieldGet3, __classPrivateFieldSet3, _ChatCompletionStream_instances, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_addChunk, _ChatCompletionStream_endRequest, _ChatCompletionStream_accumulateChatCompletion, ChatCompletionStream; var init_ChatCompletionStream = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/ChatCompletionStream.mjs"() { init_error(); init_AbstractChatCompletionRunner(); init_streaming(); __classPrivateFieldGet3 = function(receiver, state, kind4, f4) { if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); }; __classPrivateFieldSet3 = function(receiver, state, value, kind4, f4) { if (kind4 === "m") throw new TypeError("Private method is not writable"); if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; }; ChatCompletionStream = class extends AbstractChatCompletionRunner { constructor() { super(...arguments); _ChatCompletionStream_instances.add(this); _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); } get currentChatCompletionSnapshot() { return __classPrivateFieldGet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); } static fromReadableStream(stream) { const runner = new ChatCompletionStream(); runner._run(() => runner._fromReadableStream(stream)); return runner; } static createChatCompletion(completions, params, options) { const runner = new ChatCompletionStream(); runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); return runner; } async _createChatCompletion(completions, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); const stream = await completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); this._connected(); for await (const chunk of stream) { __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } return this._addChatCompletion(__classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } async _fromReadableStream(readableStream, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); this._connected(); const stream = Stream.fromReadableStream(readableStream, this.controller); let chatId; for await (const chunk of stream) { if (chatId && chatId !== chunk.id) { this._addChatCompletion(__classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); chatId = chunk.id; } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } return this._addChatCompletion(__classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } [(_ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() { if (this.ended) return; __classPrivateFieldSet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) { if (this.ended) return; const completion = __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); this._emit("chunk", chunk, completion); const delta = chunk.choices[0]?.delta?.content; const snapshot = completion.choices[0]?.message; if (delta != null && snapshot?.role === "assistant" && snapshot?.content) { this._emit("content", delta, snapshot.content); } }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() { if (this.ended) { throw new OpenAIError(`stream has ended, this shouldn't happen`); } const snapshot = __classPrivateFieldGet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); if (!snapshot) { throw new OpenAIError(`request ended without sending any chunks`); } __classPrivateFieldSet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); return finalizeChatCompletion(snapshot); }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) { var _a4, _b, _c; let snapshot = __classPrivateFieldGet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); const { choices, ...rest } = chunk; if (!snapshot) { snapshot = __classPrivateFieldSet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, { ...rest, choices: [] }, "f"); } else { Object.assign(snapshot, rest); } for (const { delta, finish_reason, index: index2, logprobs = null, ...other } of chunk.choices) { let choice = snapshot.choices[index2]; if (!choice) { choice = snapshot.choices[index2] = { finish_reason, index: index2, message: {}, logprobs, ...other }; } if (logprobs) { if (!choice.logprobs) { choice.logprobs = Object.assign({}, logprobs); } else { const { content: content2, ...rest3 } = logprobs; Object.assign(choice.logprobs, rest3); if (content2) { (_a4 = choice.logprobs).content ?? (_a4.content = []); choice.logprobs.content.push(...content2); } } } if (finish_reason) choice.finish_reason = finish_reason; Object.assign(choice, other); if (!delta) continue; const { content, function_call, role, tool_calls, ...rest2 } = delta; Object.assign(choice.message, rest2); if (content) choice.message.content = (choice.message.content || "") + content; if (role) choice.message.role = role; if (function_call) { if (!choice.message.function_call) { choice.message.function_call = function_call; } else { if (function_call.name) choice.message.function_call.name = function_call.name; if (function_call.arguments) { (_b = choice.message.function_call).arguments ?? (_b.arguments = ""); choice.message.function_call.arguments += function_call.arguments; } } } if (tool_calls) { if (!choice.message.tool_calls) choice.message.tool_calls = []; for (const { index: index3, id: id2, type: type2, function: fn, ...rest3 } of tool_calls) { const tool_call = (_c = choice.message.tool_calls)[index3] ?? (_c[index3] = {}); Object.assign(tool_call, rest3); if (id2) tool_call.id = id2; if (type2) tool_call.type = type2; if (fn) tool_call.function ?? (tool_call.function = { arguments: "" }); if (fn?.name) tool_call.function.name = fn.name; if (fn?.arguments) tool_call.function.arguments += fn.arguments; } } } return snapshot; }, Symbol.asyncIterator)]() { const pushQueue = []; const readQueue = []; let done = false; this.on("chunk", (chunk) => { const reader = readQueue.shift(); if (reader) { reader.resolve(chunk); } else { pushQueue.push(chunk); } }); this.on("end", () => { done = true; for (const reader of readQueue) { reader.resolve(void 0); } readQueue.length = 0; }); this.on("abort", (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); this.on("error", (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); return { next: async () => { if (!pushQueue.length) { if (done) { return { value: void 0, done: true }; } return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true }); } const chunk = pushQueue.shift(); return { value: chunk, done: false }; }, return: async () => { this.abort(); return { value: void 0, done: true }; } }; } toReadableStream() { const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); return stream.toReadableStream(); } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs var ChatCompletionStreamingRunner; var init_ChatCompletionStreamingRunner = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs"() { init_ChatCompletionStream(); ChatCompletionStreamingRunner = class extends ChatCompletionStream { static fromReadableStream(stream) { const runner = new ChatCompletionStreamingRunner(); runner._run(() => runner._fromReadableStream(stream)); return runner; } static runFunctions(completions, params, options) { const runner = new ChatCompletionStreamingRunner(); const opts = { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions" } }; runner._run(() => runner._runFunctions(completions, params, opts)); return runner; } static runTools(completions, params, options) { const runner = new ChatCompletionStreamingRunner(); const opts = { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" } }; runner._run(() => runner._runTools(completions, params, opts)); return runner; } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/chat/completions.mjs var Completions2; var init_completions2 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/chat/completions.mjs"() { init_resource(); init_ChatCompletionRunner(); init_ChatCompletionStreamingRunner(); init_ChatCompletionStream(); Completions2 = class extends APIResource { runFunctions(body, options) { if (body.stream) { return ChatCompletionStreamingRunner.runFunctions(this._client.chat.completions, body, options); } return ChatCompletionRunner.runFunctions(this._client.chat.completions, body, options); } runTools(body, options) { if (body.stream) { return ChatCompletionStreamingRunner.runTools(this._client.chat.completions, body, options); } return ChatCompletionRunner.runTools(this._client.chat.completions, body, options); } stream(body, options) { return ChatCompletionStream.createChatCompletion(this._client.chat.completions, body, options); } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/chat/chat.mjs var Chat2; var init_chat4 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/chat/chat.mjs"() { init_resource(); init_completions2(); Chat2 = class extends APIResource { constructor() { super(...arguments); this.completions = new Completions2(this._client); } }; (function(Chat3) { Chat3.Completions = Completions2; })(Chat2 || (Chat2 = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs var __classPrivateFieldSet4, __classPrivateFieldGet4, _AbstractAssistantStreamRunner_connectedPromise, _AbstractAssistantStreamRunner_resolveConnectedPromise, _AbstractAssistantStreamRunner_rejectConnectedPromise, _AbstractAssistantStreamRunner_endPromise, _AbstractAssistantStreamRunner_resolveEndPromise, _AbstractAssistantStreamRunner_rejectEndPromise, _AbstractAssistantStreamRunner_listeners, _AbstractAssistantStreamRunner_ended, _AbstractAssistantStreamRunner_errored, _AbstractAssistantStreamRunner_aborted, _AbstractAssistantStreamRunner_catchingPromiseCreated, _AbstractAssistantStreamRunner_handleError, AbstractAssistantStreamRunner; var init_AbstractAssistantStreamRunner = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs"() { init_error(); __classPrivateFieldSet4 = function(receiver, state, value, kind4, f4) { if (kind4 === "m") throw new TypeError("Private method is not writable"); if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; }; __classPrivateFieldGet4 = function(receiver, state, kind4, f4) { if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); }; AbstractAssistantStreamRunner = class { constructor() { this.controller = new AbortController(); _AbstractAssistantStreamRunner_connectedPromise.set(this, void 0); _AbstractAssistantStreamRunner_resolveConnectedPromise.set(this, () => { }); _AbstractAssistantStreamRunner_rejectConnectedPromise.set(this, () => { }); _AbstractAssistantStreamRunner_endPromise.set(this, void 0); _AbstractAssistantStreamRunner_resolveEndPromise.set(this, () => { }); _AbstractAssistantStreamRunner_rejectEndPromise.set(this, () => { }); _AbstractAssistantStreamRunner_listeners.set(this, {}); _AbstractAssistantStreamRunner_ended.set(this, false); _AbstractAssistantStreamRunner_errored.set(this, false); _AbstractAssistantStreamRunner_aborted.set(this, false); _AbstractAssistantStreamRunner_catchingPromiseCreated.set(this, false); _AbstractAssistantStreamRunner_handleError.set(this, (error) => { __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_errored, true, "f"); if (error instanceof Error && error.name === "AbortError") { error = new APIUserAbortError(); } if (error instanceof APIUserAbortError) { __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_aborted, true, "f"); return this._emit("abort", error); } if (error instanceof OpenAIError) { return this._emit("error", error); } if (error instanceof Error) { const openAIError = new OpenAIError(error.message); openAIError.cause = error; return this._emit("error", openAIError); } return this._emit("error", new OpenAIError(String(error))); }); __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_connectedPromise, new Promise((resolve, reject) => { __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_resolveConnectedPromise, resolve, "f"); __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, reject, "f"); }), "f"); __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_endPromise, new Promise((resolve, reject) => { __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_resolveEndPromise, resolve, "f"); __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_rejectEndPromise, reject, "f"); }), "f"); __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_connectedPromise, "f").catch(() => { }); __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_endPromise, "f").catch(() => { }); } _run(executor) { setTimeout(() => { executor().then(() => { this._emit("end"); }, __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_handleError, "f")); }, 0); } _addRun(run) { return run; } _connected() { if (this.ended) return; __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_resolveConnectedPromise, "f").call(this); this._emit("connect"); } get ended() { return __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_ended, "f"); } get errored() { return __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_errored, "f"); } get aborted() { return __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_aborted, "f"); } abort() { this.controller.abort(); } on(event2, listener) { const listeners = __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_listeners, "f")[event2] || (__classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_listeners, "f")[event2] = []); listeners.push({ listener }); return this; } off(event2, listener) { const listeners = __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_listeners, "f")[event2]; if (!listeners) return this; const index2 = listeners.findIndex((l2) => l2.listener === listener); if (index2 >= 0) listeners.splice(index2, 1); return this; } once(event2, listener) { const listeners = __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_listeners, "f")[event2] || (__classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_listeners, "f")[event2] = []); listeners.push({ listener, once: true }); return this; } emitted(event2) { return new Promise((resolve, reject) => { __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, true, "f"); if (event2 !== "error") this.once("error", reject); this.once(event2, resolve); }); } async done() { __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, true, "f"); await __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_endPromise, "f"); } _emit(event2, ...args) { if (__classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_ended, "f")) { return; } if (event2 === "end") { __classPrivateFieldSet4(this, _AbstractAssistantStreamRunner_ended, true, "f"); __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_resolveEndPromise, "f").call(this); } const listeners = __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_listeners, "f")[event2]; if (listeners) { __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_listeners, "f")[event2] = listeners.filter((l2) => !l2.once); listeners.forEach(({ listener }) => listener(...args)); } if (event2 === "abort") { const error = args[0]; if (!__classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, "f") && !listeners?.length) { Promise.reject(error); } __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_rejectEndPromise, "f").call(this, error); this._emit("end"); return; } if (event2 === "error") { const error = args[0]; if (!__classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, "f") && !listeners?.length) { Promise.reject(error); } __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet4(this, _AbstractAssistantStreamRunner_rejectEndPromise, "f").call(this, error); this._emit("end"); } } async _threadAssistantStream(body, thread, options) { return await this._createThreadAssistantStream(thread, body, options); } async _runAssistantStream(threadId, runs, params, options) { return await this._createAssistantStream(runs, threadId, params, options); } async _runToolAssistantStream(threadId, runId, runs, params, options) { return await this._createToolAssistantStream(runs, threadId, runId, params, options); } async _createThreadAssistantStream(thread, body, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } const runResult = await thread.createAndRun({ ...body, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); return this._addRun(runResult); } async _createToolAssistantStream(run, threadId, runId, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } const runResult = await run.submitToolOutputs(threadId, runId, { ...params, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); return this._addRun(runResult); } async _createAssistantStream(run, threadId, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } const runResult = await run.create(threadId, { ...params, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); return this._addRun(runResult); } }; _AbstractAssistantStreamRunner_connectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_resolveConnectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_rejectConnectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_endPromise = new WeakMap(), _AbstractAssistantStreamRunner_resolveEndPromise = new WeakMap(), _AbstractAssistantStreamRunner_rejectEndPromise = new WeakMap(), _AbstractAssistantStreamRunner_listeners = new WeakMap(), _AbstractAssistantStreamRunner_ended = new WeakMap(), _AbstractAssistantStreamRunner_errored = new WeakMap(), _AbstractAssistantStreamRunner_aborted = new WeakMap(), _AbstractAssistantStreamRunner_catchingPromiseCreated = new WeakMap(), _AbstractAssistantStreamRunner_handleError = new WeakMap(); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/AssistantStream.mjs var __classPrivateFieldGet5, __classPrivateFieldSet5, _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun, AssistantStream; var init_AssistantStream = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/lib/AssistantStream.mjs"() { init_core2(); init_AbstractAssistantStreamRunner(); init_streaming(); init_error(); __classPrivateFieldGet5 = function(receiver, state, kind4, f4) { if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); }; __classPrivateFieldSet5 = function(receiver, state, value, kind4, f4) { if (kind4 === "m") throw new TypeError("Private method is not writable"); if (kind4 === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; }; AssistantStream = class extends AbstractAssistantStreamRunner { constructor() { super(...arguments); _AssistantStream_instances.add(this); _AssistantStream_events.set(this, []); _AssistantStream_runStepSnapshots.set(this, {}); _AssistantStream_messageSnapshots.set(this, {}); _AssistantStream_messageSnapshot.set(this, void 0); _AssistantStream_finalRun.set(this, void 0); _AssistantStream_currentContentIndex.set(this, void 0); _AssistantStream_currentContent.set(this, void 0); _AssistantStream_currentToolCallIndex.set(this, void 0); _AssistantStream_currentToolCall.set(this, void 0); _AssistantStream_currentEvent.set(this, void 0); _AssistantStream_currentRunSnapshot.set(this, void 0); _AssistantStream_currentRunStepSnapshot.set(this, void 0); } [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { const pushQueue = []; const readQueue = []; let done = false; this.on("event", (event2) => { const reader = readQueue.shift(); if (reader) { reader.resolve(event2); } else { pushQueue.push(event2); } }); this.on("end", () => { done = true; for (const reader of readQueue) { reader.resolve(void 0); } readQueue.length = 0; }); this.on("abort", (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); this.on("error", (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); return { next: async () => { if (!pushQueue.length) { if (done) { return { value: void 0, done: true }; } return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true }); } const chunk = pushQueue.shift(); return { value: chunk, done: false }; }, return: async () => { this.abort(); return { value: void 0, done: true }; } }; } toReadableStream() { const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); return stream.toReadableStream(); } static createToolAssistantStream(threadId, runId, runs, body, options) { const runner = new AssistantStream(); runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, body, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); return runner; } async _createToolAssistantStream(run, threadId, runId, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } const body = { ...params, stream: true }; const stream = await run.submitToolOutputs(threadId, runId, body, { ...options, signal: this.controller.signal }); this._connected(); for await (const event2 of stream) { __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event2); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } return this._addRun(__classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } static createThreadAssistantStream(body, thread, options) { const runner = new AssistantStream(); runner._run(() => runner._threadAssistantStream(body, thread, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); return runner; } static createAssistantStream(threadId, runs, params, options) { const runner = new AssistantStream(); runner._run(() => runner._runAssistantStream(threadId, runs, params, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); return runner; } currentEvent() { return __classPrivateFieldGet5(this, _AssistantStream_currentEvent, "f"); } currentRun() { return __classPrivateFieldGet5(this, _AssistantStream_currentRunSnapshot, "f"); } currentMessageSnapshot() { return __classPrivateFieldGet5(this, _AssistantStream_messageSnapshot, "f"); } currentRunStepSnapshot() { return __classPrivateFieldGet5(this, _AssistantStream_currentRunStepSnapshot, "f"); } async finalRunSteps() { await this.done(); return Object.values(__classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")); } async finalMessages() { await this.done(); return Object.values(__classPrivateFieldGet5(this, _AssistantStream_messageSnapshots, "f")); } async finalRun() { await this.done(); if (!__classPrivateFieldGet5(this, _AssistantStream_finalRun, "f")) throw Error("Final run was not received."); return __classPrivateFieldGet5(this, _AssistantStream_finalRun, "f"); } async _createThreadAssistantStream(thread, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } const body = { ...params, stream: true }; const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); this._connected(); for await (const event2 of stream) { __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event2); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } return this._addRun(__classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } async _createAssistantStream(run, threadId, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } const body = { ...params, stream: true }; const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); this._connected(); for await (const event2 of stream) { __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event2); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } return this._addRun(__classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } static accumulateDelta(acc, delta) { for (const [key, deltaValue] of Object.entries(delta)) { if (!acc.hasOwnProperty(key)) { acc[key] = deltaValue; continue; } let accValue = acc[key]; if (accValue === null || accValue === void 0) { acc[key] = deltaValue; continue; } if (key === "index" || key === "type") { acc[key] = deltaValue; continue; } if (typeof accValue === "string" && typeof deltaValue === "string") { accValue += deltaValue; } else if (typeof accValue === "number" && typeof deltaValue === "number") { accValue += deltaValue; } else if (isObj(accValue) && isObj(deltaValue)) { accValue = this.accumulateDelta(accValue, deltaValue); } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { if (accValue.every((x2) => typeof x2 === "string" || typeof x2 === "number")) { accValue.push(...deltaValue); continue; } } else { throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); } acc[key] = accValue; } return acc; } }; _AssistantStream_addEvent = function _AssistantStream_addEvent2(event2) { if (this.ended) return; __classPrivateFieldSet5(this, _AssistantStream_currentEvent, event2, "f"); __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event2); switch (event2.event) { case "thread.created": break; case "thread.run.created": case "thread.run.queued": case "thread.run.in_progress": case "thread.run.requires_action": case "thread.run.completed": case "thread.run.failed": case "thread.run.cancelling": case "thread.run.cancelled": case "thread.run.expired": __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event2); break; case "thread.run.step.created": case "thread.run.step.in_progress": case "thread.run.step.delta": case "thread.run.step.completed": case "thread.run.step.failed": case "thread.run.step.cancelled": case "thread.run.step.expired": __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event2); break; case "thread.message.created": case "thread.message.in_progress": case "thread.message.delta": case "thread.message.completed": case "thread.message.incomplete": __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event2); break; case "error": throw new Error("Encountered an error event in event processing - errors should be processed earlier"); } }, _AssistantStream_endRequest = function _AssistantStream_endRequest2() { if (this.ended) { throw new OpenAIError(`stream has ended, this shouldn't happen`); } if (!__classPrivateFieldGet5(this, _AssistantStream_finalRun, "f")) throw Error("Final run has been been received"); return __classPrivateFieldGet5(this, _AssistantStream_finalRun, "f"); }, _AssistantStream_handleMessage = function _AssistantStream_handleMessage2(event2) { const [accumulatedMessage, newContent] = __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event2, __classPrivateFieldGet5(this, _AssistantStream_messageSnapshot, "f")); __classPrivateFieldSet5(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); __classPrivateFieldGet5(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; for (const content of newContent) { const snapshotContent = accumulatedMessage.content[content.index]; if (snapshotContent?.type == "text") { this._emit("textCreated", snapshotContent.text); } } switch (event2.event) { case "thread.message.created": this._emit("messageCreated", event2.data); break; case "thread.message.in_progress": break; case "thread.message.delta": this._emit("messageDelta", event2.data.delta, accumulatedMessage); if (event2.data.delta.content) { for (const content of event2.data.delta.content) { if (content.type == "text" && content.text) { let textDelta = content.text; let snapshot = accumulatedMessage.content[content.index]; if (snapshot && snapshot.type == "text") { this._emit("textDelta", textDelta, snapshot.text); } else { throw Error("The snapshot associated with this text delta is not text or missing"); } } if (content.index != __classPrivateFieldGet5(this, _AssistantStream_currentContentIndex, "f")) { if (__classPrivateFieldGet5(this, _AssistantStream_currentContent, "f")) { switch (__classPrivateFieldGet5(this, _AssistantStream_currentContent, "f").type) { case "text": this._emit("textDone", __classPrivateFieldGet5(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet5(this, _AssistantStream_messageSnapshot, "f")); break; case "image_file": this._emit("imageFileDone", __classPrivateFieldGet5(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet5(this, _AssistantStream_messageSnapshot, "f")); break; } } __classPrivateFieldSet5(this, _AssistantStream_currentContentIndex, content.index, "f"); } __classPrivateFieldSet5(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); } } break; case "thread.message.completed": case "thread.message.incomplete": if (__classPrivateFieldGet5(this, _AssistantStream_currentContentIndex, "f") !== void 0) { const currentContent = event2.data.content[__classPrivateFieldGet5(this, _AssistantStream_currentContentIndex, "f")]; if (currentContent) { switch (currentContent.type) { case "image_file": this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet5(this, _AssistantStream_messageSnapshot, "f")); break; case "text": this._emit("textDone", currentContent.text, __classPrivateFieldGet5(this, _AssistantStream_messageSnapshot, "f")); break; } } } if (__classPrivateFieldGet5(this, _AssistantStream_messageSnapshot, "f")) { this._emit("messageDone", event2.data); } __classPrivateFieldSet5(this, _AssistantStream_messageSnapshot, void 0, "f"); } }, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep2(event2) { const accumulatedRunStep = __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event2); __classPrivateFieldSet5(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); switch (event2.event) { case "thread.run.step.created": this._emit("runStepCreated", event2.data); break; case "thread.run.step.delta": const delta = event2.data.delta; if (delta.step_details && delta.step_details.type == "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type == "tool_calls") { for (const toolCall of delta.step_details.tool_calls) { if (toolCall.index == __classPrivateFieldGet5(this, _AssistantStream_currentToolCallIndex, "f")) { this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); } else { if (__classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")) { this._emit("toolCallDone", __classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")); } __classPrivateFieldSet5(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); __classPrivateFieldSet5(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); if (__classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")) this._emit("toolCallCreated", __classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")); } } } this._emit("runStepDelta", event2.data.delta, accumulatedRunStep); break; case "thread.run.step.completed": case "thread.run.step.failed": case "thread.run.step.cancelled": case "thread.run.step.expired": __classPrivateFieldSet5(this, _AssistantStream_currentRunStepSnapshot, void 0, "f"); const details = event2.data.step_details; if (details.type == "tool_calls") { if (__classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")) { this._emit("toolCallDone", __classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")); __classPrivateFieldSet5(this, _AssistantStream_currentToolCall, void 0, "f"); } } this._emit("runStepDone", event2.data, accumulatedRunStep); break; case "thread.run.step.in_progress": break; } }, _AssistantStream_handleEvent = function _AssistantStream_handleEvent2(event2) { __classPrivateFieldGet5(this, _AssistantStream_events, "f").push(event2); this._emit("event", event2); }, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep2(event2) { switch (event2.event) { case "thread.run.step.created": __classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")[event2.data.id] = event2.data; return event2.data; case "thread.run.step.delta": let snapshot = __classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")[event2.data.id]; if (!snapshot) { throw Error("Received a RunStepDelta before creation of a snapshot"); } let data = event2.data; if (data.delta) { const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta); __classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")[event2.data.id] = accumulated; } return __classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")[event2.data.id]; case "thread.run.step.completed": case "thread.run.step.failed": case "thread.run.step.cancelled": case "thread.run.step.expired": case "thread.run.step.in_progress": __classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")[event2.data.id] = event2.data; break; } if (__classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")[event2.data.id]) return __classPrivateFieldGet5(this, _AssistantStream_runStepSnapshots, "f")[event2.data.id]; throw new Error("No snapshot available"); }, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage2(event2, snapshot) { let newContent = []; switch (event2.event) { case "thread.message.created": return [event2.data, newContent]; case "thread.message.delta": if (!snapshot) { throw Error("Received a delta with no existing snapshot (there should be one from message creation)"); } let data = event2.data; if (data.delta.content) { for (const contentElement of data.delta.content) { if (contentElement.index in snapshot.content) { let currentContent = snapshot.content[contentElement.index]; snapshot.content[contentElement.index] = __classPrivateFieldGet5(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); } else { snapshot.content[contentElement.index] = contentElement; newContent.push(contentElement); } } } return [snapshot, newContent]; case "thread.message.in_progress": case "thread.message.completed": case "thread.message.incomplete": if (snapshot) { return [snapshot, newContent]; } else { throw Error("Received thread message event with no existing snapshot"); } } throw Error("Tried to accumulate a non-message event"); }, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent2(contentElement, currentContent) { return AssistantStream.accumulateDelta(currentContent, contentElement); }, _AssistantStream_handleRun = function _AssistantStream_handleRun2(event2) { __classPrivateFieldSet5(this, _AssistantStream_currentRunSnapshot, event2.data, "f"); switch (event2.event) { case "thread.run.created": break; case "thread.run.queued": break; case "thread.run.in_progress": break; case "thread.run.requires_action": case "thread.run.cancelled": case "thread.run.failed": case "thread.run.completed": case "thread.run.expired": __classPrivateFieldSet5(this, _AssistantStream_finalRun, event2.data, "f"); if (__classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")) { this._emit("toolCallDone", __classPrivateFieldGet5(this, _AssistantStream_currentToolCall, "f")); __classPrivateFieldSet5(this, _AssistantStream_currentToolCall, void 0, "f"); } break; case "thread.run.cancelling": break; } }; } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/messages/files.mjs var Files2, MessageFilesPage; var init_files2 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/messages/files.mjs"() { init_resource(); init_core2(); init_files2(); init_pagination(); Files2 = class extends APIResource { retrieve(threadId, messageId, fileId, options) { return this._client.get(`/threads/${threadId}/messages/${messageId}/files/${fileId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } list(threadId, messageId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, messageId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/messages/${messageId}/files`, MessageFilesPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } }; MessageFilesPage = class extends CursorPage { }; (function(Files4) { Files4.MessageFilesPage = MessageFilesPage; })(Files2 || (Files2 = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/messages/messages.mjs var Messages, MessagesPage; var init_messages4 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/messages/messages.mjs"() { init_resource(); init_core2(); init_messages4(); init_files2(); init_pagination(); Messages = class extends APIResource { constructor() { super(...arguments); this.files = new Files2(this._client); } create(threadId, body, options) { return this._client.post(`/threads/${threadId}/messages`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } retrieve(threadId, messageId, options) { return this._client.get(`/threads/${threadId}/messages/${messageId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } update(threadId, messageId, body, options) { return this._client.post(`/threads/${threadId}/messages/${messageId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } list(threadId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } }; MessagesPage = class extends CursorPage { }; (function(Messages3) { Messages3.MessagesPage = MessagesPage; Messages3.Files = Files2; Messages3.MessageFilesPage = MessageFilesPage; })(Messages || (Messages = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/runs/steps.mjs var Steps, RunStepsPage; var init_steps = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/runs/steps.mjs"() { init_resource(); init_core2(); init_steps(); init_pagination(); Steps = class extends APIResource { retrieve(threadId, runId, stepId, options) { return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } list(threadId, runId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, runId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } }; RunStepsPage = class extends CursorPage { }; (function(Steps2) { Steps2.RunStepsPage = RunStepsPage; })(Steps || (Steps = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/runs/runs.mjs var Runs, RunsPage; var init_runs = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/runs/runs.mjs"() { init_resource(); init_core2(); init_AssistantStream(); init_runs(); init_steps(); init_pagination(); Runs = class extends APIResource { constructor() { super(...arguments); this.steps = new Steps(this._client); } create(threadId, body, options) { return this._client.post(`/threads/${threadId}/runs`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers }, stream: body.stream ?? false }); } retrieve(threadId, runId, options) { return this._client.get(`/threads/${threadId}/runs/${runId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } update(threadId, runId, body, options) { return this._client.post(`/threads/${threadId}/runs/${runId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } list(threadId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } cancel(threadId, runId, options) { return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } createAndStream(threadId, body, options) { return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); } submitToolOutputs(threadId, runId, body, options) { return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers }, stream: body.stream ?? false }); } submitToolOutputsStream(threadId, runId, body, options) { return AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options); } }; RunsPage = class extends CursorPage { }; (function(Runs2) { Runs2.RunsPage = RunsPage; Runs2.Steps = Steps; Runs2.RunStepsPage = RunStepsPage; })(Runs || (Runs = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/threads.mjs var Threads; var init_threads = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/threads/threads.mjs"() { init_resource(); init_core2(); init_AssistantStream(); init_messages4(); init_runs(); Threads = class extends APIResource { constructor() { super(...arguments); this.runs = new Runs(this._client); this.messages = new Messages(this._client); } create(body = {}, options) { if (isRequestOptions(body)) { return this.create({}, body); } return this._client.post("/threads", { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } retrieve(threadId, options) { return this._client.get(`/threads/${threadId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } update(threadId, body, options) { return this._client.post(`/threads/${threadId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } del(threadId, options) { return this._client.delete(`/threads/${threadId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers } }); } createAndRun(body, options) { return this._client.post("/threads/runs", { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options?.headers }, stream: body.stream ?? false }); } createAndRunStream(body, options) { return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); } }; (function(Threads2) { Threads2.Runs = Runs; Threads2.RunsPage = RunsPage; Threads2.Messages = Messages; Threads2.MessagesPage = MessagesPage; })(Threads || (Threads = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/beta.mjs var Beta; var init_beta = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/beta/beta.mjs"() { init_resource(); init_assistants(); init_chat4(); init_threads(); Beta = class extends APIResource { constructor() { super(...arguments); this.chat = new Chat2(this._client); this.assistants = new Assistants(this._client); this.threads = new Threads(this._client); } }; (function(Beta2) { Beta2.Chat = Chat2; Beta2.Assistants = Assistants; Beta2.AssistantsPage = AssistantsPage; Beta2.Threads = Threads; })(Beta || (Beta = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/completions.mjs var Completions3; var init_completions3 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/completions.mjs"() { init_resource(); Completions3 = class extends APIResource { create(body, options) { return this._client.post("/completions", { body, ...options, stream: body.stream ?? false }); } }; (function(Completions6) { })(Completions3 || (Completions3 = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/embeddings.mjs var Embeddings2; var init_embeddings2 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/embeddings.mjs"() { init_resource(); Embeddings2 = class extends APIResource { create(body, options) { return this._client.post("/embeddings", { body, ...options }); } }; (function(Embeddings3) { })(Embeddings2 || (Embeddings2 = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/files.mjs var Files3, FileObjectsPage; var init_files3 = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/files.mjs"() { init_resource(); init_core2(); init_core2(); init_error(); init_files3(); init_core2(); init_pagination(); Files3 = class extends APIResource { create(body, options) { return this._client.post("/files", multipartFormRequestOptions({ body, ...options })); } retrieve(fileId, options) { return this._client.get(`/files/${fileId}`, options); } list(query = {}, options) { if (isRequestOptions(query)) { return this.list({}, query); } return this._client.getAPIList("/files", FileObjectsPage, { query, ...options }); } del(fileId, options) { return this._client.delete(`/files/${fileId}`, options); } content(fileId, options) { return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true }); } retrieveContent(fileId, options) { return this._client.get(`/files/${fileId}/content`, { ...options, headers: { Accept: "application/json", ...options?.headers } }); } async waitForProcessing(id2, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) { const TERMINAL_STATES = new Set(["processed", "error", "deleted"]); const start = Date.now(); let file = await this.retrieve(id2); while (!file.status || !TERMINAL_STATES.has(file.status)) { await sleep(pollInterval); file = await this.retrieve(id2); if (Date.now() - start > maxWait) { throw new APIConnectionTimeoutError({ message: `Giving up on waiting for file ${id2} to finish processing after ${maxWait} milliseconds.` }); } } return file; } }; FileObjectsPage = class extends Page { }; (function(Files4) { Files4.FileObjectsPage = FileObjectsPage; })(Files3 || (Files3 = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/fine-tuning/jobs.mjs var Jobs, FineTuningJobsPage, FineTuningJobEventsPage; var init_jobs = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/fine-tuning/jobs.mjs"() { init_resource(); init_core2(); init_jobs(); init_pagination(); Jobs = class extends APIResource { create(body, options) { return this._client.post("/fine_tuning/jobs", { body, ...options }); } retrieve(fineTuningJobId, options) { return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); } list(query = {}, options) { if (isRequestOptions(query)) { return this.list({}, query); } return this._client.getAPIList("/fine_tuning/jobs", FineTuningJobsPage, { query, ...options }); } cancel(fineTuningJobId, options) { return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); } listEvents(fineTuningJobId, query = {}, options) { if (isRequestOptions(query)) { return this.listEvents(fineTuningJobId, {}, query); } return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { query, ...options }); } }; FineTuningJobsPage = class extends CursorPage { }; FineTuningJobEventsPage = class extends CursorPage { }; (function(Jobs2) { Jobs2.FineTuningJobsPage = FineTuningJobsPage; Jobs2.FineTuningJobEventsPage = FineTuningJobEventsPage; })(Jobs || (Jobs = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/fine-tuning/fine-tuning.mjs var FineTuning; var init_fine_tuning = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/fine-tuning/fine-tuning.mjs"() { init_resource(); init_jobs(); FineTuning = class extends APIResource { constructor() { super(...arguments); this.jobs = new Jobs(this._client); } }; (function(FineTuning2) { FineTuning2.Jobs = Jobs; FineTuning2.FineTuningJobsPage = FineTuningJobsPage; FineTuning2.FineTuningJobEventsPage = FineTuningJobEventsPage; })(FineTuning || (FineTuning = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/images.mjs var Images; var init_images = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/images.mjs"() { init_resource(); init_core2(); Images = class extends APIResource { createVariation(body, options) { return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options })); } edit(body, options) { return this._client.post("/images/edits", multipartFormRequestOptions({ body, ...options })); } generate(body, options) { return this._client.post("/images/generations", { body, ...options }); } }; (function(Images2) { })(Images || (Images = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/models.mjs var Models, ModelsPage; var init_models = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/models.mjs"() { init_resource(); init_models(); init_pagination(); Models = class extends APIResource { retrieve(model, options) { return this._client.get(`/models/${model}`, options); } list(options) { return this._client.getAPIList("/models", ModelsPage, options); } del(model, options) { return this._client.delete(`/models/${model}`, options); } }; ModelsPage = class extends Page { }; (function(Models2) { Models2.ModelsPage = ModelsPage; })(Models || (Models = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/moderations.mjs var Moderations; var init_moderations = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/moderations.mjs"() { init_resource(); Moderations = class extends APIResource { create(body, options) { return this._client.post("/moderations", { body, ...options }); } }; (function(Moderations2) { })(Moderations || (Moderations = {})); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/index.mjs var init_resources = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/resources/index.mjs"() { init_chat3(); init_shared(); init_audio(); init_beta(); init_completions3(); init_embeddings2(); init_files3(); init_fine_tuning(); init_images(); init_models(); init_moderations(); } }); // node_modules/.pnpm/openai@4.29.1/node_modules/openai/index.mjs var _a, OpenAI, OpenAIError2, APIError2, APIConnectionError2, APIConnectionTimeoutError2, APIUserAbortError2, NotFoundError2, ConflictError2, RateLimitError2, BadRequestError2, AuthenticationError2, InternalServerError2, PermissionDeniedError2, UnprocessableEntityError2, toFile2; var init_openai = __esm({ "node_modules/.pnpm/openai@4.29.1/node_modules/openai/index.mjs"() { init_core2(); init_error(); init_uploads(); init_pagination(); init_resources(); OpenAI = class extends APIClient { constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY"), organization = readEnv("OPENAI_ORG_ID") ?? null, ...opts } = {}) { if (apiKey === void 0) { throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); } const options = { apiKey, organization, ...opts, baseURL: baseURL || `https://api.openai.com/v1` }; if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); } super({ baseURL: options.baseURL, timeout: options.timeout ?? 6e5, httpAgent: options.httpAgent, maxRetries: options.maxRetries, fetch: options.fetch }); this.completions = new Completions3(this); this.chat = new Chat(this); this.embeddings = new Embeddings2(this); this.files = new Files3(this); this.images = new Images(this); this.audio = new Audio(this); this.moderations = new Moderations(this); this.models = new Models(this); this.fineTuning = new FineTuning(this); this.beta = new Beta(this); this._options = options; this.apiKey = apiKey; this.organization = organization; } defaultQuery() { return this._options.defaultQuery; } defaultHeaders(opts) { return { ...super.defaultHeaders(opts), "OpenAI-Organization": this.organization, ...this._options.defaultHeaders }; } authHeaders(opts) { return { Authorization: `Bearer ${this.apiKey}` }; } }; _a = OpenAI; OpenAI.OpenAI = _a; OpenAI.OpenAIError = OpenAIError; OpenAI.APIError = APIError; OpenAI.APIConnectionError = APIConnectionError; OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError; OpenAI.APIUserAbortError = APIUserAbortError; OpenAI.NotFoundError = NotFoundError; OpenAI.ConflictError = ConflictError; OpenAI.RateLimitError = RateLimitError; OpenAI.BadRequestError = BadRequestError; OpenAI.AuthenticationError = AuthenticationError; OpenAI.InternalServerError = InternalServerError; OpenAI.PermissionDeniedError = PermissionDeniedError; OpenAI.UnprocessableEntityError = UnprocessableEntityError; ({ OpenAIError: OpenAIError2, APIError: APIError2, APIConnectionError: APIConnectionError2, APIConnectionTimeoutError: APIConnectionTimeoutError2, APIUserAbortError: APIUserAbortError2, NotFoundError: NotFoundError2, ConflictError: ConflictError2, RateLimitError: RateLimitError2, BadRequestError: BadRequestError2, AuthenticationError: AuthenticationError2, InternalServerError: InternalServerError2, PermissionDeniedError: PermissionDeniedError2, UnprocessableEntityError: UnprocessableEntityError2 } = error_exports); toFile2 = toFile; (function(OpenAI4) { OpenAI4.toFile = toFile; OpenAI4.fileFromPath = fileFromPath; OpenAI4.Page = Page; OpenAI4.CursorPage = CursorPage; OpenAI4.Completions = Completions3; OpenAI4.Chat = Chat; OpenAI4.Embeddings = Embeddings2; OpenAI4.Files = Files3; OpenAI4.FileObjectsPage = FileObjectsPage; OpenAI4.Images = Images; OpenAI4.Audio = Audio; OpenAI4.Moderations = Moderations; OpenAI4.Models = Models; OpenAI4.ModelsPage = ModelsPage; OpenAI4.FineTuning = FineTuning; OpenAI4.Beta = Beta; })(OpenAI || (OpenAI = {})); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/language_models/chat_models.js var init_chat_models2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/language_models/chat_models.js"() { init_chat_models(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js var JsonOutputToolsParser, JsonOutputKeyToolsParser; var init_json_output_tools_parsers = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js"() { init_base7(); JsonOutputToolsParser = class extends BaseLLMOutputParser { static lc_name() { return "JsonOutputToolsParser"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "returnId", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "output_parsers", "openai_tools"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); this.returnId = fields2?.returnId ?? this.returnId; } async parseResult(generations) { const toolCalls = generations[0].message.additional_kwargs.tool_calls; if (!toolCalls) { throw new Error(`No tools_call in message ${JSON.stringify(generations)}`); } const clonedToolCalls = JSON.parse(JSON.stringify(toolCalls)); const parsedToolCalls = []; for (const toolCall of clonedToolCalls) { if (toolCall.function !== void 0) { const parsedToolCall = { type: toolCall.function.name, args: JSON.parse(toolCall.function.arguments) }; if (this.returnId) { parsedToolCall.id = toolCall.id; } Object.defineProperty(parsedToolCall, "name", { get() { return this.type; } }); Object.defineProperty(parsedToolCall, "arguments", { get() { return this.args; } }); parsedToolCalls.push(parsedToolCall); } } return parsedToolCalls; } }; JsonOutputKeyToolsParser = class extends BaseLLMOutputParser { static lc_name() { return "JsonOutputKeyToolsParser"; } constructor(params) { super(params); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "output_parsers", "openai_tools"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "returnId", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "keyName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "returnSingle", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "initialParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "zodSchema", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.keyName = params.keyName; this.returnSingle = params.returnSingle ?? this.returnSingle; this.initialParser = new JsonOutputToolsParser(params); this.zodSchema = params.zodSchema; } async _validateResult(result) { if (this.zodSchema === void 0) { return result; } const zodParsedResult = await this.zodSchema.safeParseAsync(result); if (zodParsedResult.success) { return zodParsedResult.data; } else { throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(result, null, 2)); } } async parseResult(generations) { const results = await this.initialParser.parseResult(generations); const matchingResults = results.filter((result) => result.type === this.keyName); let returnedValues = matchingResults; if (!this.returnId) { returnedValues = matchingResults.map((result) => result.args); } if (this.returnSingle) { return this._validateResult(returnedValues[0]); } const toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value))); return toolCallResults; } }; } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js var init_openai_tools = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js"() { init_json_output_tools_parsers(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/output_parsers/openai_tools.js var init_openai_tools2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/output_parsers/openai_tools.js"() { init_openai_tools(); } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/utils/azure.js function getEndpoint(config) { const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL } = config; if (azureOpenAIApiKey && azureOpenAIBasePath && azureOpenAIApiDeploymentName) { return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; } if (azureOpenAIApiKey) { if (!azureOpenAIApiInstanceName) { throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey"); } if (!azureOpenAIApiDeploymentName) { throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey"); } return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`; } return baseURL; } var init_azure = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/utils/azure.js"() { } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/utils/openai.js function wrapOpenAIClientError(e2) { let error; if (e2.constructor.name === APIConnectionTimeoutError2.name) { error = new Error(e2.message); error.name = "TimeoutError"; } else if (e2.constructor.name === APIUserAbortError2.name) { error = new Error(e2.message); error.name = "AbortError"; } else { error = e2; } return error; } function formatToOpenAIAssistantTool(tool) { return { type: "function", function: { name: tool.name, description: tool.description, parameters: zodToJsonSchema(tool.schema) } }; } var init_openai2 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/utils/openai.js"() { init_openai(); init_esm(); init_function_calling2(); } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/utils/openai-format-fndef.js function isAnyOfProp(prop) { return prop.anyOf !== void 0 && Array.isArray(prop.anyOf); } function formatFunctionDefinitions(functions) { const lines = ["namespace functions {", ""]; for (const f4 of functions) { if (f4.description) { lines.push(`// ${f4.description}`); } if (Object.keys(f4.parameters.properties ?? {}).length > 0) { lines.push(`type ${f4.name} = (_: {`); lines.push(formatObjectProperties(f4.parameters, 0)); lines.push("}) => any;"); } else { lines.push(`type ${f4.name} = () => any;`); } lines.push(""); } lines.push("} // namespace functions"); return lines.join("\n"); } function formatObjectProperties(obj, indent) { const lines = []; for (const [name2, param] of Object.entries(obj.properties ?? {})) { if (param.description && indent < 2) { lines.push(`// ${param.description}`); } if (obj.required?.includes(name2)) { lines.push(`${name2}: ${formatType(param, indent)},`); } else { lines.push(`${name2}?: ${formatType(param, indent)},`); } } return lines.map((line) => " ".repeat(indent) + line).join("\n"); } function formatType(param, indent) { if (isAnyOfProp(param)) { return param.anyOf.map((v2) => formatType(v2, indent)).join(" | "); } switch (param.type) { case "string": if (param.enum) { return param.enum.map((v2) => `"${v2}"`).join(" | "); } return "string"; case "number": if (param.enum) { return param.enum.map((v2) => `${v2}`).join(" | "); } return "number"; case "integer": if (param.enum) { return param.enum.map((v2) => `${v2}`).join(" | "); } return "number"; case "boolean": return "boolean"; case "null": return "null"; case "object": return ["{", formatObjectProperties(param, indent + 2), "}"].join("\n"); case "array": if (param.items) { return `${formatType(param.items, indent)}[]`; } return "any[]"; default: return ""; } } var init_openai_format_fndef = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/utils/openai-format-fndef.js"() { } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/chat_models.js function extractGenericMessageCustomRole(message) { if (message.role !== "system" && message.role !== "assistant" && message.role !== "user" && message.role !== "function" && message.role !== "tool") { console.warn(`Unknown message role: ${message.role}`); } return message.role; } function messageToOpenAIRole(message) { const type2 = message._getType(); switch (type2) { case "system": return "system"; case "ai": return "assistant"; case "human": return "user"; case "function": return "function"; case "tool": return "tool"; case "generic": { if (!ChatMessage.isInstance(message)) throw new Error("Invalid generic chat message"); return extractGenericMessageCustomRole(message); } default: throw new Error(`Unknown message type: ${type2}`); } } function openAIResponseToChatMessage(message) { switch (message.role) { case "assistant": return new AIMessage(message.content || "", { function_call: message.function_call, tool_calls: message.tool_calls }); default: return new ChatMessage(message.content || "", message.role ?? "unknown"); } } function _convertDeltaToMessageChunk(delta, defaultRole) { const role = delta.role ?? defaultRole; const content = delta.content ?? ""; let additional_kwargs; if (delta.function_call) { additional_kwargs = { function_call: delta.function_call }; } else if (delta.tool_calls) { additional_kwargs = { tool_calls: delta.tool_calls }; } else { additional_kwargs = {}; } if (role === "user") { return new HumanMessageChunk({ content }); } else if (role === "assistant") { return new AIMessageChunk({ content, additional_kwargs }); } else if (role === "system") { return new SystemMessageChunk({ content }); } else if (role === "function") { return new FunctionMessageChunk({ content, additional_kwargs, name: delta.name }); } else if (role === "tool") { return new ToolMessageChunk({ content, additional_kwargs, tool_call_id: delta.tool_call_id }); } else { return new ChatMessageChunk({ content, role }); } } function convertMessagesToOpenAIParams(messages4) { return messages4.map((message) => ({ role: messageToOpenAIRole(message), content: message.content, name: message.name, function_call: message.additional_kwargs.function_call, tool_calls: message.additional_kwargs.tool_calls, tool_call_id: message.tool_call_id })); } function isZodSchema(input) { return typeof input?.parse === "function"; } function isStructuredOutputMethodParams(x2) { return x2 !== void 0 && typeof x2.schema === "object"; } var ChatOpenAI; var init_chat_models3 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/chat_models.js"() { init_openai(); init_messages2(); init_outputs2(); init_env2(); init_chat_models2(); init_function_calling2(); init_runnables2(); init_output_parsers2(); init_openai_tools2(); init_esm(); init_azure(); init_openai2(); init_openai_format_fndef(); ChatOpenAI = class extends BaseChatModel { static lc_name() { return "ChatOpenAI"; } get callKeys() { return [ ...super.callKeys, "options", "function_call", "functions", "tools", "tool_choice", "promptIndex", "response_format", "seed" ]; } get lc_secrets() { return { openAIApiKey: "OPENAI_API_KEY", azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", organization: "OPENAI_ORGANIZATION" }; } get lc_aliases() { return { modelName: "model", openAIApiKey: "openai_api_key", azureOpenAIApiVersion: "azure_openai_api_version", azureOpenAIApiKey: "azure_openai_api_key", azureOpenAIApiInstanceName: "azure_openai_api_instance_name", azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name" }; } constructor(fields2, configuration) { super(fields2 ?? {}); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "temperature", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "topP", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "frequencyPenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "presencePenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "n", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "logitBias", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "modelName", { enumerable: true, configurable: true, writable: true, value: "gpt-3.5-turbo" }); Object.defineProperty(this, "modelKwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "stop", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "user", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "timeout", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "streaming", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "maxTokens", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "logprobs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "topLogprobs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "openAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiVersion", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiInstanceName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiDeploymentName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIBasePath", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "organization", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "clientConfig", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.openAIApiKey = fields2?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); this.azureOpenAIApiKey = fields2?.azureOpenAIApiKey ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); if (!this.azureOpenAIApiKey && !this.openAIApiKey) { throw new Error("OpenAI or Azure OpenAI API key not found"); } this.azureOpenAIApiInstanceName = fields2?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); this.azureOpenAIApiDeploymentName = fields2?.azureOpenAIApiDeploymentName ?? getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"); this.azureOpenAIApiVersion = fields2?.azureOpenAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); this.azureOpenAIBasePath = fields2?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); this.organization = fields2?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); this.modelName = fields2?.modelName ?? this.modelName; this.modelKwargs = fields2?.modelKwargs ?? {}; this.timeout = fields2?.timeout; this.temperature = fields2?.temperature ?? this.temperature; this.topP = fields2?.topP ?? this.topP; this.frequencyPenalty = fields2?.frequencyPenalty ?? this.frequencyPenalty; this.presencePenalty = fields2?.presencePenalty ?? this.presencePenalty; this.maxTokens = fields2?.maxTokens; this.logprobs = fields2?.logprobs; this.topLogprobs = fields2?.topLogprobs; this.n = fields2?.n ?? this.n; this.logitBias = fields2?.logitBias; this.stop = fields2?.stop; this.user = fields2?.user; this.streaming = fields2?.streaming ?? false; if (this.azureOpenAIApiKey) { if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { throw new Error("Azure OpenAI API instance name not found"); } if (!this.azureOpenAIApiDeploymentName) { throw new Error("Azure OpenAI API deployment name not found"); } if (!this.azureOpenAIApiVersion) { throw new Error("Azure OpenAI API version not found"); } this.openAIApiKey = this.openAIApiKey ?? ""; } this.clientConfig = { apiKey: this.openAIApiKey, organization: this.organization, baseURL: configuration?.basePath ?? fields2?.configuration?.basePath, dangerouslyAllowBrowser: true, defaultHeaders: configuration?.baseOptions?.headers ?? fields2?.configuration?.baseOptions?.headers, defaultQuery: configuration?.baseOptions?.params ?? fields2?.configuration?.baseOptions?.params, ...configuration, ...fields2?.configuration }; } invocationParams(options) { function isStructuredToolArray(tools) { return tools !== void 0 && tools.every((tool) => Array.isArray(tool.lc_namespace)); } const params = { model: this.modelName, temperature: this.temperature, top_p: this.topP, frequency_penalty: this.frequencyPenalty, presence_penalty: this.presencePenalty, max_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens, logprobs: this.logprobs, top_logprobs: this.topLogprobs, n: this.n, logit_bias: this.logitBias, stop: options?.stop ?? this.stop, user: this.user, stream: this.streaming, functions: options?.functions, function_call: options?.function_call, tools: isStructuredToolArray(options?.tools) ? options?.tools.map(convertToOpenAITool) : options?.tools, tool_choice: options?.tool_choice, response_format: options?.response_format, seed: options?.seed, ...this.modelKwargs }; return params; } _identifyingParams() { return { model_name: this.modelName, ...this.invocationParams(), ...this.clientConfig }; } async *_streamResponseChunks(messages4, options, runManager) { const messagesMapped = convertMessagesToOpenAIParams(messages4); const params = { ...this.invocationParams(options), messages: messagesMapped, stream: true }; let defaultRole; const streamIterable = await this.completionWithRetry(params, options); for await (const data of streamIterable) { const choice = data?.choices[0]; if (!choice) { continue; } const { delta } = choice; if (!delta) { continue; } const chunk = _convertDeltaToMessageChunk(delta, defaultRole); defaultRole = delta.role ?? defaultRole; const newTokenIndices = { prompt: options.promptIndex ?? 0, completion: choice.index ?? 0 }; if (typeof chunk.content !== "string") { console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported."); continue; } const generationInfo = { ...newTokenIndices }; if (choice.finish_reason !== void 0) { generationInfo.finish_reason = choice.finish_reason; } if (this.logprobs) { generationInfo.logprobs = choice.logprobs; } const generationChunk = new ChatGenerationChunk({ message: chunk, text: chunk.content, generationInfo }); yield generationChunk; void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk }); } if (options.signal?.aborted) { throw new Error("AbortError"); } } identifyingParams() { return this._identifyingParams(); } async _generate(messages4, options, runManager) { const tokenUsage = {}; const params = this.invocationParams(options); const messagesMapped = convertMessagesToOpenAIParams(messages4); if (params.stream) { const stream = this._streamResponseChunks(messages4, options, runManager); const finalChunks = {}; for await (const chunk of stream) { chunk.message.response_metadata = { ...chunk.generationInfo, ...chunk.message.response_metadata }; const index2 = chunk.generationInfo?.completion ?? 0; if (finalChunks[index2] === void 0) { finalChunks[index2] = chunk; } else { finalChunks[index2] = finalChunks[index2].concat(chunk); } } const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_2, value]) => value); const { functions, function_call } = this.invocationParams(options); const promptTokenUsage = await this.getEstimatedTokenCountFromPrompt(messages4, functions, function_call); const completionTokenUsage = await this.getNumTokensFromGenerations(generations); tokenUsage.promptTokens = promptTokenUsage; tokenUsage.completionTokens = completionTokenUsage; tokenUsage.totalTokens = promptTokenUsage + completionTokenUsage; return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } }; } else { const data = await this.completionWithRetry({ ...params, stream: false, messages: messagesMapped }, { signal: options?.signal, ...options?.options }); const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = data?.usage ?? {}; if (completionTokens) { tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + completionTokens; } if (promptTokens) { tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; } if (totalTokens) { tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; } const generations = []; for (const part of data?.choices ?? []) { const text = part.message?.content ?? ""; const generation = { text, message: openAIResponseToChatMessage(part.message ?? { role: "assistant" }) }; generation.generationInfo = { ...part.finish_reason ? { finish_reason: part.finish_reason } : {}, ...part.logprobs ? { logprobs: part.logprobs } : {} }; generations.push(generation); } return { generations, llmOutput: { tokenUsage } }; } } async getEstimatedTokenCountFromPrompt(messages4, functions, function_call) { let tokens = (await this.getNumTokensFromMessages(messages4)).totalCount; if (functions && function_call !== "auto") { const promptDefinitions = formatFunctionDefinitions(functions); tokens += await this.getNumTokens(promptDefinitions); tokens += 9; } if (functions && messages4.find((m2) => m2._getType() === "system")) { tokens -= 4; } if (function_call === "none") { tokens += 1; } else if (typeof function_call === "object") { tokens += await this.getNumTokens(function_call.name) + 4; } return tokens; } async getNumTokensFromGenerations(generations) { const generationUsages = await Promise.all(generations.map(async (generation) => { if (generation.message.additional_kwargs?.function_call) { return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0]; } else { return await this.getNumTokens(generation.message.content); } })); return generationUsages.reduce((a2, b2) => a2 + b2, 0); } async getNumTokensFromMessages(messages4) { let totalCount = 0; let tokensPerMessage = 0; let tokensPerName = 0; if (this.modelName === "gpt-3.5-turbo-0301") { tokensPerMessage = 4; tokensPerName = -1; } else { tokensPerMessage = 3; tokensPerName = 1; } const countPerMessage = await Promise.all(messages4.map(async (message) => { const textCount = await this.getNumTokens(message.content); const roleCount = await this.getNumTokens(messageToOpenAIRole(message)); const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0; let count = textCount + tokensPerMessage + roleCount + nameCount; const openAIMessage = message; if (openAIMessage._getType() === "function") { count -= 2; } if (openAIMessage.additional_kwargs?.function_call) { count += 3; } if (openAIMessage?.additional_kwargs.function_call?.name) { count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name); } if (openAIMessage.additional_kwargs.function_call?.arguments) { count += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments))); } totalCount += count; return count; })); totalCount += 3; return { totalCount, countPerMessage }; } async completionWithRetry(request7, options) { const requestOptions = this._getClientOptions(options); return this.caller.call(async () => { try { const res = await this.client.chat.completions.create(request7, requestOptions); return res; } catch (e2) { const error = wrapOpenAIClientError(e2); throw error; } }); } _getClientOptions(options) { if (!this.client) { const openAIEndpointConfig = { azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, azureOpenAIApiKey: this.azureOpenAIApiKey, azureOpenAIBasePath: this.azureOpenAIBasePath, baseURL: this.clientConfig.baseURL }; const endpoint = getEndpoint(openAIEndpointConfig); const params = { ...this.clientConfig, baseURL: endpoint, timeout: this.timeout, maxRetries: 0 }; if (!params.baseURL) { delete params.baseURL; } this.client = new OpenAI(params); } const requestOptions = { ...this.clientConfig, ...options }; if (this.azureOpenAIApiKey) { requestOptions.headers = { "api-key": this.azureOpenAIApiKey, ...requestOptions.headers }; requestOptions.query = { "api-version": this.azureOpenAIApiVersion, ...requestOptions.query }; } return requestOptions; } _llmType() { return "openai"; } _combineLLMOutput(...llmOutputs) { return llmOutputs.reduce((acc, llmOutput) => { if (llmOutput && llmOutput.tokenUsage) { acc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0; acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0; acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0; } return acc; }, { tokenUsage: { completionTokens: 0, promptTokens: 0, totalTokens: 0 } }); } withStructuredOutput(outputSchema, config) { let schema3; let name2; let method; let includeRaw; if (isStructuredOutputMethodParams(outputSchema)) { schema3 = outputSchema.schema; name2 = outputSchema.name; method = outputSchema.method; includeRaw = outputSchema.includeRaw; } else { schema3 = outputSchema; name2 = config?.name; method = config?.method; includeRaw = config?.includeRaw; } let llm; let outputParser; if (method === "jsonMode") { llm = this.bind({ response_format: { type: "json_object" } }); if (isZodSchema(schema3)) { outputParser = StructuredOutputParser.fromZodSchema(schema3); } else { outputParser = new JsonOutputParser(); } } else { let functionName = name2 ?? "extract"; if (isZodSchema(schema3)) { const asJsonSchema = zodToJsonSchema(schema3); llm = this.bind({ tools: [ { type: "function", function: { name: functionName, description: asJsonSchema.description, parameters: asJsonSchema } } ], tool_choice: { type: "function", function: { name: functionName } } }); outputParser = new JsonOutputKeyToolsParser({ returnSingle: true, keyName: functionName, zodSchema: schema3 }); } else { let openAIFunctionDefinition; if (typeof schema3.name === "string" && typeof schema3.parameters === "object" && schema3.parameters != null) { openAIFunctionDefinition = schema3; functionName = schema3.name; } else { openAIFunctionDefinition = { name: functionName, description: schema3.description ?? "", parameters: schema3 }; } llm = this.bind({ tools: [ { type: "function", function: openAIFunctionDefinition } ], tool_choice: { type: "function", function: { name: functionName } } }); outputParser = new JsonOutputKeyToolsParser({ returnSingle: true, keyName: functionName }); } } if (!includeRaw) { return llm.pipe(outputParser); } const parserAssign = RunnablePassthrough.assign({ parsed: (input, config2) => outputParser.invoke(input.raw, config2) }); const parserNone = RunnablePassthrough.assign({ parsed: () => null }); const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); return RunnableSequence.from([ { raw: llm }, parsedWithFallback ]); } }; } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/azure/chat_models.js var init_chat_models4 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/azure/chat_models.js"() { init_chat_models3(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/language_models/llms.js var init_llms2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/language_models/llms.js"() { init_llms(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/utils/chunk_array.js var init_chunk_array2 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/utils/chunk_array.js"() { init_chunk_array(); } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/legacy.js var OpenAIChat; var init_legacy = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/legacy.js"() { init_openai(); init_outputs2(); init_env2(); init_llms2(); init_azure(); init_openai2(); OpenAIChat = class extends LLM { static lc_name() { return "OpenAIChat"; } get callKeys() { return [...super.callKeys, "options", "promptIndex"]; } get lc_secrets() { return { openAIApiKey: "OPENAI_API_KEY", azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", organization: "OPENAI_ORGANIZATION" }; } get lc_aliases() { return { modelName: "model", openAIApiKey: "openai_api_key", azureOpenAIApiVersion: "azure_openai_api_version", azureOpenAIApiKey: "azure_openai_api_key", azureOpenAIApiInstanceName: "azure_openai_api_instance_name", azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name" }; } constructor(fields2, configuration) { super(fields2 ?? {}); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "temperature", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "topP", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "frequencyPenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "presencePenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "n", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "logitBias", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "maxTokens", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "modelName", { enumerable: true, configurable: true, writable: true, value: "gpt-3.5-turbo" }); Object.defineProperty(this, "prefixMessages", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "modelKwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "timeout", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "stop", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "user", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "streaming", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "openAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiVersion", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiInstanceName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiDeploymentName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIBasePath", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "organization", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "clientConfig", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.openAIApiKey = fields2?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); this.azureOpenAIApiKey = fields2?.azureOpenAIApiKey ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); if (!this.azureOpenAIApiKey && !this.openAIApiKey) { throw new Error("OpenAI or Azure OpenAI API key not found"); } this.azureOpenAIApiInstanceName = fields2?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); this.azureOpenAIApiDeploymentName = (fields2?.azureOpenAIApiCompletionsDeploymentName || fields2?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); this.azureOpenAIApiVersion = fields2?.azureOpenAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); this.azureOpenAIBasePath = fields2?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); this.organization = fields2?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); this.modelName = fields2?.modelName ?? this.modelName; this.prefixMessages = fields2?.prefixMessages ?? this.prefixMessages; this.modelKwargs = fields2?.modelKwargs ?? {}; this.timeout = fields2?.timeout; this.temperature = fields2?.temperature ?? this.temperature; this.topP = fields2?.topP ?? this.topP; this.frequencyPenalty = fields2?.frequencyPenalty ?? this.frequencyPenalty; this.presencePenalty = fields2?.presencePenalty ?? this.presencePenalty; this.n = fields2?.n ?? this.n; this.logitBias = fields2?.logitBias; this.maxTokens = fields2?.maxTokens; this.stop = fields2?.stop; this.user = fields2?.user; this.streaming = fields2?.streaming ?? false; if (this.n > 1) { throw new Error("Cannot use n > 1 in OpenAIChat LLM. Use ChatOpenAI Chat Model instead."); } if (this.azureOpenAIApiKey) { if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { throw new Error("Azure OpenAI API instance name not found"); } if (!this.azureOpenAIApiDeploymentName) { throw new Error("Azure OpenAI API deployment name not found"); } if (!this.azureOpenAIApiVersion) { throw new Error("Azure OpenAI API version not found"); } this.openAIApiKey = this.openAIApiKey ?? ""; } this.clientConfig = { apiKey: this.openAIApiKey, organization: this.organization, baseURL: configuration?.basePath ?? fields2?.configuration?.basePath, dangerouslyAllowBrowser: true, defaultHeaders: configuration?.baseOptions?.headers ?? fields2?.configuration?.baseOptions?.headers, defaultQuery: configuration?.baseOptions?.params ?? fields2?.configuration?.baseOptions?.params, ...configuration, ...fields2?.configuration }; } invocationParams(options) { return { model: this.modelName, temperature: this.temperature, top_p: this.topP, frequency_penalty: this.frequencyPenalty, presence_penalty: this.presencePenalty, n: this.n, logit_bias: this.logitBias, max_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens, stop: options?.stop ?? this.stop, user: this.user, stream: this.streaming, ...this.modelKwargs }; } _identifyingParams() { return { model_name: this.modelName, ...this.invocationParams(), ...this.clientConfig }; } identifyingParams() { return { model_name: this.modelName, ...this.invocationParams(), ...this.clientConfig }; } formatMessages(prompt) { const message = { role: "user", content: prompt }; return this.prefixMessages ? [...this.prefixMessages, message] : [message]; } async *_streamResponseChunks(prompt, options, runManager) { const params = { ...this.invocationParams(options), messages: this.formatMessages(prompt), stream: true }; const stream = await this.completionWithRetry(params, options); for await (const data of stream) { const choice = data?.choices[0]; if (!choice) { continue; } const { delta } = choice; const generationChunk = new GenerationChunk({ text: delta.content ?? "" }); yield generationChunk; const newTokenIndices = { prompt: options.promptIndex ?? 0, completion: choice.index ?? 0 }; void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices); } if (options.signal?.aborted) { throw new Error("AbortError"); } } async _call(prompt, options, runManager) { const params = this.invocationParams(options); if (params.stream) { const stream = await this._streamResponseChunks(prompt, options, runManager); let finalChunk; for await (const chunk of stream) { if (finalChunk === void 0) { finalChunk = chunk; } else { finalChunk = finalChunk.concat(chunk); } } return finalChunk?.text ?? ""; } else { const response = await this.completionWithRetry({ ...params, stream: false, messages: this.formatMessages(prompt) }, { signal: options.signal, ...options.options }); return response?.choices[0]?.message?.content ?? ""; } } async completionWithRetry(request7, options) { const requestOptions = this._getClientOptions(options); return this.caller.call(async () => { try { const res = await this.client.chat.completions.create(request7, requestOptions); return res; } catch (e2) { const error = wrapOpenAIClientError(e2); throw error; } }); } _getClientOptions(options) { if (!this.client) { const openAIEndpointConfig = { azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, azureOpenAIApiKey: this.azureOpenAIApiKey, azureOpenAIBasePath: this.azureOpenAIBasePath, baseURL: this.clientConfig.baseURL }; const endpoint = getEndpoint(openAIEndpointConfig); const params = { ...this.clientConfig, baseURL: endpoint, timeout: this.timeout, maxRetries: 0 }; if (!params.baseURL) { delete params.baseURL; } this.client = new OpenAI(params); } const requestOptions = { ...this.clientConfig, ...options }; if (this.azureOpenAIApiKey) { requestOptions.headers = { "api-key": this.azureOpenAIApiKey, ...requestOptions.headers }; requestOptions.query = { "api-version": this.azureOpenAIApiVersion, ...requestOptions.query }; } return requestOptions; } _llmType() { return "openai"; } }; } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/llms.js var OpenAI2; var init_llms3 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/llms.js"() { init_openai(); init_base8(); init_outputs2(); init_env2(); init_llms2(); init_chunk_array2(); init_azure(); init_legacy(); init_openai2(); OpenAI2 = class extends BaseLLM { static lc_name() { return "OpenAI"; } get callKeys() { return [...super.callKeys, "options"]; } get lc_secrets() { return { openAIApiKey: "OPENAI_API_KEY", azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", organization: "OPENAI_ORGANIZATION" }; } get lc_aliases() { return { modelName: "model", openAIApiKey: "openai_api_key", azureOpenAIApiVersion: "azure_openai_api_version", azureOpenAIApiKey: "azure_openai_api_key", azureOpenAIApiInstanceName: "azure_openai_api_instance_name", azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name" }; } constructor(fields2, configuration) { if ((fields2?.modelName?.startsWith("gpt-3.5-turbo") || fields2?.modelName?.startsWith("gpt-4")) && !fields2?.modelName?.includes("-instruct")) { return new OpenAIChat(fields2, configuration); } super(fields2 ?? {}); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "temperature", { enumerable: true, configurable: true, writable: true, value: 0.7 }); Object.defineProperty(this, "maxTokens", { enumerable: true, configurable: true, writable: true, value: 256 }); Object.defineProperty(this, "topP", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "frequencyPenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "presencePenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "n", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "bestOf", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "logitBias", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "modelName", { enumerable: true, configurable: true, writable: true, value: "gpt-3.5-turbo-instruct" }); Object.defineProperty(this, "modelKwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "batchSize", { enumerable: true, configurable: true, writable: true, value: 20 }); Object.defineProperty(this, "timeout", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "stop", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "user", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "streaming", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "openAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiVersion", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiInstanceName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiDeploymentName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIBasePath", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "organization", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "clientConfig", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.openAIApiKey = fields2?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); this.azureOpenAIApiKey = fields2?.azureOpenAIApiKey ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); if (!this.azureOpenAIApiKey && !this.openAIApiKey) { throw new Error("OpenAI or Azure OpenAI API key not found"); } this.azureOpenAIApiInstanceName = fields2?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); this.azureOpenAIApiDeploymentName = (fields2?.azureOpenAIApiCompletionsDeploymentName || fields2?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); this.azureOpenAIApiVersion = fields2?.azureOpenAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); this.azureOpenAIBasePath = fields2?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); this.organization = fields2?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); this.modelName = fields2?.modelName ?? this.modelName; this.modelKwargs = fields2?.modelKwargs ?? {}; this.batchSize = fields2?.batchSize ?? this.batchSize; this.timeout = fields2?.timeout; this.temperature = fields2?.temperature ?? this.temperature; this.maxTokens = fields2?.maxTokens ?? this.maxTokens; this.topP = fields2?.topP ?? this.topP; this.frequencyPenalty = fields2?.frequencyPenalty ?? this.frequencyPenalty; this.presencePenalty = fields2?.presencePenalty ?? this.presencePenalty; this.n = fields2?.n ?? this.n; this.bestOf = fields2?.bestOf ?? this.bestOf; this.logitBias = fields2?.logitBias; this.stop = fields2?.stop; this.user = fields2?.user; this.streaming = fields2?.streaming ?? false; if (this.streaming && this.bestOf && this.bestOf > 1) { throw new Error("Cannot stream results when bestOf > 1"); } if (this.azureOpenAIApiKey) { if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { throw new Error("Azure OpenAI API instance name not found"); } if (!this.azureOpenAIApiDeploymentName) { throw new Error("Azure OpenAI API deployment name not found"); } if (!this.azureOpenAIApiVersion) { throw new Error("Azure OpenAI API version not found"); } this.openAIApiKey = this.openAIApiKey ?? ""; } this.clientConfig = { apiKey: this.openAIApiKey, organization: this.organization, baseURL: configuration?.basePath ?? fields2?.configuration?.basePath, dangerouslyAllowBrowser: true, defaultHeaders: configuration?.baseOptions?.headers ?? fields2?.configuration?.baseOptions?.headers, defaultQuery: configuration?.baseOptions?.params ?? fields2?.configuration?.baseOptions?.params, ...configuration, ...fields2?.configuration }; } invocationParams(options) { return { model: this.modelName, temperature: this.temperature, max_tokens: this.maxTokens, top_p: this.topP, frequency_penalty: this.frequencyPenalty, presence_penalty: this.presencePenalty, n: this.n, best_of: this.bestOf, logit_bias: this.logitBias, stop: options?.stop ?? this.stop, user: this.user, stream: this.streaming, ...this.modelKwargs }; } _identifyingParams() { return { model_name: this.modelName, ...this.invocationParams(), ...this.clientConfig }; } identifyingParams() { return this._identifyingParams(); } async _generate(prompts, options, runManager) { const subPrompts = chunkArray(prompts, this.batchSize); const choices = []; const tokenUsage = {}; const params = this.invocationParams(options); if (params.max_tokens === -1) { if (prompts.length !== 1) { throw new Error("max_tokens set to -1 not supported for multiple inputs"); } params.max_tokens = await calculateMaxTokens({ prompt: prompts[0], modelName: this.modelName }); } for (let i2 = 0; i2 < subPrompts.length; i2 += 1) { const data = params.stream ? await (async () => { const choices2 = []; let response; const stream = await this.completionWithRetry({ ...params, stream: true, prompt: subPrompts[i2] }, options); for await (const message of stream) { if (!response) { response = { id: message.id, object: message.object, created: message.created, model: message.model }; } for (const part of message.choices) { if (!choices2[part.index]) { choices2[part.index] = part; } else { const choice = choices2[part.index]; choice.text += part.text; choice.finish_reason = part.finish_reason; choice.logprobs = part.logprobs; } void runManager?.handleLLMNewToken(part.text, { prompt: Math.floor(part.index / this.n), completion: part.index % this.n }); } } if (options.signal?.aborted) { throw new Error("AbortError"); } return { ...response, choices: choices2 }; })() : await this.completionWithRetry({ ...params, stream: false, prompt: subPrompts[i2] }, { signal: options.signal, ...options.options }); choices.push(...data.choices); const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = data.usage ? data.usage : { completion_tokens: void 0, prompt_tokens: void 0, total_tokens: void 0 }; if (completionTokens) { tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + completionTokens; } if (promptTokens) { tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; } if (totalTokens) { tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; } } const generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({ text: choice.text ?? "", generationInfo: { finishReason: choice.finish_reason, logprobs: choice.logprobs } }))); return { generations, llmOutput: { tokenUsage } }; } async *_streamResponseChunks(input, options, runManager) { const params = { ...this.invocationParams(options), prompt: input, stream: true }; const stream = await this.completionWithRetry(params, options); for await (const data of stream) { const choice = data?.choices[0]; if (!choice) { continue; } const chunk = new GenerationChunk({ text: choice.text, generationInfo: { finishReason: choice.finish_reason } }); yield chunk; void runManager?.handleLLMNewToken(chunk.text ?? ""); } if (options.signal?.aborted) { throw new Error("AbortError"); } } async completionWithRetry(request7, options) { const requestOptions = this._getClientOptions(options); return this.caller.call(async () => { try { const res = await this.client.completions.create(request7, requestOptions); return res; } catch (e2) { const error = wrapOpenAIClientError(e2); throw error; } }); } _getClientOptions(options) { if (!this.client) { const openAIEndpointConfig = { azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, azureOpenAIApiKey: this.azureOpenAIApiKey, azureOpenAIBasePath: this.azureOpenAIBasePath, baseURL: this.clientConfig.baseURL }; const endpoint = getEndpoint(openAIEndpointConfig); const params = { ...this.clientConfig, baseURL: endpoint, timeout: this.timeout, maxRetries: 0 }; if (!params.baseURL) { delete params.baseURL; } this.client = new OpenAI(params); } const requestOptions = { ...this.clientConfig, ...options }; if (this.azureOpenAIApiKey) { requestOptions.headers = { "api-key": this.azureOpenAIApiKey, ...requestOptions.headers }; requestOptions.query = { "api-version": this.azureOpenAIApiVersion, ...requestOptions.query }; } return requestOptions; } _llmType() { return "openai"; } }; } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/azure/llms.js var init_llms4 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/azure/llms.js"() { init_llms3(); } }); // node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/embeddings.js var init_embeddings3 = __esm({ "node_modules/.pnpm/@langchain+core@0.1.48/node_modules/@langchain/core/embeddings.js"() { init_embeddings(); } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/embeddings.js var OpenAIEmbeddings; var init_embeddings4 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/embeddings.js"() { init_openai(); init_env2(); init_embeddings3(); init_chunk_array2(); init_azure(); init_openai2(); OpenAIEmbeddings = class extends Embeddings { constructor(fields2, configuration) { const fieldsWithDefaults = { maxConcurrency: 2, ...fields2 }; super(fieldsWithDefaults); Object.defineProperty(this, "modelName", { enumerable: true, configurable: true, writable: true, value: "text-embedding-ada-002" }); Object.defineProperty(this, "batchSize", { enumerable: true, configurable: true, writable: true, value: 512 }); Object.defineProperty(this, "stripNewLines", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "dimensions", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "timeout", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiVersion", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiInstanceName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiDeploymentName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIBasePath", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "organization", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "clientConfig", { enumerable: true, configurable: true, writable: true, value: void 0 }); let apiKey = fieldsWithDefaults?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); const azureApiKey = fieldsWithDefaults?.azureOpenAIApiKey ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); if (!azureApiKey && !apiKey) { throw new Error("OpenAI or Azure OpenAI API key not found"); } const azureApiInstanceName = fieldsWithDefaults?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); const azureApiDeploymentName = (fieldsWithDefaults?.azureOpenAIApiEmbeddingsDeploymentName || fieldsWithDefaults?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); const azureApiVersion = fieldsWithDefaults?.azureOpenAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); this.azureOpenAIBasePath = fieldsWithDefaults?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); this.organization = fieldsWithDefaults?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); this.modelName = fieldsWithDefaults?.modelName ?? this.modelName; this.batchSize = fieldsWithDefaults?.batchSize ?? (azureApiKey ? 1 : this.batchSize); this.stripNewLines = fieldsWithDefaults?.stripNewLines ?? this.stripNewLines; this.timeout = fieldsWithDefaults?.timeout; this.dimensions = fieldsWithDefaults?.dimensions; this.azureOpenAIApiVersion = azureApiVersion; this.azureOpenAIApiKey = azureApiKey; this.azureOpenAIApiInstanceName = azureApiInstanceName; this.azureOpenAIApiDeploymentName = azureApiDeploymentName; if (this.azureOpenAIApiKey) { if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { throw new Error("Azure OpenAI API instance name not found"); } if (!this.azureOpenAIApiDeploymentName) { throw new Error("Azure OpenAI API deployment name not found"); } if (!this.azureOpenAIApiVersion) { throw new Error("Azure OpenAI API version not found"); } apiKey = apiKey ?? ""; } this.clientConfig = { apiKey, organization: this.organization, baseURL: configuration?.basePath, dangerouslyAllowBrowser: true, defaultHeaders: configuration?.baseOptions?.headers, defaultQuery: configuration?.baseOptions?.params, ...configuration, ...fields2?.configuration }; } async embedDocuments(texts) { const batches = chunkArray(this.stripNewLines ? texts.map((t2) => t2.replace(/\n/g, " ")) : texts, this.batchSize); const batchRequests = batches.map((batch) => { const params = { model: this.modelName, input: batch }; if (this.dimensions) { params.dimensions = this.dimensions; } return this.embeddingWithRetry(params); }); const batchResponses = await Promise.all(batchRequests); const embeddings = []; for (let i2 = 0; i2 < batchResponses.length; i2 += 1) { const batch = batches[i2]; const { data: batchResponse } = batchResponses[i2]; for (let j2 = 0; j2 < batch.length; j2 += 1) { embeddings.push(batchResponse[j2].embedding); } } return embeddings; } async embedQuery(text) { const params = { model: this.modelName, input: this.stripNewLines ? text.replace(/\n/g, " ") : text }; if (this.dimensions) { params.dimensions = this.dimensions; } const { data } = await this.embeddingWithRetry(params); return data[0].embedding; } async embeddingWithRetry(request7) { if (!this.client) { const openAIEndpointConfig = { azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, azureOpenAIApiKey: this.azureOpenAIApiKey, azureOpenAIBasePath: this.azureOpenAIBasePath, baseURL: this.clientConfig.baseURL }; const endpoint = getEndpoint(openAIEndpointConfig); const params = { ...this.clientConfig, baseURL: endpoint, timeout: this.timeout, maxRetries: 0 }; if (!params.baseURL) { delete params.baseURL; } this.client = new OpenAI(params); } const requestOptions = {}; if (this.azureOpenAIApiKey) { requestOptions.headers = { "api-key": this.azureOpenAIApiKey, ...requestOptions.headers }; requestOptions.query = { "api-version": this.azureOpenAIApiVersion, ...requestOptions.query }; } return this.caller.call(async () => { try { const res = await this.client.embeddings.create(request7, requestOptions); return res; } catch (e2) { const error = wrapOpenAIClientError(e2); throw error; } }); } }; } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/types.js var init_types3 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/types.js"() { } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/tools/dalle.js var DallEAPIWrapper; var init_dalle = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/tools/dalle.js"() { init_env2(); init_openai(); init_tools2(); DallEAPIWrapper = class extends Tool { static lc_name() { return "DallEAPIWrapper"; } constructor(fields2) { super(fields2); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "dalle_api_wrapper" }); Object.defineProperty(this, "description", { enumerable: true, configurable: true, writable: true, value: "A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description." }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "modelName", { enumerable: true, configurable: true, writable: true, value: "dall-e-3" }); Object.defineProperty(this, "style", { enumerable: true, configurable: true, writable: true, value: "vivid" }); Object.defineProperty(this, "quality", { enumerable: true, configurable: true, writable: true, value: "standard" }); Object.defineProperty(this, "n", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "size", { enumerable: true, configurable: true, writable: true, value: "1024x1024" }); Object.defineProperty(this, "responseFormat", { enumerable: true, configurable: true, writable: true, value: "url" }); Object.defineProperty(this, "user", { enumerable: true, configurable: true, writable: true, value: void 0 }); const openAIApiKey = fields2?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); const organization = fields2?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); const clientConfig = { apiKey: openAIApiKey, organization, dangerouslyAllowBrowser: true }; this.client = new OpenAI(clientConfig); this.modelName = fields2?.modelName ?? this.modelName; this.style = fields2?.style ?? this.style; this.quality = fields2?.quality ?? this.quality; this.n = fields2?.n ?? this.n; this.size = fields2?.size ?? this.size; this.responseFormat = fields2?.responseFormat ?? this.responseFormat; this.user = fields2?.user; } async _call(input) { const response = await this.client.images.generate({ model: this.modelName, prompt: input, n: this.n, size: this.size, response_format: this.responseFormat, style: this.style, quality: this.quality, user: this.user }); let data = ""; if (this.responseFormat === "url") { [data] = response.data.map((item) => item.url).filter((url) => url !== "undefined"); } else { [data] = response.data.map((item) => item.b64_json).filter((b64_json) => b64_json !== "undefined"); } return data; } }; Object.defineProperty(DallEAPIWrapper, "toolName", { enumerable: true, configurable: true, writable: true, value: "dalle_api_wrapper" }); } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/tools/index.js var init_tools3 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/tools/index.js"() { init_dalle(); } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/index.js var init_dist2 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/dist/index.js"() { init_openai(); init_chat_models3(); init_chat_models4(); init_llms3(); init_llms4(); init_embeddings4(); init_types3(); init_openai2(); init_azure(); init_tools3(); } }); // node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/index.js var init_openai3 = __esm({ "node_modules/.pnpm/@langchain+openai@0.0.21/node_modules/@langchain/openai/index.js"() { init_dist2(); } }); // src/lib/async-handlebars-helper/utils.js var require_utils2 = __commonJS({ "src/lib/async-handlebars-helper/utils.js"(exports2, module2) { function blockParams(params, ids) { params.path = ids; return params; } function extend4(obj) { for (let i2 = 1; i2 < arguments.length; i2++) { for (const key in arguments[i2]) { if (Object.prototype.hasOwnProperty.call(arguments[i2], key)) { obj[key] = arguments[i2][key]; } } } return obj; } function appendContextPath(contextPath, id2) { return (contextPath ? `${contextPath}.` : "") + id2; } function createFrame2(object) { const frame = extend4({}, object); frame._parent = object; return frame; } function isEmpty6(value) { if (!value && value !== 0) { return true; } if (Array.isArray(value) && value.length === 0) { return true; } return false; } function isPromise(value) { return typeof value === "object" && value !== null && typeof value.then === "function"; } module2.exports = { blockParams, extend: extend4, appendContextPath, createFrame: createFrame2, isEmpty: isEmpty6, isPromise }; } }); // src/lib/async-handlebars-helper/helpers/each.js var require_each2 = __commonJS({ "src/lib/async-handlebars-helper/helpers/each.js"(exports2, module2) { var { appendContextPath, createFrame: createFrame2, blockParams, isPromise } = require_utils2(); module2.exports = (handlebars3) => { handlebars3.registerHelper("each", async function(context, options) { if (!options) { throw new Error("Must pass iterator to #each"); } let { fn } = options, { inverse } = options, i2 = 0, ret = [], data, contextPath; if (options.data && options.ids) { contextPath = `${appendContextPath(options.data.contextPath, options.ids[0])}.`; } if (typeof context === "function") { context = context.call(this); } if (options.data) { data = createFrame2(options.data); } async function execIteration(field, index2, last) { if (data) { data.key = field; data.index = index2; data.first = index2 === 0; data.last = !!last; if (contextPath) { data.contextPath = contextPath + field; } } ret.push(fn(context[field], { data, blockParams: blockParams([context[field], field], [contextPath + field, null]) })); } if (context && typeof context === "object") { if (isPromise(context)) { context = await context; } if (Array.isArray(context)) { for (let j2 = context.length; i2 < j2; i2++) { if (i2 in context) { execIteration(i2, i2, i2 === context.length - 1); } } } else if (global.Symbol && context[global.Symbol.iterator]) { const newContext = [], iterator = context[global.Symbol.iterator](); for (let it = iterator.next(); !it.done; it = iterator.next()) { newContext.push(it.value); } context = newContext; for (let j2 = context.length; i2 < j2; i2++) { execIteration(i2, i2, i2 === context.length - 1); } } else { let priorKey; for (const key of Object.keys(context)) { if (priorKey !== void 0) { execIteration(priorKey, i2 - 1); } priorKey = key; i2++; } if (priorKey !== void 0) { execIteration(priorKey, i2 - 1, true); } } } if (i2 === 0) { ret = inverse(this); } return (await Promise.all(ret)).join(""); }); }; } }); // src/lib/async-handlebars-helper/helpers/if.js var require_if2 = __commonJS({ "src/lib/async-handlebars-helper/helpers/if.js"(exports2, module2) { var { isPromise, isEmpty: isEmpty6 } = require_utils2(); module2.exports = (handlebars3) => { handlebars3.registerHelper("if", async function(conditional, options) { if (arguments.length !== 2) { throw new Error("#if requires exactly one argument"); } if (typeof conditional === "function") { conditional = conditional.call(this); } else if (isPromise(conditional)) { conditional = await conditional; } if (!options.hash.includeZero && !conditional || isEmpty6(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); handlebars3.registerHelper("unless", function(conditional, options) { if (arguments.length !== 2) { throw new Error("#unless requires exactly one argument"); } return handlebars3.helpers["if"].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash }); }); }; } }); // src/lib/async-handlebars-helper/helpers/with.js var require_with2 = __commonJS({ "src/lib/async-handlebars-helper/helpers/with.js"(exports2, module2) { var { isPromise, isEmpty: isEmpty6, createFrame: createFrame2, appendContextPath, blockParams } = require_utils2(); module2.exports = (handlebars3) => { handlebars3.registerHelper("with", async function(context, options) { if (arguments.length !== 2) { throw new Error("#with requires exactly one argument"); } if (typeof context === "function") { context = context.call(this); } else if (isPromise(context)) { context = await context; } const { fn } = options; if (!isEmpty6(context)) { let { data } = options; if (options.data && options.ids) { data = createFrame2(options.data); data.contextPath = appendContextPath(options.data.contextPath, options.ids[0]); } return fn(context, { data, blockParams: blockParams([context], [data && data.contextPath]) }); } return options.inverse(this); }); }; } }); // src/lib/async-handlebars-helper/helpers/index.js var require_helpers3 = __commonJS({ "src/lib/async-handlebars-helper/helpers/index.js"(exports2, module2) { module2.exports = { registerCoreHelpers: (handlebars3) => { require_each2()(handlebars3); require_if2()(handlebars3); require_with2()(handlebars3); } }; } }); // node_modules/.pnpm/json5@2.2.3/node_modules/json5/dist/index.js var require_dist2 = __commonJS({ "node_modules/.pnpm/json5@2.2.3/node_modules/json5/dist/index.js"(exports2, module2) { (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.JSON5 = factory(); })(exports2, function() { "use strict"; function createCommonjsModule(fn, module3) { return module3 = { exports: {} }, fn(module3, module3.exports), module3.exports; } var _global = createCommonjsModule(function(module3) { var global2 = module3.exports = typeof window != "undefined" && window.Math == Math ? window : typeof self != "undefined" && self.Math == Math ? self : Function("return this")(); if (typeof __g == "number") { __g = global2; } }); var _core = createCommonjsModule(function(module3) { var core2 = module3.exports = { version: "2.6.5" }; if (typeof __e == "number") { __e = core2; } }); var _core_1 = _core.version; var _isObject = function(it) { return typeof it === "object" ? it !== null : typeof it === "function"; }; var _anObject = function(it) { if (!_isObject(it)) { throw TypeError(it + " is not an object!"); } return it; }; var _fails = function(exec) { try { return !!exec(); } catch (e2) { return true; } }; var _descriptors = !_fails(function() { return Object.defineProperty({}, "a", { get: function() { return 7; } }).a != 7; }); var document2 = _global.document; var is2 = _isObject(document2) && _isObject(document2.createElement); var _domCreate = function(it) { return is2 ? document2.createElement(it) : {}; }; var _ie8DomDefine = !_descriptors && !_fails(function() { return Object.defineProperty(_domCreate("div"), "a", { get: function() { return 7; } }).a != 7; }); var _toPrimitive = function(it, S2) { if (!_isObject(it)) { return it; } var fn, val; if (S2 && typeof (fn = it.toString) == "function" && !_isObject(val = fn.call(it))) { return val; } if (typeof (fn = it.valueOf) == "function" && !_isObject(val = fn.call(it))) { return val; } if (!S2 && typeof (fn = it.toString) == "function" && !_isObject(val = fn.call(it))) { return val; } throw TypeError("Can't convert object to primitive value"); }; var dP = Object.defineProperty; var f4 = _descriptors ? Object.defineProperty : function defineProperty(O2, P2, Attributes) { _anObject(O2); P2 = _toPrimitive(P2, true); _anObject(Attributes); if (_ie8DomDefine) { try { return dP(O2, P2, Attributes); } catch (e2) { } } if ("get" in Attributes || "set" in Attributes) { throw TypeError("Accessors not supported!"); } if ("value" in Attributes) { O2[P2] = Attributes.value; } return O2; }; var _objectDp = { f: f4 }; var _propertyDesc = function(bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value }; }; var _hide = _descriptors ? function(object, key2, value) { return _objectDp.f(object, key2, _propertyDesc(1, value)); } : function(object, key2, value) { object[key2] = value; return object; }; var hasOwnProperty2 = {}.hasOwnProperty; var _has = function(it, key2) { return hasOwnProperty2.call(it, key2); }; var id2 = 0; var px = Math.random(); var _uid = function(key2) { return "Symbol(".concat(key2 === void 0 ? "" : key2, ")_", (++id2 + px).toString(36)); }; var _library = false; var _shared = createCommonjsModule(function(module3) { var SHARED = "__core-js_shared__"; var store = _global[SHARED] || (_global[SHARED] = {}); (module3.exports = function(key2, value) { return store[key2] || (store[key2] = value !== void 0 ? value : {}); })("versions", []).push({ version: _core.version, mode: _library ? "pure" : "global", copyright: "\xA9 2019 Denis Pushkarev (zloirock.ru)" }); }); var _functionToString = _shared("native-function-to-string", Function.toString); var _redefine = createCommonjsModule(function(module3) { var SRC = _uid("src"); var TO_STRING = "toString"; var TPL = ("" + _functionToString).split(TO_STRING); _core.inspectSource = function(it) { return _functionToString.call(it); }; (module3.exports = function(O2, key2, val, safe) { var isFunction = typeof val == "function"; if (isFunction) { _has(val, "name") || _hide(val, "name", key2); } if (O2[key2] === val) { return; } if (isFunction) { _has(val, SRC) || _hide(val, SRC, O2[key2] ? "" + O2[key2] : TPL.join(String(key2))); } if (O2 === _global) { O2[key2] = val; } else if (!safe) { delete O2[key2]; _hide(O2, key2, val); } else if (O2[key2]) { O2[key2] = val; } else { _hide(O2, key2, val); } })(Function.prototype, TO_STRING, function toString3() { return typeof this == "function" && this[SRC] || _functionToString.call(this); }); }); var _aFunction = function(it) { if (typeof it != "function") { throw TypeError(it + " is not a function!"); } return it; }; var _ctx = function(fn, that, length) { _aFunction(fn); if (that === void 0) { return fn; } switch (length) { case 1: return function(a2) { return fn.call(that, a2); }; case 2: return function(a2, b2) { return fn.call(that, a2, b2); }; case 3: return function(a2, b2, c3) { return fn.call(that, a2, b2, c3); }; } return function() { return fn.apply(that, arguments); }; }; var PROTOTYPE = "prototype"; var $export = function(type2, name2, source2) { var IS_FORCED = type2 & $export.F; var IS_GLOBAL = type2 & $export.G; var IS_STATIC = type2 & $export.S; var IS_PROTO = type2 & $export.P; var IS_BIND = type2 & $export.B; var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name2] || (_global[name2] = {}) : (_global[name2] || {})[PROTOTYPE]; var exports3 = IS_GLOBAL ? _core : _core[name2] || (_core[name2] = {}); var expProto = exports3[PROTOTYPE] || (exports3[PROTOTYPE] = {}); var key2, own, out, exp; if (IS_GLOBAL) { source2 = name2; } for (key2 in source2) { own = !IS_FORCED && target && target[key2] !== void 0; out = (own ? target : source2)[key2]; exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == "function" ? _ctx(Function.call, out) : out; if (target) { _redefine(target, key2, out, type2 & $export.U); } if (exports3[key2] != out) { _hide(exports3, key2, exp); } if (IS_PROTO && expProto[key2] != out) { expProto[key2] = out; } } }; _global.core = _core; $export.F = 1; $export.G = 2; $export.S = 4; $export.P = 8; $export.B = 16; $export.W = 32; $export.U = 64; $export.R = 128; var _export = $export; var ceil = Math.ceil; var floor = Math.floor; var _toInteger = function(it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; var _defined = function(it) { if (it == void 0) { throw TypeError("Can't call method on " + it); } return it; }; var _stringAt = function(TO_STRING) { return function(that, pos2) { var s2 = String(_defined(that)); var i2 = _toInteger(pos2); var l2 = s2.length; var a2, b2; if (i2 < 0 || i2 >= l2) { return TO_STRING ? "" : void 0; } a2 = s2.charCodeAt(i2); return a2 < 55296 || a2 > 56319 || i2 + 1 === l2 || (b2 = s2.charCodeAt(i2 + 1)) < 56320 || b2 > 57343 ? TO_STRING ? s2.charAt(i2) : a2 : TO_STRING ? s2.slice(i2, i2 + 2) : (a2 - 55296 << 10) + (b2 - 56320) + 65536; }; }; var $at = _stringAt(false); _export(_export.P, "String", { codePointAt: function codePointAt3(pos2) { return $at(this, pos2); } }); var codePointAt2 = _core.String.codePointAt; var max = Math.max; var min = Math.min; var _toAbsoluteIndex = function(index2, length) { index2 = _toInteger(index2); return index2 < 0 ? max(index2 + length, 0) : min(index2, length); }; var fromCharCode = String.fromCharCode; var $fromCodePoint = String.fromCodePoint; _export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), "String", { fromCodePoint: function fromCodePoint2(x2) { var arguments$1 = arguments; var res = []; var aLen = arguments.length; var i2 = 0; var code; while (aLen > i2) { code = +arguments$1[i2++]; if (_toAbsoluteIndex(code, 1114111) !== code) { throw RangeError(code + " is not a valid code point"); } res.push(code < 65536 ? fromCharCode(code) : fromCharCode(((code -= 65536) >> 10) + 55296, code % 1024 + 56320)); } return res.join(""); } }); var fromCodePoint = _core.String.fromCodePoint; var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; var unicode = { Space_Separator, ID_Start, ID_Continue }; var util3 = { isSpaceSeparator: function isSpaceSeparator(c3) { return typeof c3 === "string" && unicode.Space_Separator.test(c3); }, isIdStartChar: function isIdStartChar(c3) { return typeof c3 === "string" && (c3 >= "a" && c3 <= "z" || c3 >= "A" && c3 <= "Z" || c3 === "$" || c3 === "_" || unicode.ID_Start.test(c3)); }, isIdContinueChar: function isIdContinueChar(c3) { return typeof c3 === "string" && (c3 >= "a" && c3 <= "z" || c3 >= "A" && c3 <= "Z" || c3 >= "0" && c3 <= "9" || c3 === "$" || c3 === "_" || c3 === "\u200C" || c3 === "\u200D" || unicode.ID_Continue.test(c3)); }, isDigit: function isDigit(c3) { return typeof c3 === "string" && /[0-9]/.test(c3); }, isHexDigit: function isHexDigit(c3) { return typeof c3 === "string" && /[0-9A-Fa-f]/.test(c3); } }; var source; var parseState; var stack; var pos; var line; var column; var token; var key; var root3; var parse3 = function parse4(text, reviver2) { source = String(text); parseState = "start"; stack = []; pos = 0; line = 1; column = 0; token = void 0; key = void 0; root3 = void 0; do { token = lex(); parseStates[parseState](); } while (token.type !== "eof"); if (typeof reviver2 === "function") { return internalize({ "": root3 }, "", reviver2); } return root3; }; function internalize(holder, name2, reviver2) { var value = holder[name2]; if (value != null && typeof value === "object") { if (Array.isArray(value)) { for (var i2 = 0; i2 < value.length; i2++) { var key2 = String(i2); var replacement = internalize(value, key2, reviver2); if (replacement === void 0) { delete value[key2]; } else { Object.defineProperty(value, key2, { value: replacement, writable: true, enumerable: true, configurable: true }); } } } else { for (var key$1 in value) { var replacement$1 = internalize(value, key$1, reviver2); if (replacement$1 === void 0) { delete value[key$1]; } else { Object.defineProperty(value, key$1, { value: replacement$1, writable: true, enumerable: true, configurable: true }); } } } } return reviver2.call(holder, name2, value); } var lexState; var buffer; var doubleQuote; var sign; var c2; function lex() { lexState = "default"; buffer = ""; doubleQuote = false; sign = 1; for (; ; ) { c2 = peek(); var token2 = lexStates[lexState](); if (token2) { return token2; } } } function peek() { if (source[pos]) { return String.fromCodePoint(source.codePointAt(pos)); } } function read2() { var c3 = peek(); if (c3 === "\n") { line++; column = 0; } else if (c3) { column += c3.length; } else { column++; } if (c3) { pos += c3.length; } return c3; } var lexStates = { default: function default$1() { switch (c2) { case " ": case "\v": case "\f": case " ": case "\xA0": case "\uFEFF": case "\n": case "\r": case "\u2028": case "\u2029": read2(); return; case "/": read2(); lexState = "comment"; return; case void 0: read2(); return newToken("eof"); } if (util3.isSpaceSeparator(c2)) { read2(); return; } return lexStates[parseState](); }, comment: function comment() { switch (c2) { case "*": read2(); lexState = "multiLineComment"; return; case "/": read2(); lexState = "singleLineComment"; return; } throw invalidChar(read2()); }, multiLineComment: function multiLineComment() { switch (c2) { case "*": read2(); lexState = "multiLineCommentAsterisk"; return; case void 0: throw invalidChar(read2()); } read2(); }, multiLineCommentAsterisk: function multiLineCommentAsterisk() { switch (c2) { case "*": read2(); return; case "/": read2(); lexState = "default"; return; case void 0: throw invalidChar(read2()); } read2(); lexState = "multiLineComment"; }, singleLineComment: function singleLineComment() { switch (c2) { case "\n": case "\r": case "\u2028": case "\u2029": read2(); lexState = "default"; return; case void 0: read2(); return newToken("eof"); } read2(); }, value: function value() { switch (c2) { case "{": case "[": return newToken("punctuator", read2()); case "n": read2(); literal("ull"); return newToken("null", null); case "t": read2(); literal("rue"); return newToken("boolean", true); case "f": read2(); literal("alse"); return newToken("boolean", false); case "-": case "+": if (read2() === "-") { sign = -1; } lexState = "sign"; return; case ".": buffer = read2(); lexState = "decimalPointLeading"; return; case "0": buffer = read2(); lexState = "zero"; return; case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": buffer = read2(); lexState = "decimalInteger"; return; case "I": read2(); literal("nfinity"); return newToken("numeric", Infinity); case "N": read2(); literal("aN"); return newToken("numeric", NaN); case '"': case "'": doubleQuote = read2() === '"'; buffer = ""; lexState = "string"; return; } throw invalidChar(read2()); }, identifierNameStartEscape: function identifierNameStartEscape() { if (c2 !== "u") { throw invalidChar(read2()); } read2(); var u2 = unicodeEscape(); switch (u2) { case "$": case "_": break; default: if (!util3.isIdStartChar(u2)) { throw invalidIdentifier(); } break; } buffer += u2; lexState = "identifierName"; }, identifierName: function identifierName() { switch (c2) { case "$": case "_": case "\u200C": case "\u200D": buffer += read2(); return; case "\\": read2(); lexState = "identifierNameEscape"; return; } if (util3.isIdContinueChar(c2)) { buffer += read2(); return; } return newToken("identifier", buffer); }, identifierNameEscape: function identifierNameEscape() { if (c2 !== "u") { throw invalidChar(read2()); } read2(); var u2 = unicodeEscape(); switch (u2) { case "$": case "_": case "\u200C": case "\u200D": break; default: if (!util3.isIdContinueChar(u2)) { throw invalidIdentifier(); } break; } buffer += u2; lexState = "identifierName"; }, sign: function sign$1() { switch (c2) { case ".": buffer = read2(); lexState = "decimalPointLeading"; return; case "0": buffer = read2(); lexState = "zero"; return; case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": buffer = read2(); lexState = "decimalInteger"; return; case "I": read2(); literal("nfinity"); return newToken("numeric", sign * Infinity); case "N": read2(); literal("aN"); return newToken("numeric", NaN); } throw invalidChar(read2()); }, zero: function zero() { switch (c2) { case ".": buffer += read2(); lexState = "decimalPoint"; return; case "e": case "E": buffer += read2(); lexState = "decimalExponent"; return; case "x": case "X": buffer += read2(); lexState = "hexadecimal"; return; } return newToken("numeric", sign * 0); }, decimalInteger: function decimalInteger() { switch (c2) { case ".": buffer += read2(); lexState = "decimalPoint"; return; case "e": case "E": buffer += read2(); lexState = "decimalExponent"; return; } if (util3.isDigit(c2)) { buffer += read2(); return; } return newToken("numeric", sign * Number(buffer)); }, decimalPointLeading: function decimalPointLeading() { if (util3.isDigit(c2)) { buffer += read2(); lexState = "decimalFraction"; return; } throw invalidChar(read2()); }, decimalPoint: function decimalPoint() { switch (c2) { case "e": case "E": buffer += read2(); lexState = "decimalExponent"; return; } if (util3.isDigit(c2)) { buffer += read2(); lexState = "decimalFraction"; return; } return newToken("numeric", sign * Number(buffer)); }, decimalFraction: function decimalFraction() { switch (c2) { case "e": case "E": buffer += read2(); lexState = "decimalExponent"; return; } if (util3.isDigit(c2)) { buffer += read2(); return; } return newToken("numeric", sign * Number(buffer)); }, decimalExponent: function decimalExponent() { switch (c2) { case "+": case "-": buffer += read2(); lexState = "decimalExponentSign"; return; } if (util3.isDigit(c2)) { buffer += read2(); lexState = "decimalExponentInteger"; return; } throw invalidChar(read2()); }, decimalExponentSign: function decimalExponentSign() { if (util3.isDigit(c2)) { buffer += read2(); lexState = "decimalExponentInteger"; return; } throw invalidChar(read2()); }, decimalExponentInteger: function decimalExponentInteger() { if (util3.isDigit(c2)) { buffer += read2(); return; } return newToken("numeric", sign * Number(buffer)); }, hexadecimal: function hexadecimal() { if (util3.isHexDigit(c2)) { buffer += read2(); lexState = "hexadecimalInteger"; return; } throw invalidChar(read2()); }, hexadecimalInteger: function hexadecimalInteger() { if (util3.isHexDigit(c2)) { buffer += read2(); return; } return newToken("numeric", sign * Number(buffer)); }, string: function string() { switch (c2) { case "\\": read2(); buffer += escape(); return; case '"': if (doubleQuote) { read2(); return newToken("string", buffer); } buffer += read2(); return; case "'": if (!doubleQuote) { read2(); return newToken("string", buffer); } buffer += read2(); return; case "\n": case "\r": throw invalidChar(read2()); case "\u2028": case "\u2029": separatorChar(c2); break; case void 0: throw invalidChar(read2()); } buffer += read2(); }, start: function start() { switch (c2) { case "{": case "[": return newToken("punctuator", read2()); } lexState = "value"; }, beforePropertyName: function beforePropertyName() { switch (c2) { case "$": case "_": buffer = read2(); lexState = "identifierName"; return; case "\\": read2(); lexState = "identifierNameStartEscape"; return; case "}": return newToken("punctuator", read2()); case '"': case "'": doubleQuote = read2() === '"'; lexState = "string"; return; } if (util3.isIdStartChar(c2)) { buffer += read2(); lexState = "identifierName"; return; } throw invalidChar(read2()); }, afterPropertyName: function afterPropertyName() { if (c2 === ":") { return newToken("punctuator", read2()); } throw invalidChar(read2()); }, beforePropertyValue: function beforePropertyValue() { lexState = "value"; }, afterPropertyValue: function afterPropertyValue() { switch (c2) { case ",": case "}": return newToken("punctuator", read2()); } throw invalidChar(read2()); }, beforeArrayValue: function beforeArrayValue() { if (c2 === "]") { return newToken("punctuator", read2()); } lexState = "value"; }, afterArrayValue: function afterArrayValue() { switch (c2) { case ",": case "]": return newToken("punctuator", read2()); } throw invalidChar(read2()); }, end: function end() { throw invalidChar(read2()); } }; function newToken(type2, value) { return { type: type2, value, line, column }; } function literal(s2) { for (var i2 = 0, list = s2; i2 < list.length; i2 += 1) { var c3 = list[i2]; var p2 = peek(); if (p2 !== c3) { throw invalidChar(read2()); } read2(); } } function escape() { var c3 = peek(); switch (c3) { case "b": read2(); return "\b"; case "f": read2(); return "\f"; case "n": read2(); return "\n"; case "r": read2(); return "\r"; case "t": read2(); return " "; case "v": read2(); return "\v"; case "0": read2(); if (util3.isDigit(peek())) { throw invalidChar(read2()); } return "\0"; case "x": read2(); return hexEscape(); case "u": read2(); return unicodeEscape(); case "\n": case "\u2028": case "\u2029": read2(); return ""; case "\r": read2(); if (peek() === "\n") { read2(); } return ""; case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": throw invalidChar(read2()); case void 0: throw invalidChar(read2()); } return read2(); } function hexEscape() { var buffer2 = ""; var c3 = peek(); if (!util3.isHexDigit(c3)) { throw invalidChar(read2()); } buffer2 += read2(); c3 = peek(); if (!util3.isHexDigit(c3)) { throw invalidChar(read2()); } buffer2 += read2(); return String.fromCodePoint(parseInt(buffer2, 16)); } function unicodeEscape() { var buffer2 = ""; var count = 4; while (count-- > 0) { var c3 = peek(); if (!util3.isHexDigit(c3)) { throw invalidChar(read2()); } buffer2 += read2(); } return String.fromCodePoint(parseInt(buffer2, 16)); } var parseStates = { start: function start() { if (token.type === "eof") { throw invalidEOF(); } push(); }, beforePropertyName: function beforePropertyName() { switch (token.type) { case "identifier": case "string": key = token.value; parseState = "afterPropertyName"; return; case "punctuator": pop(); return; case "eof": throw invalidEOF(); } }, afterPropertyName: function afterPropertyName() { if (token.type === "eof") { throw invalidEOF(); } parseState = "beforePropertyValue"; }, beforePropertyValue: function beforePropertyValue() { if (token.type === "eof") { throw invalidEOF(); } push(); }, beforeArrayValue: function beforeArrayValue() { if (token.type === "eof") { throw invalidEOF(); } if (token.type === "punctuator" && token.value === "]") { pop(); return; } push(); }, afterPropertyValue: function afterPropertyValue() { if (token.type === "eof") { throw invalidEOF(); } switch (token.value) { case ",": parseState = "beforePropertyName"; return; case "}": pop(); } }, afterArrayValue: function afterArrayValue() { if (token.type === "eof") { throw invalidEOF(); } switch (token.value) { case ",": parseState = "beforeArrayValue"; return; case "]": pop(); } }, end: function end() { } }; function push() { var value; switch (token.type) { case "punctuator": switch (token.value) { case "{": value = {}; break; case "[": value = []; break; } break; case "null": case "boolean": case "numeric": case "string": value = token.value; break; } if (root3 === void 0) { root3 = value; } else { var parent = stack[stack.length - 1]; if (Array.isArray(parent)) { parent.push(value); } else { Object.defineProperty(parent, key, { value, writable: true, enumerable: true, configurable: true }); } } if (value !== null && typeof value === "object") { stack.push(value); if (Array.isArray(value)) { parseState = "beforeArrayValue"; } else { parseState = "beforePropertyName"; } } else { var current = stack[stack.length - 1]; if (current == null) { parseState = "end"; } else if (Array.isArray(current)) { parseState = "afterArrayValue"; } else { parseState = "afterPropertyValue"; } } } function pop() { stack.pop(); var current = stack[stack.length - 1]; if (current == null) { parseState = "end"; } else if (Array.isArray(current)) { parseState = "afterArrayValue"; } else { parseState = "afterPropertyValue"; } } function invalidChar(c3) { if (c3 === void 0) { return syntaxError("JSON5: invalid end of input at " + line + ":" + column); } return syntaxError("JSON5: invalid character '" + formatChar(c3) + "' at " + line + ":" + column); } function invalidEOF() { return syntaxError("JSON5: invalid end of input at " + line + ":" + column); } function invalidIdentifier() { column -= 5; return syntaxError("JSON5: invalid identifier character at " + line + ":" + column); } function separatorChar(c3) { console.warn("JSON5: '" + formatChar(c3) + "' in strings is not valid ECMAScript; consider escaping"); } function formatChar(c3) { var replacements = { "'": "\\'", '"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", " ": "\\t", "\v": "\\v", "\0": "\\0", "\u2028": "\\u2028", "\u2029": "\\u2029" }; if (replacements[c3]) { return replacements[c3]; } if (c3 < " ") { var hexString = c3.charCodeAt(0).toString(16); return "\\x" + ("00" + hexString).substring(hexString.length); } return c3; } function syntaxError(message) { var err = new SyntaxError(message); err.lineNumber = line; err.columnNumber = column; return err; } var stringify2 = function stringify3(value, replacer, space) { var stack2 = []; var indent = ""; var propertyList; var replacerFunc; var gap = ""; var quote; if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) { space = replacer.space; quote = replacer.quote; replacer = replacer.replacer; } if (typeof replacer === "function") { replacerFunc = replacer; } else if (Array.isArray(replacer)) { propertyList = []; for (var i2 = 0, list = replacer; i2 < list.length; i2 += 1) { var v2 = list[i2]; var item = void 0; if (typeof v2 === "string") { item = v2; } else if (typeof v2 === "number" || v2 instanceof String || v2 instanceof Number) { item = String(v2); } if (item !== void 0 && propertyList.indexOf(item) < 0) { propertyList.push(item); } } } if (space instanceof Number) { space = Number(space); } else if (space instanceof String) { space = String(space); } if (typeof space === "number") { if (space > 0) { space = Math.min(10, Math.floor(space)); gap = " ".substr(0, space); } } else if (typeof space === "string") { gap = space.substr(0, 10); } return serializeProperty("", { "": value }); function serializeProperty(key2, holder) { var value2 = holder[key2]; if (value2 != null) { if (typeof value2.toJSON5 === "function") { value2 = value2.toJSON5(key2); } else if (typeof value2.toJSON === "function") { value2 = value2.toJSON(key2); } } if (replacerFunc) { value2 = replacerFunc.call(holder, key2, value2); } if (value2 instanceof Number) { value2 = Number(value2); } else if (value2 instanceof String) { value2 = String(value2); } else if (value2 instanceof Boolean) { value2 = value2.valueOf(); } switch (value2) { case null: return "null"; case true: return "true"; case false: return "false"; } if (typeof value2 === "string") { return quoteString(value2, false); } if (typeof value2 === "number") { return String(value2); } if (typeof value2 === "object") { return Array.isArray(value2) ? serializeArray(value2) : serializeObject(value2); } return void 0; } function quoteString(value2) { var quotes = { "'": 0.1, '"': 0.2 }; var replacements = { "'": "\\'", '"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", " ": "\\t", "\v": "\\v", "\0": "\\0", "\u2028": "\\u2028", "\u2029": "\\u2029" }; var product = ""; for (var i3 = 0; i3 < value2.length; i3++) { var c3 = value2[i3]; switch (c3) { case "'": case '"': quotes[c3]++; product += c3; continue; case "\0": if (util3.isDigit(value2[i3 + 1])) { product += "\\x00"; continue; } } if (replacements[c3]) { product += replacements[c3]; continue; } if (c3 < " ") { var hexString = c3.charCodeAt(0).toString(16); product += "\\x" + ("00" + hexString).substring(hexString.length); continue; } product += c3; } var quoteChar = quote || Object.keys(quotes).reduce(function(a2, b2) { return quotes[a2] < quotes[b2] ? a2 : b2; }); product = product.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]); return quoteChar + product + quoteChar; } function serializeObject(value2) { if (stack2.indexOf(value2) >= 0) { throw TypeError("Converting circular structure to JSON5"); } stack2.push(value2); var stepback = indent; indent = indent + gap; var keys = propertyList || Object.keys(value2); var partial = []; for (var i3 = 0, list2 = keys; i3 < list2.length; i3 += 1) { var key2 = list2[i3]; var propertyString = serializeProperty(key2, value2); if (propertyString !== void 0) { var member = serializeKey(key2) + ":"; if (gap !== "") { member += " "; } member += propertyString; partial.push(member); } } var final; if (partial.length === 0) { final = "{}"; } else { var properties; if (gap === "") { properties = partial.join(","); final = "{" + properties + "}"; } else { var separator = ",\n" + indent; properties = partial.join(separator); final = "{\n" + indent + properties + ",\n" + stepback + "}"; } } stack2.pop(); indent = stepback; return final; } function serializeKey(key2) { if (key2.length === 0) { return quoteString(key2, true); } var firstChar = String.fromCodePoint(key2.codePointAt(0)); if (!util3.isIdStartChar(firstChar)) { return quoteString(key2, true); } for (var i3 = firstChar.length; i3 < key2.length; i3++) { if (!util3.isIdContinueChar(String.fromCodePoint(key2.codePointAt(i3)))) { return quoteString(key2, true); } } return key2; } function serializeArray(value2) { if (stack2.indexOf(value2) >= 0) { throw TypeError("Converting circular structure to JSON5"); } stack2.push(value2); var stepback = indent; indent = indent + gap; var partial = []; for (var i3 = 0; i3 < value2.length; i3++) { var propertyString = serializeProperty(String(i3), value2); partial.push(propertyString !== void 0 ? propertyString : "null"); } var final; if (partial.length === 0) { final = "[]"; } else { if (gap === "") { var properties = partial.join(","); final = "[" + properties + "]"; } else { var separator = ",\n" + indent; var properties$1 = partial.join(separator); final = "[\n" + indent + properties$1 + ",\n" + stepback + "]"; } } stack2.pop(); indent = stepback; return final; } }; var JSON514 = { parse: parse3, stringify: stringify2 }; var lib = JSON514; var es5 = lib; return es5; }); } }); // node_modules/.pnpm/@mozilla+readability@0.4.4/node_modules/@mozilla/readability/Readability.js var require_Readability = __commonJS({ "node_modules/.pnpm/@mozilla+readability@0.4.4/node_modules/@mozilla/readability/Readability.js"(exports2, module2) { function Readability2(doc, options) { if (options && options.documentElement) { doc = options; options = arguments[2]; } else if (!doc || !doc.documentElement) { throw new Error("First argument to Readability constructor should be a document object."); } options = options || {}; this._doc = doc; this._docJSDOMParser = this._doc.firstChild.__JSDOMParser__; this._articleTitle = null; this._articleByline = null; this._articleDir = null; this._articleSiteName = null; this._attempts = []; this._debug = !!options.debug; this._maxElemsToParse = options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE; this._nbTopCandidates = options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES; this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD; this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve || []); this._keepClasses = !!options.keepClasses; this._serializer = options.serializer || function(el) { return el.innerHTML; }; this._disableJSONLD = !!options.disableJSONLD; this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos; this._flags = this.FLAG_STRIP_UNLIKELYS | this.FLAG_WEIGHT_CLASSES | this.FLAG_CLEAN_CONDITIONALLY; if (this._debug) { let logNode = function(node) { if (node.nodeType == node.TEXT_NODE) { return `${node.nodeName} ("${node.textContent}")`; } let attrPairs = Array.from(node.attributes || [], function(attr) { return `${attr.name}="${attr.value}"`; }).join(" "); return `<${node.localName} ${attrPairs}>`; }; this.log = function() { if (typeof console !== "undefined") { let args = Array.from(arguments, (arg) => { if (arg && arg.nodeType == this.ELEMENT_NODE) { return logNode(arg); } return arg; }); args.unshift("Reader: (Readability)"); console.log.apply(console, args); } else if (typeof dump !== "undefined") { var msg = Array.prototype.map.call(arguments, function(x2) { return x2 && x2.nodeName ? logNode(x2) : x2; }).join(" "); dump("Reader: (Readability) " + msg + "\n"); } }; } else { this.log = function() { }; } } Readability2.prototype = { FLAG_STRIP_UNLIKELYS: 1, FLAG_WEIGHT_CLASSES: 2, FLAG_CLEAN_CONDITIONALLY: 4, ELEMENT_NODE: 1, TEXT_NODE: 3, DEFAULT_MAX_ELEMS_TO_PARSE: 0, DEFAULT_N_TOP_CANDIDATES: 5, DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","), DEFAULT_CHAR_THRESHOLD: 500, REGEXPS: { unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i, positive: /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i, negative: /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i, extraneous: /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i, byline: /byline|author|dateline|writtenby|p-author/i, replaceFonts: /<(\/?)font[^>]*>/gi, normalize: /\s{2,}/g, videos: /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i, shareElements: /(\b|_)(share|sharedaddy)(\b|_)/i, nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i, prevLink: /(prev|earl|old|new|<|«)/i, tokenize: /\W+/g, whitespace: /^\s*$/, hasContent: /\S$/, hashUrl: /^#.+/, srcsetUrl: /(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g, b64DataUrl: /^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i, jsonLdArticleTypes: /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/ }, UNLIKELY_ROLES: ["menu", "menubar", "complementary", "navigation", "alert", "alertdialog", "dialog"], DIV_TO_P_ELEMS: new Set(["BLOCKQUOTE", "DL", "DIV", "IMG", "OL", "P", "PRE", "TABLE", "UL"]), ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P"], PRESENTATIONAL_ATTRIBUTES: ["align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "hspace", "rules", "style", "valign", "vspace"], DEPRECATED_SIZE_ATTRIBUTE_ELEMS: ["TABLE", "TH", "TD", "HR", "PRE"], PHRASING_ELEMS: [ "ABBR", "AUDIO", "B", "BDO", "BR", "BUTTON", "CITE", "CODE", "DATA", "DATALIST", "DFN", "EM", "EMBED", "I", "IMG", "INPUT", "KBD", "LABEL", "MARK", "MATH", "METER", "NOSCRIPT", "OBJECT", "OUTPUT", "PROGRESS", "Q", "RUBY", "SAMP", "SCRIPT", "SELECT", "SMALL", "SPAN", "STRONG", "SUB", "SUP", "TEXTAREA", "TIME", "VAR", "WBR" ], CLASSES_TO_PRESERVE: ["page"], HTML_ESCAPE_MAP: { "lt": "<", "gt": ">", "amp": "&", "quot": '"', "apos": "'" }, _postProcessContent: function(articleContent) { this._fixRelativeUris(articleContent); this._simplifyNestedElements(articleContent); if (!this._keepClasses) { this._cleanClasses(articleContent); } }, _removeNodes: function(nodeList, filterFn) { if (this._docJSDOMParser && nodeList._isLiveNodeList) { throw new Error("Do not pass live node lists to _removeNodes"); } for (var i2 = nodeList.length - 1; i2 >= 0; i2--) { var node = nodeList[i2]; var parentNode = node.parentNode; if (parentNode) { if (!filterFn || filterFn.call(this, node, i2, nodeList)) { parentNode.removeChild(node); } } } }, _replaceNodeTags: function(nodeList, newTagName) { if (this._docJSDOMParser && nodeList._isLiveNodeList) { throw new Error("Do not pass live node lists to _replaceNodeTags"); } for (const node of nodeList) { this._setNodeTag(node, newTagName); } }, _forEachNode: function(nodeList, fn) { Array.prototype.forEach.call(nodeList, fn, this); }, _findNode: function(nodeList, fn) { return Array.prototype.find.call(nodeList, fn, this); }, _someNode: function(nodeList, fn) { return Array.prototype.some.call(nodeList, fn, this); }, _everyNode: function(nodeList, fn) { return Array.prototype.every.call(nodeList, fn, this); }, _concatNodeLists: function() { var slice = Array.prototype.slice; var args = slice.call(arguments); var nodeLists = args.map(function(list) { return slice.call(list); }); return Array.prototype.concat.apply([], nodeLists); }, _getAllNodesWithTag: function(node, tagNames) { if (node.querySelectorAll) { return node.querySelectorAll(tagNames.join(",")); } return [].concat.apply([], tagNames.map(function(tag) { var collection = node.getElementsByTagName(tag); return Array.isArray(collection) ? collection : Array.from(collection); })); }, _cleanClasses: function(node) { var classesToPreserve = this._classesToPreserve; var className = (node.getAttribute("class") || "").split(/\s+/).filter(function(cls) { return classesToPreserve.indexOf(cls) != -1; }).join(" "); if (className) { node.setAttribute("class", className); } else { node.removeAttribute("class"); } for (node = node.firstElementChild; node; node = node.nextElementSibling) { this._cleanClasses(node); } }, _fixRelativeUris: function(articleContent) { var baseURI = this._doc.baseURI; var documentURI = this._doc.documentURI; function toAbsoluteURI(uri2) { if (baseURI == documentURI && uri2.charAt(0) == "#") { return uri2; } try { return new URL(uri2, baseURI).href; } catch (ex) { } return uri2; } var links = this._getAllNodesWithTag(articleContent, ["a"]); this._forEachNode(links, function(link) { var href = link.getAttribute("href"); if (href) { if (href.indexOf("javascript:") === 0) { if (link.childNodes.length === 1 && link.childNodes[0].nodeType === this.TEXT_NODE) { var text = this._doc.createTextNode(link.textContent); link.parentNode.replaceChild(text, link); } else { var container = this._doc.createElement("span"); while (link.firstChild) { container.appendChild(link.firstChild); } link.parentNode.replaceChild(container, link); } } else { link.setAttribute("href", toAbsoluteURI(href)); } } }); var medias = this._getAllNodesWithTag(articleContent, [ "img", "picture", "figure", "video", "audio", "source" ]); this._forEachNode(medias, function(media) { var src = media.getAttribute("src"); var poster = media.getAttribute("poster"); var srcset = media.getAttribute("srcset"); if (src) { media.setAttribute("src", toAbsoluteURI(src)); } if (poster) { media.setAttribute("poster", toAbsoluteURI(poster)); } if (srcset) { var newSrcset = srcset.replace(this.REGEXPS.srcsetUrl, function(_2, p1, p2, p3) { return toAbsoluteURI(p1) + (p2 || "") + p3; }); media.setAttribute("srcset", newSrcset); } }); }, _simplifyNestedElements: function(articleContent) { var node = articleContent; while (node) { if (node.parentNode && ["DIV", "SECTION"].includes(node.tagName) && !(node.id && node.id.startsWith("readability"))) { if (this._isElementWithoutContent(node)) { node = this._removeAndGetNext(node); continue; } else if (this._hasSingleTagInsideElement(node, "DIV") || this._hasSingleTagInsideElement(node, "SECTION")) { var child = node.children[0]; for (var i2 = 0; i2 < node.attributes.length; i2++) { child.setAttribute(node.attributes[i2].name, node.attributes[i2].value); } node.parentNode.replaceChild(child, node); node = child; continue; } } node = this._getNextNode(node); } }, _getArticleTitle: function() { var doc = this._doc; var curTitle = ""; var origTitle = ""; try { curTitle = origTitle = doc.title.trim(); if (typeof curTitle !== "string") curTitle = origTitle = this._getInnerText(doc.getElementsByTagName("title")[0]); } catch (e2) { } var titleHadHierarchicalSeparators = false; function wordCount(str3) { return str3.split(/\s+/).length; } if (/ [\|\-\\\/>»] /.test(curTitle)) { titleHadHierarchicalSeparators = / [\\\/>»] /.test(curTitle); curTitle = origTitle.replace(/(.*)[\|\-\\\/>»] .*/gi, "$1"); if (wordCount(curTitle) < 3) curTitle = origTitle.replace(/[^\|\-\\\/>»]*[\|\-\\\/>»](.*)/gi, "$1"); } else if (curTitle.indexOf(": ") !== -1) { var headings = this._concatNodeLists(doc.getElementsByTagName("h1"), doc.getElementsByTagName("h2")); var trimmedTitle = curTitle.trim(); var match = this._someNode(headings, function(heading) { return heading.textContent.trim() === trimmedTitle; }); if (!match) { curTitle = origTitle.substring(origTitle.lastIndexOf(":") + 1); if (wordCount(curTitle) < 3) { curTitle = origTitle.substring(origTitle.indexOf(":") + 1); } else if (wordCount(origTitle.substr(0, origTitle.indexOf(":"))) > 5) { curTitle = origTitle; } } } else if (curTitle.length > 150 || curTitle.length < 15) { var hOnes = doc.getElementsByTagName("h1"); if (hOnes.length === 1) curTitle = this._getInnerText(hOnes[0]); } curTitle = curTitle.trim().replace(this.REGEXPS.normalize, " "); var curTitleWordCount = wordCount(curTitle); if (curTitleWordCount <= 4 && (!titleHadHierarchicalSeparators || curTitleWordCount != wordCount(origTitle.replace(/[\|\-\\\/>»]+/g, "")) - 1)) { curTitle = origTitle; } return curTitle; }, _prepDocument: function() { var doc = this._doc; this._removeNodes(this._getAllNodesWithTag(doc, ["style"])); if (doc.body) { this._replaceBrs(doc.body); } this._replaceNodeTags(this._getAllNodesWithTag(doc, ["font"]), "SPAN"); }, _nextNode: function(node) { var next2 = node; while (next2 && next2.nodeType != this.ELEMENT_NODE && this.REGEXPS.whitespace.test(next2.textContent)) { next2 = next2.nextSibling; } return next2; }, _replaceBrs: function(elem) { this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function(br) { var next2 = br.nextSibling; var replaced = false; while ((next2 = this._nextNode(next2)) && next2.tagName == "BR") { replaced = true; var brSibling = next2.nextSibling; next2.parentNode.removeChild(next2); next2 = brSibling; } if (replaced) { var p2 = this._doc.createElement("p"); br.parentNode.replaceChild(p2, br); next2 = p2.nextSibling; while (next2) { if (next2.tagName == "BR") { var nextElem = this._nextNode(next2.nextSibling); if (nextElem && nextElem.tagName == "BR") break; } if (!this._isPhrasingContent(next2)) break; var sibling = next2.nextSibling; p2.appendChild(next2); next2 = sibling; } while (p2.lastChild && this._isWhitespace(p2.lastChild)) { p2.removeChild(p2.lastChild); } if (p2.parentNode.tagName === "P") this._setNodeTag(p2.parentNode, "DIV"); } }); }, _setNodeTag: function(node, tag) { this.log("_setNodeTag", node, tag); if (this._docJSDOMParser) { node.localName = tag.toLowerCase(); node.tagName = tag.toUpperCase(); return node; } var replacement = node.ownerDocument.createElement(tag); while (node.firstChild) { replacement.appendChild(node.firstChild); } node.parentNode.replaceChild(replacement, node); if (node.readability) replacement.readability = node.readability; for (var i2 = 0; i2 < node.attributes.length; i2++) { try { replacement.setAttribute(node.attributes[i2].name, node.attributes[i2].value); } catch (ex) { } } return replacement; }, _prepArticle: function(articleContent) { this._cleanStyles(articleContent); this._markDataTables(articleContent); this._fixLazyImages(articleContent); this._cleanConditionally(articleContent, "form"); this._cleanConditionally(articleContent, "fieldset"); this._clean(articleContent, "object"); this._clean(articleContent, "embed"); this._clean(articleContent, "footer"); this._clean(articleContent, "link"); this._clean(articleContent, "aside"); var shareElementThreshold = this.DEFAULT_CHAR_THRESHOLD; this._forEachNode(articleContent.children, function(topCandidate) { this._cleanMatchedNodes(topCandidate, function(node, matchString) { return this.REGEXPS.shareElements.test(matchString) && node.textContent.length < shareElementThreshold; }); }); this._clean(articleContent, "iframe"); this._clean(articleContent, "input"); this._clean(articleContent, "textarea"); this._clean(articleContent, "select"); this._clean(articleContent, "button"); this._cleanHeaders(articleContent); this._cleanConditionally(articleContent, "table"); this._cleanConditionally(articleContent, "ul"); this._cleanConditionally(articleContent, "div"); this._replaceNodeTags(this._getAllNodesWithTag(articleContent, ["h1"]), "h2"); this._removeNodes(this._getAllNodesWithTag(articleContent, ["p"]), function(paragraph) { var imgCount = paragraph.getElementsByTagName("img").length; var embedCount = paragraph.getElementsByTagName("embed").length; var objectCount = paragraph.getElementsByTagName("object").length; var iframeCount = paragraph.getElementsByTagName("iframe").length; var totalCount = imgCount + embedCount + objectCount + iframeCount; return totalCount === 0 && !this._getInnerText(paragraph, false); }); this._forEachNode(this._getAllNodesWithTag(articleContent, ["br"]), function(br) { var next2 = this._nextNode(br.nextSibling); if (next2 && next2.tagName == "P") br.parentNode.removeChild(br); }); this._forEachNode(this._getAllNodesWithTag(articleContent, ["table"]), function(table) { var tbody = this._hasSingleTagInsideElement(table, "TBODY") ? table.firstElementChild : table; if (this._hasSingleTagInsideElement(tbody, "TR")) { var row = tbody.firstElementChild; if (this._hasSingleTagInsideElement(row, "TD")) { var cell = row.firstElementChild; cell = this._setNodeTag(cell, this._everyNode(cell.childNodes, this._isPhrasingContent) ? "P" : "DIV"); table.parentNode.replaceChild(cell, table); } } }); }, _initializeNode: function(node) { node.readability = { "contentScore": 0 }; switch (node.tagName) { case "DIV": node.readability.contentScore += 5; break; case "PRE": case "TD": case "BLOCKQUOTE": node.readability.contentScore += 3; break; case "ADDRESS": case "OL": case "UL": case "DL": case "DD": case "DT": case "LI": case "FORM": node.readability.contentScore -= 3; break; case "H1": case "H2": case "H3": case "H4": case "H5": case "H6": case "TH": node.readability.contentScore -= 5; break; } node.readability.contentScore += this._getClassWeight(node); }, _removeAndGetNext: function(node) { var nextNode = this._getNextNode(node, true); node.parentNode.removeChild(node); return nextNode; }, _getNextNode: function(node, ignoreSelfAndKids) { if (!ignoreSelfAndKids && node.firstElementChild) { return node.firstElementChild; } if (node.nextElementSibling) { return node.nextElementSibling; } do { node = node.parentNode; } while (node && !node.nextElementSibling); return node && node.nextElementSibling; }, _textSimilarity: function(textA, textB) { var tokensA = textA.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean); var tokensB = textB.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean); if (!tokensA.length || !tokensB.length) { return 0; } var uniqTokensB = tokensB.filter((token) => !tokensA.includes(token)); var distanceB = uniqTokensB.join(" ").length / tokensB.join(" ").length; return 1 - distanceB; }, _checkByline: function(node, matchString) { if (this._articleByline) { return false; } if (node.getAttribute !== void 0) { var rel = node.getAttribute("rel"); var itemprop = node.getAttribute("itemprop"); } if ((rel === "author" || itemprop && itemprop.indexOf("author") !== -1 || this.REGEXPS.byline.test(matchString)) && this._isValidByline(node.textContent)) { this._articleByline = node.textContent.trim(); return true; } return false; }, _getNodeAncestors: function(node, maxDepth) { maxDepth = maxDepth || 0; var i2 = 0, ancestors = []; while (node.parentNode) { ancestors.push(node.parentNode); if (maxDepth && ++i2 === maxDepth) break; node = node.parentNode; } return ancestors; }, _grabArticle: function(page) { this.log("**** grabArticle ****"); var doc = this._doc; var isPaging = page !== null; page = page ? page : this._doc.body; if (!page) { this.log("No body found in document. Abort."); return null; } var pageCacheHtml = page.innerHTML; while (true) { this.log("Starting grabArticle loop"); var stripUnlikelyCandidates = this._flagIsActive(this.FLAG_STRIP_UNLIKELYS); var elementsToScore = []; var node = this._doc.documentElement; let shouldRemoveTitleHeader = true; while (node) { if (node.tagName === "HTML") { this._articleLang = node.getAttribute("lang"); } var matchString = node.className + " " + node.id; if (!this._isProbablyVisible(node)) { this.log("Removing hidden node - " + matchString); node = this._removeAndGetNext(node); continue; } if (node.getAttribute("aria-modal") == "true" && node.getAttribute("role") == "dialog") { node = this._removeAndGetNext(node); continue; } if (this._checkByline(node, matchString)) { node = this._removeAndGetNext(node); continue; } if (shouldRemoveTitleHeader && this._headerDuplicatesTitle(node)) { this.log("Removing header: ", node.textContent.trim(), this._articleTitle.trim()); shouldRemoveTitleHeader = false; node = this._removeAndGetNext(node); continue; } if (stripUnlikelyCandidates) { if (this.REGEXPS.unlikelyCandidates.test(matchString) && !this.REGEXPS.okMaybeItsACandidate.test(matchString) && !this._hasAncestorTag(node, "table") && !this._hasAncestorTag(node, "code") && node.tagName !== "BODY" && node.tagName !== "A") { this.log("Removing unlikely candidate - " + matchString); node = this._removeAndGetNext(node); continue; } if (this.UNLIKELY_ROLES.includes(node.getAttribute("role"))) { this.log("Removing content with role " + node.getAttribute("role") + " - " + matchString); node = this._removeAndGetNext(node); continue; } } if ((node.tagName === "DIV" || node.tagName === "SECTION" || node.tagName === "HEADER" || node.tagName === "H1" || node.tagName === "H2" || node.tagName === "H3" || node.tagName === "H4" || node.tagName === "H5" || node.tagName === "H6") && this._isElementWithoutContent(node)) { node = this._removeAndGetNext(node); continue; } if (this.DEFAULT_TAGS_TO_SCORE.indexOf(node.tagName) !== -1) { elementsToScore.push(node); } if (node.tagName === "DIV") { var p2 = null; var childNode = node.firstChild; while (childNode) { var nextSibling = childNode.nextSibling; if (this._isPhrasingContent(childNode)) { if (p2 !== null) { p2.appendChild(childNode); } else if (!this._isWhitespace(childNode)) { p2 = doc.createElement("p"); node.replaceChild(p2, childNode); p2.appendChild(childNode); } } else if (p2 !== null) { while (p2.lastChild && this._isWhitespace(p2.lastChild)) { p2.removeChild(p2.lastChild); } p2 = null; } childNode = nextSibling; } if (this._hasSingleTagInsideElement(node, "P") && this._getLinkDensity(node) < 0.25) { var newNode = node.children[0]; node.parentNode.replaceChild(newNode, node); node = newNode; elementsToScore.push(node); } else if (!this._hasChildBlockElement(node)) { node = this._setNodeTag(node, "P"); elementsToScore.push(node); } } node = this._getNextNode(node); } var candidates = []; this._forEachNode(elementsToScore, function(elementToScore) { if (!elementToScore.parentNode || typeof elementToScore.parentNode.tagName === "undefined") return; var innerText = this._getInnerText(elementToScore); if (innerText.length < 25) return; var ancestors2 = this._getNodeAncestors(elementToScore, 5); if (ancestors2.length === 0) return; var contentScore = 0; contentScore += 1; contentScore += innerText.split(",").length; contentScore += Math.min(Math.floor(innerText.length / 100), 3); this._forEachNode(ancestors2, function(ancestor, level) { if (!ancestor.tagName || !ancestor.parentNode || typeof ancestor.parentNode.tagName === "undefined") return; if (typeof ancestor.readability === "undefined") { this._initializeNode(ancestor); candidates.push(ancestor); } if (level === 0) var scoreDivider = 1; else if (level === 1) scoreDivider = 2; else scoreDivider = level * 3; ancestor.readability.contentScore += contentScore / scoreDivider; }); }); var topCandidates = []; for (var c2 = 0, cl = candidates.length; c2 < cl; c2 += 1) { var candidate = candidates[c2]; var candidateScore = candidate.readability.contentScore * (1 - this._getLinkDensity(candidate)); candidate.readability.contentScore = candidateScore; this.log("Candidate:", candidate, "with score " + candidateScore); for (var t2 = 0; t2 < this._nbTopCandidates; t2++) { var aTopCandidate = topCandidates[t2]; if (!aTopCandidate || candidateScore > aTopCandidate.readability.contentScore) { topCandidates.splice(t2, 0, candidate); if (topCandidates.length > this._nbTopCandidates) topCandidates.pop(); break; } } } var topCandidate = topCandidates[0] || null; var neededToCreateTopCandidate = false; var parentOfTopCandidate; if (topCandidate === null || topCandidate.tagName === "BODY") { topCandidate = doc.createElement("DIV"); neededToCreateTopCandidate = true; while (page.firstChild) { this.log("Moving child out:", page.firstChild); topCandidate.appendChild(page.firstChild); } page.appendChild(topCandidate); this._initializeNode(topCandidate); } else if (topCandidate) { var alternativeCandidateAncestors = []; for (var i2 = 1; i2 < topCandidates.length; i2++) { if (topCandidates[i2].readability.contentScore / topCandidate.readability.contentScore >= 0.75) { alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i2])); } } var MINIMUM_TOPCANDIDATES = 3; if (alternativeCandidateAncestors.length >= MINIMUM_TOPCANDIDATES) { parentOfTopCandidate = topCandidate.parentNode; while (parentOfTopCandidate.tagName !== "BODY") { var listsContainingThisAncestor = 0; for (var ancestorIndex = 0; ancestorIndex < alternativeCandidateAncestors.length && listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; ancestorIndex++) { listsContainingThisAncestor += Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate)); } if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) { topCandidate = parentOfTopCandidate; break; } parentOfTopCandidate = parentOfTopCandidate.parentNode; } } if (!topCandidate.readability) { this._initializeNode(topCandidate); } parentOfTopCandidate = topCandidate.parentNode; var lastScore = topCandidate.readability.contentScore; var scoreThreshold = lastScore / 3; while (parentOfTopCandidate.tagName !== "BODY") { if (!parentOfTopCandidate.readability) { parentOfTopCandidate = parentOfTopCandidate.parentNode; continue; } var parentScore = parentOfTopCandidate.readability.contentScore; if (parentScore < scoreThreshold) break; if (parentScore > lastScore) { topCandidate = parentOfTopCandidate; break; } lastScore = parentOfTopCandidate.readability.contentScore; parentOfTopCandidate = parentOfTopCandidate.parentNode; } parentOfTopCandidate = topCandidate.parentNode; while (parentOfTopCandidate.tagName != "BODY" && parentOfTopCandidate.children.length == 1) { topCandidate = parentOfTopCandidate; parentOfTopCandidate = topCandidate.parentNode; } if (!topCandidate.readability) { this._initializeNode(topCandidate); } } var articleContent = doc.createElement("DIV"); if (isPaging) articleContent.id = "readability-content"; var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2); parentOfTopCandidate = topCandidate.parentNode; var siblings = parentOfTopCandidate.children; for (var s2 = 0, sl = siblings.length; s2 < sl; s2++) { var sibling = siblings[s2]; var append = false; this.log("Looking at sibling node:", sibling, sibling.readability ? "with score " + sibling.readability.contentScore : ""); this.log("Sibling has score", sibling.readability ? sibling.readability.contentScore : "Unknown"); if (sibling === topCandidate) { append = true; } else { var contentBonus = 0; if (sibling.className === topCandidate.className && topCandidate.className !== "") contentBonus += topCandidate.readability.contentScore * 0.2; if (sibling.readability && sibling.readability.contentScore + contentBonus >= siblingScoreThreshold) { append = true; } else if (sibling.nodeName === "P") { var linkDensity = this._getLinkDensity(sibling); var nodeContent = this._getInnerText(sibling); var nodeLength = nodeContent.length; if (nodeLength > 80 && linkDensity < 0.25) { append = true; } else if (nodeLength < 80 && nodeLength > 0 && linkDensity === 0 && nodeContent.search(/\.( |$)/) !== -1) { append = true; } } } if (append) { this.log("Appending node:", sibling); if (this.ALTER_TO_DIV_EXCEPTIONS.indexOf(sibling.nodeName) === -1) { this.log("Altering sibling:", sibling, "to div."); sibling = this._setNodeTag(sibling, "DIV"); } articleContent.appendChild(sibling); siblings = parentOfTopCandidate.children; s2 -= 1; sl -= 1; } } if (this._debug) this.log("Article content pre-prep: " + articleContent.innerHTML); this._prepArticle(articleContent); if (this._debug) this.log("Article content post-prep: " + articleContent.innerHTML); if (neededToCreateTopCandidate) { topCandidate.id = "readability-page-1"; topCandidate.className = "page"; } else { var div = doc.createElement("DIV"); div.id = "readability-page-1"; div.className = "page"; while (articleContent.firstChild) { div.appendChild(articleContent.firstChild); } articleContent.appendChild(div); } if (this._debug) this.log("Article content after paging: " + articleContent.innerHTML); var parseSuccessful = true; var textLength = this._getInnerText(articleContent, true).length; if (textLength < this._charThreshold) { parseSuccessful = false; page.innerHTML = pageCacheHtml; if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) { this._removeFlag(this.FLAG_STRIP_UNLIKELYS); this._attempts.push({ articleContent, textLength }); } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) { this._removeFlag(this.FLAG_WEIGHT_CLASSES); this._attempts.push({ articleContent, textLength }); } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) { this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY); this._attempts.push({ articleContent, textLength }); } else { this._attempts.push({ articleContent, textLength }); this._attempts.sort(function(a2, b2) { return b2.textLength - a2.textLength; }); if (!this._attempts[0].textLength) { return null; } articleContent = this._attempts[0].articleContent; parseSuccessful = true; } } if (parseSuccessful) { var ancestors = [parentOfTopCandidate, topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate)); this._someNode(ancestors, function(ancestor) { if (!ancestor.tagName) return false; var articleDir = ancestor.getAttribute("dir"); if (articleDir) { this._articleDir = articleDir; return true; } return false; }); return articleContent; } } }, _isValidByline: function(byline) { if (typeof byline == "string" || byline instanceof String) { byline = byline.trim(); return byline.length > 0 && byline.length < 100; } return false; }, _unescapeHtmlEntities: function(str3) { if (!str3) { return str3; } var htmlEscapeMap = this.HTML_ESCAPE_MAP; return str3.replace(/&(quot|amp|apos|lt|gt);/g, function(_2, tag) { return htmlEscapeMap[tag]; }).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi, function(_2, hex, numStr) { var num = parseInt(hex || numStr, hex ? 16 : 10); return String.fromCharCode(num); }); }, _getJSONLD: function(doc) { var scripts2 = this._getAllNodesWithTag(doc, ["script"]); var metadata; this._forEachNode(scripts2, function(jsonLdElement) { if (!metadata && jsonLdElement.getAttribute("type") === "application/ld+json") { try { var content = jsonLdElement.textContent.replace(/^\s*\s*$/g, ""); var parsed = JSON.parse(content); if (!parsed["@context"] || !parsed["@context"].match(/^https?\:\/\/schema\.org$/)) { return; } if (!parsed["@type"] && Array.isArray(parsed["@graph"])) { parsed = parsed["@graph"].find(function(it) { return (it["@type"] || "").match(this.REGEXPS.jsonLdArticleTypes); }); } if (!parsed || !parsed["@type"] || !parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes)) { return; } metadata = {}; if (typeof parsed.name === "string" && typeof parsed.headline === "string" && parsed.name !== parsed.headline) { var title = this._getArticleTitle(); var nameMatches = this._textSimilarity(parsed.name, title) > 0.75; var headlineMatches = this._textSimilarity(parsed.headline, title) > 0.75; if (headlineMatches && !nameMatches) { metadata.title = parsed.headline; } else { metadata.title = parsed.name; } } else if (typeof parsed.name === "string") { metadata.title = parsed.name.trim(); } else if (typeof parsed.headline === "string") { metadata.title = parsed.headline.trim(); } if (parsed.author) { if (typeof parsed.author.name === "string") { metadata.byline = parsed.author.name.trim(); } else if (Array.isArray(parsed.author) && parsed.author[0] && typeof parsed.author[0].name === "string") { metadata.byline = parsed.author.filter(function(author2) { return author2 && typeof author2.name === "string"; }).map(function(author2) { return author2.name.trim(); }).join(", "); } } if (typeof parsed.description === "string") { metadata.excerpt = parsed.description.trim(); } if (parsed.publisher && typeof parsed.publisher.name === "string") { metadata.siteName = parsed.publisher.name.trim(); } return; } catch (err) { this.log(err.message); } } }); return metadata ? metadata : {}; }, _getArticleMetadata: function(jsonld) { var metadata = {}; var values = {}; var metaElements = this._doc.getElementsByTagName("meta"); var propertyPattern = /\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|site_name)\s*/gi; var namePattern = /^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i; this._forEachNode(metaElements, function(element) { var elementName = element.getAttribute("name"); var elementProperty = element.getAttribute("property"); var content = element.getAttribute("content"); if (!content) { return; } var matches = null; var name2 = null; if (elementProperty) { matches = elementProperty.match(propertyPattern); if (matches) { name2 = matches[0].toLowerCase().replace(/\s/g, ""); values[name2] = content.trim(); } } if (!matches && elementName && namePattern.test(elementName)) { name2 = elementName; if (content) { name2 = name2.toLowerCase().replace(/\s/g, "").replace(/\./g, ":"); values[name2] = content.trim(); } } }); metadata.title = jsonld.title || values["dc:title"] || values["dcterm:title"] || values["og:title"] || values["weibo:article:title"] || values["weibo:webpage:title"] || values["title"] || values["twitter:title"]; if (!metadata.title) { metadata.title = this._getArticleTitle(); } metadata.byline = jsonld.byline || values["dc:creator"] || values["dcterm:creator"] || values["author"]; metadata.excerpt = jsonld.excerpt || values["dc:description"] || values["dcterm:description"] || values["og:description"] || values["weibo:article:description"] || values["weibo:webpage:description"] || values["description"] || values["twitter:description"]; metadata.siteName = jsonld.siteName || values["og:site_name"]; metadata.title = this._unescapeHtmlEntities(metadata.title); metadata.byline = this._unescapeHtmlEntities(metadata.byline); metadata.excerpt = this._unescapeHtmlEntities(metadata.excerpt); metadata.siteName = this._unescapeHtmlEntities(metadata.siteName); return metadata; }, _isSingleImage: function(node) { if (node.tagName === "IMG") { return true; } if (node.children.length !== 1 || node.textContent.trim() !== "") { return false; } return this._isSingleImage(node.children[0]); }, _unwrapNoscriptImages: function(doc) { var imgs = Array.from(doc.getElementsByTagName("img")); this._forEachNode(imgs, function(img) { for (var i2 = 0; i2 < img.attributes.length; i2++) { var attr = img.attributes[i2]; switch (attr.name) { case "src": case "srcset": case "data-src": case "data-srcset": return; } if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) { return; } } img.parentNode.removeChild(img); }); var noscripts = Array.from(doc.getElementsByTagName("noscript")); this._forEachNode(noscripts, function(noscript) { var tmp = doc.createElement("div"); tmp.innerHTML = noscript.innerHTML; if (!this._isSingleImage(tmp)) { return; } var prevElement = noscript.previousElementSibling; if (prevElement && this._isSingleImage(prevElement)) { var prevImg = prevElement; if (prevImg.tagName !== "IMG") { prevImg = prevElement.getElementsByTagName("img")[0]; } var newImg = tmp.getElementsByTagName("img")[0]; for (var i2 = 0; i2 < prevImg.attributes.length; i2++) { var attr = prevImg.attributes[i2]; if (attr.value === "") { continue; } if (attr.name === "src" || attr.name === "srcset" || /\.(jpg|jpeg|png|webp)/i.test(attr.value)) { if (newImg.getAttribute(attr.name) === attr.value) { continue; } var attrName = attr.name; if (newImg.hasAttribute(attrName)) { attrName = "data-old-" + attrName; } newImg.setAttribute(attrName, attr.value); } } noscript.parentNode.replaceChild(tmp.firstElementChild, prevElement); } }); }, _removeScripts: function(doc) { this._removeNodes(this._getAllNodesWithTag(doc, ["script", "noscript"])); }, _hasSingleTagInsideElement: function(element, tag) { if (element.children.length != 1 || element.children[0].tagName !== tag) { return false; } return !this._someNode(element.childNodes, function(node) { return node.nodeType === this.TEXT_NODE && this.REGEXPS.hasContent.test(node.textContent); }); }, _isElementWithoutContent: function(node) { return node.nodeType === this.ELEMENT_NODE && node.textContent.trim().length == 0 && (node.children.length == 0 || node.children.length == node.getElementsByTagName("br").length + node.getElementsByTagName("hr").length); }, _hasChildBlockElement: function(element) { return this._someNode(element.childNodes, function(node) { return this.DIV_TO_P_ELEMS.has(node.tagName) || this._hasChildBlockElement(node); }); }, _isPhrasingContent: function(node) { return node.nodeType === this.TEXT_NODE || this.PHRASING_ELEMS.indexOf(node.tagName) !== -1 || (node.tagName === "A" || node.tagName === "DEL" || node.tagName === "INS") && this._everyNode(node.childNodes, this._isPhrasingContent); }, _isWhitespace: function(node) { return node.nodeType === this.TEXT_NODE && node.textContent.trim().length === 0 || node.nodeType === this.ELEMENT_NODE && node.tagName === "BR"; }, _getInnerText: function(e2, normalizeSpaces) { normalizeSpaces = typeof normalizeSpaces === "undefined" ? true : normalizeSpaces; var textContent = e2.textContent.trim(); if (normalizeSpaces) { return textContent.replace(this.REGEXPS.normalize, " "); } return textContent; }, _getCharCount: function(e2, s2) { s2 = s2 || ","; return this._getInnerText(e2).split(s2).length - 1; }, _cleanStyles: function(e2) { if (!e2 || e2.tagName.toLowerCase() === "svg") return; for (var i2 = 0; i2 < this.PRESENTATIONAL_ATTRIBUTES.length; i2++) { e2.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i2]); } if (this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.indexOf(e2.tagName) !== -1) { e2.removeAttribute("width"); e2.removeAttribute("height"); } var cur = e2.firstElementChild; while (cur !== null) { this._cleanStyles(cur); cur = cur.nextElementSibling; } }, _getLinkDensity: function(element) { var textLength = this._getInnerText(element).length; if (textLength === 0) return 0; var linkLength = 0; this._forEachNode(element.getElementsByTagName("a"), function(linkNode) { var href = linkNode.getAttribute("href"); var coefficient = href && this.REGEXPS.hashUrl.test(href) ? 0.3 : 1; linkLength += this._getInnerText(linkNode).length * coefficient; }); return linkLength / textLength; }, _getClassWeight: function(e2) { if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) return 0; var weight = 0; if (typeof e2.className === "string" && e2.className !== "") { if (this.REGEXPS.negative.test(e2.className)) weight -= 25; if (this.REGEXPS.positive.test(e2.className)) weight += 25; } if (typeof e2.id === "string" && e2.id !== "") { if (this.REGEXPS.negative.test(e2.id)) weight -= 25; if (this.REGEXPS.positive.test(e2.id)) weight += 25; } return weight; }, _clean: function(e2, tag) { var isEmbed = ["object", "embed", "iframe"].indexOf(tag) !== -1; this._removeNodes(this._getAllNodesWithTag(e2, [tag]), function(element) { if (isEmbed) { for (var i2 = 0; i2 < element.attributes.length; i2++) { if (this._allowedVideoRegex.test(element.attributes[i2].value)) { return false; } } if (element.tagName === "object" && this._allowedVideoRegex.test(element.innerHTML)) { return false; } } return true; }); }, _hasAncestorTag: function(node, tagName, maxDepth, filterFn) { maxDepth = maxDepth || 3; tagName = tagName.toUpperCase(); var depth = 0; while (node.parentNode) { if (maxDepth > 0 && depth > maxDepth) return false; if (node.parentNode.tagName === tagName && (!filterFn || filterFn(node.parentNode))) return true; node = node.parentNode; depth++; } return false; }, _getRowAndColumnCount: function(table) { var rows = 0; var columns = 0; var trs = table.getElementsByTagName("tr"); for (var i2 = 0; i2 < trs.length; i2++) { var rowspan = trs[i2].getAttribute("rowspan") || 0; if (rowspan) { rowspan = parseInt(rowspan, 10); } rows += rowspan || 1; var columnsInThisRow = 0; var cells = trs[i2].getElementsByTagName("td"); for (var j2 = 0; j2 < cells.length; j2++) { var colspan = cells[j2].getAttribute("colspan") || 0; if (colspan) { colspan = parseInt(colspan, 10); } columnsInThisRow += colspan || 1; } columns = Math.max(columns, columnsInThisRow); } return { rows, columns }; }, _markDataTables: function(root3) { var tables = root3.getElementsByTagName("table"); for (var i2 = 0; i2 < tables.length; i2++) { var table = tables[i2]; var role = table.getAttribute("role"); if (role == "presentation") { table._readabilityDataTable = false; continue; } var datatable = table.getAttribute("datatable"); if (datatable == "0") { table._readabilityDataTable = false; continue; } var summary = table.getAttribute("summary"); if (summary) { table._readabilityDataTable = true; continue; } var caption = table.getElementsByTagName("caption")[0]; if (caption && caption.childNodes.length > 0) { table._readabilityDataTable = true; continue; } var dataTableDescendants = ["col", "colgroup", "tfoot", "thead", "th"]; var descendantExists = function(tag) { return !!table.getElementsByTagName(tag)[0]; }; if (dataTableDescendants.some(descendantExists)) { this.log("Data table because found data-y descendant"); table._readabilityDataTable = true; continue; } if (table.getElementsByTagName("table")[0]) { table._readabilityDataTable = false; continue; } var sizeInfo = this._getRowAndColumnCount(table); if (sizeInfo.rows >= 10 || sizeInfo.columns > 4) { table._readabilityDataTable = true; continue; } table._readabilityDataTable = sizeInfo.rows * sizeInfo.columns > 10; } }, _fixLazyImages: function(root3) { this._forEachNode(this._getAllNodesWithTag(root3, ["img", "picture", "figure"]), function(elem) { if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) { var parts = this.REGEXPS.b64DataUrl.exec(elem.src); if (parts[1] === "image/svg+xml") { return; } var srcCouldBeRemoved = false; for (var i2 = 0; i2 < elem.attributes.length; i2++) { var attr = elem.attributes[i2]; if (attr.name === "src") { continue; } if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) { srcCouldBeRemoved = true; break; } } if (srcCouldBeRemoved) { var b64starts = elem.src.search(/base64\s*/i) + 7; var b64length = elem.src.length - b64starts; if (b64length < 133) { elem.removeAttribute("src"); } } } if ((elem.src || elem.srcset && elem.srcset != "null") && elem.className.toLowerCase().indexOf("lazy") === -1) { return; } for (var j2 = 0; j2 < elem.attributes.length; j2++) { attr = elem.attributes[j2]; if (attr.name === "src" || attr.name === "srcset" || attr.name === "alt") { continue; } var copyTo = null; if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) { copyTo = "srcset"; } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) { copyTo = "src"; } if (copyTo) { if (elem.tagName === "IMG" || elem.tagName === "PICTURE") { elem.setAttribute(copyTo, attr.value); } else if (elem.tagName === "FIGURE" && !this._getAllNodesWithTag(elem, ["img", "picture"]).length) { var img = this._doc.createElement("img"); img.setAttribute(copyTo, attr.value); elem.appendChild(img); } } } }); }, _getTextDensity: function(e2, tags) { var textLength = this._getInnerText(e2, true).length; if (textLength === 0) { return 0; } var childrenLength = 0; var children2 = this._getAllNodesWithTag(e2, tags); this._forEachNode(children2, (child) => childrenLength += this._getInnerText(child, true).length); return childrenLength / textLength; }, _cleanConditionally: function(e2, tag) { if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) return; this._removeNodes(this._getAllNodesWithTag(e2, [tag]), function(node) { var isDataTable = function(t2) { return t2._readabilityDataTable; }; var isList = tag === "ul" || tag === "ol"; if (!isList) { var listLength = 0; var listNodes = this._getAllNodesWithTag(node, ["ul", "ol"]); this._forEachNode(listNodes, (list) => listLength += this._getInnerText(list).length); isList = listLength / this._getInnerText(node).length > 0.9; } if (tag === "table" && isDataTable(node)) { return false; } if (this._hasAncestorTag(node, "table", -1, isDataTable)) { return false; } if (this._hasAncestorTag(node, "code")) { return false; } var weight = this._getClassWeight(node); this.log("Cleaning Conditionally", node); var contentScore = 0; if (weight + contentScore < 0) { return true; } if (this._getCharCount(node, ",") < 10) { var p2 = node.getElementsByTagName("p").length; var img = node.getElementsByTagName("img").length; var li = node.getElementsByTagName("li").length - 100; var input = node.getElementsByTagName("input").length; var headingDensity = this._getTextDensity(node, ["h1", "h2", "h3", "h4", "h5", "h6"]); var embedCount = 0; var embeds = this._getAllNodesWithTag(node, ["object", "embed", "iframe"]); for (var i2 = 0; i2 < embeds.length; i2++) { for (var j2 = 0; j2 < embeds[i2].attributes.length; j2++) { if (this._allowedVideoRegex.test(embeds[i2].attributes[j2].value)) { return false; } } if (embeds[i2].tagName === "object" && this._allowedVideoRegex.test(embeds[i2].innerHTML)) { return false; } embedCount++; } var linkDensity = this._getLinkDensity(node); var contentLength = this._getInnerText(node).length; var haveToRemove = img > 1 && p2 / img < 0.5 && !this._hasAncestorTag(node, "figure") || !isList && li > p2 || input > Math.floor(p2 / 3) || !isList && headingDensity < 0.9 && contentLength < 25 && (img === 0 || img > 2) && !this._hasAncestorTag(node, "figure") || !isList && weight < 25 && linkDensity > 0.2 || weight >= 25 && linkDensity > 0.5 || (embedCount === 1 && contentLength < 75 || embedCount > 1); if (isList && haveToRemove) { for (var x2 = 0; x2 < node.children.length; x2++) { let child = node.children[x2]; if (child.children.length > 1) { return haveToRemove; } } let li_count = node.getElementsByTagName("li").length; if (img == li_count) { return false; } } return haveToRemove; } return false; }); }, _cleanMatchedNodes: function(e2, filter) { var endOfSearchMarkerNode = this._getNextNode(e2, true); var next2 = this._getNextNode(e2); while (next2 && next2 != endOfSearchMarkerNode) { if (filter.call(this, next2, next2.className + " " + next2.id)) { next2 = this._removeAndGetNext(next2); } else { next2 = this._getNextNode(next2); } } }, _cleanHeaders: function(e2) { let headingNodes = this._getAllNodesWithTag(e2, ["h1", "h2"]); this._removeNodes(headingNodes, function(node) { let shouldRemove = this._getClassWeight(node) < 0; if (shouldRemove) { this.log("Removing header with low class weight:", node); } return shouldRemove; }); }, _headerDuplicatesTitle: function(node) { if (node.tagName != "H1" && node.tagName != "H2") { return false; } var heading = this._getInnerText(node, false); this.log("Evaluating similarity of header:", heading, this._articleTitle); return this._textSimilarity(this._articleTitle, heading) > 0.75; }, _flagIsActive: function(flag) { return (this._flags & flag) > 0; }, _removeFlag: function(flag) { this._flags = this._flags & ~flag; }, _isProbablyVisible: function(node) { return (!node.style || node.style.display != "none") && !node.hasAttribute("hidden") && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1); }, parse: function() { if (this._maxElemsToParse > 0) { var numTags = this._doc.getElementsByTagName("*").length; if (numTags > this._maxElemsToParse) { throw new Error("Aborting parsing document; " + numTags + " elements found"); } } this._unwrapNoscriptImages(this._doc); var jsonLd = this._disableJSONLD ? {} : this._getJSONLD(this._doc); this._removeScripts(this._doc); this._prepDocument(); var metadata = this._getArticleMetadata(jsonLd); this._articleTitle = metadata.title; var articleContent = this._grabArticle(); if (!articleContent) return null; this.log("Grabbed: " + articleContent.innerHTML); this._postProcessContent(articleContent); if (!metadata.excerpt) { var paragraphs = articleContent.getElementsByTagName("p"); if (paragraphs.length > 0) { metadata.excerpt = paragraphs[0].textContent.trim(); } } var textContent = articleContent.textContent; return { title: this._articleTitle, byline: metadata.byline || this._articleByline, dir: this._articleDir, lang: this._articleLang, content: this._serializer(articleContent), textContent, length: textContent.length, excerpt: metadata.excerpt, siteName: metadata.siteName || this._articleSiteName }; } }; if (typeof module2 === "object") { module2.exports = Readability2; } } }); // node_modules/.pnpm/@mozilla+readability@0.4.4/node_modules/@mozilla/readability/Readability-readerable.js var require_Readability_readerable = __commonJS({ "node_modules/.pnpm/@mozilla+readability@0.4.4/node_modules/@mozilla/readability/Readability-readerable.js"(exports2, module2) { var REGEXPS = { unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i }; function isNodeVisible(node) { return (!node.style || node.style.display != "none") && !node.hasAttribute("hidden") && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1); } function isProbablyReaderable(doc, options = {}) { if (typeof options == "function") { options = { visibilityChecker: options }; } var defaultOptions2 = { minScore: 20, minContentLength: 140, visibilityChecker: isNodeVisible }; options = Object.assign(defaultOptions2, options); var nodes = doc.querySelectorAll("p, pre, article"); var brNodes = doc.querySelectorAll("div > br"); if (brNodes.length) { var set13 = new Set(nodes); [].forEach.call(brNodes, function(node) { set13.add(node.parentNode); }); nodes = Array.from(set13); } var score = 0; return [].some.call(nodes, function(node) { if (!options.visibilityChecker(node)) { return false; } var matchString = node.className + " " + node.id; if (REGEXPS.unlikelyCandidates.test(matchString) && !REGEXPS.okMaybeItsACandidate.test(matchString)) { return false; } if (node.matches("li p")) { return false; } var textContentLength = node.textContent.trim().length; if (textContentLength < options.minContentLength) { return false; } score += Math.sqrt(textContentLength - options.minContentLength); if (score > options.minScore) { return true; } return false; }); } if (typeof module2 === "object") { module2.exports = isProbablyReaderable; } } }); // node_modules/.pnpm/@mozilla+readability@0.4.4/node_modules/@mozilla/readability/index.js var require_readability = __commonJS({ "node_modules/.pnpm/@mozilla+readability@0.4.4/node_modules/@mozilla/readability/index.js"(exports2, module2) { var Readability2 = require_Readability(); var isProbablyReaderable = require_Readability_readerable(); module2.exports = { Readability: Readability2, isProbablyReaderable }; } }); // node_modules/.pnpm/react@18.2.0/node_modules/react/cjs/react.development.js var require_react_development = __commonJS({ "node_modules/.pnpm/react@18.2.0/node_modules/react/cjs/react.development.js"(exports2, module2) { "use strict"; if (true) { (function() { "use strict"; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var ReactVersion = "18.2.0"; var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === "function") { return maybeIterator; } return null; } var ReactCurrentDispatcher = { current: null }; var ReactCurrentBatchConfig = { transition: null }; var ReactCurrentActQueue = { current: null, isBatchingLegacy: false, didScheduleLegacyUpdate: false }; var ReactCurrentOwner = { current: null }; var ReactDebugCurrentFrame = {}; var currentExtraStackFrame = null; function setExtraStackFrame(stack) { { currentExtraStackFrame = stack; } } { ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { { currentExtraStackFrame = stack; } }; ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function() { var stack = ""; if (currentExtraStackFrame) { stack += currentExtraStackFrame; } var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ""; } return stack; }; } var enableScopeAPI = false; var enableCacheElement = false; var enableTransitionTracing = false; var enableLegacyHidden = false; var enableDebugTracing = false; var ReactSharedInternals = { ReactCurrentDispatcher, ReactCurrentBatchConfig, ReactCurrentOwner }; { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } function warn(format) { { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning("warn", format, args); } } } function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame2.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } var ReactNoopUpdateQueue = { isMounted: function(publicInstance) { return false; }, enqueueForceUpdate: function(publicInstance, callback, callerName) { warnNoop(publicInstance, "forceUpdate"); }, enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, "replaceState"); }, enqueueSetState: function(publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, "setState"); } }; var assign = Object.assign; var emptyObject = {}; { Object.freeze(emptyObject); } function Component7(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } Component7.prototype.isReactComponent = {}; Component7.prototype.setState = function(partialState, callback) { if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); } this.updater.enqueueSetState(this, partialState, callback, "setState"); }; Component7.prototype.forceUpdate = function(callback) { this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); }; { var deprecatedAPIs = { isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] }; var defineDeprecationWarning = function(methodName, info) { Object.defineProperty(Component7.prototype, methodName, { get: function() { warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); return void 0; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() { } ComponentDummy.prototype = Component7.prototype; function PureComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; assign(pureComponentPrototype, Component7.prototype); pureComponentPrototype.isPureReactComponent = true; function createRef2() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var isArrayImpl = Array.isArray; function isArray(a2) { return isArrayImpl(a2); } function typeName(value) { { var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; return type2; } } function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e2) { return true; } } } function testStringCoercion(value) { return "" + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ""; return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; } function getContextName(type2) { return type2.displayName || "Context"; } function getComponentNameFromType(type2) { if (type2 == null) { return null; } { if (typeof type2.tag === "number") { error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); } } if (typeof type2 === "function") { return type2.displayName || type2.name || null; } if (typeof type2 === "string") { return type2; } switch (type2) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_CONTEXT_TYPE: var context = type2; return getContextName(context) + ".Consumer"; case REACT_PROVIDER_TYPE: var provider = type2; return getContextName(provider._context) + ".Provider"; case REACT_FORWARD_REF_TYPE: return getWrappedName(type2, type2.render, "ForwardRef"); case REACT_MEMO_TYPE: var outerName = type2.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type2.type) || "Memo"; case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return getComponentNameFromType(init2(payload)); } catch (x2) { return null; } } } } return null; } var hasOwnProperty2 = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty2.call(config, "ref")) { var getter = Object.getOwnPropertyDescriptor(config, "ref").get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== void 0; } function hasValidKey(config) { { if (hasOwnProperty2.call(config, "key")) { var getter = Object.getOwnPropertyDescriptor(config, "key").get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== void 0; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function() { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, "key", { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function() { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, "ref", { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); didWarnAboutStringRefs[componentName] = true; } } } } var ReactElement = function(type2, key, ref, self2, source, owner, props) { var element = { $$typeof: REACT_ELEMENT_TYPE, type: type2, key, ref, props, _owner: owner }; { element._store = {}; Object.defineProperty(element._store, "validated", { configurable: false, enumerable: false, writable: true, value: false }); Object.defineProperty(element, "_self", { configurable: false, enumerable: false, writable: false, value: self2 }); Object.defineProperty(element, "_source", { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; function createElement10(type2, config, children2) { var propName; var props = {}; var key = null; var ref = null; var self2 = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } self2 = config.__self === void 0 ? null : config.__self; source = config.__source === void 0 ? null : config.__source; for (propName in config) { if (hasOwnProperty2.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children2; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i2 = 0; i2 < childrenLength; i2++) { childArray[i2] = arguments[i2 + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } if (type2 && type2.defaultProps) { var defaultProps = type2.defaultProps; for (propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type2 === "function" ? type2.displayName || type2.name || "Unknown" : type2; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type2, key, ref, self2, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } function cloneElement2(element, config, children2) { if (element === null || element === void 0) { throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); } var propName; var props = assign({}, element.props); var key = element.key; var ref = element.ref; var self2 = element._self; var source = element._source; var owner = element._owner; if (config != null) { if (hasValidRef(config)) { ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty2.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === void 0 && defaultProps !== void 0) { props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children2; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i2 = 0; i2 < childrenLength; i2++) { childArray[i2] = arguments[i2 + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self2, source, owner, props); } function isValidElement(object) { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = "."; var SUBSEPARATOR = ":"; function escape(key) { var escapeRegex2 = /[=:]/g; var escaperLookup = { "=": "=0", ":": "=2" }; var escapedString = key.replace(escapeRegex2, function(match) { return escaperLookup[match]; }); return "$" + escapedString; } var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return text.replace(userProvidedKeyEscapeRegex, "$&/"); } function getElementKey(element, index2) { if (typeof element === "object" && element !== null && element.key != null) { { checkKeyStringCoercion(element.key); } return escape("" + element.key); } return index2.toString(36); } function mapIntoArray(children2, array, escapedPrefix, nameSoFar, callback) { var type2 = typeof children2; if (type2 === "undefined" || type2 === "boolean") { children2 = null; } var invokeCallback = false; if (children2 === null) { invokeCallback = true; } else { switch (type2) { case "string": case "number": invokeCallback = true; break; case "object": switch (children2.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { var _child = children2; var mappedChild = callback(_child); var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; if (isArray(mappedChild)) { var escapedChildKey = ""; if (childKey != null) { escapedChildKey = escapeUserProvidedKey(childKey) + "/"; } mapIntoArray(mappedChild, array, escapedChildKey, "", function(c2) { return c2; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { { if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { checkKeyStringCoercion(mappedChild.key); } } mappedChild = cloneAndReplaceKey(mappedChild, escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey); } array.push(mappedChild); } return 1; } var child; var nextName; var subtreeCount = 0; var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (isArray(children2)) { for (var i2 = 0; i2 < children2.length; i2++) { child = children2[i2]; nextName = nextNamePrefix + getElementKey(child, i2); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else { var iteratorFn = getIteratorFn(children2); if (typeof iteratorFn === "function") { var iterableChildren = children2; { if (iteratorFn === iterableChildren.entries) { if (!didWarnAboutMaps) { warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(iterableChildren); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getElementKey(child, ii++); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else if (type2 === "object") { var childrenString = String(children2); throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children2).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); } } return subtreeCount; } function mapChildren(children2, func, context) { if (children2 == null) { return children2; } var result = []; var count = 0; mapIntoArray(children2, result, "", "", function(child) { return func.call(context, child, count++); }); return result; } function countChildren(children2) { var n2 = 0; mapChildren(children2, function() { n2++; }); return n2; } function forEachChildren(children2, forEachFunc, forEachContext) { mapChildren(children2, function() { forEachFunc.apply(this, arguments); }, forEachContext); } function toArray4(children2) { return mapChildren(children2, function(child) { return child; }) || []; } function onlyChild(children2) { if (!isValidElement(children2)) { throw new Error("React.Children.only expected to receive a single React element child."); } return children2; } function createContext2(defaultValue) { var context = { $$typeof: REACT_CONTEXT_TYPE, _currentValue: defaultValue, _currentValue2: defaultValue, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; var hasWarnedAboutDisplayNameOnConsumer = false; { var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context }; Object.defineProperties(Consumer, { Provider: { get: function() { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Provider; }, set: function(_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function() { return context._currentValue; }, set: function(_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function() { return context._currentValue2; }, set: function(_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function() { return context._threadCount; }, set: function(_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function() { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Consumer; } }, displayName: { get: function() { return context.displayName; }, set: function(displayName) { if (!hasWarnedAboutDisplayNameOnConsumer) { warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); hasWarnedAboutDisplayNameOnConsumer = true; } } } }); context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function lazyInitializer(payload) { if (payload._status === Uninitialized) { var ctor = payload._result; var thenable = ctor(); thenable.then(function(moduleObject2) { if (payload._status === Pending || payload._status === Uninitialized) { var resolved = payload; resolved._status = Resolved; resolved._result = moduleObject2; } }, function(error2) { if (payload._status === Pending || payload._status === Uninitialized) { var rejected = payload; rejected._status = Rejected; rejected._result = error2; } }); if (payload._status === Uninitialized) { var pending = payload; pending._status = Pending; pending._result = thenable; } } if (payload._status === Resolved) { var moduleObject = payload._result; { if (moduleObject === void 0) { error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); } } { if (!("default" in moduleObject)) { error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); } } return moduleObject.default; } else { throw payload._result; } } function lazy(ctor) { var payload = { _status: Uninitialized, _result: ctor }; var lazyType2 = { $$typeof: REACT_LAZY_TYPE, _payload: payload, _init: lazyInitializer }; { var defaultProps; var propTypes; Object.defineProperties(lazyType2, { defaultProps: { configurable: true, get: function() { return defaultProps; }, set: function(newDefaultProps) { error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); defaultProps = newDefaultProps; Object.defineProperty(lazyType2, "defaultProps", { enumerable: true }); } }, propTypes: { configurable: true, get: function() { return propTypes; }, set: function(newPropTypes) { error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); propTypes = newPropTypes; Object.defineProperty(lazyType2, "propTypes", { enumerable: true }); } } }); } return lazyType2; } function forwardRef3(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); } else if (typeof render !== "function") { error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); } } } var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name2) { ownName = name2; if (!render.name && !render.displayName) { render.displayName = name2; } } }); } return elementType; } var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); } function isValidElementType(type2) { if (typeof type2 === "string" || typeof type2 === "function") { return true; } if (type2 === REACT_FRAGMENT_TYPE || type2 === REACT_PROFILER_TYPE || enableDebugTracing || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type2 === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { return true; } if (typeof type2 === "object" && type2 !== null) { if (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || type2.$$typeof === REACT_MODULE_REFERENCE || type2.getModuleId !== void 0) { return true; } } return false; } function memo(type2, compare2) { { if (!isValidElementType(type2)) { error("memo: The first argument must be a component. Instead received: %s", type2 === null ? "null" : typeof type2); } } var elementType = { $$typeof: REACT_MEMO_TYPE, type: type2, compare: compare2 === void 0 ? null : compare2 }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name2) { ownName = name2; if (!type2.name && !type2.displayName) { type2.displayName = name2; } } }); } return elementType; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; { if (dispatcher === null) { error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); } } return dispatcher; } function useContext2(Context) { var dispatcher = resolveDispatcher(); { if (Context._context !== void 0) { var realContext = Context._context; if (realContext.Consumer === Context) { error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); } else if (realContext.Provider === Context) { error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); } } } return dispatcher.useContext(Context); } function useState24(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer3(reducer, initialArg, init2) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init2); } function useRef3(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect29(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useInsertionEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useInsertionEffect(create, deps); } function useLayoutEffect2(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback14(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo14(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } function useTransition() { var dispatcher = resolveDispatcher(); return dispatcher.useTransition(); } function useDeferredValue(value) { var dispatcher = resolveDispatcher(); return dispatcher.useDeferredValue(value); } function useId16() { var dispatcher = resolveDispatcher(); return dispatcher.useId(); } function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var dispatcher = resolveDispatcher(); return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() { } disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); } if (disabledDepth < 0) { error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name2, source, ownerFn) { { if (prefix === void 0) { try { throw Error(); } catch (x2) { var match = x2.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ""; } } return "\n" + prefix + name2; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) { return ""; } { var frame = componentFrameCache.get(fn); if (frame !== void 0) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = null; disableLogs(); } try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if (typeof Reflect === "object" && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x2) { control = x2; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x2) { control = x2; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x2) { control = x2; } fn(); } } catch (sample) { if (sample && control && typeof sample.stack === "string") { var sampleLines = sample.stack.split("\n"); var controlLines = control.stack.split("\n"); var s2 = sampleLines.length - 1; var c2 = controlLines.length - 1; while (s2 >= 1 && c2 >= 0 && sampleLines[s2] !== controlLines[c2]) { c2--; } for (; s2 >= 1 && c2 >= 0; s2--, c2--) { if (sampleLines[s2] !== controlLines[c2]) { if (s2 !== 1 || c2 !== 1) { do { s2--; c2--; if (c2 < 0 || sampleLines[s2] !== controlLines[c2]) { var _frame = "\n" + sampleLines[s2].replace(" at new ", " at "); if (fn.displayName && _frame.includes("")) { _frame = _frame.replace("", fn.displayName); } { if (typeof fn === "function") { componentFrameCache.set(fn, _frame); } } return _frame; } } while (s2 >= 1 && c2 >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher$1.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } var name2 = fn ? fn.displayName || fn.name : ""; var syntheticFrame = name2 ? describeBuiltInComponentFrame(name2) : ""; { if (typeof fn === "function") { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component8) { var prototype = Component8.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) { if (type2 == null) { return ""; } if (typeof type2 === "function") { { return describeNativeComponentFrame(type2, shouldConstruct(type2)); } } if (typeof type2 === "string") { return describeBuiltInComponentFrame(type2); } switch (type2) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type2.render); case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn); } catch (x2) { } } } } return ""; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location2, componentName, element) { { var has6 = Function.call.bind(hasOwnProperty2); for (var typeSpecName in typeSpecs) { if (has6(typeSpecs, typeSpecName)) { var error$1 = void 0; try { if (typeof typeSpecs[typeSpecName] !== "function") { var err = Error((componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); err.name = "Invariant Violation"; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location2, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error("Failed %s type: %s", location2, error$1.message); setCurrentlyValidatingElement(null); } } } } } function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); setExtraStackFrame(stack); } else { setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name2 = getComponentNameFromType(ReactCurrentOwner.current.type); if (name2) { return "\n\nCheck the render method of `" + name2 + "`."; } } return ""; } function getSourceInfoErrorAddendum(source) { if (source !== void 0) { var fileName = source.fileName.replace(/^.*[\\\/]/, ""); var lineNumber = source.lineNumber; return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; } return ""; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== void 0) { return getSourceInfoErrorAddendum(elementProps.__source); } return ""; } var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; var childOwner = ""; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } { setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } function validateChildKeys(node, parentType) { if (typeof node !== "object") { return; } if (isArray(node)) { for (var i2 = 0; i2 < node.length; i2++) { var child = node[i2]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === "function") { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } function validatePropTypes(element) { { var type2 = element.type; if (type2 === null || type2 === void 0 || typeof type2 === "string") { return; } var propTypes; if (typeof type2 === "function") { propTypes = type2.propTypes; } else if (typeof type2 === "object" && (type2.$$typeof === REACT_FORWARD_REF_TYPE || type2.$$typeof === REACT_MEMO_TYPE)) { propTypes = type2.propTypes; } else { return; } if (propTypes) { var name2 = getComponentNameFromType(type2); checkPropTypes(propTypes, element.props, "prop", name2, element); } else if (type2.PropTypes !== void 0 && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; var _name = getComponentNameFromType(type2); error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); } if (typeof type2.getDefaultProps === "function" && !type2.getDefaultProps.isReactClassApproved) { error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } } function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i2 = 0; i2 < keys.length; i2++) { var key = keys[i2]; if (key !== "children" && key !== "key") { setCurrentlyValidatingElement$1(fragment); error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error("Invalid attribute `ref` supplied to `React.Fragment`."); setCurrentlyValidatingElement$1(null); } } } function createElementWithValidation(type2, props, children2) { var validType = isValidElementType(type2); if (!validType) { var info = ""; if (type2 === void 0 || typeof type2 === "object" && type2 !== null && Object.keys(type2).length === 0) { info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type2 === null) { typeString = "null"; } else if (isArray(type2)) { typeString = "array"; } else if (type2 !== void 0 && type2.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type2.type) || "Unknown") + " />"; info = " Did you accidentally export a JSX literal instead of a component?"; } else { typeString = typeof type2; } { error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); } } var element = createElement10.apply(this, arguments); if (element == null) { return element; } if (validType) { for (var i2 = 2; i2 < arguments.length; i2++) { validateChildKeys(arguments[i2], type2); } } if (type2 === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type2) { var validatedFactory = createElementWithValidation.bind(null, type2); validatedFactory.type = type2; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); } Object.defineProperty(validatedFactory, "type", { enumerable: false, get: function() { warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); Object.defineProperty(this, "type", { value: type2 }); return type2; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children2) { var newElement = cloneElement2.apply(this, arguments); for (var i2 = 2; i2 < arguments.length; i2++) { validateChildKeys(arguments[i2], newElement.type); } validatePropTypes(newElement); return newElement; } function startTransition(scope, options) { var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = {}; var currentTransition = ReactCurrentBatchConfig.transition; { ReactCurrentBatchConfig.transition._updatedFibers = new Set(); } try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); } currentTransition._updatedFibers.clear(); } } } } var didWarnAboutMessageChannel = false; var enqueueTaskImpl = null; function enqueueTask(task) { if (enqueueTaskImpl === null) { try { var requireString = ("require" + Math.random()).slice(0, 7); var nodeRequire = module2 && module2[requireString]; enqueueTaskImpl = nodeRequire.call(module2, "timers").setImmediate; } catch (_err) { enqueueTaskImpl = function(callback) { { if (didWarnAboutMessageChannel === false) { didWarnAboutMessageChannel = true; if (typeof MessageChannel === "undefined") { error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); } } } var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(void 0); }; } } return enqueueTaskImpl(task); } var actScopeDepth = 0; var didWarnNoAwaitAct = false; function act(callback) { { var prevActScopeDepth = actScopeDepth; actScopeDepth++; if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; } var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; var result; try { ReactCurrentActQueue.isBatchingLegacy = true; result = callback(); if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { var queue2 = ReactCurrentActQueue.current; if (queue2 !== null) { ReactCurrentActQueue.didScheduleLegacyUpdate = false; flushActQueue(queue2); } } } catch (error2) { popActScope(prevActScopeDepth); throw error2; } finally { ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } if (result !== null && typeof result === "object" && typeof result.then === "function") { var thenableResult = result; var wasAwaited = false; var thenable = { then: function(resolve, reject) { wasAwaited = true; thenableResult.then(function(returnValue2) { popActScope(prevActScopeDepth); if (actScopeDepth === 0) { recursivelyFlushAsyncActWork(returnValue2, resolve, reject); } else { resolve(returnValue2); } }, function(error2) { popActScope(prevActScopeDepth); reject(error2); }); } }; { if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { Promise.resolve().then(function() { }).then(function() { if (!wasAwaited) { didWarnNoAwaitAct = true; error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); } }); } } return thenable; } else { var returnValue = result; popActScope(prevActScopeDepth); if (actScopeDepth === 0) { var _queue = ReactCurrentActQueue.current; if (_queue !== null) { flushActQueue(_queue); ReactCurrentActQueue.current = null; } var _thenable = { then: function(resolve, reject) { if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } } }; return _thenable; } else { var _thenable2 = { then: function(resolve, reject) { resolve(returnValue); } }; return _thenable2; } } } } function popActScope(prevActScopeDepth) { { if (prevActScopeDepth !== actScopeDepth - 1) { error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { { var queue2 = ReactCurrentActQueue.current; if (queue2 !== null) { try { flushActQueue(queue2); enqueueTask(function() { if (queue2.length === 0) { ReactCurrentActQueue.current = null; resolve(returnValue); } else { recursivelyFlushAsyncActWork(returnValue, resolve, reject); } }); } catch (error2) { reject(error2); } } else { resolve(returnValue); } } } var isFlushing = false; function flushActQueue(queue2) { { if (!isFlushing) { isFlushing = true; var i2 = 0; try { for (; i2 < queue2.length; i2++) { var callback = queue2[i2]; do { callback = callback(true); } while (callback !== null); } queue2.length = 0; } catch (error2) { queue2 = queue2.slice(i2 + 1); throw error2; } finally { isFlushing = false; } } } } var createElement$1 = createElementWithValidation; var cloneElement$1 = cloneElementWithValidation; var createFactory = createFactoryWithValidation; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray4, only: onlyChild }; exports2.Children = Children; exports2.Component = Component7; exports2.Fragment = REACT_FRAGMENT_TYPE; exports2.Profiler = REACT_PROFILER_TYPE; exports2.PureComponent = PureComponent; exports2.StrictMode = REACT_STRICT_MODE_TYPE; exports2.Suspense = REACT_SUSPENSE_TYPE; exports2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; exports2.cloneElement = cloneElement$1; exports2.createContext = createContext2; exports2.createElement = createElement$1; exports2.createFactory = createFactory; exports2.createRef = createRef2; exports2.forwardRef = forwardRef3; exports2.isValidElement = isValidElement; exports2.lazy = lazy; exports2.memo = memo; exports2.startTransition = startTransition; exports2.unstable_act = act; exports2.useCallback = useCallback14; exports2.useContext = useContext2; exports2.useDebugValue = useDebugValue; exports2.useDeferredValue = useDeferredValue; exports2.useEffect = useEffect29; exports2.useId = useId16; exports2.useImperativeHandle = useImperativeHandle; exports2.useInsertionEffect = useInsertionEffect; exports2.useLayoutEffect = useLayoutEffect2; exports2.useMemo = useMemo14; exports2.useReducer = useReducer3; exports2.useRef = useRef3; exports2.useState = useState24; exports2.useSyncExternalStore = useSyncExternalStore; exports2.useTransition = useTransition; exports2.version = ReactVersion; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } } }); // node_modules/.pnpm/react@18.2.0/node_modules/react/index.js var require_react = __commonJS({ "node_modules/.pnpm/react@18.2.0/node_modules/react/index.js"(exports2, module2) { "use strict"; if (false) { module2.exports = null; } else { module2.exports = require_react_development(); } } }); // node_modules/.pnpm/lodash.debounce@4.0.8/node_modules/lodash.debounce/index.js var require_lodash2 = __commonJS({ "node_modules/.pnpm/lodash.debounce@4.0.8/node_modules/lodash.debounce/index.js"(exports2, module2) { var FUNC_ERROR_TEXT = "Expected a function"; var NAN = 0 / 0; var symbolTag = "[object Symbol]"; var reTrim = /^\s+|\s+$/g; var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; var reIsBinary = /^0b[01]+$/i; var reIsOctal = /^0o[0-7]+$/i; var freeParseInt = parseInt; var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root3 = freeGlobal || freeSelf || Function("return this")(); var objectProto = Object.prototype; var objectToString = objectProto.toString; var nativeMax = Math.max; var nativeMin = Math.min; var now = function() { return root3.Date.now(); }; function debounce4(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject10(options)) { leading = !!options.leading; maxing = "maxWait" in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = "trailing" in options ? !!options.trailing : trailing; } function invokeFunc(time2) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = void 0; lastInvokeTime = time2; result = func.apply(thisArg, args); return result; } function leadingEdge(time2) { lastInvokeTime = time2; timerId = setTimeout(timerExpired, wait); return leading ? invokeFunc(time2) : result; } function remainingWait(time2) { var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime, result2 = wait - timeSinceLastCall; return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2; } function shouldInvoke(time2) { var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime; return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; } function timerExpired() { var time2 = now(); if (shouldInvoke(time2)) { return trailingEdge(time2); } timerId = setTimeout(timerExpired, remainingWait(time2)); } function trailingEdge(time2) { timerId = void 0; if (trailing && lastArgs) { return invokeFunc(time2); } lastArgs = lastThis = void 0; return result; } function cancel() { if (timerId !== void 0) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = void 0; } function flush() { return timerId === void 0 ? result : trailingEdge(now()); } function debounced() { var time2 = now(), isInvoking = shouldInvoke(time2); lastArgs = arguments; lastThis = this; lastCallTime = time2; if (isInvoking) { if (timerId === void 0) { return leadingEdge(lastCallTime); } if (maxing) { timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === void 0) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } function isObject10(value) { var type2 = typeof value; return !!value && (type2 == "object" || type2 == "function"); } function isObjectLike(value) { return !!value && typeof value == "object"; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; } function toNumber(value) { if (typeof value == "number") { return value; } if (isSymbol(value)) { return NAN; } if (isObject10(value)) { var other = typeof value.valueOf == "function" ? value.valueOf() : value; value = isObject10(other) ? other + "" : other; } if (typeof value != "string") { return value === 0 ? value : +value; } value = value.replace(reTrim, ""); var isBinary2 = reIsBinary.test(value); return isBinary2 || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary2 ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } module2.exports = debounce4; } }); // node_modules/.pnpm/react-is@16.13.1/node_modules/react-is/cjs/react-is.development.js var require_react_is_development = __commonJS({ "node_modules/.pnpm/react-is@16.13.1/node_modules/react-is/cjs/react-is.development.js"(exports2) { "use strict"; if (true) { (function() { "use strict"; var hasSymbol = typeof Symbol === "function" && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 60103; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 60106; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 60107; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 60108; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 60114; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 60109; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 60110; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 60111; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 60111; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 60112; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113; var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 60120; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 60121; var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 60117; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 60118; var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 60119; function isValidElementType(type2) { return typeof type2 === "string" || typeof type2 === "function" || type2 === REACT_FRAGMENT_TYPE || type2 === REACT_CONCURRENT_MODE_TYPE || type2 === REACT_PROFILER_TYPE || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || typeof type2 === "object" && type2 !== null && (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || type2.$$typeof === REACT_FUNDAMENTAL_TYPE || type2.$$typeof === REACT_RESPONDER_TYPE || type2.$$typeof === REACT_SCOPE_TYPE || type2.$$typeof === REACT_BLOCK_TYPE); } function typeOf(object) { if (typeof object === "object" && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type2 = object.type; switch (type2) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type2; default: var $$typeofType = type2 && type2.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return void 0; } var AsyncMode = REACT_ASYNC_MODE_TYPE; var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode7 = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API."); } } return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isConcurrentMode(object) { return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } exports2.AsyncMode = AsyncMode; exports2.ConcurrentMode = ConcurrentMode; exports2.ContextConsumer = ContextConsumer; exports2.ContextProvider = ContextProvider; exports2.Element = Element; exports2.ForwardRef = ForwardRef; exports2.Fragment = Fragment; exports2.Lazy = Lazy; exports2.Memo = Memo; exports2.Portal = Portal; exports2.Profiler = Profiler; exports2.StrictMode = StrictMode7; exports2.Suspense = Suspense; exports2.isAsyncMode = isAsyncMode; exports2.isConcurrentMode = isConcurrentMode; exports2.isContextConsumer = isContextConsumer; exports2.isContextProvider = isContextProvider; exports2.isElement = isElement; exports2.isForwardRef = isForwardRef; exports2.isFragment = isFragment; exports2.isLazy = isLazy; exports2.isMemo = isMemo; exports2.isPortal = isPortal; exports2.isProfiler = isProfiler; exports2.isStrictMode = isStrictMode; exports2.isSuspense = isSuspense; exports2.isValidElementType = isValidElementType; exports2.typeOf = typeOf; })(); } } }); // node_modules/.pnpm/react-is@16.13.1/node_modules/react-is/index.js var require_react_is = __commonJS({ "node_modules/.pnpm/react-is@16.13.1/node_modules/react-is/index.js"(exports2, module2) { "use strict"; if (false) { module2.exports = null; } else { module2.exports = require_react_is_development(); } } }); // node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js var require_object_assign = __commonJS({ "node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js"(exports2, module2) { "use strict"; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty2 = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === void 0) { throw new TypeError("Object.assign cannot be called with null or undefined"); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } var test1 = new String("abc"); test1[5] = "de"; if (Object.getOwnPropertyNames(test1)[0] === "5") { return false; } var test2 = {}; for (var i2 = 0; i2 < 10; i2++) { test2["_" + String.fromCharCode(i2)] = i2; } var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { return test2[n2]; }); if (order2.join("") !== "0123456789") { return false; } var test3 = {}; "abcdefghijklmnopqrst".split("").forEach(function(letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { return false; } return true; } catch (err) { return false; } } module2.exports = shouldUseNative() ? Object.assign : function(target, source) { var from; var to = toObject(target); var symbols; for (var s2 = 1; s2 < arguments.length; s2++) { from = Object(arguments[s2]); for (var key in from) { if (hasOwnProperty2.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i2 = 0; i2 < symbols.length; i2++) { if (propIsEnumerable.call(from, symbols[i2])) { to[symbols[i2]] = from[symbols[i2]]; } } } } return to; }; } }); // node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/lib/ReactPropTypesSecret.js var require_ReactPropTypesSecret = __commonJS({ "node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports2, module2) { "use strict"; var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"; module2.exports = ReactPropTypesSecret; } }); // node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/lib/has.js var require_has = __commonJS({ "node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/lib/has.js"(exports2, module2) { module2.exports = Function.call.bind(Object.prototype.hasOwnProperty); } }); // node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/checkPropTypes.js var require_checkPropTypes = __commonJS({ "node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/checkPropTypes.js"(exports2, module2) { "use strict"; var printWarning = function() { }; if (true) { ReactPropTypesSecret = require_ReactPropTypesSecret(); loggedTypeFailures = {}; has6 = require_has(); printWarning = function(text) { var message = "Warning: " + text; if (typeof console !== "undefined") { console.error(message); } try { throw new Error(message); } catch (x2) { } }; } var ReactPropTypesSecret; var loggedTypeFailures; var has6; function checkPropTypes(typeSpecs, values, location2, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (has6(typeSpecs, typeSpecName)) { var error; try { if (typeof typeSpecs[typeSpecName] !== "function") { var err = Error((componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); err.name = "Invariant Violation"; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, ReactPropTypesSecret); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning((componentName || "React class") + ": type specification of " + location2 + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ""; printWarning("Failed " + location2 + " type: " + error.message + (stack != null ? stack : "")); } } } } } checkPropTypes.resetWarningCache = function() { if (true) { loggedTypeFailures = {}; } }; module2.exports = checkPropTypes; } }); // node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/factoryWithTypeCheckers.js var require_factoryWithTypeCheckers = __commonJS({ "node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/factoryWithTypeCheckers.js"(exports2, module2) { "use strict"; var ReactIs2 = require_react_is(); var assign = require_object_assign(); var ReactPropTypesSecret = require_ReactPropTypesSecret(); var has6 = require_has(); var checkPropTypes = require_checkPropTypes(); var printWarning = function() { }; if (true) { printWarning = function(text) { var message = "Warning: " + text; if (typeof console !== "undefined") { console.error(message); } try { throw new Error(message); } catch (x2) { } }; } function emptyFunctionThatReturnsNull() { return null; } module2.exports = function(isValidElement, throwOnDirectAccess) { var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === "function") { return iteratorFn; } } var ANONYMOUS = "<>"; var ReactPropTypes = { array: createPrimitiveTypeChecker("array"), bigint: createPrimitiveTypeChecker("bigint"), bool: createPrimitiveTypeChecker("boolean"), func: createPrimitiveTypeChecker("function"), number: createPrimitiveTypeChecker("number"), object: createPrimitiveTypeChecker("object"), string: createPrimitiveTypeChecker("string"), symbol: createPrimitiveTypeChecker("symbol"), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker }; function is2(x2, y2) { if (x2 === y2) { return x2 !== 0 || 1 / x2 === 1 / y2; } else { return x2 !== x2 && y2 !== y2; } } function PropTypeError(message, data) { this.message = message; this.data = data && typeof data === "object" ? data : {}; this.stack = ""; } PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate5) { if (true) { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location2, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { var err = new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"); err.name = "Invariant Violation"; throw err; } else if (typeof console !== "undefined") { var cacheKey = componentName + ":" + propName; if (!manualPropTypeCallCache[cacheKey] && manualPropTypeWarningCount < 3) { printWarning("You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError("The " + location2 + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`.")); } return new PropTypeError("The " + location2 + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`.")); } return null; } else { return validate5(props, propName, componentName, location2, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate5(props, propName, componentName, location2, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var preciseType = getPreciseType(propValue); return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."), { expectedType }); } return null; } return createChainableTypeChecker(validate5); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate5(props, propName, componentName, location2, propFullName) { if (typeof typeChecker !== "function") { return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf."); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.")); } for (var i2 = 0; i2 < propValue.length; i2++) { var error = typeChecker(propValue, i2, componentName, location2, propFullName + "[" + i2 + "]", ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate5); } function createElementTypeChecker() { function validate5(props, propName, componentName, location2, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement.")); } return null; } return createChainableTypeChecker(validate5); } function createElementTypeTypeChecker() { function validate5(props, propName, componentName, location2, propFullName) { var propValue = props[propName]; if (!ReactIs2.isValidElementType(propValue)) { var propType = getPropType(propValue); return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type.")); } return null; } return createChainableTypeChecker(validate5); } function createInstanceTypeChecker(expectedClass) { function validate5(props, propName, componentName, location2, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`.")); } return null; } return createChainableTypeChecker(validate5); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { if (true) { if (arguments.length > 1) { printWarning("Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."); } else { printWarning("Invalid argument supplied to oneOf, expected an array."); } } return emptyFunctionThatReturnsNull; } function validate5(props, propName, componentName, location2, propFullName) { var propValue = props[propName]; for (var i2 = 0; i2 < expectedValues.length; i2++) { if (is2(propValue, expectedValues[i2])) { return null; } } var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { var type2 = getPreciseType(value); if (type2 === "symbol") { return String(value); } return value; }); return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".")); } return createChainableTypeChecker(validate5); } function createObjectOfTypeChecker(typeChecker) { function validate5(props, propName, componentName, location2, propFullName) { if (typeof typeChecker !== "function") { return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf."); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object.")); } for (var key in propValue) { if (has6(propValue, key)) { var error = typeChecker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate5); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { true ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0; return emptyFunctionThatReturnsNull; } for (var i2 = 0; i2 < arrayOfTypeCheckers.length; i2++) { var checker = arrayOfTypeCheckers[i2]; if (typeof checker !== "function") { printWarning("Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i2 + "."); return emptyFunctionThatReturnsNull; } } function validate5(props, propName, componentName, location2, propFullName) { var expectedTypes = []; for (var i3 = 0; i3 < arrayOfTypeCheckers.length; i3++) { var checker2 = arrayOfTypeCheckers[i3]; var checkerResult = checker2(props, propName, componentName, location2, propFullName, ReactPropTypesSecret); if (checkerResult == null) { return null; } if (checkerResult.data && has6(checkerResult.data, "expectedType")) { expectedTypes.push(checkerResult.data.expectedType); } } var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : ""; return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + ".")); } return createChainableTypeChecker(validate5); } function createNodeChecker() { function validate5(props, propName, componentName, location2, propFullName) { if (!isNode3(props[propName])) { return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode.")); } return null; } return createChainableTypeChecker(validate5); } function invalidValidatorError(componentName, location2, propFullName, key, type2) { return new PropTypeError((componentName || "React class") + ": " + location2 + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type2 + "`."); } function createShapeTypeChecker(shapeTypes) { function validate5(props, propName, componentName, location2, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`.")); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (typeof checker !== "function") { return invalidValidatorError(componentName, location2, propFullName, key, getPreciseType(checker)); } var error = checker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate5); } function createStrictShapeTypeChecker(shapeTypes) { function validate5(props, propName, componentName, location2, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`.")); } var allKeys = assign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (has6(shapeTypes, key) && typeof checker !== "function") { return invalidValidatorError(componentName, location2, propFullName, key, getPreciseType(checker)); } if (!checker) { return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, " ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, " ")); } var error = checker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate5); } function isNode3(propValue) { switch (typeof propValue) { case "number": case "string": case "undefined": return true; case "boolean": return !propValue; case "object": if (Array.isArray(propValue)) { return propValue.every(isNode3); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode3(step.value)) { return false; } } } else { while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode3(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { if (propType === "symbol") { return true; } if (!propValue) { return false; } if (propValue["@@toStringTag"] === "Symbol") { return true; } if (typeof Symbol === "function" && propValue instanceof Symbol) { return true; } return false; } function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return "array"; } if (propValue instanceof RegExp) { return "object"; } if (isSymbol(propType, propValue)) { return "symbol"; } return propType; } function getPreciseType(propValue) { if (typeof propValue === "undefined" || propValue === null) { return "" + propValue; } var propType = getPropType(propValue); if (propType === "object") { if (propValue instanceof Date) { return "date"; } else if (propValue instanceof RegExp) { return "regexp"; } } return propType; } function getPostfixForTypeWarning(value) { var type2 = getPreciseType(value); switch (type2) { case "array": case "object": return "an " + type2; case "boolean": case "date": case "regexp": return "a " + type2; default: return type2; } } function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; } }); // node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/index.js var require_prop_types = __commonJS({ "node_modules/.pnpm/prop-types@15.8.1/node_modules/prop-types/index.js"(exports2, module2) { if (true) { ReactIs2 = require_react_is(); throwOnDirectAccess = true; module2.exports = require_factoryWithTypeCheckers()(ReactIs2.isElement, throwOnDirectAccess); } else { module2.exports = null(); } var ReactIs2; var throwOnDirectAccess; } }); // node_modules/.pnpm/regenerator-runtime@0.13.11/node_modules/regenerator-runtime/runtime.js var require_runtime2 = __commonJS({ "node_modules/.pnpm/regenerator-runtime@0.13.11/node_modules/regenerator-runtime/runtime.js"(exports2, module2) { var runtime = function(exports3) { "use strict"; var Op = Object.prototype; var hasOwn3 = Op.hasOwnProperty; var defineProperty = Object.defineProperty || function(obj, key, desc) { obj[key] = desc.value; }; var undefined2; var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define2(obj, key, value) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); return obj[key]; } try { define2({}, ""); } catch (err) { define2 = function(obj, key, value) { return obj[key] = value; }; } function wrap2(innerFn, outerFn, self2, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self2, context) }); return generator; } exports3.wrap = wrap2; function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; var ContinueSentinel = {}; function Generator() { } function GeneratorFunction() { } function GeneratorFunctionPrototype() { } var IteratorPrototype = {}; define2(IteratorPrototype, iteratorSymbol, function() { return this; }); var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn3.call(NativeIteratorPrototype, iteratorSymbol)) { IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = GeneratorFunctionPrototype; defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true }); defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: true }); GeneratorFunction.displayName = define2(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { define2(prototype, method, function(arg) { return this._invoke(method, arg); }); }); } exports3.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports3.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; define2(genFun, toStringTagSymbol, "GeneratorFunction"); } genFun.prototype = Object.create(Gp); return genFun; }; exports3.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn3.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function(value2) { invoke("next", value2, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function(unwrapped) { result.value = unwrapped; resolve(result); }, function(error) { return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } defineProperty(this, "_invoke", { value: enqueue }); } defineIteratorMethods(AsyncIterator.prototype); define2(AsyncIterator.prototype, asyncIteratorSymbol, function() { return this; }); exports3.AsyncIterator = AsyncIterator; exports3.async = function(innerFn, outerFn, self2, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator(wrap2(innerFn, outerFn, self2, tryLocsList), PromiseImpl); return exports3.isGeneratorFunction(outerFn) ? iter : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self2, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self2, context); if (record.type === "normal") { state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; context.method = "throw"; context.arg = record.arg; } } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method; var method = delegate.iterator[methodName]; if (method === undefined2) { context.delegate = null; if (methodName === "throw" && delegate.iterator["return"]) { context.method = "return"; context.arg = undefined2; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { return ContinueSentinel; } } if (methodName !== "return") { context.method = "throw"; context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (!info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; if (context.method !== "return") { context.method = "next"; context.arg = undefined2; } } else { return info; } context.delegate = null; return ContinueSentinel; } defineIteratorMethods(Gp); define2(Gp, toStringTagSymbol, "Generator"); define2(Gp, iteratorSymbol, function() { return this; }); define2(Gp, "toString", function() { return "[object Generator]"; }); function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports3.keys = function(val) { var object = Object(val); var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); return function next2() { while (keys.length) { var key2 = keys.pop(); if (key2 in object) { next2.value = key2; next2.done = false; return next2; } } next2.done = true; return next2; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i2 = -1, next2 = function next3() { while (++i2 < iterable.length) { if (hasOwn3.call(iterable, i2)) { next3.value = iterable[i2]; next3.done = false; return next3; } } next3.value = undefined2; next3.done = true; return next3; }; return next2.next = next2; } } return { next: doneResult }; } exports3.values = values; function doneResult() { return { value: undefined2, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; this.sent = this._sent = undefined2; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined2; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name2 in this) { if (name2.charAt(0) === "t" && hasOwn3.call(this, name2) && !isNaN(+name2.slice(1))) { this[name2] = undefined2; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception2) { if (this.done) { throw exception2; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception2; context.next = loc; if (caught) { context.method = "next"; context.arg = undefined2; } return !!caught; } for (var i2 = this.tryEntries.length - 1; i2 >= 0; --i2) { var entry = this.tryEntries[i2]; var record = entry.completion; if (entry.tryLoc === "root") { return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn3.call(entry, "catchLoc"); var hasFinally = hasOwn3.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type2, arg) { for (var i2 = this.tryEntries.length - 1; i2 >= 0; --i2) { var entry = this.tryEntries[i2]; if (entry.tryLoc <= this.prev && hasOwn3.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type2 === "break" || type2 === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type2; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i2 = this.tryEntries.length - 1; i2 >= 0; --i2) { var entry = this.tryEntries[i2]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i2 = this.tryEntries.length - 1; i2 >= 0; --i2) { var entry = this.tryEntries[i2]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName, nextLoc }; if (this.method === "next") { this.arg = undefined2; } return ContinueSentinel; } }; return exports3; }(typeof module2 === "object" ? module2.exports : {}); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { if (typeof globalThis === "object") { globalThis.regeneratorRuntime = runtime; } else { Function("r", "regeneratorRuntime = r")(runtime); } } } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/getId.js var require_getId = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/getId.js"(exports2, module2) { module2.exports = (prefix, cnt) => `${prefix}-${cnt}-${Math.random().toString(16).slice(3, 8)}`; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/createJob.js var require_createJob = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/createJob.js"(exports2, module2) { var getId = require_getId(); var jobCounter = 0; module2.exports = ({ id: _id, action, payload = {} }) => { let id2 = _id; if (typeof id2 === "undefined") { id2 = getId("Job", jobCounter); jobCounter += 1; } return { id: id2, action, payload }; }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/log.js var require_log2 = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/log.js"(exports2) { var logging = false; exports2.logging = logging; exports2.setLogging = (_logging) => { logging = _logging; }; exports2.log = (...args) => logging ? console.log.apply(exports2, args) : null; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/createScheduler.js var require_createScheduler = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/createScheduler.js"(exports2, module2) { var createJob = require_createJob(); var { log } = require_log2(); var getId = require_getId(); var schedulerCounter = 0; module2.exports = () => { const id2 = getId("Scheduler", schedulerCounter); const workers = {}; const runningWorkers = {}; let jobQueue = []; schedulerCounter += 1; const getQueueLen = () => jobQueue.length; const getNumWorkers = () => Object.keys(workers).length; const dequeue = () => { if (jobQueue.length !== 0) { const wIds = Object.keys(workers); for (let i2 = 0; i2 < wIds.length; i2 += 1) { if (typeof runningWorkers[wIds[i2]] === "undefined") { jobQueue[0](workers[wIds[i2]]); break; } } } }; const queue2 = (action, payload) => new Promise((resolve, reject) => { const job = createJob({ action, payload }); jobQueue.push(async (w2) => { jobQueue.shift(); runningWorkers[w2.id] = job; try { resolve(await w2[action].apply(exports2, [...payload, job.id])); } catch (err) { reject(err); } finally { delete runningWorkers[w2.id]; dequeue(); } }); log(`[${id2}]: Add ${job.id} to JobQueue`); log(`[${id2}]: JobQueue length=${jobQueue.length}`); dequeue(); }); const addWorker = (w2) => { workers[w2.id] = w2; log(`[${id2}]: Add ${w2.id}`); log(`[${id2}]: Number of workers=${getNumWorkers()}`); dequeue(); return w2.id; }; const addJob = async (action, ...payload) => { if (getNumWorkers() === 0) { throw Error(`[${id2}]: You need to have at least one worker before adding jobs`); } return queue2(action, payload); }; const terminate = async () => { Object.keys(workers).forEach(async (wid) => { await workers[wid].terminate(); }); jobQueue = []; }; return { addWorker, addJob, terminate, getQueueLen, getNumWorkers }; }; } }); // node_modules/.pnpm/is-electron@2.2.2/node_modules/is-electron/index.js var require_is_electron = __commonJS({ "node_modules/.pnpm/is-electron@2.2.2/node_modules/is-electron/index.js"(exports2, module2) { function isElectron() { if (typeof window !== "undefined" && typeof window.process === "object" && window.process.type === "renderer") { return true; } if (typeof process !== "undefined" && typeof process.versions === "object" && !!process.versions.electron) { return true; } if (typeof navigator === "object" && typeof navigator.userAgent === "string" && navigator.userAgent.indexOf("Electron") >= 0) { return true; } return false; } module2.exports = isElectron; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/getEnvironment.js var require_getEnvironment = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/getEnvironment.js"(exports2, module2) { var isElectron = require_is_electron(); module2.exports = (key) => { const env = {}; if (typeof WorkerGlobalScope !== "undefined") { env.type = "webworker"; } else if (isElectron()) { env.type = "electron"; } else if (typeof document === "object") { env.type = "browser"; } else if (typeof process === "object" && typeof require === "function") { env.type = "node"; } if (typeof key === "undefined") { return env; } return env[key]; }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/resolvePaths.js var require_resolvePaths = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/resolvePaths.js"(exports2, module2) { var isBrowser4 = require_getEnvironment()("type") === "browser"; var resolveURL = isBrowser4 ? (s2) => new URL(s2, window.location.href).href : (s2) => s2; module2.exports = (options) => { const opts = { ...options }; ["corePath", "workerPath", "langPath"].forEach((key) => { if (options[key]) { opts[key] = resolveURL(opts[key]); } }); return opts; }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/circularize.js var require_circularize = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/utils/circularize.js"(exports2, module2) { module2.exports = (page) => { const blocks2 = []; const paragraphs = []; const lines = []; const words = []; const symbols = []; if (page.blocks) { page.blocks.forEach((block) => { block.paragraphs.forEach((paragraph) => { paragraph.lines.forEach((line) => { line.words.forEach((word) => { word.symbols.forEach((sym) => { symbols.push({ ...sym, page, block, paragraph, line, word }); }); words.push({ ...word, page, block, paragraph, line }); }); lines.push({ ...line, page, block, paragraph }); }); paragraphs.push({ ...paragraph, page, block }); }); blocks2.push({ ...block, page }); }); } return { ...page, blocks: blocks2, paragraphs, lines, words, symbols }; }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/OEM.js var require_OEM = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/OEM.js"(exports2, module2) { module2.exports = { TESSERACT_ONLY: 0, LSTM_ONLY: 1, TESSERACT_LSTM_COMBINED: 2, DEFAULT: 3 }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/config.js var require_config = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/config.js"(exports2, module2) { var OEM = require_OEM(); module2.exports = { defaultOEM: OEM.DEFAULT }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/package.json var require_package = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/package.json"(exports2, module2) { module2.exports = { name: "tesseract.js", version: "4.1.4", description: "Pure Javascript Multilingual OCR", main: "src/index.js", types: "src/index.d.ts", unpkg: "dist/tesseract.min.js", jsdelivr: "dist/tesseract.min.js", scripts: { start: "node scripts/server.js", build: "rimraf dist && webpack --config scripts/webpack.config.prod.js && rollup -c scripts/rollup.esm.mjs", "profile:tesseract": "webpack-bundle-analyzer dist/tesseract-stats.json", "profile:worker": "webpack-bundle-analyzer dist/worker-stats.json", prepublishOnly: "npm run build", wait: "rimraf dist && wait-on http://localhost:3000/dist/tesseract.dev.js", test: "npm-run-all -p -r start test:all", "test:all": "npm-run-all wait test:browser:* test:node:all", "test:node": "nyc mocha --exit --bail --require ./scripts/test-helper.js", "test:node:all": "npm run test:node -- ./tests/*.test.js", "test:browser-tpl": "mocha-headless-chrome -a incognito -a no-sandbox -a disable-setuid-sandbox -a disable-logging -t 300000", "test:browser:detect": "npm run test:browser-tpl -- -f ./tests/detect.test.html", "test:browser:recognize": "npm run test:browser-tpl -- -f ./tests/recognize.test.html", "test:browser:scheduler": "npm run test:browser-tpl -- -f ./tests/scheduler.test.html", "test:browser:FS": "npm run test:browser-tpl -- -f ./tests/FS.test.html", lint: "eslint src", "lint:fix": "eslint --fix src", postinstall: "opencollective-postinstall || true" }, browser: { "./src/worker/node/index.js": "./src/worker/browser/index.js" }, author: "", contributors: [ "jeromewu" ], license: "Apache-2.0", devDependencies: { "@babel/core": "^7.21.4", "@babel/eslint-parser": "^7.21.3", "@babel/preset-env": "^7.21.4", "@rollup/plugin-commonjs": "^24.1.0", acorn: "^8.8.2", "babel-loader": "^9.1.2", buffer: "^6.0.3", cors: "^2.8.5", eslint: "^7.32.0", "eslint-config-airbnb-base": "^14.2.1", "eslint-plugin-import": "^2.27.5", "expect.js": "^0.3.1", express: "^4.18.2", mocha: "^10.2.0", "mocha-headless-chrome": "^4.0.0", "npm-run-all": "^4.1.5", nyc: "^15.1.0", rimraf: "^5.0.0", rollup: "^3.20.7", "wait-on": "^7.0.1", webpack: "^5.79.0", "webpack-bundle-analyzer": "^4.8.0", "webpack-cli": "^5.0.1", "webpack-dev-middleware": "^6.0.2", "rollup-plugin-sourcemaps": "^0.6.3" }, dependencies: { "bmp-js": "^0.1.0", "idb-keyval": "^6.2.0", "is-electron": "^2.2.2", "is-url": "^1.2.4", "node-fetch": "^2.6.9", "opencollective-postinstall": "^2.0.3", "regenerator-runtime": "^0.13.3", "tesseract.js-core": "^4.0.4", "wasm-feature-detect": "^1.2.11", zlibjs: "^0.3.1" }, overrides: { "@rollup/pluginutils": "^5.0.2" }, repository: { type: "git", url: "https://github.com/naptha/tesseract.js.git" }, bugs: { url: "https://github.com/naptha/tesseract.js/issues" }, homepage: "https://github.com/naptha/tesseract.js", collective: { type: "opencollective", url: "https://opencollective.com/tesseractjs" } }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/defaultOptions.js var require_defaultOptions = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/defaultOptions.js"(exports2, module2) { module2.exports = { langPath: "https://tessdata.projectnaptha.com/4.0.0", workerBlobURL: true, logger: () => { } }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/defaultOptions.js var require_defaultOptions2 = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/defaultOptions.js"(exports2, module2) { var resolveURL = (s2) => new URL(s2, window.location.href).href; var { version: version3 } = require_package(); var defaultOptions2 = require_defaultOptions(); module2.exports = { ...defaultOptions2, workerPath: typeof process !== "undefined" && process.env.TESS_ENV === "development" ? resolveURL(`/dist/worker.dev.js?nocache=${Math.random().toString(36).slice(3)}`) : `https://cdn.jsdelivr.net/npm/tesseract.js@v${version3}/dist/worker.min.js`, corePath: null }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/spawnWorker.js var require_spawnWorker = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/spawnWorker.js"(exports2, module2) { module2.exports = ({ workerPath, workerBlobURL }) => { let worker; if (Blob && URL && workerBlobURL) { const blob = new Blob([`importScripts("${workerPath}");`], { type: "application/javascript" }); worker = new Worker(URL.createObjectURL(blob)); } else { worker = new Worker(workerPath); } return worker; }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/terminateWorker.js var require_terminateWorker = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/terminateWorker.js"(exports2, module2) { module2.exports = (worker) => { worker.terminate(); }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/onMessage.js var require_onMessage = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/onMessage.js"(exports2, module2) { module2.exports = (worker, handler) => { worker.onmessage = ({ data }) => { handler(data); }; }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/send.js var require_send = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/send.js"(exports2, module2) { module2.exports = async (worker, packet) => { worker.postMessage(packet); }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/loadImage.js var require_loadImage = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/loadImage.js"(exports2, module2) { var readFromBlobOrFile = (blob) => new Promise((resolve, reject) => { const fileReader = new FileReader(); fileReader.onload = () => { resolve(fileReader.result); }; fileReader.onerror = ({ target: { error: { code } } }) => { reject(Error(`File could not be read! Code=${code}`)); }; fileReader.readAsArrayBuffer(blob); }); var loadImage = async (image) => { let data = image; if (typeof image === "undefined") { return "undefined"; } if (typeof image === "string") { if (/data:image\/([a-zA-Z]*);base64,([^"]*)/.test(image)) { data = atob(image.split(",")[1]).split("").map((c2) => c2.charCodeAt(0)); } else { const resp = await fetch(image); data = await resp.arrayBuffer(); } } else if (typeof HTMLElement !== "undefined" && image instanceof HTMLElement) { if (image.tagName === "IMG") { data = await loadImage(image.src); } if (image.tagName === "VIDEO") { data = await loadImage(image.poster); } if (image.tagName === "CANVAS") { await new Promise((resolve) => { image.toBlob(async (blob) => { data = await readFromBlobOrFile(blob); resolve(); }); }); } } else if (typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas) { const blob = await image.convertToBlob(); data = await readFromBlobOrFile(blob); } else if (image instanceof File || image instanceof Blob) { data = await readFromBlobOrFile(image); } return new Uint8Array(data); }; module2.exports = loadImage; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/index.js var require_browser2 = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/worker/browser/index.js"(exports2, module2) { var defaultOptions2 = require_defaultOptions2(); var spawnWorker = require_spawnWorker(); var terminateWorker = require_terminateWorker(); var onMessage = require_onMessage(); var send = require_send(); var loadImage = require_loadImage(); module2.exports = { defaultOptions: defaultOptions2, spawnWorker, terminateWorker, onMessage, send, loadImage }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/createWorker.js var require_createWorker = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/createWorker.js"(exports2, module2) { var resolvePaths = require_resolvePaths(); var circularize = require_circularize(); var createJob = require_createJob(); var { log } = require_log2(); var getId = require_getId(); var { defaultOEM } = require_config(); var { defaultOptions: defaultOptions2, spawnWorker, terminateWorker, onMessage, loadImage, send } = require_browser2(); var workerCounter = 0; module2.exports = async (_options = {}) => { const id2 = getId("Worker", workerCounter); const { logger: logger41, errorHandler, ...options } = resolvePaths({ ...defaultOptions2, ..._options }); const resolves = {}; const rejects = {}; let workerResReject; let workerResResolve; const workerRes = new Promise((resolve, reject) => { workerResResolve = resolve; workerResReject = reject; }); const workerError = (event2) => { workerResReject(event2.message); }; let worker = spawnWorker(options); worker.onerror = workerError; workerCounter += 1; const setResolve = (action, res) => { resolves[action] = res; }; const setReject = (action, rej) => { rejects[action] = rej; }; const startJob = ({ id: jobId, action, payload }) => new Promise((resolve, reject) => { log(`[${id2}]: Start ${jobId}, action=${action}`); setResolve(action, resolve); setReject(action, reject); send(worker, { workerId: id2, jobId, action, payload }); }); const load4 = () => console.warn("`load` is depreciated and should be removed from code (workers now come pre-loaded)"); const loadInternal = (jobId) => startJob(createJob({ id: jobId, action: "load", payload: { options } })); const writeText = (path, text, jobId) => startJob(createJob({ id: jobId, action: "FS", payload: { method: "writeFile", args: [path, text] } })); const readText = (path, jobId) => startJob(createJob({ id: jobId, action: "FS", payload: { method: "readFile", args: [path, { encoding: "utf8" }] } })); const removeFile = (path, jobId) => startJob(createJob({ id: jobId, action: "FS", payload: { method: "unlink", args: [path] } })); const FS = (method, args, jobId) => startJob(createJob({ id: jobId, action: "FS", payload: { method, args } })); const loadLanguage = (langs = "eng", jobId) => startJob(createJob({ id: jobId, action: "loadLanguage", payload: { langs, options } })); const initialize = (langs = "eng", oem = defaultOEM, config, jobId) => startJob(createJob({ id: jobId, action: "initialize", payload: { langs, oem, config } })); const setParameters = (params = {}, jobId) => startJob(createJob({ id: jobId, action: "setParameters", payload: { params } })); const recognize = async (image, opts = {}, output = { blocks: true, text: true, hocr: true, tsv: true }, jobId) => startJob(createJob({ id: jobId, action: "recognize", payload: { image: await loadImage(image), options: opts, output } })); const getPDF = (title = "Tesseract OCR Result", textonly = false, jobId) => { console.log("`getPDF` function is depreciated. `recognize` option `savePDF` should be used instead."); return startJob(createJob({ id: jobId, action: "getPDF", payload: { title, textonly } })); }; const detect = async (image, jobId) => startJob(createJob({ id: jobId, action: "detect", payload: { image: await loadImage(image) } })); const terminate = async () => { if (worker !== null) { terminateWorker(worker); worker = null; } return Promise.resolve(); }; onMessage(worker, ({ workerId, jobId, status, action, data }) => { if (status === "resolve") { log(`[${workerId}]: Complete ${jobId}`); let d2 = data; if (action === "recognize") { d2 = circularize(data); } else if (action === "getPDF") { d2 = Array.from({ ...data, length: Object.keys(data).length }); } resolves[action]({ jobId, data: d2 }); } else if (status === "reject") { rejects[action](data); if (action === "load") workerResReject(data); if (errorHandler) { errorHandler(data); } else { throw Error(data); } } else if (status === "progress") { logger41({ ...data, userJobId: jobId }); } }); const resolveObj = { id: id2, worker, setResolve, setReject, load: load4, writeText, readText, removeFile, FS, loadLanguage, initialize, setParameters, recognize, getPDF, detect, terminate }; loadInternal().then(() => workerResResolve(resolveObj)).catch(() => { }); return workerRes; }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/Tesseract.js var require_Tesseract = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/Tesseract.js"(exports2, module2) { var createWorker = require_createWorker(); var recognize = async (image, langs, options) => { const worker = await createWorker(options); await worker.loadLanguage(langs); await worker.initialize(langs); return worker.recognize(image).finally(async () => { await worker.terminate(); }); }; var detect = async (image, options) => { const worker = await createWorker(options); await worker.loadLanguage("osd"); await worker.initialize("osd"); return worker.detect(image).finally(async () => { await worker.terminate(); }); }; module2.exports = { recognize, detect }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/languages.js var require_languages = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/languages.js"(exports2, module2) { module2.exports = { AFR: "afr", AMH: "amh", ARA: "ara", ASM: "asm", AZE: "aze", AZE_CYRL: "aze_cyrl", BEL: "bel", BEN: "ben", BOD: "bod", BOS: "bos", BUL: "bul", CAT: "cat", CEB: "ceb", CES: "ces", CHI_SIM: "chi_sim", CHI_TRA: "chi_tra", CHR: "chr", CYM: "cym", DAN: "dan", DEU: "deu", DZO: "dzo", ELL: "ell", ENG: "eng", ENM: "enm", EPO: "epo", EST: "est", EUS: "eus", FAS: "fas", FIN: "fin", FRA: "fra", FRK: "frk", FRM: "frm", GLE: "gle", GLG: "glg", GRC: "grc", GUJ: "guj", HAT: "hat", HEB: "heb", HIN: "hin", HRV: "hrv", HUN: "hun", IKU: "iku", IND: "ind", ISL: "isl", ITA: "ita", ITA_OLD: "ita_old", JAV: "jav", JPN: "jpn", KAN: "kan", KAT: "kat", KAT_OLD: "kat_old", KAZ: "kaz", KHM: "khm", KIR: "kir", KOR: "kor", KUR: "kur", LAO: "lao", LAT: "lat", LAV: "lav", LIT: "lit", MAL: "mal", MAR: "mar", MKD: "mkd", MLT: "mlt", MSA: "msa", MYA: "mya", NEP: "nep", NLD: "nld", NOR: "nor", ORI: "ori", PAN: "pan", POL: "pol", POR: "por", PUS: "pus", RON: "ron", RUS: "rus", SAN: "san", SIN: "sin", SLK: "slk", SLV: "slv", SPA: "spa", SPA_OLD: "spa_old", SQI: "sqi", SRP: "srp", SRP_LATN: "srp_latn", SWA: "swa", SWE: "swe", SYR: "syr", TAM: "tam", TEL: "tel", TGK: "tgk", TGL: "tgl", THA: "tha", TIR: "tir", TUR: "tur", UIG: "uig", UKR: "ukr", URD: "urd", UZB: "uzb", UZB_CYRL: "uzb_cyrl", VIE: "vie", YID: "yid" }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/PSM.js var require_PSM = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/constants/PSM.js"(exports2, module2) { module2.exports = { OSD_ONLY: "0", AUTO_OSD: "1", AUTO_ONLY: "2", AUTO: "3", SINGLE_COLUMN: "4", SINGLE_BLOCK_VERT_TEXT: "5", SINGLE_BLOCK: "6", SINGLE_LINE: "7", SINGLE_WORD: "8", CIRCLE_WORD: "9", SINGLE_CHAR: "10", SPARSE_TEXT: "11", SPARSE_TEXT_OSD: "12", RAW_LINE: "13" }; } }); // node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/index.js var require_src = __commonJS({ "node_modules/.pnpm/tesseract.js@4.1.4/node_modules/tesseract.js/src/index.js"(exports2, module2) { require_runtime2(); var createScheduler = require_createScheduler(); var createWorker = require_createWorker(); var Tesseract3 = require_Tesseract(); var languages2 = require_languages(); var OEM = require_OEM(); var PSM = require_PSM(); var { setLogging } = require_log2(); module2.exports = { languages: languages2, OEM, PSM, createScheduler, createWorker, setLogging, ...Tesseract3 }; } }); // node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/defaults.js var require_defaults = __commonJS({ "node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/defaults.js"(exports2) { (function() { exports2.defaults = { "0.1": { explicitCharkey: false, trim: true, normalize: true, normalizeTags: false, attrkey: "@", charkey: "#", explicitArray: false, ignoreAttrs: false, mergeAttrs: false, explicitRoot: false, validator: null, xmlns: false, explicitChildren: false, childkey: "@@", charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, emptyTag: "" }, "0.2": { explicitCharkey: false, trim: false, normalize: false, normalizeTags: false, attrkey: "$", charkey: "_", explicitArray: true, ignoreAttrs: false, mergeAttrs: false, explicitRoot: true, validator: null, xmlns: false, explicitChildren: false, preserveChildrenOrder: false, childkey: "$$", charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, rootName: "root", xmldec: { "version": "1.0", "encoding": "UTF-8", "standalone": true }, doctype: null, renderOpts: { "pretty": true, "indent": " ", "newline": "\n" }, headless: false, chunkSize: 1e4, emptyTag: "", cdata: false } }; }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/Utility.js var require_Utility = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/Utility.js"(exports2, module2) { (function() { var assign, getValue3, isArray, isEmpty6, isFunction, isObject10, isPlainObject4, slice = [].slice, hasProp = {}.hasOwnProperty; assign = function() { var i2, key, len, source, sources, target; target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : []; if (isFunction(Object.assign)) { Object.assign.apply(null, arguments); } else { for (i2 = 0, len = sources.length; i2 < len; i2++) { source = sources[i2]; if (source != null) { for (key in source) { if (!hasProp.call(source, key)) continue; target[key] = source[key]; } } } } return target; }; isFunction = function(val) { return !!val && Object.prototype.toString.call(val) === "[object Function]"; }; isObject10 = function(val) { var ref; return !!val && ((ref = typeof val) === "function" || ref === "object"); }; isArray = function(val) { if (isFunction(Array.isArray)) { return Array.isArray(val); } else { return Object.prototype.toString.call(val) === "[object Array]"; } }; isEmpty6 = function(val) { var key; if (isArray(val)) { return !val.length; } else { for (key in val) { if (!hasProp.call(val, key)) continue; return false; } return true; } }; isPlainObject4 = function(val) { var ctor, proto; return isObject10(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object); }; getValue3 = function(obj) { if (isFunction(obj.valueOf)) { return obj.valueOf(); } else { return obj; } }; module2.exports.assign = assign; module2.exports.isFunction = isFunction; module2.exports.isObject = isObject10; module2.exports.isArray = isArray; module2.exports.isEmpty = isEmpty6; module2.exports.isPlainObject = isPlainObject4; module2.exports.getValue = getValue3; }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMImplementation.js var require_XMLDOMImplementation = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMImplementation.js"(exports2, module2) { (function() { var XMLDOMImplementation; module2.exports = XMLDOMImplementation = function() { function XMLDOMImplementation2() { } XMLDOMImplementation2.prototype.hasFeature = function(feature, version3) { return true; }; XMLDOMImplementation2.prototype.createDocumentType = function(qualifiedName, publicId, systemId) { throw new Error("This DOM method is not implemented."); }; XMLDOMImplementation2.prototype.createDocument = function(namespaceURI, qualifiedName, doctype) { throw new Error("This DOM method is not implemented."); }; XMLDOMImplementation2.prototype.createHTMLDocument = function(title) { throw new Error("This DOM method is not implemented."); }; XMLDOMImplementation2.prototype.getFeature = function(feature, version3) { throw new Error("This DOM method is not implemented."); }; return XMLDOMImplementation2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js var require_XMLDOMErrorHandler = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js"(exports2, module2) { (function() { var XMLDOMErrorHandler; module2.exports = XMLDOMErrorHandler = function() { function XMLDOMErrorHandler2() { } XMLDOMErrorHandler2.prototype.handleError = function(error) { throw new Error(error); }; return XMLDOMErrorHandler2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMStringList.js var require_XMLDOMStringList = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMStringList.js"(exports2, module2) { (function() { var XMLDOMStringList; module2.exports = XMLDOMStringList = function() { function XMLDOMStringList2(arr) { this.arr = arr || []; } Object.defineProperty(XMLDOMStringList2.prototype, "length", { get: function() { return this.arr.length; } }); XMLDOMStringList2.prototype.item = function(index2) { return this.arr[index2] || null; }; XMLDOMStringList2.prototype.contains = function(str3) { return this.arr.indexOf(str3) !== -1; }; return XMLDOMStringList2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js var require_XMLDOMConfiguration = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js"(exports2, module2) { (function() { var XMLDOMConfiguration, XMLDOMErrorHandler, XMLDOMStringList; XMLDOMErrorHandler = require_XMLDOMErrorHandler(); XMLDOMStringList = require_XMLDOMStringList(); module2.exports = XMLDOMConfiguration = function() { function XMLDOMConfiguration2() { var clonedSelf; this.defaultParams = { "canonical-form": false, "cdata-sections": false, "comments": false, "datatype-normalization": false, "element-content-whitespace": true, "entities": true, "error-handler": new XMLDOMErrorHandler(), "infoset": true, "validate-if-schema": false, "namespaces": true, "namespace-declarations": true, "normalize-characters": false, "schema-location": "", "schema-type": "", "split-cdata-sections": true, "validate": false, "well-formed": true }; this.params = clonedSelf = Object.create(this.defaultParams); } Object.defineProperty(XMLDOMConfiguration2.prototype, "parameterNames", { get: function() { return new XMLDOMStringList(Object.keys(this.defaultParams)); } }); XMLDOMConfiguration2.prototype.getParameter = function(name2) { if (this.params.hasOwnProperty(name2)) { return this.params[name2]; } else { return null; } }; XMLDOMConfiguration2.prototype.canSetParameter = function(name2, value) { return true; }; XMLDOMConfiguration2.prototype.setParameter = function(name2, value) { if (value != null) { return this.params[name2] = value; } else { return delete this.params[name2]; } }; return XMLDOMConfiguration2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/NodeType.js var require_NodeType = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/NodeType.js"(exports2, module2) { (function() { module2.exports = { Element: 1, Attribute: 2, Text: 3, CData: 4, EntityReference: 5, EntityDeclaration: 6, ProcessingInstruction: 7, Comment: 8, Document: 9, DocType: 10, DocumentFragment: 11, NotationDeclaration: 12, Declaration: 201, Raw: 202, AttributeDeclaration: 203, ElementDeclaration: 204, Dummy: 205 }; }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLAttribute.js var require_XMLAttribute = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLAttribute.js"(exports2, module2) { (function() { var NodeType, XMLAttribute, XMLNode; NodeType = require_NodeType(); XMLNode = require_XMLNode(); module2.exports = XMLAttribute = function() { function XMLAttribute2(parent, name2, value) { this.parent = parent; if (this.parent) { this.options = this.parent.options; this.stringify = this.parent.stringify; } if (name2 == null) { throw new Error("Missing attribute name. " + this.debugInfo(name2)); } this.name = this.stringify.name(name2); this.value = this.stringify.attValue(value); this.type = NodeType.Attribute; this.isId = false; this.schemaTypeInfo = null; } Object.defineProperty(XMLAttribute2.prototype, "nodeType", { get: function() { return this.type; } }); Object.defineProperty(XMLAttribute2.prototype, "ownerElement", { get: function() { return this.parent; } }); Object.defineProperty(XMLAttribute2.prototype, "textContent", { get: function() { return this.value; }, set: function(value) { return this.value = value || ""; } }); Object.defineProperty(XMLAttribute2.prototype, "namespaceURI", { get: function() { return ""; } }); Object.defineProperty(XMLAttribute2.prototype, "prefix", { get: function() { return ""; } }); Object.defineProperty(XMLAttribute2.prototype, "localName", { get: function() { return this.name; } }); Object.defineProperty(XMLAttribute2.prototype, "specified", { get: function() { return true; } }); XMLAttribute2.prototype.clone = function() { return Object.create(this); }; XMLAttribute2.prototype.toString = function(options) { return this.options.writer.attribute(this, this.options.writer.filterOptions(options)); }; XMLAttribute2.prototype.debugInfo = function(name2) { name2 = name2 || this.name; if (name2 == null) { return "parent: <" + this.parent.name + ">"; } else { return "attribute: {" + name2 + "}, parent: <" + this.parent.name + ">"; } }; XMLAttribute2.prototype.isEqualNode = function(node) { if (node.namespaceURI !== this.namespaceURI) { return false; } if (node.prefix !== this.prefix) { return false; } if (node.localName !== this.localName) { return false; } if (node.value !== this.value) { return false; } return true; }; return XMLAttribute2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js var require_XMLNamedNodeMap = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js"(exports2, module2) { (function() { var XMLNamedNodeMap; module2.exports = XMLNamedNodeMap = function() { function XMLNamedNodeMap2(nodes) { this.nodes = nodes; } Object.defineProperty(XMLNamedNodeMap2.prototype, "length", { get: function() { return Object.keys(this.nodes).length || 0; } }); XMLNamedNodeMap2.prototype.clone = function() { return this.nodes = null; }; XMLNamedNodeMap2.prototype.getNamedItem = function(name2) { return this.nodes[name2]; }; XMLNamedNodeMap2.prototype.setNamedItem = function(node) { var oldNode; oldNode = this.nodes[node.nodeName]; this.nodes[node.nodeName] = node; return oldNode || null; }; XMLNamedNodeMap2.prototype.removeNamedItem = function(name2) { var oldNode; oldNode = this.nodes[name2]; delete this.nodes[name2]; return oldNode || null; }; XMLNamedNodeMap2.prototype.item = function(index2) { return this.nodes[Object.keys(this.nodes)[index2]] || null; }; XMLNamedNodeMap2.prototype.getNamedItemNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented."); }; XMLNamedNodeMap2.prototype.setNamedItemNS = function(node) { throw new Error("This DOM method is not implemented."); }; XMLNamedNodeMap2.prototype.removeNamedItemNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented."); }; return XMLNamedNodeMap2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLElement.js var require_XMLElement = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLElement.js"(exports2, module2) { (function() { var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue3, isFunction, isObject10, ref, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = require_Utility(), isObject10 = ref.isObject, isFunction = ref.isFunction, getValue3 = ref.getValue; XMLNode = require_XMLNode(); NodeType = require_NodeType(); XMLAttribute = require_XMLAttribute(); XMLNamedNodeMap = require_XMLNamedNodeMap(); module2.exports = XMLElement = function(superClass) { extend4(XMLElement2, superClass); function XMLElement2(parent, name2, attributes) { var child, j2, len, ref1; XMLElement2.__super__.constructor.call(this, parent); if (name2 == null) { throw new Error("Missing element name. " + this.debugInfo()); } this.name = this.stringify.name(name2); this.type = NodeType.Element; this.attribs = {}; this.schemaTypeInfo = null; if (attributes != null) { this.attribute(attributes); } if (parent.type === NodeType.Document) { this.isRoot = true; this.documentObject = parent; parent.rootObject = this; if (parent.children) { ref1 = parent.children; for (j2 = 0, len = ref1.length; j2 < len; j2++) { child = ref1[j2]; if (child.type === NodeType.DocType) { child.name = this.name; break; } } } } } Object.defineProperty(XMLElement2.prototype, "tagName", { get: function() { return this.name; } }); Object.defineProperty(XMLElement2.prototype, "namespaceURI", { get: function() { return ""; } }); Object.defineProperty(XMLElement2.prototype, "prefix", { get: function() { return ""; } }); Object.defineProperty(XMLElement2.prototype, "localName", { get: function() { return this.name; } }); Object.defineProperty(XMLElement2.prototype, "id", { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); Object.defineProperty(XMLElement2.prototype, "className", { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); Object.defineProperty(XMLElement2.prototype, "classList", { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); Object.defineProperty(XMLElement2.prototype, "attributes", { get: function() { if (!this.attributeMap || !this.attributeMap.nodes) { this.attributeMap = new XMLNamedNodeMap(this.attribs); } return this.attributeMap; } }); XMLElement2.prototype.clone = function() { var att, attName, clonedSelf, ref1; clonedSelf = Object.create(this); if (clonedSelf.isRoot) { clonedSelf.documentObject = null; } clonedSelf.attribs = {}; ref1 = this.attribs; for (attName in ref1) { if (!hasProp.call(ref1, attName)) continue; att = ref1[attName]; clonedSelf.attribs[attName] = att.clone(); } clonedSelf.children = []; this.children.forEach(function(child) { var clonedChild; clonedChild = child.clone(); clonedChild.parent = clonedSelf; return clonedSelf.children.push(clonedChild); }); return clonedSelf; }; XMLElement2.prototype.attribute = function(name2, value) { var attName, attValue; if (name2 != null) { name2 = getValue3(name2); } if (isObject10(name2)) { for (attName in name2) { if (!hasProp.call(name2, attName)) continue; attValue = name2[attName]; this.attribute(attName, attValue); } } else { if (isFunction(value)) { value = value.apply(); } if (this.options.keepNullAttributes && value == null) { this.attribs[name2] = new XMLAttribute(this, name2, ""); } else if (value != null) { this.attribs[name2] = new XMLAttribute(this, name2, value); } } return this; }; XMLElement2.prototype.removeAttribute = function(name2) { var attName, j2, len; if (name2 == null) { throw new Error("Missing attribute name. " + this.debugInfo()); } name2 = getValue3(name2); if (Array.isArray(name2)) { for (j2 = 0, len = name2.length; j2 < len; j2++) { attName = name2[j2]; delete this.attribs[attName]; } } else { delete this.attribs[name2]; } return this; }; XMLElement2.prototype.toString = function(options) { return this.options.writer.element(this, this.options.writer.filterOptions(options)); }; XMLElement2.prototype.att = function(name2, value) { return this.attribute(name2, value); }; XMLElement2.prototype.a = function(name2, value) { return this.attribute(name2, value); }; XMLElement2.prototype.getAttribute = function(name2) { if (this.attribs.hasOwnProperty(name2)) { return this.attribs[name2].value; } else { return null; } }; XMLElement2.prototype.setAttribute = function(name2, value) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getAttributeNode = function(name2) { if (this.attribs.hasOwnProperty(name2)) { return this.attribs[name2]; } else { return null; } }; XMLElement2.prototype.setAttributeNode = function(newAttr) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.removeAttributeNode = function(oldAttr) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getElementsByTagName = function(name2) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getAttributeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.removeAttributeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getAttributeNodeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.setAttributeNodeNS = function(newAttr) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.hasAttribute = function(name2) { return this.attribs.hasOwnProperty(name2); }; XMLElement2.prototype.hasAttributeNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.setIdAttribute = function(name2, isId) { if (this.attribs.hasOwnProperty(name2)) { return this.attribs[name2].isId; } else { return isId; } }; XMLElement2.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.setIdAttributeNode = function(idAttr, isId) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getElementsByTagName = function(tagname) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.getElementsByClassName = function(classNames) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.isEqualNode = function(node) { var i2, j2, ref1; if (!XMLElement2.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.namespaceURI !== this.namespaceURI) { return false; } if (node.prefix !== this.prefix) { return false; } if (node.localName !== this.localName) { return false; } if (node.attribs.length !== this.attribs.length) { return false; } for (i2 = j2 = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j2 <= ref1 : j2 >= ref1; i2 = 0 <= ref1 ? ++j2 : --j2) { if (!this.attribs[i2].isEqualNode(node.attribs[i2])) { return false; } } return true; }; return XMLElement2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLCharacterData.js var require_XMLCharacterData = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLCharacterData.js"(exports2, module2) { (function() { var XMLCharacterData, XMLNode, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = require_XMLNode(); module2.exports = XMLCharacterData = function(superClass) { extend4(XMLCharacterData2, superClass); function XMLCharacterData2(parent) { XMLCharacterData2.__super__.constructor.call(this, parent); this.value = ""; } Object.defineProperty(XMLCharacterData2.prototype, "data", { get: function() { return this.value; }, set: function(value) { return this.value = value || ""; } }); Object.defineProperty(XMLCharacterData2.prototype, "length", { get: function() { return this.value.length; } }); Object.defineProperty(XMLCharacterData2.prototype, "textContent", { get: function() { return this.value; }, set: function(value) { return this.value = value || ""; } }); XMLCharacterData2.prototype.clone = function() { return Object.create(this); }; XMLCharacterData2.prototype.substringData = function(offset, count) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData2.prototype.appendData = function(arg) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData2.prototype.insertData = function(offset, arg) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData2.prototype.deleteData = function(offset, count) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData2.prototype.replaceData = function(offset, count, arg) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLCharacterData2.prototype.isEqualNode = function(node) { if (!XMLCharacterData2.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.data !== this.data) { return false; } return true; }; return XMLCharacterData2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLCData.js var require_XMLCData = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLCData.js"(exports2, module2) { (function() { var NodeType, XMLCData, XMLCharacterData, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = require_NodeType(); XMLCharacterData = require_XMLCharacterData(); module2.exports = XMLCData = function(superClass) { extend4(XMLCData2, superClass); function XMLCData2(parent, text) { XMLCData2.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing CDATA text. " + this.debugInfo()); } this.name = "#cdata-section"; this.type = NodeType.CData; this.value = this.stringify.cdata(text); } XMLCData2.prototype.clone = function() { return Object.create(this); }; XMLCData2.prototype.toString = function(options) { return this.options.writer.cdata(this, this.options.writer.filterOptions(options)); }; return XMLCData2; }(XMLCharacterData); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLComment.js var require_XMLComment = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLComment.js"(exports2, module2) { (function() { var NodeType, XMLCharacterData, XMLComment, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = require_NodeType(); XMLCharacterData = require_XMLCharacterData(); module2.exports = XMLComment = function(superClass) { extend4(XMLComment2, superClass); function XMLComment2(parent, text) { XMLComment2.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing comment text. " + this.debugInfo()); } this.name = "#comment"; this.type = NodeType.Comment; this.value = this.stringify.comment(text); } XMLComment2.prototype.clone = function() { return Object.create(this); }; XMLComment2.prototype.toString = function(options) { return this.options.writer.comment(this, this.options.writer.filterOptions(options)); }; return XMLComment2; }(XMLCharacterData); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDeclaration.js var require_XMLDeclaration = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDeclaration.js"(exports2, module2) { (function() { var NodeType, XMLDeclaration, XMLNode, isObject10, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject10 = require_Utility().isObject; XMLNode = require_XMLNode(); NodeType = require_NodeType(); module2.exports = XMLDeclaration = function(superClass) { extend4(XMLDeclaration2, superClass); function XMLDeclaration2(parent, version3, encoding, standalone) { var ref; XMLDeclaration2.__super__.constructor.call(this, parent); if (isObject10(version3)) { ref = version3, version3 = ref.version, encoding = ref.encoding, standalone = ref.standalone; } if (!version3) { version3 = "1.0"; } this.type = NodeType.Declaration; this.version = this.stringify.xmlVersion(version3); if (encoding != null) { this.encoding = this.stringify.xmlEncoding(encoding); } if (standalone != null) { this.standalone = this.stringify.xmlStandalone(standalone); } } XMLDeclaration2.prototype.toString = function(options) { return this.options.writer.declaration(this, this.options.writer.filterOptions(options)); }; return XMLDeclaration2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDAttList.js var require_XMLDTDAttList = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDAttList.js"(exports2, module2) { (function() { var NodeType, XMLDTDAttList, XMLNode, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = require_XMLNode(); NodeType = require_NodeType(); module2.exports = XMLDTDAttList = function(superClass) { extend4(XMLDTDAttList2, superClass); function XMLDTDAttList2(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) { XMLDTDAttList2.__super__.constructor.call(this, parent); if (elementName == null) { throw new Error("Missing DTD element name. " + this.debugInfo()); } if (attributeName == null) { throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName)); } if (!attributeType) { throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName)); } if (!defaultValueType) { throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName)); } if (defaultValueType.indexOf("#") !== 0) { defaultValueType = "#" + defaultValueType; } if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) { throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName)); } if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) { throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName)); } this.elementName = this.stringify.name(elementName); this.type = NodeType.AttributeDeclaration; this.attributeName = this.stringify.name(attributeName); this.attributeType = this.stringify.dtdAttType(attributeType); if (defaultValue) { this.defaultValue = this.stringify.dtdAttDefault(defaultValue); } this.defaultValueType = defaultValueType; } XMLDTDAttList2.prototype.toString = function(options) { return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options)); }; return XMLDTDAttList2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDEntity.js var require_XMLDTDEntity = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDEntity.js"(exports2, module2) { (function() { var NodeType, XMLDTDEntity, XMLNode, isObject10, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject10 = require_Utility().isObject; XMLNode = require_XMLNode(); NodeType = require_NodeType(); module2.exports = XMLDTDEntity = function(superClass) { extend4(XMLDTDEntity2, superClass); function XMLDTDEntity2(parent, pe2, name2, value) { XMLDTDEntity2.__super__.constructor.call(this, parent); if (name2 == null) { throw new Error("Missing DTD entity name. " + this.debugInfo(name2)); } if (value == null) { throw new Error("Missing DTD entity value. " + this.debugInfo(name2)); } this.pe = !!pe2; this.name = this.stringify.name(name2); this.type = NodeType.EntityDeclaration; if (!isObject10(value)) { this.value = this.stringify.dtdEntityValue(value); this.internal = true; } else { if (!value.pubID && !value.sysID) { throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name2)); } if (value.pubID && !value.sysID) { throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name2)); } this.internal = false; if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } if (value.nData != null) { this.nData = this.stringify.dtdNData(value.nData); } if (this.pe && this.nData) { throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name2)); } } } Object.defineProperty(XMLDTDEntity2.prototype, "publicId", { get: function() { return this.pubID; } }); Object.defineProperty(XMLDTDEntity2.prototype, "systemId", { get: function() { return this.sysID; } }); Object.defineProperty(XMLDTDEntity2.prototype, "notationName", { get: function() { return this.nData || null; } }); Object.defineProperty(XMLDTDEntity2.prototype, "inputEncoding", { get: function() { return null; } }); Object.defineProperty(XMLDTDEntity2.prototype, "xmlEncoding", { get: function() { return null; } }); Object.defineProperty(XMLDTDEntity2.prototype, "xmlVersion", { get: function() { return null; } }); XMLDTDEntity2.prototype.toString = function(options) { return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options)); }; return XMLDTDEntity2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDElement.js var require_XMLDTDElement = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDElement.js"(exports2, module2) { (function() { var NodeType, XMLDTDElement, XMLNode, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = require_XMLNode(); NodeType = require_NodeType(); module2.exports = XMLDTDElement = function(superClass) { extend4(XMLDTDElement2, superClass); function XMLDTDElement2(parent, name2, value) { XMLDTDElement2.__super__.constructor.call(this, parent); if (name2 == null) { throw new Error("Missing DTD element name. " + this.debugInfo()); } if (!value) { value = "(#PCDATA)"; } if (Array.isArray(value)) { value = "(" + value.join(",") + ")"; } this.name = this.stringify.name(name2); this.type = NodeType.ElementDeclaration; this.value = this.stringify.dtdElementValue(value); } XMLDTDElement2.prototype.toString = function(options) { return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options)); }; return XMLDTDElement2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDNotation.js var require_XMLDTDNotation = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDTDNotation.js"(exports2, module2) { (function() { var NodeType, XMLDTDNotation, XMLNode, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = require_XMLNode(); NodeType = require_NodeType(); module2.exports = XMLDTDNotation = function(superClass) { extend4(XMLDTDNotation2, superClass); function XMLDTDNotation2(parent, name2, value) { XMLDTDNotation2.__super__.constructor.call(this, parent); if (name2 == null) { throw new Error("Missing DTD notation name. " + this.debugInfo(name2)); } if (!value.pubID && !value.sysID) { throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name2)); } this.name = this.stringify.name(name2); this.type = NodeType.NotationDeclaration; if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } } Object.defineProperty(XMLDTDNotation2.prototype, "publicId", { get: function() { return this.pubID; } }); Object.defineProperty(XMLDTDNotation2.prototype, "systemId", { get: function() { return this.sysID; } }); XMLDTDNotation2.prototype.toString = function(options) { return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options)); }; return XMLDTDNotation2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDocType.js var require_XMLDocType = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDocType.js"(exports2, module2) { (function() { var NodeType, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNamedNodeMap, XMLNode, isObject10, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isObject10 = require_Utility().isObject; XMLNode = require_XMLNode(); NodeType = require_NodeType(); XMLDTDAttList = require_XMLDTDAttList(); XMLDTDEntity = require_XMLDTDEntity(); XMLDTDElement = require_XMLDTDElement(); XMLDTDNotation = require_XMLDTDNotation(); XMLNamedNodeMap = require_XMLNamedNodeMap(); module2.exports = XMLDocType = function(superClass) { extend4(XMLDocType2, superClass); function XMLDocType2(parent, pubID, sysID) { var child, i2, len, ref, ref1, ref2; XMLDocType2.__super__.constructor.call(this, parent); this.type = NodeType.DocType; if (parent.children) { ref = parent.children; for (i2 = 0, len = ref.length; i2 < len; i2++) { child = ref[i2]; if (child.type === NodeType.Element) { this.name = child.name; break; } } } this.documentObject = parent; if (isObject10(pubID)) { ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID; } if (sysID == null) { ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1]; } if (pubID != null) { this.pubID = this.stringify.dtdPubID(pubID); } if (sysID != null) { this.sysID = this.stringify.dtdSysID(sysID); } } Object.defineProperty(XMLDocType2.prototype, "entities", { get: function() { var child, i2, len, nodes, ref; nodes = {}; ref = this.children; for (i2 = 0, len = ref.length; i2 < len; i2++) { child = ref[i2]; if (child.type === NodeType.EntityDeclaration && !child.pe) { nodes[child.name] = child; } } return new XMLNamedNodeMap(nodes); } }); Object.defineProperty(XMLDocType2.prototype, "notations", { get: function() { var child, i2, len, nodes, ref; nodes = {}; ref = this.children; for (i2 = 0, len = ref.length; i2 < len; i2++) { child = ref[i2]; if (child.type === NodeType.NotationDeclaration) { nodes[child.name] = child; } } return new XMLNamedNodeMap(nodes); } }); Object.defineProperty(XMLDocType2.prototype, "publicId", { get: function() { return this.pubID; } }); Object.defineProperty(XMLDocType2.prototype, "systemId", { get: function() { return this.sysID; } }); Object.defineProperty(XMLDocType2.prototype, "internalSubset", { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); XMLDocType2.prototype.element = function(name2, value) { var child; child = new XMLDTDElement(this, name2, value); this.children.push(child); return this; }; XMLDocType2.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { var child; child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); this.children.push(child); return this; }; XMLDocType2.prototype.entity = function(name2, value) { var child; child = new XMLDTDEntity(this, false, name2, value); this.children.push(child); return this; }; XMLDocType2.prototype.pEntity = function(name2, value) { var child; child = new XMLDTDEntity(this, true, name2, value); this.children.push(child); return this; }; XMLDocType2.prototype.notation = function(name2, value) { var child; child = new XMLDTDNotation(this, name2, value); this.children.push(child); return this; }; XMLDocType2.prototype.toString = function(options) { return this.options.writer.docType(this, this.options.writer.filterOptions(options)); }; XMLDocType2.prototype.ele = function(name2, value) { return this.element(name2, value); }; XMLDocType2.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue); }; XMLDocType2.prototype.ent = function(name2, value) { return this.entity(name2, value); }; XMLDocType2.prototype.pent = function(name2, value) { return this.pEntity(name2, value); }; XMLDocType2.prototype.not = function(name2, value) { return this.notation(name2, value); }; XMLDocType2.prototype.up = function() { return this.root() || this.documentObject; }; XMLDocType2.prototype.isEqualNode = function(node) { if (!XMLDocType2.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.name !== this.name) { return false; } if (node.publicId !== this.publicId) { return false; } if (node.systemId !== this.systemId) { return false; } return true; }; return XMLDocType2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLRaw.js var require_XMLRaw = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLRaw.js"(exports2, module2) { (function() { var NodeType, XMLNode, XMLRaw, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = require_NodeType(); XMLNode = require_XMLNode(); module2.exports = XMLRaw = function(superClass) { extend4(XMLRaw2, superClass); function XMLRaw2(parent, text) { XMLRaw2.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing raw text. " + this.debugInfo()); } this.type = NodeType.Raw; this.value = this.stringify.raw(text); } XMLRaw2.prototype.clone = function() { return Object.create(this); }; XMLRaw2.prototype.toString = function(options) { return this.options.writer.raw(this, this.options.writer.filterOptions(options)); }; return XMLRaw2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLText.js var require_XMLText = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLText.js"(exports2, module2) { (function() { var NodeType, XMLCharacterData, XMLText, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = require_NodeType(); XMLCharacterData = require_XMLCharacterData(); module2.exports = XMLText = function(superClass) { extend4(XMLText2, superClass); function XMLText2(parent, text) { XMLText2.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing element text. " + this.debugInfo()); } this.name = "#text"; this.type = NodeType.Text; this.value = this.stringify.text(text); } Object.defineProperty(XMLText2.prototype, "isElementContentWhitespace", { get: function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); Object.defineProperty(XMLText2.prototype, "wholeText", { get: function() { var next2, prev, str3; str3 = ""; prev = this.previousSibling; while (prev) { str3 = prev.data + str3; prev = prev.previousSibling; } str3 += this.data; next2 = this.nextSibling; while (next2) { str3 = str3 + next2.data; next2 = next2.nextSibling; } return str3; } }); XMLText2.prototype.clone = function() { return Object.create(this); }; XMLText2.prototype.toString = function(options) { return this.options.writer.text(this, this.options.writer.filterOptions(options)); }; XMLText2.prototype.splitText = function(offset) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLText2.prototype.replaceWholeText = function(content) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; return XMLText2; }(XMLCharacterData); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js var require_XMLProcessingInstruction = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js"(exports2, module2) { (function() { var NodeType, XMLCharacterData, XMLProcessingInstruction, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = require_NodeType(); XMLCharacterData = require_XMLCharacterData(); module2.exports = XMLProcessingInstruction = function(superClass) { extend4(XMLProcessingInstruction2, superClass); function XMLProcessingInstruction2(parent, target, value) { XMLProcessingInstruction2.__super__.constructor.call(this, parent); if (target == null) { throw new Error("Missing instruction target. " + this.debugInfo()); } this.type = NodeType.ProcessingInstruction; this.target = this.stringify.insTarget(target); this.name = this.target; if (value) { this.value = this.stringify.insValue(value); } } XMLProcessingInstruction2.prototype.clone = function() { return Object.create(this); }; XMLProcessingInstruction2.prototype.toString = function(options) { return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options)); }; XMLProcessingInstruction2.prototype.isEqualNode = function(node) { if (!XMLProcessingInstruction2.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } if (node.target !== this.target) { return false; } return true; }; return XMLProcessingInstruction2; }(XMLCharacterData); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDummy.js var require_XMLDummy = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDummy.js"(exports2, module2) { (function() { var NodeType, XMLDummy, XMLNode, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLNode = require_XMLNode(); NodeType = require_NodeType(); module2.exports = XMLDummy = function(superClass) { extend4(XMLDummy2, superClass); function XMLDummy2(parent) { XMLDummy2.__super__.constructor.call(this, parent); this.type = NodeType.Dummy; } XMLDummy2.prototype.clone = function() { return Object.create(this); }; XMLDummy2.prototype.toString = function(options) { return ""; }; return XMLDummy2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLNodeList.js var require_XMLNodeList = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLNodeList.js"(exports2, module2) { (function() { var XMLNodeList; module2.exports = XMLNodeList = function() { function XMLNodeList2(nodes) { this.nodes = nodes; } Object.defineProperty(XMLNodeList2.prototype, "length", { get: function() { return this.nodes.length || 0; } }); XMLNodeList2.prototype.clone = function() { return this.nodes = null; }; XMLNodeList2.prototype.item = function(index2) { return this.nodes[index2] || null; }; return XMLNodeList2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/DocumentPosition.js var require_DocumentPosition = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/DocumentPosition.js"(exports2, module2) { (function() { module2.exports = { Disconnected: 1, Preceding: 2, Following: 4, Contains: 8, ContainedBy: 16, ImplementationSpecific: 32 }; }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLNode.js var require_XMLNode = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLNode.js"(exports2, module2) { (function() { var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNamedNodeMap, XMLNode, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue3, isEmpty6, isFunction, isObject10, ref1, hasProp = {}.hasOwnProperty; ref1 = require_Utility(), isObject10 = ref1.isObject, isFunction = ref1.isFunction, isEmpty6 = ref1.isEmpty, getValue3 = ref1.getValue; XMLElement = null; XMLCData = null; XMLComment = null; XMLDeclaration = null; XMLDocType = null; XMLRaw = null; XMLText = null; XMLProcessingInstruction = null; XMLDummy = null; NodeType = null; XMLNodeList = null; XMLNamedNodeMap = null; DocumentPosition = null; module2.exports = XMLNode = function() { function XMLNode2(parent1) { this.parent = parent1; if (this.parent) { this.options = this.parent.options; this.stringify = this.parent.stringify; } this.value = null; this.children = []; this.baseURI = null; if (!XMLElement) { XMLElement = require_XMLElement(); XMLCData = require_XMLCData(); XMLComment = require_XMLComment(); XMLDeclaration = require_XMLDeclaration(); XMLDocType = require_XMLDocType(); XMLRaw = require_XMLRaw(); XMLText = require_XMLText(); XMLProcessingInstruction = require_XMLProcessingInstruction(); XMLDummy = require_XMLDummy(); NodeType = require_NodeType(); XMLNodeList = require_XMLNodeList(); XMLNamedNodeMap = require_XMLNamedNodeMap(); DocumentPosition = require_DocumentPosition(); } } Object.defineProperty(XMLNode2.prototype, "nodeName", { get: function() { return this.name; } }); Object.defineProperty(XMLNode2.prototype, "nodeType", { get: function() { return this.type; } }); Object.defineProperty(XMLNode2.prototype, "nodeValue", { get: function() { return this.value; } }); Object.defineProperty(XMLNode2.prototype, "parentNode", { get: function() { return this.parent; } }); Object.defineProperty(XMLNode2.prototype, "childNodes", { get: function() { if (!this.childNodeList || !this.childNodeList.nodes) { this.childNodeList = new XMLNodeList(this.children); } return this.childNodeList; } }); Object.defineProperty(XMLNode2.prototype, "firstChild", { get: function() { return this.children[0] || null; } }); Object.defineProperty(XMLNode2.prototype, "lastChild", { get: function() { return this.children[this.children.length - 1] || null; } }); Object.defineProperty(XMLNode2.prototype, "previousSibling", { get: function() { var i2; i2 = this.parent.children.indexOf(this); return this.parent.children[i2 - 1] || null; } }); Object.defineProperty(XMLNode2.prototype, "nextSibling", { get: function() { var i2; i2 = this.parent.children.indexOf(this); return this.parent.children[i2 + 1] || null; } }); Object.defineProperty(XMLNode2.prototype, "ownerDocument", { get: function() { return this.document() || null; } }); Object.defineProperty(XMLNode2.prototype, "textContent", { get: function() { var child, j2, len, ref2, str3; if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) { str3 = ""; ref2 = this.children; for (j2 = 0, len = ref2.length; j2 < len; j2++) { child = ref2[j2]; if (child.textContent) { str3 += child.textContent; } } return str3; } else { return null; } }, set: function(value) { throw new Error("This DOM method is not implemented." + this.debugInfo()); } }); XMLNode2.prototype.setParent = function(parent) { var child, j2, len, ref2, results; this.parent = parent; if (parent) { this.options = parent.options; this.stringify = parent.stringify; } ref2 = this.children; results = []; for (j2 = 0, len = ref2.length; j2 < len; j2++) { child = ref2[j2]; results.push(child.setParent(this)); } return results; }; XMLNode2.prototype.element = function(name2, attributes, text) { var childNode, item, j2, k2, key, lastChild, len, len1, ref2, ref3, val; lastChild = null; if (attributes === null && text == null) { ref2 = [{}, null], attributes = ref2[0], text = ref2[1]; } if (attributes == null) { attributes = {}; } attributes = getValue3(attributes); if (!isObject10(attributes)) { ref3 = [attributes, text], text = ref3[0], attributes = ref3[1]; } if (name2 != null) { name2 = getValue3(name2); } if (Array.isArray(name2)) { for (j2 = 0, len = name2.length; j2 < len; j2++) { item = name2[j2]; lastChild = this.element(item); } } else if (isFunction(name2)) { lastChild = this.element(name2.apply()); } else if (isObject10(name2)) { for (key in name2) { if (!hasProp.call(name2, key)) continue; val = name2[key]; if (isFunction(val)) { val = val.apply(); } if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) { lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val); } else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty6(val)) { lastChild = this.dummy(); } else if (isObject10(val) && isEmpty6(val)) { lastChild = this.element(key); } else if (!this.options.keepNullNodes && val == null) { lastChild = this.dummy(); } else if (!this.options.separateArrayItems && Array.isArray(val)) { for (k2 = 0, len1 = val.length; k2 < len1; k2++) { item = val[k2]; childNode = {}; childNode[key] = item; lastChild = this.element(childNode); } } else if (isObject10(val)) { if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) { lastChild = this.element(val); } else { lastChild = this.element(key); lastChild.element(val); } } else { lastChild = this.element(key, val); } } } else if (!this.options.keepNullNodes && text === null) { lastChild = this.dummy(); } else { if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name2.indexOf(this.stringify.convertTextKey) === 0) { lastChild = this.text(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name2.indexOf(this.stringify.convertCDataKey) === 0) { lastChild = this.cdata(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name2.indexOf(this.stringify.convertCommentKey) === 0) { lastChild = this.comment(text); } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name2.indexOf(this.stringify.convertRawKey) === 0) { lastChild = this.raw(text); } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name2.indexOf(this.stringify.convertPIKey) === 0) { lastChild = this.instruction(name2.substr(this.stringify.convertPIKey.length), text); } else { lastChild = this.node(name2, attributes, text); } } if (lastChild == null) { throw new Error("Could not create any elements with: " + name2 + ". " + this.debugInfo()); } return lastChild; }; XMLNode2.prototype.insertBefore = function(name2, attributes, text) { var child, i2, newChild, refChild, removed; if (name2 != null ? name2.type : void 0) { newChild = name2; refChild = attributes; newChild.setParent(this); if (refChild) { i2 = children.indexOf(refChild); removed = children.splice(i2); children.push(newChild); Array.prototype.push.apply(children, removed); } else { children.push(newChild); } return newChild; } else { if (this.isRoot) { throw new Error("Cannot insert elements at root level. " + this.debugInfo(name2)); } i2 = this.parent.children.indexOf(this); removed = this.parent.children.splice(i2); child = this.parent.element(name2, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; } }; XMLNode2.prototype.insertAfter = function(name2, attributes, text) { var child, i2, removed; if (this.isRoot) { throw new Error("Cannot insert elements at root level. " + this.debugInfo(name2)); } i2 = this.parent.children.indexOf(this); removed = this.parent.children.splice(i2 + 1); child = this.parent.element(name2, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; }; XMLNode2.prototype.remove = function() { var i2, ref2; if (this.isRoot) { throw new Error("Cannot remove the root element. " + this.debugInfo()); } i2 = this.parent.children.indexOf(this); [].splice.apply(this.parent.children, [i2, i2 - i2 + 1].concat(ref2 = [])), ref2; return this.parent; }; XMLNode2.prototype.node = function(name2, attributes, text) { var child, ref2; if (name2 != null) { name2 = getValue3(name2); } attributes || (attributes = {}); attributes = getValue3(attributes); if (!isObject10(attributes)) { ref2 = [attributes, text], text = ref2[0], attributes = ref2[1]; } child = new XMLElement(this, name2, attributes); if (text != null) { child.text(text); } this.children.push(child); return child; }; XMLNode2.prototype.text = function(value) { var child; if (isObject10(value)) { this.element(value); } child = new XMLText(this, value); this.children.push(child); return this; }; XMLNode2.prototype.cdata = function(value) { var child; child = new XMLCData(this, value); this.children.push(child); return this; }; XMLNode2.prototype.comment = function(value) { var child; child = new XMLComment(this, value); this.children.push(child); return this; }; XMLNode2.prototype.commentBefore = function(value) { var child, i2, removed; i2 = this.parent.children.indexOf(this); removed = this.parent.children.splice(i2); child = this.parent.comment(value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode2.prototype.commentAfter = function(value) { var child, i2, removed; i2 = this.parent.children.indexOf(this); removed = this.parent.children.splice(i2 + 1); child = this.parent.comment(value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode2.prototype.raw = function(value) { var child; child = new XMLRaw(this, value); this.children.push(child); return this; }; XMLNode2.prototype.dummy = function() { var child; child = new XMLDummy(this); return child; }; XMLNode2.prototype.instruction = function(target, value) { var insTarget, insValue, instruction, j2, len; if (target != null) { target = getValue3(target); } if (value != null) { value = getValue3(value); } if (Array.isArray(target)) { for (j2 = 0, len = target.length; j2 < len; j2++) { insTarget = target[j2]; this.instruction(insTarget); } } else if (isObject10(target)) { for (insTarget in target) { if (!hasProp.call(target, insTarget)) continue; insValue = target[insTarget]; this.instruction(insTarget, insValue); } } else { if (isFunction(value)) { value = value.apply(); } instruction = new XMLProcessingInstruction(this, target, value); this.children.push(instruction); } return this; }; XMLNode2.prototype.instructionBefore = function(target, value) { var child, i2, removed; i2 = this.parent.children.indexOf(this); removed = this.parent.children.splice(i2); child = this.parent.instruction(target, value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode2.prototype.instructionAfter = function(target, value) { var child, i2, removed; i2 = this.parent.children.indexOf(this); removed = this.parent.children.splice(i2 + 1); child = this.parent.instruction(target, value); Array.prototype.push.apply(this.parent.children, removed); return this; }; XMLNode2.prototype.declaration = function(version3, encoding, standalone) { var doc, xmldec; doc = this.document(); xmldec = new XMLDeclaration(doc, version3, encoding, standalone); if (doc.children.length === 0) { doc.children.unshift(xmldec); } else if (doc.children[0].type === NodeType.Declaration) { doc.children[0] = xmldec; } else { doc.children.unshift(xmldec); } return doc.root() || doc; }; XMLNode2.prototype.dtd = function(pubID, sysID) { var child, doc, doctype, i2, j2, k2, len, len1, ref2, ref3; doc = this.document(); doctype = new XMLDocType(doc, pubID, sysID); ref2 = doc.children; for (i2 = j2 = 0, len = ref2.length; j2 < len; i2 = ++j2) { child = ref2[i2]; if (child.type === NodeType.DocType) { doc.children[i2] = doctype; return doctype; } } ref3 = doc.children; for (i2 = k2 = 0, len1 = ref3.length; k2 < len1; i2 = ++k2) { child = ref3[i2]; if (child.isRoot) { doc.children.splice(i2, 0, doctype); return doctype; } } doc.children.push(doctype); return doctype; }; XMLNode2.prototype.up = function() { if (this.isRoot) { throw new Error("The root node has no parent. Use doc() if you need to get the document object."); } return this.parent; }; XMLNode2.prototype.root = function() { var node; node = this; while (node) { if (node.type === NodeType.Document) { return node.rootObject; } else if (node.isRoot) { return node; } else { node = node.parent; } } }; XMLNode2.prototype.document = function() { var node; node = this; while (node) { if (node.type === NodeType.Document) { return node; } else { node = node.parent; } } }; XMLNode2.prototype.end = function(options) { return this.document().end(options); }; XMLNode2.prototype.prev = function() { var i2; i2 = this.parent.children.indexOf(this); if (i2 < 1) { throw new Error("Already at the first node. " + this.debugInfo()); } return this.parent.children[i2 - 1]; }; XMLNode2.prototype.next = function() { var i2; i2 = this.parent.children.indexOf(this); if (i2 === -1 || i2 === this.parent.children.length - 1) { throw new Error("Already at the last node. " + this.debugInfo()); } return this.parent.children[i2 + 1]; }; XMLNode2.prototype.importDocument = function(doc) { var clonedRoot; clonedRoot = doc.root().clone(); clonedRoot.parent = this; clonedRoot.isRoot = false; this.children.push(clonedRoot); return this; }; XMLNode2.prototype.debugInfo = function(name2) { var ref2, ref3; name2 = name2 || this.name; if (name2 == null && !((ref2 = this.parent) != null ? ref2.name : void 0)) { return ""; } else if (name2 == null) { return "parent: <" + this.parent.name + ">"; } else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) { return "node: <" + name2 + ">"; } else { return "node: <" + name2 + ">, parent: <" + this.parent.name + ">"; } }; XMLNode2.prototype.ele = function(name2, attributes, text) { return this.element(name2, attributes, text); }; XMLNode2.prototype.nod = function(name2, attributes, text) { return this.node(name2, attributes, text); }; XMLNode2.prototype.txt = function(value) { return this.text(value); }; XMLNode2.prototype.dat = function(value) { return this.cdata(value); }; XMLNode2.prototype.com = function(value) { return this.comment(value); }; XMLNode2.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLNode2.prototype.doc = function() { return this.document(); }; XMLNode2.prototype.dec = function(version3, encoding, standalone) { return this.declaration(version3, encoding, standalone); }; XMLNode2.prototype.e = function(name2, attributes, text) { return this.element(name2, attributes, text); }; XMLNode2.prototype.n = function(name2, attributes, text) { return this.node(name2, attributes, text); }; XMLNode2.prototype.t = function(value) { return this.text(value); }; XMLNode2.prototype.d = function(value) { return this.cdata(value); }; XMLNode2.prototype.c = function(value) { return this.comment(value); }; XMLNode2.prototype.r = function(value) { return this.raw(value); }; XMLNode2.prototype.i = function(target, value) { return this.instruction(target, value); }; XMLNode2.prototype.u = function() { return this.up(); }; XMLNode2.prototype.importXMLBuilder = function(doc) { return this.importDocument(doc); }; XMLNode2.prototype.replaceChild = function(newChild, oldChild) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.removeChild = function(oldChild) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.appendChild = function(newChild) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.hasChildNodes = function() { return this.children.length !== 0; }; XMLNode2.prototype.cloneNode = function(deep) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.normalize = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.isSupported = function(feature, version3) { return true; }; XMLNode2.prototype.hasAttributes = function() { return this.attribs.length !== 0; }; XMLNode2.prototype.compareDocumentPosition = function(other) { var ref, res; ref = this; if (ref === other) { return 0; } else if (this.document() !== other.document()) { res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific; if (Math.random() < 0.5) { res |= DocumentPosition.Preceding; } else { res |= DocumentPosition.Following; } return res; } else if (ref.isAncestor(other)) { return DocumentPosition.Contains | DocumentPosition.Preceding; } else if (ref.isDescendant(other)) { return DocumentPosition.Contains | DocumentPosition.Following; } else if (ref.isPreceding(other)) { return DocumentPosition.Preceding; } else { return DocumentPosition.Following; } }; XMLNode2.prototype.isSameNode = function(other) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.lookupPrefix = function(namespaceURI) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.isDefaultNamespace = function(namespaceURI) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.lookupNamespaceURI = function(prefix) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.isEqualNode = function(node) { var i2, j2, ref2; if (node.nodeType !== this.nodeType) { return false; } if (node.children.length !== this.children.length) { return false; } for (i2 = j2 = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j2 <= ref2 : j2 >= ref2; i2 = 0 <= ref2 ? ++j2 : --j2) { if (!this.children[i2].isEqualNode(node.children[i2])) { return false; } } return true; }; XMLNode2.prototype.getFeature = function(feature, version3) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.setUserData = function(key, data, handler) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.getUserData = function(key) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.contains = function(other) { if (!other) { return false; } return other === this || this.isDescendant(other); }; XMLNode2.prototype.isDescendant = function(node) { var child, isDescendantChild, j2, len, ref2; ref2 = this.children; for (j2 = 0, len = ref2.length; j2 < len; j2++) { child = ref2[j2]; if (node === child) { return true; } isDescendantChild = child.isDescendant(node); if (isDescendantChild) { return true; } } return false; }; XMLNode2.prototype.isAncestor = function(node) { return node.isDescendant(this); }; XMLNode2.prototype.isPreceding = function(node) { var nodePos, thisPos; nodePos = this.treePosition(node); thisPos = this.treePosition(this); if (nodePos === -1 || thisPos === -1) { return false; } else { return nodePos < thisPos; } }; XMLNode2.prototype.isFollowing = function(node) { var nodePos, thisPos; nodePos = this.treePosition(node); thisPos = this.treePosition(this); if (nodePos === -1 || thisPos === -1) { return false; } else { return nodePos > thisPos; } }; XMLNode2.prototype.treePosition = function(node) { var found, pos; pos = 0; found = false; this.foreachTreeNode(this.document(), function(childNode) { pos++; if (!found && childNode === node) { return found = true; } }); if (found) { return pos; } else { return -1; } }; XMLNode2.prototype.foreachTreeNode = function(node, func) { var child, j2, len, ref2, res; node || (node = this.document()); ref2 = node.children; for (j2 = 0, len = ref2.length; j2 < len; j2++) { child = ref2[j2]; if (res = func(child)) { return res; } else { res = this.foreachTreeNode(child, func); if (res) { return res; } } } }; return XMLNode2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLStringifier.js var require_XMLStringifier = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLStringifier.js"(exports2, module2) { (function() { var XMLStringifier, bind2 = function(fn, me2) { return function() { return fn.apply(me2, arguments); }; }, hasProp = {}.hasOwnProperty; module2.exports = XMLStringifier = function() { function XMLStringifier2(options) { this.assertLegalName = bind2(this.assertLegalName, this); this.assertLegalChar = bind2(this.assertLegalChar, this); var key, ref, value; options || (options = {}); this.options = options; if (!this.options.version) { this.options.version = "1.0"; } ref = options.stringify || {}; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this[key] = value; } } XMLStringifier2.prototype.name = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalName("" + val || ""); }; XMLStringifier2.prototype.text = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar(this.textEscape("" + val || "")); }; XMLStringifier2.prototype.cdata = function(val) { if (this.options.noValidation) { return val; } val = "" + val || ""; val = val.replace("]]>", "]]]]>"); return this.assertLegalChar(val); }; XMLStringifier2.prototype.comment = function(val) { if (this.options.noValidation) { return val; } val = "" + val || ""; if (val.match(/--/)) { throw new Error("Comment text cannot contain double-hypen: " + val); } return this.assertLegalChar(val); }; XMLStringifier2.prototype.raw = function(val) { if (this.options.noValidation) { return val; } return "" + val || ""; }; XMLStringifier2.prototype.attValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar(this.attEscape(val = "" + val || "")); }; XMLStringifier2.prototype.insTarget = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.insValue = function(val) { if (this.options.noValidation) { return val; } val = "" + val || ""; if (val.match(/\?>/)) { throw new Error("Invalid processing instruction value: " + val); } return this.assertLegalChar(val); }; XMLStringifier2.prototype.xmlVersion = function(val) { if (this.options.noValidation) { return val; } val = "" + val || ""; if (!val.match(/1\.[0-9]+/)) { throw new Error("Invalid version number: " + val); } return val; }; XMLStringifier2.prototype.xmlEncoding = function(val) { if (this.options.noValidation) { return val; } val = "" + val || ""; if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) { throw new Error("Invalid encoding: " + val); } return this.assertLegalChar(val); }; XMLStringifier2.prototype.xmlStandalone = function(val) { if (this.options.noValidation) { return val; } if (val) { return "yes"; } else { return "no"; } }; XMLStringifier2.prototype.dtdPubID = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.dtdSysID = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.dtdElementValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.dtdAttType = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.dtdAttDefault = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.dtdEntityValue = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.dtdNData = function(val) { if (this.options.noValidation) { return val; } return this.assertLegalChar("" + val || ""); }; XMLStringifier2.prototype.convertAttKey = "@"; XMLStringifier2.prototype.convertPIKey = "?"; XMLStringifier2.prototype.convertTextKey = "#text"; XMLStringifier2.prototype.convertCDataKey = "#cdata"; XMLStringifier2.prototype.convertCommentKey = "#comment"; XMLStringifier2.prototype.convertRawKey = "#raw"; XMLStringifier2.prototype.assertLegalChar = function(str3) { var regex2, res; if (this.options.noValidation) { return str3; } regex2 = ""; if (this.options.version === "1.0") { regex2 = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; if (res = str3.match(regex2)) { throw new Error("Invalid character in string: " + str3 + " at index " + res.index); } } else if (this.options.version === "1.1") { regex2 = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; if (res = str3.match(regex2)) { throw new Error("Invalid character in string: " + str3 + " at index " + res.index); } } return str3; }; XMLStringifier2.prototype.assertLegalName = function(str3) { var regex2; if (this.options.noValidation) { return str3; } this.assertLegalChar(str3); regex2 = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/; if (!str3.match(regex2)) { throw new Error("Invalid character in name"); } return str3; }; XMLStringifier2.prototype.textEscape = function(str3) { var ampregex; if (this.options.noValidation) { return str3; } ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str3.replace(ampregex, "&").replace(//g, ">").replace(/\r/g, " "); }; XMLStringifier2.prototype.attEscape = function(str3) { var ampregex; if (this.options.noValidation) { return str3; } ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; return str3.replace(ampregex, "&").replace(/ 0) { return new Array(indentLevel).join(options.indent); } } return ""; }; XMLWriterBase2.prototype.endline = function(node, options, level) { if (!options.pretty || options.suppressPrettyCount) { return ""; } else { return options.newline; } }; XMLWriterBase2.prototype.attribute = function(att, options, level) { var r3; this.openAttribute(att, options, level); r3 = " " + att.name + '="' + att.value + '"'; this.closeAttribute(att, options, level); return r3; }; XMLWriterBase2.prototype.cdata = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + "" + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.comment = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + "" + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.declaration = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + ""; r3 += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.docType = function(node, options, level) { var child, i2, len, r3, ref; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level); r3 += " 0) { r3 += " ["; r3 += this.endline(node, options, level); options.state = WriterState.InsideTag; ref = node.children; for (i2 = 0, len = ref.length; i2 < len; i2++) { child = ref[i2]; r3 += this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; r3 += "]"; } options.state = WriterState.CloseTag; r3 += options.spaceBeforeSlash + ">"; r3 += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.element = function(node, options, level) { var att, child, childNodeCount, firstChildNode, i2, j2, len, len1, name2, prettySuppressed, r3, ref, ref1, ref2; level || (level = 0); prettySuppressed = false; r3 = ""; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 += this.indent(node, options, level) + "<" + node.name; ref = node.attribs; for (name2 in ref) { if (!hasProp.call(ref, name2)) continue; att = ref[name2]; r3 += this.attribute(att, options, level); } childNodeCount = node.children.length; firstChildNode = childNodeCount === 0 ? null : node.children[0]; if (childNodeCount === 0 || node.children.every(function(e2) { return (e2.type === NodeType.Text || e2.type === NodeType.Raw) && e2.value === ""; })) { if (options.allowEmpty) { r3 += ">"; options.state = WriterState.CloseTag; r3 += "" + this.endline(node, options, level); } else { options.state = WriterState.CloseTag; r3 += options.spaceBeforeSlash + "/>" + this.endline(node, options, level); } } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && firstChildNode.value != null) { r3 += ">"; options.state = WriterState.InsideTag; options.suppressPrettyCount++; prettySuppressed = true; r3 += this.writeChildNode(firstChildNode, options, level + 1); options.suppressPrettyCount--; prettySuppressed = false; options.state = WriterState.CloseTag; r3 += "" + this.endline(node, options, level); } else { if (options.dontPrettyTextNodes) { ref1 = node.children; for (i2 = 0, len = ref1.length; i2 < len; i2++) { child = ref1[i2]; if ((child.type === NodeType.Text || child.type === NodeType.Raw) && child.value != null) { options.suppressPrettyCount++; prettySuppressed = true; break; } } } r3 += ">" + this.endline(node, options, level); options.state = WriterState.InsideTag; ref2 = node.children; for (j2 = 0, len1 = ref2.length; j2 < len1; j2++) { child = ref2[j2]; r3 += this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; r3 += this.indent(node, options, level) + ""; if (prettySuppressed) { options.suppressPrettyCount--; } r3 += this.endline(node, options, level); options.state = WriterState.None; } this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.writeChildNode = function(node, options, level) { switch (node.type) { case NodeType.CData: return this.cdata(node, options, level); case NodeType.Comment: return this.comment(node, options, level); case NodeType.Element: return this.element(node, options, level); case NodeType.Raw: return this.raw(node, options, level); case NodeType.Text: return this.text(node, options, level); case NodeType.ProcessingInstruction: return this.processingInstruction(node, options, level); case NodeType.Dummy: return ""; case NodeType.Declaration: return this.declaration(node, options, level); case NodeType.DocType: return this.docType(node, options, level); case NodeType.AttributeDeclaration: return this.dtdAttList(node, options, level); case NodeType.ElementDeclaration: return this.dtdElement(node, options, level); case NodeType.EntityDeclaration: return this.dtdEntity(node, options, level); case NodeType.NotationDeclaration: return this.dtdNotation(node, options, level); default: throw new Error("Unknown XML node type: " + node.constructor.name); } }; XMLWriterBase2.prototype.processingInstruction = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + ""; r3 += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.raw = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level); options.state = WriterState.InsideTag; r3 += node.value; options.state = WriterState.CloseTag; r3 += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.text = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level); options.state = WriterState.InsideTag; r3 += node.value; options.state = WriterState.CloseTag; r3 += this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.dtdAttList = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + "" + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.dtdElement = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + "" + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.dtdEntity = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + "" + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.dtdNotation = function(node, options, level) { var r3; this.openNode(node, options, level); options.state = WriterState.OpenTag; r3 = this.indent(node, options, level) + "" + this.endline(node, options, level); options.state = WriterState.None; this.closeNode(node, options, level); return r3; }; XMLWriterBase2.prototype.openNode = function(node, options, level) { }; XMLWriterBase2.prototype.closeNode = function(node, options, level) { }; XMLWriterBase2.prototype.openAttribute = function(att, options, level) { }; XMLWriterBase2.prototype.closeAttribute = function(att, options, level) { }; return XMLWriterBase2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLStringWriter.js var require_XMLStringWriter = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLStringWriter.js"(exports2, module2) { (function() { var XMLStringWriter, XMLWriterBase, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; XMLWriterBase = require_XMLWriterBase(); module2.exports = XMLStringWriter = function(superClass) { extend4(XMLStringWriter2, superClass); function XMLStringWriter2(options) { XMLStringWriter2.__super__.constructor.call(this, options); } XMLStringWriter2.prototype.document = function(doc, options) { var child, i2, len, r3, ref; options = this.filterOptions(options); r3 = ""; ref = doc.children; for (i2 = 0, len = ref.length; i2 < len; i2++) { child = ref[i2]; r3 += this.writeChildNode(child, options, 0); } if (options.pretty && r3.slice(-options.newline.length) === options.newline) { r3 = r3.slice(0, -options.newline.length); } return r3; }; return XMLStringWriter2; }(XMLWriterBase); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDocument.js var require_XMLDocument = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDocument.js"(exports2, module2) { (function() { var NodeType, XMLDOMConfiguration, XMLDOMImplementation, XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject4, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; isPlainObject4 = require_Utility().isPlainObject; XMLDOMImplementation = require_XMLDOMImplementation(); XMLDOMConfiguration = require_XMLDOMConfiguration(); XMLNode = require_XMLNode(); NodeType = require_NodeType(); XMLStringifier = require_XMLStringifier(); XMLStringWriter = require_XMLStringWriter(); module2.exports = XMLDocument = function(superClass) { extend4(XMLDocument2, superClass); function XMLDocument2(options) { XMLDocument2.__super__.constructor.call(this, null); this.name = "#document"; this.type = NodeType.Document; this.documentURI = null; this.domConfig = new XMLDOMConfiguration(); options || (options = {}); if (!options.writer) { options.writer = new XMLStringWriter(); } this.options = options; this.stringify = new XMLStringifier(options); } Object.defineProperty(XMLDocument2.prototype, "implementation", { value: new XMLDOMImplementation() }); Object.defineProperty(XMLDocument2.prototype, "doctype", { get: function() { var child, i2, len, ref; ref = this.children; for (i2 = 0, len = ref.length; i2 < len; i2++) { child = ref[i2]; if (child.type === NodeType.DocType) { return child; } } return null; } }); Object.defineProperty(XMLDocument2.prototype, "documentElement", { get: function() { return this.rootObject || null; } }); Object.defineProperty(XMLDocument2.prototype, "inputEncoding", { get: function() { return null; } }); Object.defineProperty(XMLDocument2.prototype, "strictErrorChecking", { get: function() { return false; } }); Object.defineProperty(XMLDocument2.prototype, "xmlEncoding", { get: function() { if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { return this.children[0].encoding; } else { return null; } } }); Object.defineProperty(XMLDocument2.prototype, "xmlStandalone", { get: function() { if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { return this.children[0].standalone === "yes"; } else { return false; } } }); Object.defineProperty(XMLDocument2.prototype, "xmlVersion", { get: function() { if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { return this.children[0].version; } else { return "1.0"; } } }); Object.defineProperty(XMLDocument2.prototype, "URL", { get: function() { return this.documentURI; } }); Object.defineProperty(XMLDocument2.prototype, "origin", { get: function() { return null; } }); Object.defineProperty(XMLDocument2.prototype, "compatMode", { get: function() { return null; } }); Object.defineProperty(XMLDocument2.prototype, "characterSet", { get: function() { return null; } }); Object.defineProperty(XMLDocument2.prototype, "contentType", { get: function() { return null; } }); XMLDocument2.prototype.end = function(writer) { var writerOptions; writerOptions = {}; if (!writer) { writer = this.options.writer; } else if (isPlainObject4(writer)) { writerOptions = writer; writer = this.options.writer; } return writer.document(this, writer.filterOptions(writerOptions)); }; XMLDocument2.prototype.toString = function(options) { return this.options.writer.document(this, this.options.writer.filterOptions(options)); }; XMLDocument2.prototype.createElement = function(tagName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createDocumentFragment = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createTextNode = function(data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createComment = function(data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createCDATASection = function(data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createProcessingInstruction = function(target, data) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createAttribute = function(name2) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createEntityReference = function(name2) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.getElementsByTagName = function(tagname) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.importNode = function(importedNode, deep) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createElementNS = function(namespaceURI, qualifiedName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createAttributeNS = function(namespaceURI, qualifiedName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.getElementById = function(elementId) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.adoptNode = function(source) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.normalizeDocument = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.renameNode = function(node, namespaceURI, qualifiedName) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.getElementsByClassName = function(classNames) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createEvent = function(eventInterface) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createRange = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createNodeIterator = function(root3, whatToShow, filter) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLDocument2.prototype.createTreeWalker = function(root3, whatToShow, filter) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; return XMLDocument2; }(XMLNode); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDocumentCB.js var require_XMLDocumentCB = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLDocumentCB.js"(exports2, module2) { (function() { var NodeType, WriterState, XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocument, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue3, isFunction, isObject10, isPlainObject4, ref, hasProp = {}.hasOwnProperty; ref = require_Utility(), isObject10 = ref.isObject, isFunction = ref.isFunction, isPlainObject4 = ref.isPlainObject, getValue3 = ref.getValue; NodeType = require_NodeType(); XMLDocument = require_XMLDocument(); XMLElement = require_XMLElement(); XMLCData = require_XMLCData(); XMLComment = require_XMLComment(); XMLRaw = require_XMLRaw(); XMLText = require_XMLText(); XMLProcessingInstruction = require_XMLProcessingInstruction(); XMLDeclaration = require_XMLDeclaration(); XMLDocType = require_XMLDocType(); XMLDTDAttList = require_XMLDTDAttList(); XMLDTDEntity = require_XMLDTDEntity(); XMLDTDElement = require_XMLDTDElement(); XMLDTDNotation = require_XMLDTDNotation(); XMLAttribute = require_XMLAttribute(); XMLStringifier = require_XMLStringifier(); XMLStringWriter = require_XMLStringWriter(); WriterState = require_WriterState(); module2.exports = XMLDocumentCB = function() { function XMLDocumentCB2(options, onData, onEnd) { var writerOptions; this.name = "?xml"; this.type = NodeType.Document; options || (options = {}); writerOptions = {}; if (!options.writer) { options.writer = new XMLStringWriter(); } else if (isPlainObject4(options.writer)) { writerOptions = options.writer; options.writer = new XMLStringWriter(); } this.options = options; this.writer = options.writer; this.writerOptions = this.writer.filterOptions(writerOptions); this.stringify = new XMLStringifier(options); this.onDataCallback = onData || function() { }; this.onEndCallback = onEnd || function() { }; this.currentNode = null; this.currentLevel = -1; this.openTags = {}; this.documentStarted = false; this.documentCompleted = false; this.root = null; } XMLDocumentCB2.prototype.createChildNode = function(node) { var att, attName, attributes, child, i2, len, ref1, ref2; switch (node.type) { case NodeType.CData: this.cdata(node.value); break; case NodeType.Comment: this.comment(node.value); break; case NodeType.Element: attributes = {}; ref1 = node.attribs; for (attName in ref1) { if (!hasProp.call(ref1, attName)) continue; att = ref1[attName]; attributes[attName] = att.value; } this.node(node.name, attributes); break; case NodeType.Dummy: this.dummy(); break; case NodeType.Raw: this.raw(node.value); break; case NodeType.Text: this.text(node.value); break; case NodeType.ProcessingInstruction: this.instruction(node.target, node.value); break; default: throw new Error("This XML node type is not supported in a JS object: " + node.constructor.name); } ref2 = node.children; for (i2 = 0, len = ref2.length; i2 < len; i2++) { child = ref2[i2]; this.createChildNode(child); if (child.type === NodeType.Element) { this.up(); } } return this; }; XMLDocumentCB2.prototype.dummy = function() { return this; }; XMLDocumentCB2.prototype.node = function(name2, attributes, text) { var ref1; if (name2 == null) { throw new Error("Missing node name."); } if (this.root && this.currentLevel === -1) { throw new Error("Document can only have one root node. " + this.debugInfo(name2)); } this.openCurrent(); name2 = getValue3(name2); if (attributes == null) { attributes = {}; } attributes = getValue3(attributes); if (!isObject10(attributes)) { ref1 = [attributes, text], text = ref1[0], attributes = ref1[1]; } this.currentNode = new XMLElement(this, name2, attributes); this.currentNode.children = false; this.currentLevel++; this.openTags[this.currentLevel] = this.currentNode; if (text != null) { this.text(text); } return this; }; XMLDocumentCB2.prototype.element = function(name2, attributes, text) { var child, i2, len, oldValidationFlag, ref1, root3; if (this.currentNode && this.currentNode.type === NodeType.DocType) { this.dtdElement.apply(this, arguments); } else { if (Array.isArray(name2) || isObject10(name2) || isFunction(name2)) { oldValidationFlag = this.options.noValidation; this.options.noValidation = true; root3 = new XMLDocument(this.options).element("TEMP_ROOT"); root3.element(name2); this.options.noValidation = oldValidationFlag; ref1 = root3.children; for (i2 = 0, len = ref1.length; i2 < len; i2++) { child = ref1[i2]; this.createChildNode(child); if (child.type === NodeType.Element) { this.up(); } } } else { this.node(name2, attributes, text); } } return this; }; XMLDocumentCB2.prototype.attribute = function(name2, value) { var attName, attValue; if (!this.currentNode || this.currentNode.children) { throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name2)); } if (name2 != null) { name2 = getValue3(name2); } if (isObject10(name2)) { for (attName in name2) { if (!hasProp.call(name2, attName)) continue; attValue = name2[attName]; this.attribute(attName, attValue); } } else { if (isFunction(value)) { value = value.apply(); } if (this.options.keepNullAttributes && value == null) { this.currentNode.attribs[name2] = new XMLAttribute(this, name2, ""); } else if (value != null) { this.currentNode.attribs[name2] = new XMLAttribute(this, name2, value); } } return this; }; XMLDocumentCB2.prototype.text = function(value) { var node; this.openCurrent(); node = new XMLText(this, value); this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.cdata = function(value) { var node; this.openCurrent(); node = new XMLCData(this, value); this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.comment = function(value) { var node; this.openCurrent(); node = new XMLComment(this, value); this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.raw = function(value) { var node; this.openCurrent(); node = new XMLRaw(this, value); this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.instruction = function(target, value) { var i2, insTarget, insValue, len, node; this.openCurrent(); if (target != null) { target = getValue3(target); } if (value != null) { value = getValue3(value); } if (Array.isArray(target)) { for (i2 = 0, len = target.length; i2 < len; i2++) { insTarget = target[i2]; this.instruction(insTarget); } } else if (isObject10(target)) { for (insTarget in target) { if (!hasProp.call(target, insTarget)) continue; insValue = target[insTarget]; this.instruction(insTarget, insValue); } } else { if (isFunction(value)) { value = value.apply(); } node = new XMLProcessingInstruction(this, target, value); this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); } return this; }; XMLDocumentCB2.prototype.declaration = function(version3, encoding, standalone) { var node; this.openCurrent(); if (this.documentStarted) { throw new Error("declaration() must be the first node."); } node = new XMLDeclaration(this, version3, encoding, standalone); this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.doctype = function(root3, pubID, sysID) { this.openCurrent(); if (root3 == null) { throw new Error("Missing root node name."); } if (this.root) { throw new Error("dtd() must come before the root node."); } this.currentNode = new XMLDocType(this, pubID, sysID); this.currentNode.rootNodeName = root3; this.currentNode.children = false; this.currentLevel++; this.openTags[this.currentLevel] = this.currentNode; return this; }; XMLDocumentCB2.prototype.dtdElement = function(name2, value) { var node; this.openCurrent(); node = new XMLDTDElement(this, name2, value); this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { var node; this.openCurrent(); node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.entity = function(name2, value) { var node; this.openCurrent(); node = new XMLDTDEntity(this, false, name2, value); this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.pEntity = function(name2, value) { var node; this.openCurrent(); node = new XMLDTDEntity(this, true, name2, value); this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.notation = function(name2, value) { var node; this.openCurrent(); node = new XMLDTDNotation(this, name2, value); this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); return this; }; XMLDocumentCB2.prototype.up = function() { if (this.currentLevel < 0) { throw new Error("The document node has no parent."); } if (this.currentNode) { if (this.currentNode.children) { this.closeNode(this.currentNode); } else { this.openNode(this.currentNode); } this.currentNode = null; } else { this.closeNode(this.openTags[this.currentLevel]); } delete this.openTags[this.currentLevel]; this.currentLevel--; return this; }; XMLDocumentCB2.prototype.end = function() { while (this.currentLevel >= 0) { this.up(); } return this.onEnd(); }; XMLDocumentCB2.prototype.openCurrent = function() { if (this.currentNode) { this.currentNode.children = true; return this.openNode(this.currentNode); } }; XMLDocumentCB2.prototype.openNode = function(node) { var att, chunk, name2, ref1; if (!node.isOpen) { if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) { this.root = node; } chunk = ""; if (node.type === NodeType.Element) { this.writerOptions.state = WriterState.OpenTag; chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + "<" + node.name; ref1 = node.attribs; for (name2 in ref1) { if (!hasProp.call(ref1, name2)) continue; att = ref1[name2]; chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel); } chunk += (node.children ? ">" : "/>") + this.writer.endline(node, this.writerOptions, this.currentLevel); this.writerOptions.state = WriterState.InsideTag; } else { this.writerOptions.state = WriterState.OpenTag; chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ""; } chunk += this.writer.endline(node, this.writerOptions, this.currentLevel); } this.onData(chunk, this.currentLevel); return node.isOpen = true; } }; XMLDocumentCB2.prototype.closeNode = function(node) { var chunk; if (!node.isClosed) { chunk = ""; this.writerOptions.state = WriterState.CloseTag; if (node.type === NodeType.Element) { chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + "" + this.writer.endline(node, this.writerOptions, this.currentLevel); } else { chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + "]>" + this.writer.endline(node, this.writerOptions, this.currentLevel); } this.writerOptions.state = WriterState.None; this.onData(chunk, this.currentLevel); return node.isClosed = true; } }; XMLDocumentCB2.prototype.onData = function(chunk, level) { this.documentStarted = true; return this.onDataCallback(chunk, level + 1); }; XMLDocumentCB2.prototype.onEnd = function() { this.documentCompleted = true; return this.onEndCallback(); }; XMLDocumentCB2.prototype.debugInfo = function(name2) { if (name2 == null) { return ""; } else { return "node: <" + name2 + ">"; } }; XMLDocumentCB2.prototype.ele = function() { return this.element.apply(this, arguments); }; XMLDocumentCB2.prototype.nod = function(name2, attributes, text) { return this.node(name2, attributes, text); }; XMLDocumentCB2.prototype.txt = function(value) { return this.text(value); }; XMLDocumentCB2.prototype.dat = function(value) { return this.cdata(value); }; XMLDocumentCB2.prototype.com = function(value) { return this.comment(value); }; XMLDocumentCB2.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLDocumentCB2.prototype.dec = function(version3, encoding, standalone) { return this.declaration(version3, encoding, standalone); }; XMLDocumentCB2.prototype.dtd = function(root3, pubID, sysID) { return this.doctype(root3, pubID, sysID); }; XMLDocumentCB2.prototype.e = function(name2, attributes, text) { return this.element(name2, attributes, text); }; XMLDocumentCB2.prototype.n = function(name2, attributes, text) { return this.node(name2, attributes, text); }; XMLDocumentCB2.prototype.t = function(value) { return this.text(value); }; XMLDocumentCB2.prototype.d = function(value) { return this.cdata(value); }; XMLDocumentCB2.prototype.c = function(value) { return this.comment(value); }; XMLDocumentCB2.prototype.r = function(value) { return this.raw(value); }; XMLDocumentCB2.prototype.i = function(target, value) { return this.instruction(target, value); }; XMLDocumentCB2.prototype.att = function() { if (this.currentNode && this.currentNode.type === NodeType.DocType) { return this.attList.apply(this, arguments); } else { return this.attribute.apply(this, arguments); } }; XMLDocumentCB2.prototype.a = function() { if (this.currentNode && this.currentNode.type === NodeType.DocType) { return this.attList.apply(this, arguments); } else { return this.attribute.apply(this, arguments); } }; XMLDocumentCB2.prototype.ent = function(name2, value) { return this.entity(name2, value); }; XMLDocumentCB2.prototype.pent = function(name2, value) { return this.pEntity(name2, value); }; XMLDocumentCB2.prototype.not = function(name2, value) { return this.notation(name2, value); }; return XMLDocumentCB2; }(); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLStreamWriter.js var require_XMLStreamWriter = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/XMLStreamWriter.js"(exports2, module2) { (function() { var NodeType, WriterState, XMLStreamWriter, XMLWriterBase, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NodeType = require_NodeType(); XMLWriterBase = require_XMLWriterBase(); WriterState = require_WriterState(); module2.exports = XMLStreamWriter = function(superClass) { extend4(XMLStreamWriter2, superClass); function XMLStreamWriter2(stream, options) { this.stream = stream; XMLStreamWriter2.__super__.constructor.call(this, options); } XMLStreamWriter2.prototype.endline = function(node, options, level) { if (node.isLastRootNode && options.state === WriterState.CloseTag) { return ""; } else { return XMLStreamWriter2.__super__.endline.call(this, node, options, level); } }; XMLStreamWriter2.prototype.document = function(doc, options) { var child, i2, j2, k2, len, len1, ref, ref1, results; ref = doc.children; for (i2 = j2 = 0, len = ref.length; j2 < len; i2 = ++j2) { child = ref[i2]; child.isLastRootNode = i2 === doc.children.length - 1; } options = this.filterOptions(options); ref1 = doc.children; results = []; for (k2 = 0, len1 = ref1.length; k2 < len1; k2++) { child = ref1[k2]; results.push(this.writeChildNode(child, options, 0)); } return results; }; XMLStreamWriter2.prototype.attribute = function(att, options, level) { return this.stream.write(XMLStreamWriter2.__super__.attribute.call(this, att, options, level)); }; XMLStreamWriter2.prototype.cdata = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.cdata.call(this, node, options, level)); }; XMLStreamWriter2.prototype.comment = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.comment.call(this, node, options, level)); }; XMLStreamWriter2.prototype.declaration = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.declaration.call(this, node, options, level)); }; XMLStreamWriter2.prototype.docType = function(node, options, level) { var child, j2, len, ref; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; this.stream.write(this.indent(node, options, level)); this.stream.write(" 0) { this.stream.write(" ["); this.stream.write(this.endline(node, options, level)); options.state = WriterState.InsideTag; ref = node.children; for (j2 = 0, len = ref.length; j2 < len; j2++) { child = ref[j2]; this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; this.stream.write("]"); } options.state = WriterState.CloseTag; this.stream.write(options.spaceBeforeSlash + ">"); this.stream.write(this.endline(node, options, level)); options.state = WriterState.None; return this.closeNode(node, options, level); }; XMLStreamWriter2.prototype.element = function(node, options, level) { var att, child, childNodeCount, firstChildNode, j2, len, name2, prettySuppressed, ref, ref1; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; this.stream.write(this.indent(node, options, level) + "<" + node.name); ref = node.attribs; for (name2 in ref) { if (!hasProp.call(ref, name2)) continue; att = ref[name2]; this.attribute(att, options, level); } childNodeCount = node.children.length; firstChildNode = childNodeCount === 0 ? null : node.children[0]; if (childNodeCount === 0 || node.children.every(function(e2) { return (e2.type === NodeType.Text || e2.type === NodeType.Raw) && e2.value === ""; })) { if (options.allowEmpty) { this.stream.write(">"); options.state = WriterState.CloseTag; this.stream.write(""); } else { options.state = WriterState.CloseTag; this.stream.write(options.spaceBeforeSlash + "/>"); } } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && firstChildNode.value != null) { this.stream.write(">"); options.state = WriterState.InsideTag; options.suppressPrettyCount++; prettySuppressed = true; this.writeChildNode(firstChildNode, options, level + 1); options.suppressPrettyCount--; prettySuppressed = false; options.state = WriterState.CloseTag; this.stream.write(""); } else { this.stream.write(">" + this.endline(node, options, level)); options.state = WriterState.InsideTag; ref1 = node.children; for (j2 = 0, len = ref1.length; j2 < len; j2++) { child = ref1[j2]; this.writeChildNode(child, options, level + 1); } options.state = WriterState.CloseTag; this.stream.write(this.indent(node, options, level) + ""); } this.stream.write(this.endline(node, options, level)); options.state = WriterState.None; return this.closeNode(node, options, level); }; XMLStreamWriter2.prototype.processingInstruction = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.processingInstruction.call(this, node, options, level)); }; XMLStreamWriter2.prototype.raw = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.raw.call(this, node, options, level)); }; XMLStreamWriter2.prototype.text = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.text.call(this, node, options, level)); }; XMLStreamWriter2.prototype.dtdAttList = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.dtdAttList.call(this, node, options, level)); }; XMLStreamWriter2.prototype.dtdElement = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.dtdElement.call(this, node, options, level)); }; XMLStreamWriter2.prototype.dtdEntity = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.dtdEntity.call(this, node, options, level)); }; XMLStreamWriter2.prototype.dtdNotation = function(node, options, level) { return this.stream.write(XMLStreamWriter2.__super__.dtdNotation.call(this, node, options, level)); }; return XMLStreamWriter2; }(XMLWriterBase); }).call(exports2); } }); // node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/index.js var require_lib = __commonJS({ "node_modules/.pnpm/xmlbuilder@11.0.1/node_modules/xmlbuilder/lib/index.js"(exports2, module2) { (function() { var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref; ref = require_Utility(), assign = ref.assign, isFunction = ref.isFunction; XMLDOMImplementation = require_XMLDOMImplementation(); XMLDocument = require_XMLDocument(); XMLDocumentCB = require_XMLDocumentCB(); XMLStringWriter = require_XMLStringWriter(); XMLStreamWriter = require_XMLStreamWriter(); NodeType = require_NodeType(); WriterState = require_WriterState(); module2.exports.create = function(name2, xmldec, doctype, options) { var doc, root3; if (name2 == null) { throw new Error("Root element needs a name."); } options = assign({}, xmldec, doctype, options); doc = new XMLDocument(options); root3 = doc.element(name2); if (!options.headless) { doc.declaration(options); if (options.pubID != null || options.sysID != null) { doc.dtd(options); } } return root3; }; module2.exports.begin = function(options, onData, onEnd) { var ref1; if (isFunction(options)) { ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1]; options = {}; } if (onData) { return new XMLDocumentCB(options, onData, onEnd); } else { return new XMLDocument(options); } }; module2.exports.stringWriter = function(options) { return new XMLStringWriter(options); }; module2.exports.streamWriter = function(stream, options) { return new XMLStreamWriter(stream, options); }; module2.exports.implementation = new XMLDOMImplementation(); module2.exports.nodeType = NodeType; module2.exports.writerState = WriterState; }).call(exports2); } }); // node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/builder.js var require_builder = __commonJS({ "node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/builder.js"(exports2) { (function() { "use strict"; var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, hasProp = {}.hasOwnProperty; builder = require_lib(); defaults = require_defaults().defaults; requiresCDATA = function(entry) { return typeof entry === "string" && (entry.indexOf("&") >= 0 || entry.indexOf(">") >= 0 || entry.indexOf("<") >= 0); }; wrapCDATA = function(entry) { return ""; }; escapeCDATA = function(entry) { return entry.replace("]]>", "]]]]>"); }; exports2.Builder = function() { function Builder(opts) { var key, ref, value; this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } } Builder.prototype.buildObject = function(rootObj) { var attrkey, charkey, render, rootElement, rootName; attrkey = this.options.attrkey; charkey = this.options.charkey; if (Object.keys(rootObj).length === 1 && this.options.rootName === defaults["0.2"].rootName) { rootName = Object.keys(rootObj)[0]; rootObj = rootObj[rootName]; } else { rootName = this.options.rootName; } render = function(_this) { return function(element, obj) { var attr, child, entry, index2, key, value; if (typeof obj !== "object") { if (_this.options.cdata && requiresCDATA(obj)) { element.raw(wrapCDATA(obj)); } else { element.txt(obj); } } else if (Array.isArray(obj)) { for (index2 in obj) { if (!hasProp.call(obj, index2)) continue; child = obj[index2]; for (key in child) { entry = child[key]; element = render(element.ele(key), entry).up(); } } } else { for (key in obj) { if (!hasProp.call(obj, key)) continue; child = obj[key]; if (key === attrkey) { if (typeof child === "object") { for (attr in child) { value = child[attr]; element = element.att(attr, value); } } } else if (key === charkey) { if (_this.options.cdata && requiresCDATA(child)) { element = element.raw(wrapCDATA(child)); } else { element = element.txt(child); } } else if (Array.isArray(child)) { for (index2 in child) { if (!hasProp.call(child, index2)) continue; entry = child[index2]; if (typeof entry === "string") { if (_this.options.cdata && requiresCDATA(entry)) { element = element.ele(key).raw(wrapCDATA(entry)).up(); } else { element = element.ele(key, entry).up(); } } else { element = render(element.ele(key), entry).up(); } } } else if (typeof child === "object") { element = render(element.ele(key), child).up(); } else { if (typeof child === "string" && _this.options.cdata && requiresCDATA(child)) { element = element.ele(key).raw(wrapCDATA(child)).up(); } else { if (child == null) { child = ""; } element = element.ele(key, child.toString()).up(); } } } } return element; }; }(this); rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, { headless: this.options.headless, allowSurrogateChars: this.options.allowSurrogateChars }); return render(rootElement, rootObj).end(this.options.renderOpts); }; return Builder; }(); }).call(exports2); } }); // node_modules/.pnpm/sax@1.3.0/node_modules/sax/lib/sax.js var require_sax = __commonJS({ "node_modules/.pnpm/sax@1.3.0/node_modules/sax/lib/sax.js"(exports2) { (function(sax2) { sax2.parser = function(strict, opt) { return new SAXParser(strict, opt); }; sax2.SAXParser = SAXParser; sax2.SAXStream = SAXStream; sax2.createStream = createStream; sax2.MAX_BUFFER_LENGTH = 64 * 1024; var buffers = [ "comment", "sgmlDecl", "textNode", "tagName", "doctype", "procInstName", "procInstBody", "entity", "attribName", "attribValue", "cdata", "script" ]; sax2.EVENTS = [ "text", "processinginstruction", "sgmldeclaration", "doctype", "comment", "opentagstart", "attribute", "opentag", "closetag", "opencdata", "cdata", "closecdata", "error", "end", "ready", "script", "opennamespace", "closenamespace" ]; function SAXParser(strict, opt) { if (!(this instanceof SAXParser)) { return new SAXParser(strict, opt); } var parser = this; clearBuffers(parser); parser.q = parser.c = ""; parser.bufferCheckPosition = sax2.MAX_BUFFER_LENGTH; parser.opt = opt || {}; parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; parser.tags = []; parser.closed = parser.closedRoot = parser.sawRoot = false; parser.tag = parser.error = null; parser.strict = !!strict; parser.noscript = !!(strict || parser.opt.noscript); parser.state = S2.BEGIN; parser.strictEntities = parser.opt.strictEntities; parser.ENTITIES = parser.strictEntities ? Object.create(sax2.XML_ENTITIES) : Object.create(sax2.ENTITIES); parser.attribList = []; if (parser.opt.xmlns) { parser.ns = Object.create(rootNS); } parser.trackPosition = parser.opt.position !== false; if (parser.trackPosition) { parser.position = parser.line = parser.column = 0; } emit(parser, "onready"); } if (!Object.create) { Object.create = function(o2) { function F2() { } F2.prototype = o2; var newf = new F2(); return newf; }; } if (!Object.keys) { Object.keys = function(o2) { var a2 = []; for (var i2 in o2) if (o2.hasOwnProperty(i2)) a2.push(i2); return a2; }; } function checkBufferLength(parser) { var maxAllowed = Math.max(sax2.MAX_BUFFER_LENGTH, 10); var maxActual = 0; for (var i2 = 0, l2 = buffers.length; i2 < l2; i2++) { var len = parser[buffers[i2]].length; if (len > maxAllowed) { switch (buffers[i2]) { case "textNode": closeText(parser); break; case "cdata": emitNode(parser, "oncdata", parser.cdata); parser.cdata = ""; break; case "script": emitNode(parser, "onscript", parser.script); parser.script = ""; break; default: error(parser, "Max buffer length exceeded: " + buffers[i2]); } } maxActual = Math.max(maxActual, len); } var m2 = sax2.MAX_BUFFER_LENGTH - maxActual; parser.bufferCheckPosition = m2 + parser.position; } function clearBuffers(parser) { for (var i2 = 0, l2 = buffers.length; i2 < l2; i2++) { parser[buffers[i2]] = ""; } } function flushBuffers(parser) { closeText(parser); if (parser.cdata !== "") { emitNode(parser, "oncdata", parser.cdata); parser.cdata = ""; } if (parser.script !== "") { emitNode(parser, "onscript", parser.script); parser.script = ""; } } SAXParser.prototype = { end: function() { end(this); }, write, resume: function() { this.error = null; return this; }, close: function() { return this.write(null); }, flush: function() { flushBuffers(this); } }; var Stream4; try { Stream4 = require("stream").Stream; } catch (ex) { Stream4 = function() { }; } if (!Stream4) Stream4 = function() { }; var streamWraps = sax2.EVENTS.filter(function(ev) { return ev !== "error" && ev !== "end"; }); function createStream(strict, opt) { return new SAXStream(strict, opt); } function SAXStream(strict, opt) { if (!(this instanceof SAXStream)) { return new SAXStream(strict, opt); } Stream4.apply(this); this._parser = new SAXParser(strict, opt); this.writable = true; this.readable = true; var me2 = this; this._parser.onend = function() { me2.emit("end"); }; this._parser.onerror = function(er) { me2.emit("error", er); me2._parser.error = null; }; this._decoder = null; streamWraps.forEach(function(ev) { Object.defineProperty(me2, "on" + ev, { get: function() { return me2._parser["on" + ev]; }, set: function(h2) { if (!h2) { me2.removeAllListeners(ev); me2._parser["on" + ev] = h2; return h2; } me2.on(ev, h2); }, enumerable: true, configurable: false }); }); } SAXStream.prototype = Object.create(Stream4.prototype, { constructor: { value: SAXStream } }); SAXStream.prototype.write = function(data) { if (typeof Buffer === "function" && typeof Buffer.isBuffer === "function" && Buffer.isBuffer(data)) { if (!this._decoder) { var SD = require("string_decoder").StringDecoder; this._decoder = new SD("utf8"); } data = this._decoder.write(data); } this._parser.write(data.toString()); this.emit("data", data); return true; }; SAXStream.prototype.end = function(chunk) { if (chunk && chunk.length) { this.write(chunk); } this._parser.end(); return true; }; SAXStream.prototype.on = function(ev, handler) { var me2 = this; if (!me2._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) { me2._parser["on" + ev] = function() { var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); args.splice(0, 0, ev); me2.emit.apply(me2, args); }; } return Stream4.prototype.on.call(me2, ev, handler); }; var CDATA = "[CDATA["; var DOCTYPE = "DOCTYPE"; var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }; var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; function isWhitespace2(c2) { return c2 === " " || c2 === "\n" || c2 === "\r" || c2 === " "; } function isQuote(c2) { return c2 === '"' || c2 === "'"; } function isAttribEnd(c2) { return c2 === ">" || isWhitespace2(c2); } function isMatch(regex2, c2) { return regex2.test(c2); } function notMatch(regex2, c2) { return !isMatch(regex2, c2); } var S2 = 0; sax2.STATE = { BEGIN: S2++, BEGIN_WHITESPACE: S2++, TEXT: S2++, TEXT_ENTITY: S2++, OPEN_WAKA: S2++, SGML_DECL: S2++, SGML_DECL_QUOTED: S2++, DOCTYPE: S2++, DOCTYPE_QUOTED: S2++, DOCTYPE_DTD: S2++, DOCTYPE_DTD_QUOTED: S2++, COMMENT_STARTING: S2++, COMMENT: S2++, COMMENT_ENDING: S2++, COMMENT_ENDED: S2++, CDATA: S2++, CDATA_ENDING: S2++, CDATA_ENDING_2: S2++, PROC_INST: S2++, PROC_INST_BODY: S2++, PROC_INST_ENDING: S2++, OPEN_TAG: S2++, OPEN_TAG_SLASH: S2++, ATTRIB: S2++, ATTRIB_NAME: S2++, ATTRIB_NAME_SAW_WHITE: S2++, ATTRIB_VALUE: S2++, ATTRIB_VALUE_QUOTED: S2++, ATTRIB_VALUE_CLOSED: S2++, ATTRIB_VALUE_UNQUOTED: S2++, ATTRIB_VALUE_ENTITY_Q: S2++, ATTRIB_VALUE_ENTITY_U: S2++, CLOSE_TAG: S2++, CLOSE_TAG_SAW_WHITE: S2++, SCRIPT: S2++, SCRIPT_ENDING: S2++ }; sax2.XML_ENTITIES = { "amp": "&", "gt": ">", "lt": "<", "quot": '"', "apos": "'" }; sax2.ENTITIES = { "amp": "&", "gt": ">", "lt": "<", "quot": '"', "apos": "'", "AElig": 198, "Aacute": 193, "Acirc": 194, "Agrave": 192, "Aring": 197, "Atilde": 195, "Auml": 196, "Ccedil": 199, "ETH": 208, "Eacute": 201, "Ecirc": 202, "Egrave": 200, "Euml": 203, "Iacute": 205, "Icirc": 206, "Igrave": 204, "Iuml": 207, "Ntilde": 209, "Oacute": 211, "Ocirc": 212, "Ograve": 210, "Oslash": 216, "Otilde": 213, "Ouml": 214, "THORN": 222, "Uacute": 218, "Ucirc": 219, "Ugrave": 217, "Uuml": 220, "Yacute": 221, "aacute": 225, "acirc": 226, "aelig": 230, "agrave": 224, "aring": 229, "atilde": 227, "auml": 228, "ccedil": 231, "eacute": 233, "ecirc": 234, "egrave": 232, "eth": 240, "euml": 235, "iacute": 237, "icirc": 238, "igrave": 236, "iuml": 239, "ntilde": 241, "oacute": 243, "ocirc": 244, "ograve": 242, "oslash": 248, "otilde": 245, "ouml": 246, "szlig": 223, "thorn": 254, "uacute": 250, "ucirc": 251, "ugrave": 249, "uuml": 252, "yacute": 253, "yuml": 255, "copy": 169, "reg": 174, "nbsp": 160, "iexcl": 161, "cent": 162, "pound": 163, "curren": 164, "yen": 165, "brvbar": 166, "sect": 167, "uml": 168, "ordf": 170, "laquo": 171, "not": 172, "shy": 173, "macr": 175, "deg": 176, "plusmn": 177, "sup1": 185, "sup2": 178, "sup3": 179, "acute": 180, "micro": 181, "para": 182, "middot": 183, "cedil": 184, "ordm": 186, "raquo": 187, "frac14": 188, "frac12": 189, "frac34": 190, "iquest": 191, "times": 215, "divide": 247, "OElig": 338, "oelig": 339, "Scaron": 352, "scaron": 353, "Yuml": 376, "fnof": 402, "circ": 710, "tilde": 732, "Alpha": 913, "Beta": 914, "Gamma": 915, "Delta": 916, "Epsilon": 917, "Zeta": 918, "Eta": 919, "Theta": 920, "Iota": 921, "Kappa": 922, "Lambda": 923, "Mu": 924, "Nu": 925, "Xi": 926, "Omicron": 927, "Pi": 928, "Rho": 929, "Sigma": 931, "Tau": 932, "Upsilon": 933, "Phi": 934, "Chi": 935, "Psi": 936, "Omega": 937, "alpha": 945, "beta": 946, "gamma": 947, "delta": 948, "epsilon": 949, "zeta": 950, "eta": 951, "theta": 952, "iota": 953, "kappa": 954, "lambda": 955, "mu": 956, "nu": 957, "xi": 958, "omicron": 959, "pi": 960, "rho": 961, "sigmaf": 962, "sigma": 963, "tau": 964, "upsilon": 965, "phi": 966, "chi": 967, "psi": 968, "omega": 969, "thetasym": 977, "upsih": 978, "piv": 982, "ensp": 8194, "emsp": 8195, "thinsp": 8201, "zwnj": 8204, "zwj": 8205, "lrm": 8206, "rlm": 8207, "ndash": 8211, "mdash": 8212, "lsquo": 8216, "rsquo": 8217, "sbquo": 8218, "ldquo": 8220, "rdquo": 8221, "bdquo": 8222, "dagger": 8224, "Dagger": 8225, "bull": 8226, "hellip": 8230, "permil": 8240, "prime": 8242, "Prime": 8243, "lsaquo": 8249, "rsaquo": 8250, "oline": 8254, "frasl": 8260, "euro": 8364, "image": 8465, "weierp": 8472, "real": 8476, "trade": 8482, "alefsym": 8501, "larr": 8592, "uarr": 8593, "rarr": 8594, "darr": 8595, "harr": 8596, "crarr": 8629, "lArr": 8656, "uArr": 8657, "rArr": 8658, "dArr": 8659, "hArr": 8660, "forall": 8704, "part": 8706, "exist": 8707, "empty": 8709, "nabla": 8711, "isin": 8712, "notin": 8713, "ni": 8715, "prod": 8719, "sum": 8721, "minus": 8722, "lowast": 8727, "radic": 8730, "prop": 8733, "infin": 8734, "ang": 8736, "and": 8743, "or": 8744, "cap": 8745, "cup": 8746, "int": 8747, "there4": 8756, "sim": 8764, "cong": 8773, "asymp": 8776, "ne": 8800, "equiv": 8801, "le": 8804, "ge": 8805, "sub": 8834, "sup": 8835, "nsub": 8836, "sube": 8838, "supe": 8839, "oplus": 8853, "otimes": 8855, "perp": 8869, "sdot": 8901, "lceil": 8968, "rceil": 8969, "lfloor": 8970, "rfloor": 8971, "lang": 9001, "rang": 9002, "loz": 9674, "spades": 9824, "clubs": 9827, "hearts": 9829, "diams": 9830 }; Object.keys(sax2.ENTITIES).forEach(function(key) { var e2 = sax2.ENTITIES[key]; var s3 = typeof e2 === "number" ? String.fromCharCode(e2) : e2; sax2.ENTITIES[key] = s3; }); for (var s2 in sax2.STATE) { sax2.STATE[sax2.STATE[s2]] = s2; } S2 = sax2.STATE; function emit(parser, event2, data) { parser[event2] && parser[event2](data); } function emitNode(parser, nodeType, data) { if (parser.textNode) closeText(parser); emit(parser, nodeType, data); } function closeText(parser) { parser.textNode = textopts(parser.opt, parser.textNode); if (parser.textNode) emit(parser, "ontext", parser.textNode); parser.textNode = ""; } function textopts(opt, text) { if (opt.trim) text = text.trim(); if (opt.normalize) text = text.replace(/\s+/g, " "); return text; } function error(parser, er) { closeText(parser); if (parser.trackPosition) { er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c; } er = new Error(er); parser.error = er; emit(parser, "onerror", er); return parser; } function end(parser) { if (parser.sawRoot && !parser.closedRoot) strictFail(parser, "Unclosed root tag"); if (parser.state !== S2.BEGIN && parser.state !== S2.BEGIN_WHITESPACE && parser.state !== S2.TEXT) { error(parser, "Unexpected end"); } closeText(parser); parser.c = ""; parser.closed = true; emit(parser, "onend"); SAXParser.call(parser, parser.strict, parser.opt); return parser; } function strictFail(parser, message) { if (typeof parser !== "object" || !(parser instanceof SAXParser)) { throw new Error("bad call to strictFail"); } if (parser.strict) { error(parser, message); } } function newTag(parser) { if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase](); var parent = parser.tags[parser.tags.length - 1] || parser; var tag = parser.tag = { name: parser.tagName, attributes: {} }; if (parser.opt.xmlns) { tag.ns = parent.ns; } parser.attribList.length = 0; emitNode(parser, "onopentagstart", tag); } function qname(name2, attribute) { var i2 = name2.indexOf(":"); var qualName = i2 < 0 ? ["", name2] : name2.split(":"); var prefix = qualName[0]; var local = qualName[1]; if (attribute && name2 === "xmlns") { prefix = "xmlns"; local = ""; } return { prefix, local }; } function attrib(parser) { if (!parser.strict) { parser.attribName = parser.attribName[parser.looseCase](); } if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) { parser.attribName = parser.attribValue = ""; return; } if (parser.opt.xmlns) { var qn = qname(parser.attribName, true); var prefix = qn.prefix; var local = qn.local; if (prefix === "xmlns") { if (local === "xml" && parser.attribValue !== XML_NAMESPACE) { strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + "\nActual: " + parser.attribValue); } else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) { strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + "\nActual: " + parser.attribValue); } else { var tag = parser.tag; var parent = parser.tags[parser.tags.length - 1] || parser; if (tag.ns === parent.ns) { tag.ns = Object.create(parent.ns); } tag.ns[local] = parser.attribValue; } } parser.attribList.push([parser.attribName, parser.attribValue]); } else { parser.tag.attributes[parser.attribName] = parser.attribValue; emitNode(parser, "onattribute", { name: parser.attribName, value: parser.attribValue }); } parser.attribName = parser.attribValue = ""; } function openTag(parser, selfClosing) { if (parser.opt.xmlns) { var tag = parser.tag; var qn = qname(parser.tagName); tag.prefix = qn.prefix; tag.local = qn.local; tag.uri = tag.ns[qn.prefix] || ""; if (tag.prefix && !tag.uri) { strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName)); tag.uri = qn.prefix; } var parent = parser.tags[parser.tags.length - 1] || parser; if (tag.ns && parent.ns !== tag.ns) { Object.keys(tag.ns).forEach(function(p2) { emitNode(parser, "onopennamespace", { prefix: p2, uri: tag.ns[p2] }); }); } for (var i2 = 0, l2 = parser.attribList.length; i2 < l2; i2++) { var nv = parser.attribList[i2]; var name2 = nv[0]; var value = nv[1]; var qualName = qname(name2, true); var prefix = qualName.prefix; var local = qualName.local; var uri2 = prefix === "" ? "" : tag.ns[prefix] || ""; var a2 = { name: name2, value, prefix, local, uri: uri2 }; if (prefix && prefix !== "xmlns" && !uri2) { strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); a2.uri = prefix; } parser.tag.attributes[name2] = a2; emitNode(parser, "onattribute", a2); } parser.attribList.length = 0; } parser.tag.isSelfClosing = !!selfClosing; parser.sawRoot = true; parser.tags.push(parser.tag); emitNode(parser, "onopentag", parser.tag); if (!selfClosing) { if (!parser.noscript && parser.tagName.toLowerCase() === "script") { parser.state = S2.SCRIPT; } else { parser.state = S2.TEXT; } parser.tag = null; parser.tagName = ""; } parser.attribName = parser.attribValue = ""; parser.attribList.length = 0; } function closeTag(parser) { if (!parser.tagName) { strictFail(parser, "Weird empty close tag."); parser.textNode += ""; parser.state = S2.TEXT; return; } if (parser.script) { if (parser.tagName !== "script") { parser.script += ""; parser.tagName = ""; parser.state = S2.SCRIPT; return; } emitNode(parser, "onscript", parser.script); parser.script = ""; } var t2 = parser.tags.length; var tagName = parser.tagName; if (!parser.strict) { tagName = tagName[parser.looseCase](); } var closeTo = tagName; while (t2--) { var close = parser.tags[t2]; if (close.name !== closeTo) { strictFail(parser, "Unexpected close tag"); } else { break; } } if (t2 < 0) { strictFail(parser, "Unmatched closing tag: " + parser.tagName); parser.textNode += ""; parser.state = S2.TEXT; return; } parser.tagName = tagName; var s3 = parser.tags.length; while (s3-- > t2) { var tag = parser.tag = parser.tags.pop(); parser.tagName = parser.tag.name; emitNode(parser, "onclosetag", parser.tagName); var x2 = {}; for (var i2 in tag.ns) { x2[i2] = tag.ns[i2]; } var parent = parser.tags[parser.tags.length - 1] || parser; if (parser.opt.xmlns && tag.ns !== parent.ns) { Object.keys(tag.ns).forEach(function(p2) { var n2 = tag.ns[p2]; emitNode(parser, "onclosenamespace", { prefix: p2, uri: n2 }); }); } } if (t2 === 0) parser.closedRoot = true; parser.tagName = parser.attribValue = parser.attribName = ""; parser.attribList.length = 0; parser.state = S2.TEXT; } function parseEntity(parser) { var entity = parser.entity; var entityLC = entity.toLowerCase(); var num; var numStr = ""; if (parser.ENTITIES[entity]) { return parser.ENTITIES[entity]; } if (parser.ENTITIES[entityLC]) { return parser.ENTITIES[entityLC]; } entity = entityLC; if (entity.charAt(0) === "#") { if (entity.charAt(1) === "x") { entity = entity.slice(2); num = parseInt(entity, 16); numStr = num.toString(16); } else { entity = entity.slice(1); num = parseInt(entity, 10); numStr = num.toString(10); } } entity = entity.replace(/^0+/, ""); if (isNaN(num) || numStr.toLowerCase() !== entity) { strictFail(parser, "Invalid character entity"); return "&" + parser.entity + ";"; } return String.fromCodePoint(num); } function beginWhiteSpace(parser, c2) { if (c2 === "<") { parser.state = S2.OPEN_WAKA; parser.startTagPosition = parser.position; } else if (!isWhitespace2(c2)) { strictFail(parser, "Non-whitespace before first tag."); parser.textNode = c2; parser.state = S2.TEXT; } } function charAt(chunk, i2) { var result = ""; if (i2 < chunk.length) { result = chunk.charAt(i2); } return result; } function write(chunk) { var parser = this; if (this.error) { throw this.error; } if (parser.closed) { return error(parser, "Cannot write after close. Assign an onready handler."); } if (chunk === null) { return end(parser); } if (typeof chunk === "object") { chunk = chunk.toString(); } var i2 = 0; var c2 = ""; while (true) { c2 = charAt(chunk, i2++); parser.c = c2; if (!c2) { break; } if (parser.trackPosition) { parser.position++; if (c2 === "\n") { parser.line++; parser.column = 0; } else { parser.column++; } } switch (parser.state) { case S2.BEGIN: parser.state = S2.BEGIN_WHITESPACE; if (c2 === "\uFEFF") { continue; } beginWhiteSpace(parser, c2); continue; case S2.BEGIN_WHITESPACE: beginWhiteSpace(parser, c2); continue; case S2.TEXT: if (parser.sawRoot && !parser.closedRoot) { var starti = i2 - 1; while (c2 && c2 !== "<" && c2 !== "&") { c2 = charAt(chunk, i2++); if (c2 && parser.trackPosition) { parser.position++; if (c2 === "\n") { parser.line++; parser.column = 0; } else { parser.column++; } } } parser.textNode += chunk.substring(starti, i2 - 1); } if (c2 === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { parser.state = S2.OPEN_WAKA; parser.startTagPosition = parser.position; } else { if (!isWhitespace2(c2) && (!parser.sawRoot || parser.closedRoot)) { strictFail(parser, "Text data outside of root node."); } if (c2 === "&") { parser.state = S2.TEXT_ENTITY; } else { parser.textNode += c2; } } continue; case S2.SCRIPT: if (c2 === "<") { parser.state = S2.SCRIPT_ENDING; } else { parser.script += c2; } continue; case S2.SCRIPT_ENDING: if (c2 === "/") { parser.state = S2.CLOSE_TAG; } else { parser.script += "<" + c2; parser.state = S2.SCRIPT; } continue; case S2.OPEN_WAKA: if (c2 === "!") { parser.state = S2.SGML_DECL; parser.sgmlDecl = ""; } else if (isWhitespace2(c2)) { } else if (isMatch(nameStart, c2)) { parser.state = S2.OPEN_TAG; parser.tagName = c2; } else if (c2 === "/") { parser.state = S2.CLOSE_TAG; parser.tagName = ""; } else if (c2 === "?") { parser.state = S2.PROC_INST; parser.procInstName = parser.procInstBody = ""; } else { strictFail(parser, "Unencoded <"); if (parser.startTagPosition + 1 < parser.position) { var pad2 = parser.position - parser.startTagPosition; c2 = new Array(pad2).join(" ") + c2; } parser.textNode += "<" + c2; parser.state = S2.TEXT; } continue; case S2.SGML_DECL: if ((parser.sgmlDecl + c2).toUpperCase() === CDATA) { emitNode(parser, "onopencdata"); parser.state = S2.CDATA; parser.sgmlDecl = ""; parser.cdata = ""; } else if (parser.sgmlDecl + c2 === "--") { parser.state = S2.COMMENT; parser.comment = ""; parser.sgmlDecl = ""; } else if ((parser.sgmlDecl + c2).toUpperCase() === DOCTYPE) { parser.state = S2.DOCTYPE; if (parser.doctype || parser.sawRoot) { strictFail(parser, "Inappropriately located doctype declaration"); } parser.doctype = ""; parser.sgmlDecl = ""; } else if (c2 === ">") { emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); parser.sgmlDecl = ""; parser.state = S2.TEXT; } else if (isQuote(c2)) { parser.state = S2.SGML_DECL_QUOTED; parser.sgmlDecl += c2; } else { parser.sgmlDecl += c2; } continue; case S2.SGML_DECL_QUOTED: if (c2 === parser.q) { parser.state = S2.SGML_DECL; parser.q = ""; } parser.sgmlDecl += c2; continue; case S2.DOCTYPE: if (c2 === ">") { parser.state = S2.TEXT; emitNode(parser, "ondoctype", parser.doctype); parser.doctype = true; } else { parser.doctype += c2; if (c2 === "[") { parser.state = S2.DOCTYPE_DTD; } else if (isQuote(c2)) { parser.state = S2.DOCTYPE_QUOTED; parser.q = c2; } } continue; case S2.DOCTYPE_QUOTED: parser.doctype += c2; if (c2 === parser.q) { parser.q = ""; parser.state = S2.DOCTYPE; } continue; case S2.DOCTYPE_DTD: parser.doctype += c2; if (c2 === "]") { parser.state = S2.DOCTYPE; } else if (isQuote(c2)) { parser.state = S2.DOCTYPE_DTD_QUOTED; parser.q = c2; } continue; case S2.DOCTYPE_DTD_QUOTED: parser.doctype += c2; if (c2 === parser.q) { parser.state = S2.DOCTYPE_DTD; parser.q = ""; } continue; case S2.COMMENT: if (c2 === "-") { parser.state = S2.COMMENT_ENDING; } else { parser.comment += c2; } continue; case S2.COMMENT_ENDING: if (c2 === "-") { parser.state = S2.COMMENT_ENDED; parser.comment = textopts(parser.opt, parser.comment); if (parser.comment) { emitNode(parser, "oncomment", parser.comment); } parser.comment = ""; } else { parser.comment += "-" + c2; parser.state = S2.COMMENT; } continue; case S2.COMMENT_ENDED: if (c2 !== ">") { strictFail(parser, "Malformed comment"); parser.comment += "--" + c2; parser.state = S2.COMMENT; } else { parser.state = S2.TEXT; } continue; case S2.CDATA: if (c2 === "]") { parser.state = S2.CDATA_ENDING; } else { parser.cdata += c2; } continue; case S2.CDATA_ENDING: if (c2 === "]") { parser.state = S2.CDATA_ENDING_2; } else { parser.cdata += "]" + c2; parser.state = S2.CDATA; } continue; case S2.CDATA_ENDING_2: if (c2 === ">") { if (parser.cdata) { emitNode(parser, "oncdata", parser.cdata); } emitNode(parser, "onclosecdata"); parser.cdata = ""; parser.state = S2.TEXT; } else if (c2 === "]") { parser.cdata += "]"; } else { parser.cdata += "]]" + c2; parser.state = S2.CDATA; } continue; case S2.PROC_INST: if (c2 === "?") { parser.state = S2.PROC_INST_ENDING; } else if (isWhitespace2(c2)) { parser.state = S2.PROC_INST_BODY; } else { parser.procInstName += c2; } continue; case S2.PROC_INST_BODY: if (!parser.procInstBody && isWhitespace2(c2)) { continue; } else if (c2 === "?") { parser.state = S2.PROC_INST_ENDING; } else { parser.procInstBody += c2; } continue; case S2.PROC_INST_ENDING: if (c2 === ">") { emitNode(parser, "onprocessinginstruction", { name: parser.procInstName, body: parser.procInstBody }); parser.procInstName = parser.procInstBody = ""; parser.state = S2.TEXT; } else { parser.procInstBody += "?" + c2; parser.state = S2.PROC_INST_BODY; } continue; case S2.OPEN_TAG: if (isMatch(nameBody, c2)) { parser.tagName += c2; } else { newTag(parser); if (c2 === ">") { openTag(parser); } else if (c2 === "/") { parser.state = S2.OPEN_TAG_SLASH; } else { if (!isWhitespace2(c2)) { strictFail(parser, "Invalid character in tag name"); } parser.state = S2.ATTRIB; } } continue; case S2.OPEN_TAG_SLASH: if (c2 === ">") { openTag(parser, true); closeTag(parser); } else { strictFail(parser, "Forward-slash in opening tag not followed by >"); parser.state = S2.ATTRIB; } continue; case S2.ATTRIB: if (isWhitespace2(c2)) { continue; } else if (c2 === ">") { openTag(parser); } else if (c2 === "/") { parser.state = S2.OPEN_TAG_SLASH; } else if (isMatch(nameStart, c2)) { parser.attribName = c2; parser.attribValue = ""; parser.state = S2.ATTRIB_NAME; } else { strictFail(parser, "Invalid attribute name"); } continue; case S2.ATTRIB_NAME: if (c2 === "=") { parser.state = S2.ATTRIB_VALUE; } else if (c2 === ">") { strictFail(parser, "Attribute without value"); parser.attribValue = parser.attribName; attrib(parser); openTag(parser); } else if (isWhitespace2(c2)) { parser.state = S2.ATTRIB_NAME_SAW_WHITE; } else if (isMatch(nameBody, c2)) { parser.attribName += c2; } else { strictFail(parser, "Invalid attribute name"); } continue; case S2.ATTRIB_NAME_SAW_WHITE: if (c2 === "=") { parser.state = S2.ATTRIB_VALUE; } else if (isWhitespace2(c2)) { continue; } else { strictFail(parser, "Attribute without value"); parser.tag.attributes[parser.attribName] = ""; parser.attribValue = ""; emitNode(parser, "onattribute", { name: parser.attribName, value: "" }); parser.attribName = ""; if (c2 === ">") { openTag(parser); } else if (isMatch(nameStart, c2)) { parser.attribName = c2; parser.state = S2.ATTRIB_NAME; } else { strictFail(parser, "Invalid attribute name"); parser.state = S2.ATTRIB; } } continue; case S2.ATTRIB_VALUE: if (isWhitespace2(c2)) { continue; } else if (isQuote(c2)) { parser.q = c2; parser.state = S2.ATTRIB_VALUE_QUOTED; } else { strictFail(parser, "Unquoted attribute value"); parser.state = S2.ATTRIB_VALUE_UNQUOTED; parser.attribValue = c2; } continue; case S2.ATTRIB_VALUE_QUOTED: if (c2 !== parser.q) { if (c2 === "&") { parser.state = S2.ATTRIB_VALUE_ENTITY_Q; } else { parser.attribValue += c2; } continue; } attrib(parser); parser.q = ""; parser.state = S2.ATTRIB_VALUE_CLOSED; continue; case S2.ATTRIB_VALUE_CLOSED: if (isWhitespace2(c2)) { parser.state = S2.ATTRIB; } else if (c2 === ">") { openTag(parser); } else if (c2 === "/") { parser.state = S2.OPEN_TAG_SLASH; } else if (isMatch(nameStart, c2)) { strictFail(parser, "No whitespace between attributes"); parser.attribName = c2; parser.attribValue = ""; parser.state = S2.ATTRIB_NAME; } else { strictFail(parser, "Invalid attribute name"); } continue; case S2.ATTRIB_VALUE_UNQUOTED: if (!isAttribEnd(c2)) { if (c2 === "&") { parser.state = S2.ATTRIB_VALUE_ENTITY_U; } else { parser.attribValue += c2; } continue; } attrib(parser); if (c2 === ">") { openTag(parser); } else { parser.state = S2.ATTRIB; } continue; case S2.CLOSE_TAG: if (!parser.tagName) { if (isWhitespace2(c2)) { continue; } else if (notMatch(nameStart, c2)) { if (parser.script) { parser.script += "") { closeTag(parser); } else if (isMatch(nameBody, c2)) { parser.tagName += c2; } else if (parser.script) { parser.script += "") { closeTag(parser); } else { strictFail(parser, "Invalid characters in closing tag"); } continue; case S2.TEXT_ENTITY: case S2.ATTRIB_VALUE_ENTITY_Q: case S2.ATTRIB_VALUE_ENTITY_U: var returnState; var buffer; switch (parser.state) { case S2.TEXT_ENTITY: returnState = S2.TEXT; buffer = "textNode"; break; case S2.ATTRIB_VALUE_ENTITY_Q: returnState = S2.ATTRIB_VALUE_QUOTED; buffer = "attribValue"; break; case S2.ATTRIB_VALUE_ENTITY_U: returnState = S2.ATTRIB_VALUE_UNQUOTED; buffer = "attribValue"; break; } if (c2 === ";") { if (parser.opt.unparsedEntities) { var parsedEntity = parseEntity(parser); parser.entity = ""; parser.state = returnState; parser.write(parsedEntity); } else { parser[buffer] += parseEntity(parser); parser.entity = ""; parser.state = returnState; } } else if (isMatch(parser.entity.length ? entityBody : entityStart, c2)) { parser.entity += c2; } else { strictFail(parser, "Invalid character in entity name"); parser[buffer] += "&" + parser.entity + c2; parser.entity = ""; parser.state = returnState; } continue; default: { throw new Error(parser, "Unknown state: " + parser.state); } } } if (parser.position >= parser.bufferCheckPosition) { checkBufferLength(parser); } return parser; } if (!String.fromCodePoint) { (function() { var stringFromCharCode = String.fromCharCode; var floor = Math.floor; var fromCodePoint = function() { var MAX_SIZE = 16384; var codeUnits = []; var highSurrogate; var lowSurrogate; var index2 = -1; var length = arguments.length; if (!length) { return ""; } var result = ""; while (++index2 < length) { var codePoint = Number(arguments[index2]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) { throw RangeError("Invalid code point: " + codePoint); } if (codePoint <= 65535) { codeUnits.push(codePoint); } else { codePoint -= 65536; highSurrogate = (codePoint >> 10) + 55296; lowSurrogate = codePoint % 1024 + 56320; codeUnits.push(highSurrogate, lowSurrogate); } if (index2 + 1 === length || codeUnits.length > MAX_SIZE) { result += stringFromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; }; if (Object.defineProperty) { Object.defineProperty(String, "fromCodePoint", { value: fromCodePoint, configurable: true, writable: true }); } else { String.fromCodePoint = fromCodePoint; } })(); } })(typeof exports2 === "undefined" ? exports2.sax = {} : exports2); } }); // node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/bom.js var require_bom = __commonJS({ "node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/bom.js"(exports2) { (function() { "use strict"; exports2.stripBOM = function(str3) { if (str3[0] === "\uFEFF") { return str3.substring(1); } else { return str3; } }; }).call(exports2); } }); // node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/processors.js var require_processors = __commonJS({ "node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/processors.js"(exports2) { (function() { "use strict"; var prefixMatch; prefixMatch = new RegExp(/(?!xmlns)^.*:/); exports2.normalize = function(str3) { return str3.toLowerCase(); }; exports2.firstCharLowerCase = function(str3) { return str3.charAt(0).toLowerCase() + str3.slice(1); }; exports2.stripPrefix = function(str3) { return str3.replace(prefixMatch, ""); }; exports2.parseNumbers = function(str3) { if (!isNaN(str3)) { str3 = str3 % 1 === 0 ? parseInt(str3, 10) : parseFloat(str3); } return str3; }; exports2.parseBooleans = function(str3) { if (/^(?:true|false)$/i.test(str3)) { str3 = str3.toLowerCase() === "true"; } return str3; }; }).call(exports2); } }); // node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/parser.js var require_parser2 = __commonJS({ "node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/parser.js"(exports2) { (function() { "use strict"; var bom, defaults, events, isEmpty6, processItem, processors, sax2, setImmediate2, bind2 = function(fn, me2) { return function() { return fn.apply(me2, arguments); }; }, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; sax2 = require_sax(); events = require("events"); bom = require_bom(); processors = require_processors(); setImmediate2 = require("timers").setImmediate; defaults = require_defaults().defaults; isEmpty6 = function(thing) { return typeof thing === "object" && thing != null && Object.keys(thing).length === 0; }; processItem = function(processors2, item, key) { var i2, len, process3; for (i2 = 0, len = processors2.length; i2 < len; i2++) { process3 = processors2[i2]; item = process3(item, key); } return item; }; exports2.Parser = function(superClass) { extend4(Parser2, superClass); function Parser2(opts) { this.parseStringPromise = bind2(this.parseStringPromise, this); this.parseString = bind2(this.parseString, this); this.reset = bind2(this.reset, this); this.assignOrPush = bind2(this.assignOrPush, this); this.processAsync = bind2(this.processAsync, this); var key, ref, value; if (!(this instanceof exports2.Parser)) { return new exports2.Parser(opts); } this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } if (this.options.xmlns) { this.options.xmlnskey = this.options.attrkey + "ns"; } if (this.options.normalizeTags) { if (!this.options.tagNameProcessors) { this.options.tagNameProcessors = []; } this.options.tagNameProcessors.unshift(processors.normalize); } this.reset(); } Parser2.prototype.processAsync = function() { var chunk, err; try { if (this.remaining.length <= this.options.chunkSize) { chunk = this.remaining; this.remaining = ""; this.saxParser = this.saxParser.write(chunk); return this.saxParser.close(); } else { chunk = this.remaining.substr(0, this.options.chunkSize); this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length); this.saxParser = this.saxParser.write(chunk); return setImmediate2(this.processAsync); } } catch (error1) { err = error1; if (!this.saxParser.errThrown) { this.saxParser.errThrown = true; return this.emit(err); } } }; Parser2.prototype.assignOrPush = function(obj, key, newValue) { if (!(key in obj)) { if (!this.options.explicitArray) { return obj[key] = newValue; } else { return obj[key] = [newValue]; } } else { if (!(obj[key] instanceof Array)) { obj[key] = [obj[key]]; } return obj[key].push(newValue); } }; Parser2.prototype.reset = function() { var attrkey, charkey, ontext, stack; this.removeAllListeners(); this.saxParser = sax2.parser(this.options.strict, { trim: false, normalize: false, xmlns: this.options.xmlns }); this.saxParser.errThrown = false; this.saxParser.onerror = function(_this) { return function(error) { _this.saxParser.resume(); if (!_this.saxParser.errThrown) { _this.saxParser.errThrown = true; return _this.emit("error", error); } }; }(this); this.saxParser.onend = function(_this) { return function() { if (!_this.saxParser.ended) { _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; }(this); this.saxParser.ended = false; this.EXPLICIT_CHARKEY = this.options.explicitCharkey; this.resultObject = null; stack = []; attrkey = this.options.attrkey; charkey = this.options.charkey; this.saxParser.onopentag = function(_this) { return function(node) { var key, newValue, obj, processedKey, ref; obj = Object.create(null); obj[charkey] = ""; if (!_this.options.ignoreAttrs) { ref = node.attributes; for (key in ref) { if (!hasProp.call(ref, key)) continue; if (!(attrkey in obj) && !_this.options.mergeAttrs) { obj[attrkey] = Object.create(null); } newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; if (_this.options.mergeAttrs) { _this.assignOrPush(obj, processedKey, newValue); } else { obj[attrkey][processedKey] = newValue; } } } obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name; if (_this.options.xmlns) { obj[_this.options.xmlnskey] = { uri: node.uri, local: node.local }; } return stack.push(obj); }; }(this); this.saxParser.onclosetag = function(_this) { return function() { var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s2, xpath; obj = stack.pop(); nodeName = obj["#name"]; if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { delete obj["#name"]; } if (obj.cdata === true) { cdata = obj.cdata; delete obj.cdata; } s2 = stack[stack.length - 1]; if (obj[charkey].match(/^\s*$/) && !cdata) { emptyStr = obj[charkey]; delete obj[charkey]; } else { if (_this.options.trim) { obj[charkey] = obj[charkey].trim(); } if (_this.options.normalize) { obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); } obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } if (isEmpty6(obj)) { if (typeof _this.options.emptyTag === "function") { obj = _this.options.emptyTag(); } else { obj = _this.options.emptyTag !== "" ? _this.options.emptyTag : emptyStr; } } if (_this.options.validator != null) { xpath = "/" + function() { var i2, len, results; results = []; for (i2 = 0, len = stack.length; i2 < len; i2++) { node = stack[i2]; results.push(node["#name"]); } return results; }().concat(nodeName).join("/"); (function() { var err; try { return obj = _this.options.validator(xpath, s2 && s2[nodeName], obj); } catch (error1) { err = error1; return _this.emit("error", err); } })(); } if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === "object") { if (!_this.options.preserveChildrenOrder) { node = Object.create(null); if (_this.options.attrkey in obj) { node[_this.options.attrkey] = obj[_this.options.attrkey]; delete obj[_this.options.attrkey]; } if (!_this.options.charsAsChildren && _this.options.charkey in obj) { node[_this.options.charkey] = obj[_this.options.charkey]; delete obj[_this.options.charkey]; } if (Object.getOwnPropertyNames(obj).length > 0) { node[_this.options.childkey] = obj; } obj = node; } else if (s2) { s2[_this.options.childkey] = s2[_this.options.childkey] || []; objClone = Object.create(null); for (key in obj) { if (!hasProp.call(obj, key)) continue; objClone[key] = obj[key]; } s2[_this.options.childkey].push(objClone); delete obj["#name"]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } } if (stack.length > 0) { return _this.assignOrPush(s2, nodeName, obj); } else { if (_this.options.explicitRoot) { old = obj; obj = Object.create(null); obj[nodeName] = old; } _this.resultObject = obj; _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; }(this); ontext = function(_this) { return function(text) { var charChild, s2; s2 = stack[stack.length - 1]; if (s2) { s2[charkey] += text; if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, "").trim() !== "")) { s2[_this.options.childkey] = s2[_this.options.childkey] || []; charChild = { "#name": "__text__" }; charChild[charkey] = text; if (_this.options.normalize) { charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim(); } s2[_this.options.childkey].push(charChild); } return s2; } }; }(this); this.saxParser.ontext = ontext; return this.saxParser.oncdata = function(_this) { return function(text) { var s2; s2 = ontext(text); if (s2) { return s2.cdata = true; } }; }(this); }; Parser2.prototype.parseString = function(str3, cb) { var err; if (cb != null && typeof cb === "function") { this.on("end", function(result) { this.reset(); return cb(null, result); }); this.on("error", function(err2) { this.reset(); return cb(err2); }); } try { str3 = str3.toString(); if (str3.trim() === "") { this.emit("end", null); return true; } str3 = bom.stripBOM(str3); if (this.options.async) { this.remaining = str3; setImmediate2(this.processAsync); return this.saxParser; } return this.saxParser.write(str3).close(); } catch (error1) { err = error1; if (!(this.saxParser.errThrown || this.saxParser.ended)) { this.emit("error", err); return this.saxParser.errThrown = true; } else if (this.saxParser.ended) { throw err; } } }; Parser2.prototype.parseStringPromise = function(str3) { return new Promise(function(_this) { return function(resolve, reject) { return _this.parseString(str3, function(err, value) { if (err) { return reject(err); } else { return resolve(value); } }); }; }(this)); }; return Parser2; }(events); exports2.parseString = function(str3, a2, b2) { var cb, options, parser; if (b2 != null) { if (typeof b2 === "function") { cb = b2; } if (typeof a2 === "object") { options = a2; } } else { if (typeof a2 === "function") { cb = a2; } options = {}; } parser = new exports2.Parser(options); return parser.parseString(str3, cb); }; exports2.parseStringPromise = function(str3, a2) { var options, parser; if (typeof a2 === "object") { options = a2; } parser = new exports2.Parser(options); return parser.parseStringPromise(str3); }; }).call(exports2); } }); // node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/xml2js.js var require_xml2js = __commonJS({ "node_modules/.pnpm/xml2js@0.5.0/node_modules/xml2js/lib/xml2js.js"(exports2) { (function() { "use strict"; var builder, defaults, parser, processors, extend4 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; defaults = require_defaults(); builder = require_builder(); parser = require_parser2(); processors = require_processors(); exports2.defaults = defaults.defaults; exports2.processors = processors; exports2.ValidationError = function(superClass) { extend4(ValidationError, superClass); function ValidationError(message) { this.message = message; } return ValidationError; }(Error); exports2.Builder = builder.Builder; exports2.Parser = parser.Parser; exports2.parseString = parser.parseString; exports2.parseStringPromise = parser.parseStringPromise; }).call(exports2); } }); // node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/lib/fields.js var require_fields = __commonJS({ "node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/lib/fields.js"(exports2, module2) { var fields2 = module2.exports = {}; fields2.feed = [ ["author", "creator"], ["dc:publisher", "publisher"], ["dc:creator", "creator"], ["dc:source", "source"], ["dc:title", "title"], ["dc:type", "type"], "title", "description", "author", "pubDate", "webMaster", "managingEditor", "generator", "link", "language", "copyright", "lastBuildDate", "docs", "generator", "ttl", "rating", "skipHours", "skipDays" ]; fields2.item = [ ["author", "creator"], ["dc:creator", "creator"], ["dc:date", "date"], ["dc:language", "language"], ["dc:rights", "rights"], ["dc:source", "source"], ["dc:title", "title"], "title", "link", "pubDate", "author", "summary", ["content:encoded", "content:encoded", { includeSnippet: true }], "enclosure", "dc:creator", "dc:date", "comments" ]; var mapItunesField = function(f4) { return ["itunes:" + f4, f4]; }; fields2.podcastFeed = [ "author", "subtitle", "summary", "explicit" ].map(mapItunesField); fields2.podcastItem = [ "author", "subtitle", "summary", "explicit", "duration", "image", "episode", "image", "season", "keywords", "episodeType" ].map(mapItunesField); } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/entities.json var require_entities = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/entities.json"(exports2, module2) { module2.exports = { Aacute: "\xC1", aacute: "\xE1", Abreve: "\u0102", abreve: "\u0103", ac: "\u223E", acd: "\u223F", acE: "\u223E\u0333", Acirc: "\xC2", acirc: "\xE2", acute: "\xB4", Acy: "\u0410", acy: "\u0430", AElig: "\xC6", aelig: "\xE6", af: "\u2061", Afr: "\u{1D504}", afr: "\u{1D51E}", Agrave: "\xC0", agrave: "\xE0", alefsym: "\u2135", aleph: "\u2135", Alpha: "\u0391", alpha: "\u03B1", Amacr: "\u0100", amacr: "\u0101", amalg: "\u2A3F", amp: "&", AMP: "&", andand: "\u2A55", And: "\u2A53", and: "\u2227", andd: "\u2A5C", andslope: "\u2A58", andv: "\u2A5A", ang: "\u2220", ange: "\u29A4", angle: "\u2220", angmsdaa: "\u29A8", angmsdab: "\u29A9", angmsdac: "\u29AA", angmsdad: "\u29AB", angmsdae: "\u29AC", angmsdaf: "\u29AD", angmsdag: "\u29AE", angmsdah: "\u29AF", angmsd: "\u2221", angrt: "\u221F", angrtvb: "\u22BE", angrtvbd: "\u299D", angsph: "\u2222", angst: "\xC5", angzarr: "\u237C", Aogon: "\u0104", aogon: "\u0105", Aopf: "\u{1D538}", aopf: "\u{1D552}", apacir: "\u2A6F", ap: "\u2248", apE: "\u2A70", ape: "\u224A", apid: "\u224B", apos: "'", ApplyFunction: "\u2061", approx: "\u2248", approxeq: "\u224A", Aring: "\xC5", aring: "\xE5", Ascr: "\u{1D49C}", ascr: "\u{1D4B6}", Assign: "\u2254", ast: "*", asymp: "\u2248", asympeq: "\u224D", Atilde: "\xC3", atilde: "\xE3", Auml: "\xC4", auml: "\xE4", awconint: "\u2233", awint: "\u2A11", backcong: "\u224C", backepsilon: "\u03F6", backprime: "\u2035", backsim: "\u223D", backsimeq: "\u22CD", Backslash: "\u2216", Barv: "\u2AE7", barvee: "\u22BD", barwed: "\u2305", Barwed: "\u2306", barwedge: "\u2305", bbrk: "\u23B5", bbrktbrk: "\u23B6", bcong: "\u224C", Bcy: "\u0411", bcy: "\u0431", bdquo: "\u201E", becaus: "\u2235", because: "\u2235", Because: "\u2235", bemptyv: "\u29B0", bepsi: "\u03F6", bernou: "\u212C", Bernoullis: "\u212C", Beta: "\u0392", beta: "\u03B2", beth: "\u2136", between: "\u226C", Bfr: "\u{1D505}", bfr: "\u{1D51F}", bigcap: "\u22C2", bigcirc: "\u25EF", bigcup: "\u22C3", bigodot: "\u2A00", bigoplus: "\u2A01", bigotimes: "\u2A02", bigsqcup: "\u2A06", bigstar: "\u2605", bigtriangledown: "\u25BD", bigtriangleup: "\u25B3", biguplus: "\u2A04", bigvee: "\u22C1", bigwedge: "\u22C0", bkarow: "\u290D", blacklozenge: "\u29EB", blacksquare: "\u25AA", blacktriangle: "\u25B4", blacktriangledown: "\u25BE", blacktriangleleft: "\u25C2", blacktriangleright: "\u25B8", blank: "\u2423", blk12: "\u2592", blk14: "\u2591", blk34: "\u2593", block: "\u2588", bne: "=\u20E5", bnequiv: "\u2261\u20E5", bNot: "\u2AED", bnot: "\u2310", Bopf: "\u{1D539}", bopf: "\u{1D553}", bot: "\u22A5", bottom: "\u22A5", bowtie: "\u22C8", boxbox: "\u29C9", boxdl: "\u2510", boxdL: "\u2555", boxDl: "\u2556", boxDL: "\u2557", boxdr: "\u250C", boxdR: "\u2552", boxDr: "\u2553", boxDR: "\u2554", boxh: "\u2500", boxH: "\u2550", boxhd: "\u252C", boxHd: "\u2564", boxhD: "\u2565", boxHD: "\u2566", boxhu: "\u2534", boxHu: "\u2567", boxhU: "\u2568", boxHU: "\u2569", boxminus: "\u229F", boxplus: "\u229E", boxtimes: "\u22A0", boxul: "\u2518", boxuL: "\u255B", boxUl: "\u255C", boxUL: "\u255D", boxur: "\u2514", boxuR: "\u2558", boxUr: "\u2559", boxUR: "\u255A", boxv: "\u2502", boxV: "\u2551", boxvh: "\u253C", boxvH: "\u256A", boxVh: "\u256B", boxVH: "\u256C", boxvl: "\u2524", boxvL: "\u2561", boxVl: "\u2562", boxVL: "\u2563", boxvr: "\u251C", boxvR: "\u255E", boxVr: "\u255F", boxVR: "\u2560", bprime: "\u2035", breve: "\u02D8", Breve: "\u02D8", brvbar: "\xA6", bscr: "\u{1D4B7}", Bscr: "\u212C", bsemi: "\u204F", bsim: "\u223D", bsime: "\u22CD", bsolb: "\u29C5", bsol: "\\", bsolhsub: "\u27C8", bull: "\u2022", bullet: "\u2022", bump: "\u224E", bumpE: "\u2AAE", bumpe: "\u224F", Bumpeq: "\u224E", bumpeq: "\u224F", Cacute: "\u0106", cacute: "\u0107", capand: "\u2A44", capbrcup: "\u2A49", capcap: "\u2A4B", cap: "\u2229", Cap: "\u22D2", capcup: "\u2A47", capdot: "\u2A40", CapitalDifferentialD: "\u2145", caps: "\u2229\uFE00", caret: "\u2041", caron: "\u02C7", Cayleys: "\u212D", ccaps: "\u2A4D", Ccaron: "\u010C", ccaron: "\u010D", Ccedil: "\xC7", ccedil: "\xE7", Ccirc: "\u0108", ccirc: "\u0109", Cconint: "\u2230", ccups: "\u2A4C", ccupssm: "\u2A50", Cdot: "\u010A", cdot: "\u010B", cedil: "\xB8", Cedilla: "\xB8", cemptyv: "\u29B2", cent: "\xA2", centerdot: "\xB7", CenterDot: "\xB7", cfr: "\u{1D520}", Cfr: "\u212D", CHcy: "\u0427", chcy: "\u0447", check: "\u2713", checkmark: "\u2713", Chi: "\u03A7", chi: "\u03C7", circ: "\u02C6", circeq: "\u2257", circlearrowleft: "\u21BA", circlearrowright: "\u21BB", circledast: "\u229B", circledcirc: "\u229A", circleddash: "\u229D", CircleDot: "\u2299", circledR: "\xAE", circledS: "\u24C8", CircleMinus: "\u2296", CirclePlus: "\u2295", CircleTimes: "\u2297", cir: "\u25CB", cirE: "\u29C3", cire: "\u2257", cirfnint: "\u2A10", cirmid: "\u2AEF", cirscir: "\u29C2", ClockwiseContourIntegral: "\u2232", CloseCurlyDoubleQuote: "\u201D", CloseCurlyQuote: "\u2019", clubs: "\u2663", clubsuit: "\u2663", colon: ":", Colon: "\u2237", Colone: "\u2A74", colone: "\u2254", coloneq: "\u2254", comma: ",", commat: "@", comp: "\u2201", compfn: "\u2218", complement: "\u2201", complexes: "\u2102", cong: "\u2245", congdot: "\u2A6D", Congruent: "\u2261", conint: "\u222E", Conint: "\u222F", ContourIntegral: "\u222E", copf: "\u{1D554}", Copf: "\u2102", coprod: "\u2210", Coproduct: "\u2210", copy: "\xA9", COPY: "\xA9", copysr: "\u2117", CounterClockwiseContourIntegral: "\u2233", crarr: "\u21B5", cross: "\u2717", Cross: "\u2A2F", Cscr: "\u{1D49E}", cscr: "\u{1D4B8}", csub: "\u2ACF", csube: "\u2AD1", csup: "\u2AD0", csupe: "\u2AD2", ctdot: "\u22EF", cudarrl: "\u2938", cudarrr: "\u2935", cuepr: "\u22DE", cuesc: "\u22DF", cularr: "\u21B6", cularrp: "\u293D", cupbrcap: "\u2A48", cupcap: "\u2A46", CupCap: "\u224D", cup: "\u222A", Cup: "\u22D3", cupcup: "\u2A4A", cupdot: "\u228D", cupor: "\u2A45", cups: "\u222A\uFE00", curarr: "\u21B7", curarrm: "\u293C", curlyeqprec: "\u22DE", curlyeqsucc: "\u22DF", curlyvee: "\u22CE", curlywedge: "\u22CF", curren: "\xA4", curvearrowleft: "\u21B6", curvearrowright: "\u21B7", cuvee: "\u22CE", cuwed: "\u22CF", cwconint: "\u2232", cwint: "\u2231", cylcty: "\u232D", dagger: "\u2020", Dagger: "\u2021", daleth: "\u2138", darr: "\u2193", Darr: "\u21A1", dArr: "\u21D3", dash: "\u2010", Dashv: "\u2AE4", dashv: "\u22A3", dbkarow: "\u290F", dblac: "\u02DD", Dcaron: "\u010E", dcaron: "\u010F", Dcy: "\u0414", dcy: "\u0434", ddagger: "\u2021", ddarr: "\u21CA", DD: "\u2145", dd: "\u2146", DDotrahd: "\u2911", ddotseq: "\u2A77", deg: "\xB0", Del: "\u2207", Delta: "\u0394", delta: "\u03B4", demptyv: "\u29B1", dfisht: "\u297F", Dfr: "\u{1D507}", dfr: "\u{1D521}", dHar: "\u2965", dharl: "\u21C3", dharr: "\u21C2", DiacriticalAcute: "\xB4", DiacriticalDot: "\u02D9", DiacriticalDoubleAcute: "\u02DD", DiacriticalGrave: "`", DiacriticalTilde: "\u02DC", diam: "\u22C4", diamond: "\u22C4", Diamond: "\u22C4", diamondsuit: "\u2666", diams: "\u2666", die: "\xA8", DifferentialD: "\u2146", digamma: "\u03DD", disin: "\u22F2", div: "\xF7", divide: "\xF7", divideontimes: "\u22C7", divonx: "\u22C7", DJcy: "\u0402", djcy: "\u0452", dlcorn: "\u231E", dlcrop: "\u230D", dollar: "$", Dopf: "\u{1D53B}", dopf: "\u{1D555}", Dot: "\xA8", dot: "\u02D9", DotDot: "\u20DC", doteq: "\u2250", doteqdot: "\u2251", DotEqual: "\u2250", dotminus: "\u2238", dotplus: "\u2214", dotsquare: "\u22A1", doublebarwedge: "\u2306", DoubleContourIntegral: "\u222F", DoubleDot: "\xA8", DoubleDownArrow: "\u21D3", DoubleLeftArrow: "\u21D0", DoubleLeftRightArrow: "\u21D4", DoubleLeftTee: "\u2AE4", DoubleLongLeftArrow: "\u27F8", DoubleLongLeftRightArrow: "\u27FA", DoubleLongRightArrow: "\u27F9", DoubleRightArrow: "\u21D2", DoubleRightTee: "\u22A8", DoubleUpArrow: "\u21D1", DoubleUpDownArrow: "\u21D5", DoubleVerticalBar: "\u2225", DownArrowBar: "\u2913", downarrow: "\u2193", DownArrow: "\u2193", Downarrow: "\u21D3", DownArrowUpArrow: "\u21F5", DownBreve: "\u0311", downdownarrows: "\u21CA", downharpoonleft: "\u21C3", downharpoonright: "\u21C2", DownLeftRightVector: "\u2950", DownLeftTeeVector: "\u295E", DownLeftVectorBar: "\u2956", DownLeftVector: "\u21BD", DownRightTeeVector: "\u295F", DownRightVectorBar: "\u2957", DownRightVector: "\u21C1", DownTeeArrow: "\u21A7", DownTee: "\u22A4", drbkarow: "\u2910", drcorn: "\u231F", drcrop: "\u230C", Dscr: "\u{1D49F}", dscr: "\u{1D4B9}", DScy: "\u0405", dscy: "\u0455", dsol: "\u29F6", Dstrok: "\u0110", dstrok: "\u0111", dtdot: "\u22F1", dtri: "\u25BF", dtrif: "\u25BE", duarr: "\u21F5", duhar: "\u296F", dwangle: "\u29A6", DZcy: "\u040F", dzcy: "\u045F", dzigrarr: "\u27FF", Eacute: "\xC9", eacute: "\xE9", easter: "\u2A6E", Ecaron: "\u011A", ecaron: "\u011B", Ecirc: "\xCA", ecirc: "\xEA", ecir: "\u2256", ecolon: "\u2255", Ecy: "\u042D", ecy: "\u044D", eDDot: "\u2A77", Edot: "\u0116", edot: "\u0117", eDot: "\u2251", ee: "\u2147", efDot: "\u2252", Efr: "\u{1D508}", efr: "\u{1D522}", eg: "\u2A9A", Egrave: "\xC8", egrave: "\xE8", egs: "\u2A96", egsdot: "\u2A98", el: "\u2A99", Element: "\u2208", elinters: "\u23E7", ell: "\u2113", els: "\u2A95", elsdot: "\u2A97", Emacr: "\u0112", emacr: "\u0113", empty: "\u2205", emptyset: "\u2205", EmptySmallSquare: "\u25FB", emptyv: "\u2205", EmptyVerySmallSquare: "\u25AB", emsp13: "\u2004", emsp14: "\u2005", emsp: "\u2003", ENG: "\u014A", eng: "\u014B", ensp: "\u2002", Eogon: "\u0118", eogon: "\u0119", Eopf: "\u{1D53C}", eopf: "\u{1D556}", epar: "\u22D5", eparsl: "\u29E3", eplus: "\u2A71", epsi: "\u03B5", Epsilon: "\u0395", epsilon: "\u03B5", epsiv: "\u03F5", eqcirc: "\u2256", eqcolon: "\u2255", eqsim: "\u2242", eqslantgtr: "\u2A96", eqslantless: "\u2A95", Equal: "\u2A75", equals: "=", EqualTilde: "\u2242", equest: "\u225F", Equilibrium: "\u21CC", equiv: "\u2261", equivDD: "\u2A78", eqvparsl: "\u29E5", erarr: "\u2971", erDot: "\u2253", escr: "\u212F", Escr: "\u2130", esdot: "\u2250", Esim: "\u2A73", esim: "\u2242", Eta: "\u0397", eta: "\u03B7", ETH: "\xD0", eth: "\xF0", Euml: "\xCB", euml: "\xEB", euro: "\u20AC", excl: "!", exist: "\u2203", Exists: "\u2203", expectation: "\u2130", exponentiale: "\u2147", ExponentialE: "\u2147", fallingdotseq: "\u2252", Fcy: "\u0424", fcy: "\u0444", female: "\u2640", ffilig: "\uFB03", fflig: "\uFB00", ffllig: "\uFB04", Ffr: "\u{1D509}", ffr: "\u{1D523}", filig: "\uFB01", FilledSmallSquare: "\u25FC", FilledVerySmallSquare: "\u25AA", fjlig: "fj", flat: "\u266D", fllig: "\uFB02", fltns: "\u25B1", fnof: "\u0192", Fopf: "\u{1D53D}", fopf: "\u{1D557}", forall: "\u2200", ForAll: "\u2200", fork: "\u22D4", forkv: "\u2AD9", Fouriertrf: "\u2131", fpartint: "\u2A0D", frac12: "\xBD", frac13: "\u2153", frac14: "\xBC", frac15: "\u2155", frac16: "\u2159", frac18: "\u215B", frac23: "\u2154", frac25: "\u2156", frac34: "\xBE", frac35: "\u2157", frac38: "\u215C", frac45: "\u2158", frac56: "\u215A", frac58: "\u215D", frac78: "\u215E", frasl: "\u2044", frown: "\u2322", fscr: "\u{1D4BB}", Fscr: "\u2131", gacute: "\u01F5", Gamma: "\u0393", gamma: "\u03B3", Gammad: "\u03DC", gammad: "\u03DD", gap: "\u2A86", Gbreve: "\u011E", gbreve: "\u011F", Gcedil: "\u0122", Gcirc: "\u011C", gcirc: "\u011D", Gcy: "\u0413", gcy: "\u0433", Gdot: "\u0120", gdot: "\u0121", ge: "\u2265", gE: "\u2267", gEl: "\u2A8C", gel: "\u22DB", geq: "\u2265", geqq: "\u2267", geqslant: "\u2A7E", gescc: "\u2AA9", ges: "\u2A7E", gesdot: "\u2A80", gesdoto: "\u2A82", gesdotol: "\u2A84", gesl: "\u22DB\uFE00", gesles: "\u2A94", Gfr: "\u{1D50A}", gfr: "\u{1D524}", gg: "\u226B", Gg: "\u22D9", ggg: "\u22D9", gimel: "\u2137", GJcy: "\u0403", gjcy: "\u0453", gla: "\u2AA5", gl: "\u2277", glE: "\u2A92", glj: "\u2AA4", gnap: "\u2A8A", gnapprox: "\u2A8A", gne: "\u2A88", gnE: "\u2269", gneq: "\u2A88", gneqq: "\u2269", gnsim: "\u22E7", Gopf: "\u{1D53E}", gopf: "\u{1D558}", grave: "`", GreaterEqual: "\u2265", GreaterEqualLess: "\u22DB", GreaterFullEqual: "\u2267", GreaterGreater: "\u2AA2", GreaterLess: "\u2277", GreaterSlantEqual: "\u2A7E", GreaterTilde: "\u2273", Gscr: "\u{1D4A2}", gscr: "\u210A", gsim: "\u2273", gsime: "\u2A8E", gsiml: "\u2A90", gtcc: "\u2AA7", gtcir: "\u2A7A", gt: ">", GT: ">", Gt: "\u226B", gtdot: "\u22D7", gtlPar: "\u2995", gtquest: "\u2A7C", gtrapprox: "\u2A86", gtrarr: "\u2978", gtrdot: "\u22D7", gtreqless: "\u22DB", gtreqqless: "\u2A8C", gtrless: "\u2277", gtrsim: "\u2273", gvertneqq: "\u2269\uFE00", gvnE: "\u2269\uFE00", Hacek: "\u02C7", hairsp: "\u200A", half: "\xBD", hamilt: "\u210B", HARDcy: "\u042A", hardcy: "\u044A", harrcir: "\u2948", harr: "\u2194", hArr: "\u21D4", harrw: "\u21AD", Hat: "^", hbar: "\u210F", Hcirc: "\u0124", hcirc: "\u0125", hearts: "\u2665", heartsuit: "\u2665", hellip: "\u2026", hercon: "\u22B9", hfr: "\u{1D525}", Hfr: "\u210C", HilbertSpace: "\u210B", hksearow: "\u2925", hkswarow: "\u2926", hoarr: "\u21FF", homtht: "\u223B", hookleftarrow: "\u21A9", hookrightarrow: "\u21AA", hopf: "\u{1D559}", Hopf: "\u210D", horbar: "\u2015", HorizontalLine: "\u2500", hscr: "\u{1D4BD}", Hscr: "\u210B", hslash: "\u210F", Hstrok: "\u0126", hstrok: "\u0127", HumpDownHump: "\u224E", HumpEqual: "\u224F", hybull: "\u2043", hyphen: "\u2010", Iacute: "\xCD", iacute: "\xED", ic: "\u2063", Icirc: "\xCE", icirc: "\xEE", Icy: "\u0418", icy: "\u0438", Idot: "\u0130", IEcy: "\u0415", iecy: "\u0435", iexcl: "\xA1", iff: "\u21D4", ifr: "\u{1D526}", Ifr: "\u2111", Igrave: "\xCC", igrave: "\xEC", ii: "\u2148", iiiint: "\u2A0C", iiint: "\u222D", iinfin: "\u29DC", iiota: "\u2129", IJlig: "\u0132", ijlig: "\u0133", Imacr: "\u012A", imacr: "\u012B", image: "\u2111", ImaginaryI: "\u2148", imagline: "\u2110", imagpart: "\u2111", imath: "\u0131", Im: "\u2111", imof: "\u22B7", imped: "\u01B5", Implies: "\u21D2", incare: "\u2105", in: "\u2208", infin: "\u221E", infintie: "\u29DD", inodot: "\u0131", intcal: "\u22BA", int: "\u222B", Int: "\u222C", integers: "\u2124", Integral: "\u222B", intercal: "\u22BA", Intersection: "\u22C2", intlarhk: "\u2A17", intprod: "\u2A3C", InvisibleComma: "\u2063", InvisibleTimes: "\u2062", IOcy: "\u0401", iocy: "\u0451", Iogon: "\u012E", iogon: "\u012F", Iopf: "\u{1D540}", iopf: "\u{1D55A}", Iota: "\u0399", iota: "\u03B9", iprod: "\u2A3C", iquest: "\xBF", iscr: "\u{1D4BE}", Iscr: "\u2110", isin: "\u2208", isindot: "\u22F5", isinE: "\u22F9", isins: "\u22F4", isinsv: "\u22F3", isinv: "\u2208", it: "\u2062", Itilde: "\u0128", itilde: "\u0129", Iukcy: "\u0406", iukcy: "\u0456", Iuml: "\xCF", iuml: "\xEF", Jcirc: "\u0134", jcirc: "\u0135", Jcy: "\u0419", jcy: "\u0439", Jfr: "\u{1D50D}", jfr: "\u{1D527}", jmath: "\u0237", Jopf: "\u{1D541}", jopf: "\u{1D55B}", Jscr: "\u{1D4A5}", jscr: "\u{1D4BF}", Jsercy: "\u0408", jsercy: "\u0458", Jukcy: "\u0404", jukcy: "\u0454", Kappa: "\u039A", kappa: "\u03BA", kappav: "\u03F0", Kcedil: "\u0136", kcedil: "\u0137", Kcy: "\u041A", kcy: "\u043A", Kfr: "\u{1D50E}", kfr: "\u{1D528}", kgreen: "\u0138", KHcy: "\u0425", khcy: "\u0445", KJcy: "\u040C", kjcy: "\u045C", Kopf: "\u{1D542}", kopf: "\u{1D55C}", Kscr: "\u{1D4A6}", kscr: "\u{1D4C0}", lAarr: "\u21DA", Lacute: "\u0139", lacute: "\u013A", laemptyv: "\u29B4", lagran: "\u2112", Lambda: "\u039B", lambda: "\u03BB", lang: "\u27E8", Lang: "\u27EA", langd: "\u2991", langle: "\u27E8", lap: "\u2A85", Laplacetrf: "\u2112", laquo: "\xAB", larrb: "\u21E4", larrbfs: "\u291F", larr: "\u2190", Larr: "\u219E", lArr: "\u21D0", larrfs: "\u291D", larrhk: "\u21A9", larrlp: "\u21AB", larrpl: "\u2939", larrsim: "\u2973", larrtl: "\u21A2", latail: "\u2919", lAtail: "\u291B", lat: "\u2AAB", late: "\u2AAD", lates: "\u2AAD\uFE00", lbarr: "\u290C", lBarr: "\u290E", lbbrk: "\u2772", lbrace: "{", lbrack: "[", lbrke: "\u298B", lbrksld: "\u298F", lbrkslu: "\u298D", Lcaron: "\u013D", lcaron: "\u013E", Lcedil: "\u013B", lcedil: "\u013C", lceil: "\u2308", lcub: "{", Lcy: "\u041B", lcy: "\u043B", ldca: "\u2936", ldquo: "\u201C", ldquor: "\u201E", ldrdhar: "\u2967", ldrushar: "\u294B", ldsh: "\u21B2", le: "\u2264", lE: "\u2266", LeftAngleBracket: "\u27E8", LeftArrowBar: "\u21E4", leftarrow: "\u2190", LeftArrow: "\u2190", Leftarrow: "\u21D0", LeftArrowRightArrow: "\u21C6", leftarrowtail: "\u21A2", LeftCeiling: "\u2308", LeftDoubleBracket: "\u27E6", LeftDownTeeVector: "\u2961", LeftDownVectorBar: "\u2959", LeftDownVector: "\u21C3", LeftFloor: "\u230A", leftharpoondown: "\u21BD", leftharpoonup: "\u21BC", leftleftarrows: "\u21C7", leftrightarrow: "\u2194", LeftRightArrow: "\u2194", Leftrightarrow: "\u21D4", leftrightarrows: "\u21C6", leftrightharpoons: "\u21CB", leftrightsquigarrow: "\u21AD", LeftRightVector: "\u294E", LeftTeeArrow: "\u21A4", LeftTee: "\u22A3", LeftTeeVector: "\u295A", leftthreetimes: "\u22CB", LeftTriangleBar: "\u29CF", LeftTriangle: "\u22B2", LeftTriangleEqual: "\u22B4", LeftUpDownVector: "\u2951", LeftUpTeeVector: "\u2960", LeftUpVectorBar: "\u2958", LeftUpVector: "\u21BF", LeftVectorBar: "\u2952", LeftVector: "\u21BC", lEg: "\u2A8B", leg: "\u22DA", leq: "\u2264", leqq: "\u2266", leqslant: "\u2A7D", lescc: "\u2AA8", les: "\u2A7D", lesdot: "\u2A7F", lesdoto: "\u2A81", lesdotor: "\u2A83", lesg: "\u22DA\uFE00", lesges: "\u2A93", lessapprox: "\u2A85", lessdot: "\u22D6", lesseqgtr: "\u22DA", lesseqqgtr: "\u2A8B", LessEqualGreater: "\u22DA", LessFullEqual: "\u2266", LessGreater: "\u2276", lessgtr: "\u2276", LessLess: "\u2AA1", lesssim: "\u2272", LessSlantEqual: "\u2A7D", LessTilde: "\u2272", lfisht: "\u297C", lfloor: "\u230A", Lfr: "\u{1D50F}", lfr: "\u{1D529}", lg: "\u2276", lgE: "\u2A91", lHar: "\u2962", lhard: "\u21BD", lharu: "\u21BC", lharul: "\u296A", lhblk: "\u2584", LJcy: "\u0409", ljcy: "\u0459", llarr: "\u21C7", ll: "\u226A", Ll: "\u22D8", llcorner: "\u231E", Lleftarrow: "\u21DA", llhard: "\u296B", lltri: "\u25FA", Lmidot: "\u013F", lmidot: "\u0140", lmoustache: "\u23B0", lmoust: "\u23B0", lnap: "\u2A89", lnapprox: "\u2A89", lne: "\u2A87", lnE: "\u2268", lneq: "\u2A87", lneqq: "\u2268", lnsim: "\u22E6", loang: "\u27EC", loarr: "\u21FD", lobrk: "\u27E6", longleftarrow: "\u27F5", LongLeftArrow: "\u27F5", Longleftarrow: "\u27F8", longleftrightarrow: "\u27F7", LongLeftRightArrow: "\u27F7", Longleftrightarrow: "\u27FA", longmapsto: "\u27FC", longrightarrow: "\u27F6", LongRightArrow: "\u27F6", Longrightarrow: "\u27F9", looparrowleft: "\u21AB", looparrowright: "\u21AC", lopar: "\u2985", Lopf: "\u{1D543}", lopf: "\u{1D55D}", loplus: "\u2A2D", lotimes: "\u2A34", lowast: "\u2217", lowbar: "_", LowerLeftArrow: "\u2199", LowerRightArrow: "\u2198", loz: "\u25CA", lozenge: "\u25CA", lozf: "\u29EB", lpar: "(", lparlt: "\u2993", lrarr: "\u21C6", lrcorner: "\u231F", lrhar: "\u21CB", lrhard: "\u296D", lrm: "\u200E", lrtri: "\u22BF", lsaquo: "\u2039", lscr: "\u{1D4C1}", Lscr: "\u2112", lsh: "\u21B0", Lsh: "\u21B0", lsim: "\u2272", lsime: "\u2A8D", lsimg: "\u2A8F", lsqb: "[", lsquo: "\u2018", lsquor: "\u201A", Lstrok: "\u0141", lstrok: "\u0142", ltcc: "\u2AA6", ltcir: "\u2A79", lt: "<", LT: "<", Lt: "\u226A", ltdot: "\u22D6", lthree: "\u22CB", ltimes: "\u22C9", ltlarr: "\u2976", ltquest: "\u2A7B", ltri: "\u25C3", ltrie: "\u22B4", ltrif: "\u25C2", ltrPar: "\u2996", lurdshar: "\u294A", luruhar: "\u2966", lvertneqq: "\u2268\uFE00", lvnE: "\u2268\uFE00", macr: "\xAF", male: "\u2642", malt: "\u2720", maltese: "\u2720", Map: "\u2905", map: "\u21A6", mapsto: "\u21A6", mapstodown: "\u21A7", mapstoleft: "\u21A4", mapstoup: "\u21A5", marker: "\u25AE", mcomma: "\u2A29", Mcy: "\u041C", mcy: "\u043C", mdash: "\u2014", mDDot: "\u223A", measuredangle: "\u2221", MediumSpace: "\u205F", Mellintrf: "\u2133", Mfr: "\u{1D510}", mfr: "\u{1D52A}", mho: "\u2127", micro: "\xB5", midast: "*", midcir: "\u2AF0", mid: "\u2223", middot: "\xB7", minusb: "\u229F", minus: "\u2212", minusd: "\u2238", minusdu: "\u2A2A", MinusPlus: "\u2213", mlcp: "\u2ADB", mldr: "\u2026", mnplus: "\u2213", models: "\u22A7", Mopf: "\u{1D544}", mopf: "\u{1D55E}", mp: "\u2213", mscr: "\u{1D4C2}", Mscr: "\u2133", mstpos: "\u223E", Mu: "\u039C", mu: "\u03BC", multimap: "\u22B8", mumap: "\u22B8", nabla: "\u2207", Nacute: "\u0143", nacute: "\u0144", nang: "\u2220\u20D2", nap: "\u2249", napE: "\u2A70\u0338", napid: "\u224B\u0338", napos: "\u0149", napprox: "\u2249", natural: "\u266E", naturals: "\u2115", natur: "\u266E", nbsp: "\xA0", nbump: "\u224E\u0338", nbumpe: "\u224F\u0338", ncap: "\u2A43", Ncaron: "\u0147", ncaron: "\u0148", Ncedil: "\u0145", ncedil: "\u0146", ncong: "\u2247", ncongdot: "\u2A6D\u0338", ncup: "\u2A42", Ncy: "\u041D", ncy: "\u043D", ndash: "\u2013", nearhk: "\u2924", nearr: "\u2197", neArr: "\u21D7", nearrow: "\u2197", ne: "\u2260", nedot: "\u2250\u0338", NegativeMediumSpace: "\u200B", NegativeThickSpace: "\u200B", NegativeThinSpace: "\u200B", NegativeVeryThinSpace: "\u200B", nequiv: "\u2262", nesear: "\u2928", nesim: "\u2242\u0338", NestedGreaterGreater: "\u226B", NestedLessLess: "\u226A", NewLine: "\n", nexist: "\u2204", nexists: "\u2204", Nfr: "\u{1D511}", nfr: "\u{1D52B}", ngE: "\u2267\u0338", nge: "\u2271", ngeq: "\u2271", ngeqq: "\u2267\u0338", ngeqslant: "\u2A7E\u0338", nges: "\u2A7E\u0338", nGg: "\u22D9\u0338", ngsim: "\u2275", nGt: "\u226B\u20D2", ngt: "\u226F", ngtr: "\u226F", nGtv: "\u226B\u0338", nharr: "\u21AE", nhArr: "\u21CE", nhpar: "\u2AF2", ni: "\u220B", nis: "\u22FC", nisd: "\u22FA", niv: "\u220B", NJcy: "\u040A", njcy: "\u045A", nlarr: "\u219A", nlArr: "\u21CD", nldr: "\u2025", nlE: "\u2266\u0338", nle: "\u2270", nleftarrow: "\u219A", nLeftarrow: "\u21CD", nleftrightarrow: "\u21AE", nLeftrightarrow: "\u21CE", nleq: "\u2270", nleqq: "\u2266\u0338", nleqslant: "\u2A7D\u0338", nles: "\u2A7D\u0338", nless: "\u226E", nLl: "\u22D8\u0338", nlsim: "\u2274", nLt: "\u226A\u20D2", nlt: "\u226E", nltri: "\u22EA", nltrie: "\u22EC", nLtv: "\u226A\u0338", nmid: "\u2224", NoBreak: "\u2060", NonBreakingSpace: "\xA0", nopf: "\u{1D55F}", Nopf: "\u2115", Not: "\u2AEC", not: "\xAC", NotCongruent: "\u2262", NotCupCap: "\u226D", NotDoubleVerticalBar: "\u2226", NotElement: "\u2209", NotEqual: "\u2260", NotEqualTilde: "\u2242\u0338", NotExists: "\u2204", NotGreater: "\u226F", NotGreaterEqual: "\u2271", NotGreaterFullEqual: "\u2267\u0338", NotGreaterGreater: "\u226B\u0338", NotGreaterLess: "\u2279", NotGreaterSlantEqual: "\u2A7E\u0338", NotGreaterTilde: "\u2275", NotHumpDownHump: "\u224E\u0338", NotHumpEqual: "\u224F\u0338", notin: "\u2209", notindot: "\u22F5\u0338", notinE: "\u22F9\u0338", notinva: "\u2209", notinvb: "\u22F7", notinvc: "\u22F6", NotLeftTriangleBar: "\u29CF\u0338", NotLeftTriangle: "\u22EA", NotLeftTriangleEqual: "\u22EC", NotLess: "\u226E", NotLessEqual: "\u2270", NotLessGreater: "\u2278", NotLessLess: "\u226A\u0338", NotLessSlantEqual: "\u2A7D\u0338", NotLessTilde: "\u2274", NotNestedGreaterGreater: "\u2AA2\u0338", NotNestedLessLess: "\u2AA1\u0338", notni: "\u220C", notniva: "\u220C", notnivb: "\u22FE", notnivc: "\u22FD", NotPrecedes: "\u2280", NotPrecedesEqual: "\u2AAF\u0338", NotPrecedesSlantEqual: "\u22E0", NotReverseElement: "\u220C", NotRightTriangleBar: "\u29D0\u0338", NotRightTriangle: "\u22EB", NotRightTriangleEqual: "\u22ED", NotSquareSubset: "\u228F\u0338", NotSquareSubsetEqual: "\u22E2", NotSquareSuperset: "\u2290\u0338", NotSquareSupersetEqual: "\u22E3", NotSubset: "\u2282\u20D2", NotSubsetEqual: "\u2288", NotSucceeds: "\u2281", NotSucceedsEqual: "\u2AB0\u0338", NotSucceedsSlantEqual: "\u22E1", NotSucceedsTilde: "\u227F\u0338", NotSuperset: "\u2283\u20D2", NotSupersetEqual: "\u2289", NotTilde: "\u2241", NotTildeEqual: "\u2244", NotTildeFullEqual: "\u2247", NotTildeTilde: "\u2249", NotVerticalBar: "\u2224", nparallel: "\u2226", npar: "\u2226", nparsl: "\u2AFD\u20E5", npart: "\u2202\u0338", npolint: "\u2A14", npr: "\u2280", nprcue: "\u22E0", nprec: "\u2280", npreceq: "\u2AAF\u0338", npre: "\u2AAF\u0338", nrarrc: "\u2933\u0338", nrarr: "\u219B", nrArr: "\u21CF", nrarrw: "\u219D\u0338", nrightarrow: "\u219B", nRightarrow: "\u21CF", nrtri: "\u22EB", nrtrie: "\u22ED", nsc: "\u2281", nsccue: "\u22E1", nsce: "\u2AB0\u0338", Nscr: "\u{1D4A9}", nscr: "\u{1D4C3}", nshortmid: "\u2224", nshortparallel: "\u2226", nsim: "\u2241", nsime: "\u2244", nsimeq: "\u2244", nsmid: "\u2224", nspar: "\u2226", nsqsube: "\u22E2", nsqsupe: "\u22E3", nsub: "\u2284", nsubE: "\u2AC5\u0338", nsube: "\u2288", nsubset: "\u2282\u20D2", nsubseteq: "\u2288", nsubseteqq: "\u2AC5\u0338", nsucc: "\u2281", nsucceq: "\u2AB0\u0338", nsup: "\u2285", nsupE: "\u2AC6\u0338", nsupe: "\u2289", nsupset: "\u2283\u20D2", nsupseteq: "\u2289", nsupseteqq: "\u2AC6\u0338", ntgl: "\u2279", Ntilde: "\xD1", ntilde: "\xF1", ntlg: "\u2278", ntriangleleft: "\u22EA", ntrianglelefteq: "\u22EC", ntriangleright: "\u22EB", ntrianglerighteq: "\u22ED", Nu: "\u039D", nu: "\u03BD", num: "#", numero: "\u2116", numsp: "\u2007", nvap: "\u224D\u20D2", nvdash: "\u22AC", nvDash: "\u22AD", nVdash: "\u22AE", nVDash: "\u22AF", nvge: "\u2265\u20D2", nvgt: ">\u20D2", nvHarr: "\u2904", nvinfin: "\u29DE", nvlArr: "\u2902", nvle: "\u2264\u20D2", nvlt: "<\u20D2", nvltrie: "\u22B4\u20D2", nvrArr: "\u2903", nvrtrie: "\u22B5\u20D2", nvsim: "\u223C\u20D2", nwarhk: "\u2923", nwarr: "\u2196", nwArr: "\u21D6", nwarrow: "\u2196", nwnear: "\u2927", Oacute: "\xD3", oacute: "\xF3", oast: "\u229B", Ocirc: "\xD4", ocirc: "\xF4", ocir: "\u229A", Ocy: "\u041E", ocy: "\u043E", odash: "\u229D", Odblac: "\u0150", odblac: "\u0151", odiv: "\u2A38", odot: "\u2299", odsold: "\u29BC", OElig: "\u0152", oelig: "\u0153", ofcir: "\u29BF", Ofr: "\u{1D512}", ofr: "\u{1D52C}", ogon: "\u02DB", Ograve: "\xD2", ograve: "\xF2", ogt: "\u29C1", ohbar: "\u29B5", ohm: "\u03A9", oint: "\u222E", olarr: "\u21BA", olcir: "\u29BE", olcross: "\u29BB", oline: "\u203E", olt: "\u29C0", Omacr: "\u014C", omacr: "\u014D", Omega: "\u03A9", omega: "\u03C9", Omicron: "\u039F", omicron: "\u03BF", omid: "\u29B6", ominus: "\u2296", Oopf: "\u{1D546}", oopf: "\u{1D560}", opar: "\u29B7", OpenCurlyDoubleQuote: "\u201C", OpenCurlyQuote: "\u2018", operp: "\u29B9", oplus: "\u2295", orarr: "\u21BB", Or: "\u2A54", or: "\u2228", ord: "\u2A5D", order: "\u2134", orderof: "\u2134", ordf: "\xAA", ordm: "\xBA", origof: "\u22B6", oror: "\u2A56", orslope: "\u2A57", orv: "\u2A5B", oS: "\u24C8", Oscr: "\u{1D4AA}", oscr: "\u2134", Oslash: "\xD8", oslash: "\xF8", osol: "\u2298", Otilde: "\xD5", otilde: "\xF5", otimesas: "\u2A36", Otimes: "\u2A37", otimes: "\u2297", Ouml: "\xD6", ouml: "\xF6", ovbar: "\u233D", OverBar: "\u203E", OverBrace: "\u23DE", OverBracket: "\u23B4", OverParenthesis: "\u23DC", para: "\xB6", parallel: "\u2225", par: "\u2225", parsim: "\u2AF3", parsl: "\u2AFD", part: "\u2202", PartialD: "\u2202", Pcy: "\u041F", pcy: "\u043F", percnt: "%", period: ".", permil: "\u2030", perp: "\u22A5", pertenk: "\u2031", Pfr: "\u{1D513}", pfr: "\u{1D52D}", Phi: "\u03A6", phi: "\u03C6", phiv: "\u03D5", phmmat: "\u2133", phone: "\u260E", Pi: "\u03A0", pi: "\u03C0", pitchfork: "\u22D4", piv: "\u03D6", planck: "\u210F", planckh: "\u210E", plankv: "\u210F", plusacir: "\u2A23", plusb: "\u229E", pluscir: "\u2A22", plus: "+", plusdo: "\u2214", plusdu: "\u2A25", pluse: "\u2A72", PlusMinus: "\xB1", plusmn: "\xB1", plussim: "\u2A26", plustwo: "\u2A27", pm: "\xB1", Poincareplane: "\u210C", pointint: "\u2A15", popf: "\u{1D561}", Popf: "\u2119", pound: "\xA3", prap: "\u2AB7", Pr: "\u2ABB", pr: "\u227A", prcue: "\u227C", precapprox: "\u2AB7", prec: "\u227A", preccurlyeq: "\u227C", Precedes: "\u227A", PrecedesEqual: "\u2AAF", PrecedesSlantEqual: "\u227C", PrecedesTilde: "\u227E", preceq: "\u2AAF", precnapprox: "\u2AB9", precneqq: "\u2AB5", precnsim: "\u22E8", pre: "\u2AAF", prE: "\u2AB3", precsim: "\u227E", prime: "\u2032", Prime: "\u2033", primes: "\u2119", prnap: "\u2AB9", prnE: "\u2AB5", prnsim: "\u22E8", prod: "\u220F", Product: "\u220F", profalar: "\u232E", profline: "\u2312", profsurf: "\u2313", prop: "\u221D", Proportional: "\u221D", Proportion: "\u2237", propto: "\u221D", prsim: "\u227E", prurel: "\u22B0", Pscr: "\u{1D4AB}", pscr: "\u{1D4C5}", Psi: "\u03A8", psi: "\u03C8", puncsp: "\u2008", Qfr: "\u{1D514}", qfr: "\u{1D52E}", qint: "\u2A0C", qopf: "\u{1D562}", Qopf: "\u211A", qprime: "\u2057", Qscr: "\u{1D4AC}", qscr: "\u{1D4C6}", quaternions: "\u210D", quatint: "\u2A16", quest: "?", questeq: "\u225F", quot: '"', QUOT: '"', rAarr: "\u21DB", race: "\u223D\u0331", Racute: "\u0154", racute: "\u0155", radic: "\u221A", raemptyv: "\u29B3", rang: "\u27E9", Rang: "\u27EB", rangd: "\u2992", range: "\u29A5", rangle: "\u27E9", raquo: "\xBB", rarrap: "\u2975", rarrb: "\u21E5", rarrbfs: "\u2920", rarrc: "\u2933", rarr: "\u2192", Rarr: "\u21A0", rArr: "\u21D2", rarrfs: "\u291E", rarrhk: "\u21AA", rarrlp: "\u21AC", rarrpl: "\u2945", rarrsim: "\u2974", Rarrtl: "\u2916", rarrtl: "\u21A3", rarrw: "\u219D", ratail: "\u291A", rAtail: "\u291C", ratio: "\u2236", rationals: "\u211A", rbarr: "\u290D", rBarr: "\u290F", RBarr: "\u2910", rbbrk: "\u2773", rbrace: "}", rbrack: "]", rbrke: "\u298C", rbrksld: "\u298E", rbrkslu: "\u2990", Rcaron: "\u0158", rcaron: "\u0159", Rcedil: "\u0156", rcedil: "\u0157", rceil: "\u2309", rcub: "}", Rcy: "\u0420", rcy: "\u0440", rdca: "\u2937", rdldhar: "\u2969", rdquo: "\u201D", rdquor: "\u201D", rdsh: "\u21B3", real: "\u211C", realine: "\u211B", realpart: "\u211C", reals: "\u211D", Re: "\u211C", rect: "\u25AD", reg: "\xAE", REG: "\xAE", ReverseElement: "\u220B", ReverseEquilibrium: "\u21CB", ReverseUpEquilibrium: "\u296F", rfisht: "\u297D", rfloor: "\u230B", rfr: "\u{1D52F}", Rfr: "\u211C", rHar: "\u2964", rhard: "\u21C1", rharu: "\u21C0", rharul: "\u296C", Rho: "\u03A1", rho: "\u03C1", rhov: "\u03F1", RightAngleBracket: "\u27E9", RightArrowBar: "\u21E5", rightarrow: "\u2192", RightArrow: "\u2192", Rightarrow: "\u21D2", RightArrowLeftArrow: "\u21C4", rightarrowtail: "\u21A3", RightCeiling: "\u2309", RightDoubleBracket: "\u27E7", RightDownTeeVector: "\u295D", RightDownVectorBar: "\u2955", RightDownVector: "\u21C2", RightFloor: "\u230B", rightharpoondown: "\u21C1", rightharpoonup: "\u21C0", rightleftarrows: "\u21C4", rightleftharpoons: "\u21CC", rightrightarrows: "\u21C9", rightsquigarrow: "\u219D", RightTeeArrow: "\u21A6", RightTee: "\u22A2", RightTeeVector: "\u295B", rightthreetimes: "\u22CC", RightTriangleBar: "\u29D0", RightTriangle: "\u22B3", RightTriangleEqual: "\u22B5", RightUpDownVector: "\u294F", RightUpTeeVector: "\u295C", RightUpVectorBar: "\u2954", RightUpVector: "\u21BE", RightVectorBar: "\u2953", RightVector: "\u21C0", ring: "\u02DA", risingdotseq: "\u2253", rlarr: "\u21C4", rlhar: "\u21CC", rlm: "\u200F", rmoustache: "\u23B1", rmoust: "\u23B1", rnmid: "\u2AEE", roang: "\u27ED", roarr: "\u21FE", robrk: "\u27E7", ropar: "\u2986", ropf: "\u{1D563}", Ropf: "\u211D", roplus: "\u2A2E", rotimes: "\u2A35", RoundImplies: "\u2970", rpar: ")", rpargt: "\u2994", rppolint: "\u2A12", rrarr: "\u21C9", Rrightarrow: "\u21DB", rsaquo: "\u203A", rscr: "\u{1D4C7}", Rscr: "\u211B", rsh: "\u21B1", Rsh: "\u21B1", rsqb: "]", rsquo: "\u2019", rsquor: "\u2019", rthree: "\u22CC", rtimes: "\u22CA", rtri: "\u25B9", rtrie: "\u22B5", rtrif: "\u25B8", rtriltri: "\u29CE", RuleDelayed: "\u29F4", ruluhar: "\u2968", rx: "\u211E", Sacute: "\u015A", sacute: "\u015B", sbquo: "\u201A", scap: "\u2AB8", Scaron: "\u0160", scaron: "\u0161", Sc: "\u2ABC", sc: "\u227B", sccue: "\u227D", sce: "\u2AB0", scE: "\u2AB4", Scedil: "\u015E", scedil: "\u015F", Scirc: "\u015C", scirc: "\u015D", scnap: "\u2ABA", scnE: "\u2AB6", scnsim: "\u22E9", scpolint: "\u2A13", scsim: "\u227F", Scy: "\u0421", scy: "\u0441", sdotb: "\u22A1", sdot: "\u22C5", sdote: "\u2A66", searhk: "\u2925", searr: "\u2198", seArr: "\u21D8", searrow: "\u2198", sect: "\xA7", semi: ";", seswar: "\u2929", setminus: "\u2216", setmn: "\u2216", sext: "\u2736", Sfr: "\u{1D516}", sfr: "\u{1D530}", sfrown: "\u2322", sharp: "\u266F", SHCHcy: "\u0429", shchcy: "\u0449", SHcy: "\u0428", shcy: "\u0448", ShortDownArrow: "\u2193", ShortLeftArrow: "\u2190", shortmid: "\u2223", shortparallel: "\u2225", ShortRightArrow: "\u2192", ShortUpArrow: "\u2191", shy: "\xAD", Sigma: "\u03A3", sigma: "\u03C3", sigmaf: "\u03C2", sigmav: "\u03C2", sim: "\u223C", simdot: "\u2A6A", sime: "\u2243", simeq: "\u2243", simg: "\u2A9E", simgE: "\u2AA0", siml: "\u2A9D", simlE: "\u2A9F", simne: "\u2246", simplus: "\u2A24", simrarr: "\u2972", slarr: "\u2190", SmallCircle: "\u2218", smallsetminus: "\u2216", smashp: "\u2A33", smeparsl: "\u29E4", smid: "\u2223", smile: "\u2323", smt: "\u2AAA", smte: "\u2AAC", smtes: "\u2AAC\uFE00", SOFTcy: "\u042C", softcy: "\u044C", solbar: "\u233F", solb: "\u29C4", sol: "/", Sopf: "\u{1D54A}", sopf: "\u{1D564}", spades: "\u2660", spadesuit: "\u2660", spar: "\u2225", sqcap: "\u2293", sqcaps: "\u2293\uFE00", sqcup: "\u2294", sqcups: "\u2294\uFE00", Sqrt: "\u221A", sqsub: "\u228F", sqsube: "\u2291", sqsubset: "\u228F", sqsubseteq: "\u2291", sqsup: "\u2290", sqsupe: "\u2292", sqsupset: "\u2290", sqsupseteq: "\u2292", square: "\u25A1", Square: "\u25A1", SquareIntersection: "\u2293", SquareSubset: "\u228F", SquareSubsetEqual: "\u2291", SquareSuperset: "\u2290", SquareSupersetEqual: "\u2292", SquareUnion: "\u2294", squarf: "\u25AA", squ: "\u25A1", squf: "\u25AA", srarr: "\u2192", Sscr: "\u{1D4AE}", sscr: "\u{1D4C8}", ssetmn: "\u2216", ssmile: "\u2323", sstarf: "\u22C6", Star: "\u22C6", star: "\u2606", starf: "\u2605", straightepsilon: "\u03F5", straightphi: "\u03D5", strns: "\xAF", sub: "\u2282", Sub: "\u22D0", subdot: "\u2ABD", subE: "\u2AC5", sube: "\u2286", subedot: "\u2AC3", submult: "\u2AC1", subnE: "\u2ACB", subne: "\u228A", subplus: "\u2ABF", subrarr: "\u2979", subset: "\u2282", Subset: "\u22D0", subseteq: "\u2286", subseteqq: "\u2AC5", SubsetEqual: "\u2286", subsetneq: "\u228A", subsetneqq: "\u2ACB", subsim: "\u2AC7", subsub: "\u2AD5", subsup: "\u2AD3", succapprox: "\u2AB8", succ: "\u227B", succcurlyeq: "\u227D", Succeeds: "\u227B", SucceedsEqual: "\u2AB0", SucceedsSlantEqual: "\u227D", SucceedsTilde: "\u227F", succeq: "\u2AB0", succnapprox: "\u2ABA", succneqq: "\u2AB6", succnsim: "\u22E9", succsim: "\u227F", SuchThat: "\u220B", sum: "\u2211", Sum: "\u2211", sung: "\u266A", sup1: "\xB9", sup2: "\xB2", sup3: "\xB3", sup: "\u2283", Sup: "\u22D1", supdot: "\u2ABE", supdsub: "\u2AD8", supE: "\u2AC6", supe: "\u2287", supedot: "\u2AC4", Superset: "\u2283", SupersetEqual: "\u2287", suphsol: "\u27C9", suphsub: "\u2AD7", suplarr: "\u297B", supmult: "\u2AC2", supnE: "\u2ACC", supne: "\u228B", supplus: "\u2AC0", supset: "\u2283", Supset: "\u22D1", supseteq: "\u2287", supseteqq: "\u2AC6", supsetneq: "\u228B", supsetneqq: "\u2ACC", supsim: "\u2AC8", supsub: "\u2AD4", supsup: "\u2AD6", swarhk: "\u2926", swarr: "\u2199", swArr: "\u21D9", swarrow: "\u2199", swnwar: "\u292A", szlig: "\xDF", Tab: " ", target: "\u2316", Tau: "\u03A4", tau: "\u03C4", tbrk: "\u23B4", Tcaron: "\u0164", tcaron: "\u0165", Tcedil: "\u0162", tcedil: "\u0163", Tcy: "\u0422", tcy: "\u0442", tdot: "\u20DB", telrec: "\u2315", Tfr: "\u{1D517}", tfr: "\u{1D531}", there4: "\u2234", therefore: "\u2234", Therefore: "\u2234", Theta: "\u0398", theta: "\u03B8", thetasym: "\u03D1", thetav: "\u03D1", thickapprox: "\u2248", thicksim: "\u223C", ThickSpace: "\u205F\u200A", ThinSpace: "\u2009", thinsp: "\u2009", thkap: "\u2248", thksim: "\u223C", THORN: "\xDE", thorn: "\xFE", tilde: "\u02DC", Tilde: "\u223C", TildeEqual: "\u2243", TildeFullEqual: "\u2245", TildeTilde: "\u2248", timesbar: "\u2A31", timesb: "\u22A0", times: "\xD7", timesd: "\u2A30", tint: "\u222D", toea: "\u2928", topbot: "\u2336", topcir: "\u2AF1", top: "\u22A4", Topf: "\u{1D54B}", topf: "\u{1D565}", topfork: "\u2ADA", tosa: "\u2929", tprime: "\u2034", trade: "\u2122", TRADE: "\u2122", triangle: "\u25B5", triangledown: "\u25BF", triangleleft: "\u25C3", trianglelefteq: "\u22B4", triangleq: "\u225C", triangleright: "\u25B9", trianglerighteq: "\u22B5", tridot: "\u25EC", trie: "\u225C", triminus: "\u2A3A", TripleDot: "\u20DB", triplus: "\u2A39", trisb: "\u29CD", tritime: "\u2A3B", trpezium: "\u23E2", Tscr: "\u{1D4AF}", tscr: "\u{1D4C9}", TScy: "\u0426", tscy: "\u0446", TSHcy: "\u040B", tshcy: "\u045B", Tstrok: "\u0166", tstrok: "\u0167", twixt: "\u226C", twoheadleftarrow: "\u219E", twoheadrightarrow: "\u21A0", Uacute: "\xDA", uacute: "\xFA", uarr: "\u2191", Uarr: "\u219F", uArr: "\u21D1", Uarrocir: "\u2949", Ubrcy: "\u040E", ubrcy: "\u045E", Ubreve: "\u016C", ubreve: "\u016D", Ucirc: "\xDB", ucirc: "\xFB", Ucy: "\u0423", ucy: "\u0443", udarr: "\u21C5", Udblac: "\u0170", udblac: "\u0171", udhar: "\u296E", ufisht: "\u297E", Ufr: "\u{1D518}", ufr: "\u{1D532}", Ugrave: "\xD9", ugrave: "\xF9", uHar: "\u2963", uharl: "\u21BF", uharr: "\u21BE", uhblk: "\u2580", ulcorn: "\u231C", ulcorner: "\u231C", ulcrop: "\u230F", ultri: "\u25F8", Umacr: "\u016A", umacr: "\u016B", uml: "\xA8", UnderBar: "_", UnderBrace: "\u23DF", UnderBracket: "\u23B5", UnderParenthesis: "\u23DD", Union: "\u22C3", UnionPlus: "\u228E", Uogon: "\u0172", uogon: "\u0173", Uopf: "\u{1D54C}", uopf: "\u{1D566}", UpArrowBar: "\u2912", uparrow: "\u2191", UpArrow: "\u2191", Uparrow: "\u21D1", UpArrowDownArrow: "\u21C5", updownarrow: "\u2195", UpDownArrow: "\u2195", Updownarrow: "\u21D5", UpEquilibrium: "\u296E", upharpoonleft: "\u21BF", upharpoonright: "\u21BE", uplus: "\u228E", UpperLeftArrow: "\u2196", UpperRightArrow: "\u2197", upsi: "\u03C5", Upsi: "\u03D2", upsih: "\u03D2", Upsilon: "\u03A5", upsilon: "\u03C5", UpTeeArrow: "\u21A5", UpTee: "\u22A5", upuparrows: "\u21C8", urcorn: "\u231D", urcorner: "\u231D", urcrop: "\u230E", Uring: "\u016E", uring: "\u016F", urtri: "\u25F9", Uscr: "\u{1D4B0}", uscr: "\u{1D4CA}", utdot: "\u22F0", Utilde: "\u0168", utilde: "\u0169", utri: "\u25B5", utrif: "\u25B4", uuarr: "\u21C8", Uuml: "\xDC", uuml: "\xFC", uwangle: "\u29A7", vangrt: "\u299C", varepsilon: "\u03F5", varkappa: "\u03F0", varnothing: "\u2205", varphi: "\u03D5", varpi: "\u03D6", varpropto: "\u221D", varr: "\u2195", vArr: "\u21D5", varrho: "\u03F1", varsigma: "\u03C2", varsubsetneq: "\u228A\uFE00", varsubsetneqq: "\u2ACB\uFE00", varsupsetneq: "\u228B\uFE00", varsupsetneqq: "\u2ACC\uFE00", vartheta: "\u03D1", vartriangleleft: "\u22B2", vartriangleright: "\u22B3", vBar: "\u2AE8", Vbar: "\u2AEB", vBarv: "\u2AE9", Vcy: "\u0412", vcy: "\u0432", vdash: "\u22A2", vDash: "\u22A8", Vdash: "\u22A9", VDash: "\u22AB", Vdashl: "\u2AE6", veebar: "\u22BB", vee: "\u2228", Vee: "\u22C1", veeeq: "\u225A", vellip: "\u22EE", verbar: "|", Verbar: "\u2016", vert: "|", Vert: "\u2016", VerticalBar: "\u2223", VerticalLine: "|", VerticalSeparator: "\u2758", VerticalTilde: "\u2240", VeryThinSpace: "\u200A", Vfr: "\u{1D519}", vfr: "\u{1D533}", vltri: "\u22B2", vnsub: "\u2282\u20D2", vnsup: "\u2283\u20D2", Vopf: "\u{1D54D}", vopf: "\u{1D567}", vprop: "\u221D", vrtri: "\u22B3", Vscr: "\u{1D4B1}", vscr: "\u{1D4CB}", vsubnE: "\u2ACB\uFE00", vsubne: "\u228A\uFE00", vsupnE: "\u2ACC\uFE00", vsupne: "\u228B\uFE00", Vvdash: "\u22AA", vzigzag: "\u299A", Wcirc: "\u0174", wcirc: "\u0175", wedbar: "\u2A5F", wedge: "\u2227", Wedge: "\u22C0", wedgeq: "\u2259", weierp: "\u2118", Wfr: "\u{1D51A}", wfr: "\u{1D534}", Wopf: "\u{1D54E}", wopf: "\u{1D568}", wp: "\u2118", wr: "\u2240", wreath: "\u2240", Wscr: "\u{1D4B2}", wscr: "\u{1D4CC}", xcap: "\u22C2", xcirc: "\u25EF", xcup: "\u22C3", xdtri: "\u25BD", Xfr: "\u{1D51B}", xfr: "\u{1D535}", xharr: "\u27F7", xhArr: "\u27FA", Xi: "\u039E", xi: "\u03BE", xlarr: "\u27F5", xlArr: "\u27F8", xmap: "\u27FC", xnis: "\u22FB", xodot: "\u2A00", Xopf: "\u{1D54F}", xopf: "\u{1D569}", xoplus: "\u2A01", xotime: "\u2A02", xrarr: "\u27F6", xrArr: "\u27F9", Xscr: "\u{1D4B3}", xscr: "\u{1D4CD}", xsqcup: "\u2A06", xuplus: "\u2A04", xutri: "\u25B3", xvee: "\u22C1", xwedge: "\u22C0", Yacute: "\xDD", yacute: "\xFD", YAcy: "\u042F", yacy: "\u044F", Ycirc: "\u0176", ycirc: "\u0177", Ycy: "\u042B", ycy: "\u044B", yen: "\xA5", Yfr: "\u{1D51C}", yfr: "\u{1D536}", YIcy: "\u0407", yicy: "\u0457", Yopf: "\u{1D550}", yopf: "\u{1D56A}", Yscr: "\u{1D4B4}", yscr: "\u{1D4CE}", YUcy: "\u042E", yucy: "\u044E", yuml: "\xFF", Yuml: "\u0178", Zacute: "\u0179", zacute: "\u017A", Zcaron: "\u017D", zcaron: "\u017E", Zcy: "\u0417", zcy: "\u0437", Zdot: "\u017B", zdot: "\u017C", zeetrf: "\u2128", ZeroWidthSpace: "\u200B", Zeta: "\u0396", zeta: "\u03B6", zfr: "\u{1D537}", Zfr: "\u2128", ZHcy: "\u0416", zhcy: "\u0436", zigrarr: "\u21DD", zopf: "\u{1D56B}", Zopf: "\u2124", Zscr: "\u{1D4B5}", zscr: "\u{1D4CF}", zwj: "\u200D", zwnj: "\u200C" }; } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/legacy.json var require_legacy = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/legacy.json"(exports2, module2) { module2.exports = { Aacute: "\xC1", aacute: "\xE1", Acirc: "\xC2", acirc: "\xE2", acute: "\xB4", AElig: "\xC6", aelig: "\xE6", Agrave: "\xC0", agrave: "\xE0", amp: "&", AMP: "&", Aring: "\xC5", aring: "\xE5", Atilde: "\xC3", atilde: "\xE3", Auml: "\xC4", auml: "\xE4", brvbar: "\xA6", Ccedil: "\xC7", ccedil: "\xE7", cedil: "\xB8", cent: "\xA2", copy: "\xA9", COPY: "\xA9", curren: "\xA4", deg: "\xB0", divide: "\xF7", Eacute: "\xC9", eacute: "\xE9", Ecirc: "\xCA", ecirc: "\xEA", Egrave: "\xC8", egrave: "\xE8", ETH: "\xD0", eth: "\xF0", Euml: "\xCB", euml: "\xEB", frac12: "\xBD", frac14: "\xBC", frac34: "\xBE", gt: ">", GT: ">", Iacute: "\xCD", iacute: "\xED", Icirc: "\xCE", icirc: "\xEE", iexcl: "\xA1", Igrave: "\xCC", igrave: "\xEC", iquest: "\xBF", Iuml: "\xCF", iuml: "\xEF", laquo: "\xAB", lt: "<", LT: "<", macr: "\xAF", micro: "\xB5", middot: "\xB7", nbsp: "\xA0", not: "\xAC", Ntilde: "\xD1", ntilde: "\xF1", Oacute: "\xD3", oacute: "\xF3", Ocirc: "\xD4", ocirc: "\xF4", Ograve: "\xD2", ograve: "\xF2", ordf: "\xAA", ordm: "\xBA", Oslash: "\xD8", oslash: "\xF8", Otilde: "\xD5", otilde: "\xF5", Ouml: "\xD6", ouml: "\xF6", para: "\xB6", plusmn: "\xB1", pound: "\xA3", quot: '"', QUOT: '"', raquo: "\xBB", reg: "\xAE", REG: "\xAE", sect: "\xA7", shy: "\xAD", sup1: "\xB9", sup2: "\xB2", sup3: "\xB3", szlig: "\xDF", THORN: "\xDE", thorn: "\xFE", times: "\xD7", Uacute: "\xDA", uacute: "\xFA", Ucirc: "\xDB", ucirc: "\xFB", Ugrave: "\xD9", ugrave: "\xF9", uml: "\xA8", Uuml: "\xDC", uuml: "\xFC", Yacute: "\xDD", yacute: "\xFD", yen: "\xA5", yuml: "\xFF" }; } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/xml.json var require_xml = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/xml.json"(exports2, module2) { module2.exports = { amp: "&", apos: "'", gt: ">", lt: "<", quot: '"' }; } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/decode.json var require_decode = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/maps/decode.json"(exports2, module2) { module2.exports = { "0": 65533, "128": 8364, "130": 8218, "131": 402, "132": 8222, "133": 8230, "134": 8224, "135": 8225, "136": 710, "137": 8240, "138": 352, "139": 8249, "140": 338, "142": 381, "145": 8216, "146": 8217, "147": 8220, "148": 8221, "149": 8226, "150": 8211, "151": 8212, "152": 732, "153": 8482, "154": 353, "155": 8250, "156": 339, "158": 382, "159": 376 }; } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/decode_codepoint.js var require_decode_codepoint = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/decode_codepoint.js"(exports2) { "use strict"; var __importDefault = exports2 && exports2.__importDefault || function(mod3) { return mod3 && mod3.__esModule ? mod3 : { "default": mod3 }; }; Object.defineProperty(exports2, "__esModule", { value: true }); var decode_json_1 = __importDefault(require_decode()); var fromCodePoint = String.fromCodePoint || function(codePoint) { var output = ""; if (codePoint > 65535) { codePoint -= 65536; output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296); codePoint = 56320 | codePoint & 1023; } output += String.fromCharCode(codePoint); return output; }; function decodeCodePoint(codePoint) { if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) { return "\uFFFD"; } if (codePoint in decode_json_1.default) { codePoint = decode_json_1.default[codePoint]; } return fromCodePoint(codePoint); } exports2.default = decodeCodePoint; } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/decode.js var require_decode2 = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/decode.js"(exports2) { "use strict"; var __importDefault = exports2 && exports2.__importDefault || function(mod3) { return mod3 && mod3.__esModule ? mod3 : { "default": mod3 }; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.decodeHTML = exports2.decodeHTMLStrict = exports2.decodeXML = void 0; var entities_json_1 = __importDefault(require_entities()); var legacy_json_1 = __importDefault(require_legacy()); var xml_json_1 = __importDefault(require_xml()); var decode_codepoint_1 = __importDefault(require_decode_codepoint()); var strictEntityRe = /&(?:[a-zA-Z0-9]+|#[xX][\da-fA-F]+|#\d+);/g; exports2.decodeXML = getStrictDecoder(xml_json_1.default); exports2.decodeHTMLStrict = getStrictDecoder(entities_json_1.default); function getStrictDecoder(map2) { var replace = getReplacer(map2); return function(str3) { return String(str3).replace(strictEntityRe, replace); }; } var sorter = function(a2, b2) { return a2 < b2 ? 1 : -1; }; exports2.decodeHTML = function() { var legacy = Object.keys(legacy_json_1.default).sort(sorter); var keys = Object.keys(entities_json_1.default).sort(sorter); for (var i2 = 0, j2 = 0; i2 < keys.length; i2++) { if (legacy[j2] === keys[i2]) { keys[i2] += ";?"; j2++; } else { keys[i2] += ";"; } } var re2 = new RegExp("&(?:" + keys.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g"); var replace = getReplacer(entities_json_1.default); function replacer(str3) { if (str3.substr(-1) !== ";") str3 += ";"; return replace(str3); } return function(str3) { return String(str3).replace(re2, replacer); }; }(); function getReplacer(map2) { return function replace(str3) { if (str3.charAt(1) === "#") { var secondChar = str3.charAt(2); if (secondChar === "X" || secondChar === "x") { return decode_codepoint_1.default(parseInt(str3.substr(3), 16)); } return decode_codepoint_1.default(parseInt(str3.substr(2), 10)); } return map2[str3.slice(1, -1)] || str3; }; } } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/encode.js var require_encode = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/encode.js"(exports2) { "use strict"; var __importDefault = exports2 && exports2.__importDefault || function(mod3) { return mod3 && mod3.__esModule ? mod3 : { "default": mod3 }; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.escapeUTF8 = exports2.escape = exports2.encodeNonAsciiHTML = exports2.encodeHTML = exports2.encodeXML = void 0; var xml_json_1 = __importDefault(require_xml()); var inverseXML = getInverseObj(xml_json_1.default); var xmlReplacer = getInverseReplacer(inverseXML); exports2.encodeXML = getASCIIEncoder(inverseXML); var entities_json_1 = __importDefault(require_entities()); var inverseHTML = getInverseObj(entities_json_1.default); var htmlReplacer = getInverseReplacer(inverseHTML); exports2.encodeHTML = getInverse(inverseHTML, htmlReplacer); exports2.encodeNonAsciiHTML = getASCIIEncoder(inverseHTML); function getInverseObj(obj) { return Object.keys(obj).sort().reduce(function(inverse, name2) { inverse[obj[name2]] = "&" + name2 + ";"; return inverse; }, {}); } function getInverseReplacer(inverse) { var single = []; var multiple = []; for (var _i = 0, _a4 = Object.keys(inverse); _i < _a4.length; _i++) { var k2 = _a4[_i]; if (k2.length === 1) { single.push("\\" + k2); } else { multiple.push(k2); } } single.sort(); for (var start = 0; start < single.length - 1; start++) { var end = start; while (end < single.length - 1 && single[end].charCodeAt(1) + 1 === single[end + 1].charCodeAt(1)) { end += 1; } var count = 1 + end - start; if (count < 3) continue; single.splice(start, count, single[start] + "-" + single[end]); } multiple.unshift("[" + single.join("") + "]"); return new RegExp(multiple.join("|"), "g"); } var reNonASCII = /(?:[\x80-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g; var getCodePoint = String.prototype.codePointAt != null ? function(str3) { return str3.codePointAt(0); } : function(c2) { return (c2.charCodeAt(0) - 55296) * 1024 + c2.charCodeAt(1) - 56320 + 65536; }; function singleCharReplacer(c2) { return "&#x" + (c2.length > 1 ? getCodePoint(c2) : c2.charCodeAt(0)).toString(16).toUpperCase() + ";"; } function getInverse(inverse, re2) { return function(data) { return data.replace(re2, function(name2) { return inverse[name2]; }).replace(reNonASCII, singleCharReplacer); }; } var reEscapeChars = new RegExp(xmlReplacer.source + "|" + reNonASCII.source, "g"); function escape(data) { return data.replace(reEscapeChars, singleCharReplacer); } exports2.escape = escape; function escapeUTF8(data) { return data.replace(xmlReplacer, singleCharReplacer); } exports2.escapeUTF8 = escapeUTF8; function getASCIIEncoder(obj) { return function(data) { return data.replace(reEscapeChars, function(c2) { return obj[c2] || singleCharReplacer(c2); }); }; } } }); // node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/index.js var require_lib2 = __commonJS({ "node_modules/.pnpm/entities@2.2.0/node_modules/entities/lib/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.decodeXMLStrict = exports2.decodeHTML5Strict = exports2.decodeHTML4Strict = exports2.decodeHTML5 = exports2.decodeHTML4 = exports2.decodeHTMLStrict = exports2.decodeHTML = exports2.decodeXML = exports2.encodeHTML5 = exports2.encodeHTML4 = exports2.escapeUTF8 = exports2.escape = exports2.encodeNonAsciiHTML = exports2.encodeHTML = exports2.encodeXML = exports2.encode = exports2.decodeStrict = exports2.decode = void 0; var decode_1 = require_decode2(); var encode_1 = require_encode(); function decode(data, level) { return (!level || level <= 0 ? decode_1.decodeXML : decode_1.decodeHTML)(data); } exports2.decode = decode; function decodeStrict(data, level) { return (!level || level <= 0 ? decode_1.decodeXML : decode_1.decodeHTMLStrict)(data); } exports2.decodeStrict = decodeStrict; function encode(data, level) { return (!level || level <= 0 ? encode_1.encodeXML : encode_1.encodeHTML)(data); } exports2.encode = encode; var encode_2 = require_encode(); Object.defineProperty(exports2, "encodeXML", { enumerable: true, get: function() { return encode_2.encodeXML; } }); Object.defineProperty(exports2, "encodeHTML", { enumerable: true, get: function() { return encode_2.encodeHTML; } }); Object.defineProperty(exports2, "encodeNonAsciiHTML", { enumerable: true, get: function() { return encode_2.encodeNonAsciiHTML; } }); Object.defineProperty(exports2, "escape", { enumerable: true, get: function() { return encode_2.escape; } }); Object.defineProperty(exports2, "escapeUTF8", { enumerable: true, get: function() { return encode_2.escapeUTF8; } }); Object.defineProperty(exports2, "encodeHTML4", { enumerable: true, get: function() { return encode_2.encodeHTML; } }); Object.defineProperty(exports2, "encodeHTML5", { enumerable: true, get: function() { return encode_2.encodeHTML; } }); var decode_2 = require_decode2(); Object.defineProperty(exports2, "decodeXML", { enumerable: true, get: function() { return decode_2.decodeXML; } }); Object.defineProperty(exports2, "decodeHTML", { enumerable: true, get: function() { return decode_2.decodeHTML; } }); Object.defineProperty(exports2, "decodeHTMLStrict", { enumerable: true, get: function() { return decode_2.decodeHTMLStrict; } }); Object.defineProperty(exports2, "decodeHTML4", { enumerable: true, get: function() { return decode_2.decodeHTML; } }); Object.defineProperty(exports2, "decodeHTML5", { enumerable: true, get: function() { return decode_2.decodeHTML; } }); Object.defineProperty(exports2, "decodeHTML4Strict", { enumerable: true, get: function() { return decode_2.decodeHTMLStrict; } }); Object.defineProperty(exports2, "decodeHTML5Strict", { enumerable: true, get: function() { return decode_2.decodeHTMLStrict; } }); Object.defineProperty(exports2, "decodeXMLStrict", { enumerable: true, get: function() { return decode_2.decodeXML; } }); } }); // node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/lib/utils.js var require_utils3 = __commonJS({ "node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/lib/utils.js"(exports2, module2) { var utils = module2.exports = {}; var entities = require_lib2(); var xml2js = require_xml2js(); utils.stripHtml = function(str3) { str3 = str3.replace(/([^\n])<\/?(h|br|p|ul|ol|li|blockquote|section|table|tr|div)(?:.|\n)*?>([^\n])/gm, "$1\n$3"); str3 = str3.replace(/<(?:.|\n)*?>/gm, ""); return str3; }; utils.getSnippet = function(str3) { return entities.decodeHTML(utils.stripHtml(str3)).trim(); }; utils.getLink = function(links, rel, fallbackIdx) { if (!links) return; for (let i2 = 0; i2 < links.length; ++i2) { if (links[i2].$.rel === rel) return links[i2].$.href; } if (links[fallbackIdx]) return links[fallbackIdx].$.href; }; utils.getContent = function(content) { if (typeof content._ === "string") { return content._; } else if (typeof content === "object") { let builder = new xml2js.Builder({ headless: true, explicitRoot: true, rootName: "div", renderOpts: { pretty: false } }); return builder.buildObject(content); } else { return content; } }; utils.copyFromXML = function(xml, dest, fields2) { fields2.forEach(function(f4) { let from = f4; let to = f4; let options = {}; if (Array.isArray(f4)) { from = f4[0]; to = f4[1]; if (f4.length > 2) { options = f4[2]; } } const { keepArray, includeSnippet } = options; if (xml[from] !== void 0) { dest[to] = keepArray ? xml[from] : xml[from][0]; } if (dest[to] && typeof dest[to]._ === "string") { dest[to] = dest[to]._; } if (includeSnippet && dest[to] && typeof dest[to] === "string") { dest[to + "Snippet"] = utils.getSnippet(dest[to]); } }); }; utils.maybePromisify = function(callback, promise) { if (!callback) return promise; return promise.then((data) => setTimeout(() => callback(null, data)), (err) => setTimeout(() => callback(err))); }; var DEFAULT_ENCODING = "utf8"; var ENCODING_REGEX = /(encoding|charset)\s*=\s*(\S+)/; var SUPPORTED_ENCODINGS = ["ascii", "utf8", "utf16le", "ucs2", "base64", "latin1", "binary", "hex"]; var ENCODING_ALIASES = { "utf-8": "utf8", "iso-8859-1": "latin1" }; utils.getEncodingFromContentType = function(contentType) { contentType = contentType || ""; let match = contentType.match(ENCODING_REGEX); let encoding = (match || [])[2] || ""; encoding = encoding.toLowerCase(); encoding = ENCODING_ALIASES[encoding] || encoding; if (!encoding || SUPPORTED_ENCODINGS.indexOf(encoding) === -1) { encoding = DEFAULT_ENCODING; } return encoding; }; } }); // node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/lib/parser.js var require_parser3 = __commonJS({ "node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/lib/parser.js"(exports2, module2) { "use strict"; var http = require("http"); var https = require("https"); var xml2js = require_xml2js(); var url = require("url"); var fields2 = require_fields(); var utils = require_utils3(); var DEFAULT_HEADERS = { "User-Agent": "rss-parser", "Accept": "application/rss+xml" }; var DEFAULT_MAX_REDIRECTS = 5; var DEFAULT_TIMEOUT = 6e4; var Parser2 = class { constructor(options = {}) { options.headers = options.headers || {}; options.xml2js = options.xml2js || {}; options.customFields = options.customFields || {}; options.customFields.item = options.customFields.item || []; options.customFields.feed = options.customFields.feed || []; options.requestOptions = options.requestOptions || {}; if (!options.maxRedirects) options.maxRedirects = DEFAULT_MAX_REDIRECTS; if (!options.timeout) options.timeout = DEFAULT_TIMEOUT; this.options = options; this.xmlParser = new xml2js.Parser(this.options.xml2js); } parseString(xml, callback) { let prom = new Promise((resolve, reject) => { this.xmlParser.parseString(xml, (err, result) => { if (err) return reject(err); if (!result) { return reject(new Error("Unable to parse XML.")); } let feed = null; if (result.feed) { feed = this.buildAtomFeed(result); } else if (result.rss && result.rss.$ && result.rss.$.version && result.rss.$.version.match(/^2/)) { feed = this.buildRSS2(result); } else if (result["rdf:RDF"]) { feed = this.buildRSS1(result); } else if (result.rss && result.rss.$ && result.rss.$.version && result.rss.$.version.match(/0\.9/)) { feed = this.buildRSS0_9(result); } else if (result.rss && this.options.defaultRSS) { switch (this.options.defaultRSS) { case 0.9: feed = this.buildRSS0_9(result); break; case 1: feed = this.buildRSS1(result); break; case 2: feed = this.buildRSS2(result); break; default: return reject(new Error("default RSS version not recognized.")); } } else { return reject(new Error("Feed not recognized as RSS 1 or 2.")); } resolve(feed); }); }); prom = utils.maybePromisify(callback, prom); return prom; } parseURL(feedUrl, callback, redirectCount = 0) { let xml = ""; let get22 = feedUrl.indexOf("https") === 0 ? https.get : http.get; let urlParts = url.parse(feedUrl); let headers = Object.assign({}, DEFAULT_HEADERS, this.options.headers); let timeout = null; let prom = new Promise((resolve, reject) => { const requestOpts = Object.assign({ headers }, urlParts, this.options.requestOptions); let req = get22(requestOpts, (res) => { if (this.options.maxRedirects && res.statusCode >= 300 && res.statusCode < 400 && res.headers["location"]) { if (redirectCount === this.options.maxRedirects) { return reject(new Error("Too many redirects")); } else { const newLocation = url.resolve(feedUrl, res.headers["location"]); return this.parseURL(newLocation, null, redirectCount + 1).then(resolve, reject); } } else if (res.statusCode >= 300) { return reject(new Error("Status code " + res.statusCode)); } let encoding = utils.getEncodingFromContentType(res.headers["content-type"]); res.setEncoding(encoding); res.on("data", (chunk) => { xml += chunk; }); res.on("end", () => { return this.parseString(xml).then(resolve, reject); }); }); req.on("error", reject); timeout = setTimeout(() => { return reject(new Error("Request timed out after " + this.options.timeout + "ms")); }, this.options.timeout); }).then((data) => { clearTimeout(timeout); return Promise.resolve(data); }, (e2) => { clearTimeout(timeout); return Promise.reject(e2); }); prom = utils.maybePromisify(callback, prom); return prom; } buildAtomFeed(xmlObj) { let feed = { items: [] }; utils.copyFromXML(xmlObj.feed, feed, this.options.customFields.feed); if (xmlObj.feed.link) { feed.link = utils.getLink(xmlObj.feed.link, "alternate", 0); feed.feedUrl = utils.getLink(xmlObj.feed.link, "self", 1); } if (xmlObj.feed.title) { let title = xmlObj.feed.title[0] || ""; if (title._) title = title._; if (title) feed.title = title; } if (xmlObj.feed.updated) { feed.lastBuildDate = xmlObj.feed.updated[0]; } feed.items = (xmlObj.feed.entry || []).map((entry) => this.parseItemAtom(entry)); return feed; } parseItemAtom(entry) { let item = {}; utils.copyFromXML(entry, item, this.options.customFields.item); if (entry.title) { let title = entry.title[0] || ""; if (title._) title = title._; if (title) item.title = title; } if (entry.link && entry.link.length) { item.link = utils.getLink(entry.link, "alternate", 0); } if (entry.published && entry.published.length && entry.published[0].length) item.pubDate = new Date(entry.published[0]).toISOString(); if (!item.pubDate && entry.updated && entry.updated.length && entry.updated[0].length) item.pubDate = new Date(entry.updated[0]).toISOString(); if (entry.author && entry.author.length && entry.author[0].name && entry.author[0].name.length) item.author = entry.author[0].name[0]; if (entry.content && entry.content.length) { item.content = utils.getContent(entry.content[0]); item.contentSnippet = utils.getSnippet(item.content); } if (entry.summary && entry.summary.length) { item.summary = utils.getContent(entry.summary[0]); } if (entry.id) { item.id = entry.id[0]; } this.setISODate(item); return item; } buildRSS0_9(xmlObj) { var channel = xmlObj.rss.channel[0]; var items = channel.item; return this.buildRSS(channel, items); } buildRSS1(xmlObj) { xmlObj = xmlObj["rdf:RDF"]; let channel = xmlObj.channel[0]; let items = xmlObj.item; return this.buildRSS(channel, items); } buildRSS2(xmlObj) { let channel = xmlObj.rss.channel[0]; let items = channel.item; let feed = this.buildRSS(channel, items); if (xmlObj.rss.$ && xmlObj.rss.$["xmlns:itunes"]) { this.decorateItunes(feed, channel); } return feed; } buildRSS(channel, items) { items = items || []; let feed = { items: [] }; let feedFields = fields2.feed.concat(this.options.customFields.feed); let itemFields = fields2.item.concat(this.options.customFields.item); if (channel["atom:link"] && channel["atom:link"][0] && channel["atom:link"][0].$) { feed.feedUrl = channel["atom:link"][0].$.href; } if (channel.image && channel.image[0] && channel.image[0].url) { feed.image = {}; let image = channel.image[0]; if (image.link) feed.image.link = image.link[0]; if (image.url) feed.image.url = image.url[0]; if (image.title) feed.image.title = image.title[0]; if (image.width) feed.image.width = image.width[0]; if (image.height) feed.image.height = image.height[0]; } const paginationLinks = this.generatePaginationLinks(channel); if (Object.keys(paginationLinks).length) { feed.paginationLinks = paginationLinks; } utils.copyFromXML(channel, feed, feedFields); feed.items = items.map((xmlItem) => this.parseItemRss(xmlItem, itemFields)); return feed; } parseItemRss(xmlItem, itemFields) { let item = {}; utils.copyFromXML(xmlItem, item, itemFields); if (xmlItem.enclosure) { item.enclosure = xmlItem.enclosure[0].$; } if (xmlItem.description) { item.content = utils.getContent(xmlItem.description[0]); item.contentSnippet = utils.getSnippet(item.content); } if (xmlItem.guid) { item.guid = xmlItem.guid[0]; if (item.guid._) item.guid = item.guid._; } if (xmlItem.$ && xmlItem.$["rdf:about"]) { item["rdf:about"] = xmlItem.$["rdf:about"]; } if (xmlItem.category) item.categories = xmlItem.category; this.setISODate(item); return item; } decorateItunes(feed, channel) { let items = channel.item || []; let categories = []; feed.itunes = {}; if (channel["itunes:owner"]) { let owner = {}; if (channel["itunes:owner"][0]["itunes:name"]) { owner.name = channel["itunes:owner"][0]["itunes:name"][0]; } if (channel["itunes:owner"][0]["itunes:email"]) { owner.email = channel["itunes:owner"][0]["itunes:email"][0]; } feed.itunes.owner = owner; } if (channel["itunes:image"]) { let image; let hasImageHref = channel["itunes:image"][0] && channel["itunes:image"][0].$ && channel["itunes:image"][0].$.href; image = hasImageHref ? channel["itunes:image"][0].$.href : null; if (image) { feed.itunes.image = image; } } if (channel["itunes:category"]) { const categoriesWithSubs = channel["itunes:category"].map((category) => { return { name: category && category.$ && category.$.text, subs: category["itunes:category"] ? category["itunes:category"].map((subcategory) => ({ name: subcategory && subcategory.$ && subcategory.$.text })) : null }; }); feed.itunes.categories = categoriesWithSubs.map((category) => category.name); feed.itunes.categoriesWithSubs = categoriesWithSubs; } if (channel["itunes:keywords"]) { if (channel["itunes:keywords"].length > 1) { feed.itunes.keywords = channel["itunes:keywords"].map((keyword) => keyword && keyword.$ && keyword.$.text); } else { let keywords2 = channel["itunes:keywords"][0]; if (keywords2 && typeof keywords2._ === "string") { keywords2 = keywords2._; } if (keywords2 && keywords2.$ && keywords2.$.text) { feed.itunes.keywords = keywords2.$.text.split(","); } else if (typeof keywords2 === "string") { feed.itunes.keywords = keywords2.split(","); } } } utils.copyFromXML(channel, feed.itunes, fields2.podcastFeed); items.forEach((item, index2) => { let entry = feed.items[index2]; entry.itunes = {}; utils.copyFromXML(item, entry.itunes, fields2.podcastItem); let image = item["itunes:image"]; if (image && image[0] && image[0].$ && image[0].$.href) { entry.itunes.image = image[0].$.href; } }); } setISODate(item) { let date2 = item.pubDate || item.date; if (date2) { try { item.isoDate = new Date(date2.trim()).toISOString(); } catch (e2) { } } } generatePaginationLinks(channel) { if (!channel["atom:link"]) { return {}; } const paginationRelAttributes = ["self", "first", "next", "prev", "last"]; return channel["atom:link"].reduce((paginationLinks, link) => { if (!link.$ || !paginationRelAttributes.includes(link.$.rel)) { return paginationLinks; } paginationLinks[link.$.rel] = link.$.href; return paginationLinks; }, {}); } }; module2.exports = Parser2; } }); // node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/index.js var require_rss_parser = __commonJS({ "node_modules/.pnpm/rss-parser@3.13.0/node_modules/rss-parser/index.js"(exports2, module2) { "use strict"; module2.exports = require_parser3(); } }); // node_modules/.pnpm/lodash.set@4.3.2/node_modules/lodash.set/index.js var require_lodash3 = __commonJS({ "node_modules/.pnpm/lodash.set@4.3.2/node_modules/lodash.set/index.js"(exports2, module2) { var FUNC_ERROR_TEXT = "Expected a function"; var HASH_UNDEFINED = "__lodash_hash_undefined__"; var INFINITY = 1 / 0; var MAX_SAFE_INTEGER = 9007199254740991; var funcTag = "[object Function]"; var genTag = "[object GeneratorFunction]"; var symbolTag = "[object Symbol]"; var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; var reIsPlainProp = /^\w*$/; var reLeadingDot = /^\./; var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var reEscapeChar = /\\(\\)?/g; var reIsHostCtor = /^\[object .+?Constructor\]$/; var reIsUint = /^(?:0|[1-9]\d*)$/; var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root3 = freeGlobal || freeSelf || Function("return this")(); function getValue3(object, key) { return object == null ? void 0 : object[key]; } function isHostObject(value) { var result = false; if (value != null && typeof value.toString != "function") { try { result = !!(value + ""); } catch (e2) { } } return result; } var arrayProto = Array.prototype; var funcProto = Function.prototype; var objectProto = Object.prototype; var coreJsData = root3["__core-js_shared__"]; var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : ""; }(); var funcToString = funcProto.toString; var hasOwnProperty2 = objectProto.hasOwnProperty; var objectToString = objectProto.toString; var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); var Symbol2 = root3.Symbol; var splice = arrayProto.splice; var Map2 = getNative(root3, "Map"); var nativeCreate = getNative(Object, "create"); var symbolProto = Symbol2 ? Symbol2.prototype : void 0; var symbolToString = symbolProto ? symbolProto.toString : void 0; function Hash(entries) { var index2 = -1, length = entries ? entries.length : 0; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? void 0 : result; } return hasOwnProperty2.call(data, key) ? data[key] : void 0; } function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== void 0 : hasOwnProperty2.call(data, key); } function hashSet(key, value) { var data = this.__data__; data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; return this; } Hash.prototype.clear = hashClear; Hash.prototype["delete"] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; function ListCache(entries) { var index2 = -1, length = entries ? entries.length : 0; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function listCacheClear() { this.__data__ = []; } function listCacheDelete(key) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { return false; } var lastIndex = data.length - 1; if (index2 == lastIndex) { data.pop(); } else { splice.call(data, index2, 1); } return true; } function listCacheGet(key) { var data = this.__data__, index2 = assocIndexOf(data, key); return index2 < 0 ? void 0 : data[index2][1]; } function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } function listCacheSet(key, value) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { data.push([key, value]); } else { data[index2][1] = value; } return this; } ListCache.prototype.clear = listCacheClear; ListCache.prototype["delete"] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; function MapCache(entries) { var index2 = -1, length = entries ? entries.length : 0; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function mapCacheClear() { this.__data__ = { "hash": new Hash(), "map": new (Map2 || ListCache)(), "string": new Hash() }; } function mapCacheDelete(key) { return getMapData(this, key)["delete"](key); } function mapCacheGet(key) { return getMapData(this, key).get(key); } function mapCacheHas(key) { return getMapData(this, key).has(key); } function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } MapCache.prototype.clear = mapCacheClear; MapCache.prototype["delete"] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty2.call(object, key) && eq(objValue, value)) || value === void 0 && !(key in object)) { object[key] = value; } } function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } function baseIsNative(value) { if (!isObject10(value) || isMasked(value)) { return false; } var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } function baseSet(object, path, value, customizer) { if (!isObject10(object)) { return object; } path = isKey(path, object) ? [path] : castPath(path); var index2 = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index2 < length) { var key = toKey(path[index2]), newValue = value; if (index2 != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : void 0; if (newValue === void 0) { newValue = isObject10(objValue) ? objValue : isIndex(path[index2 + 1]) ? [] : {}; } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } function baseToString(value) { if (typeof value == "string") { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ""; } var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result; } function castPath(value) { return isArray(value) ? value : stringToPath(value); } function getMapData(map2, key) { var data = map2.__data__; return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; } function getNative(object, key) { var value = getValue3(object, key); return baseIsNative(value) ? value : void 0; } function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } function isKey(value, object) { if (isArray(value)) { return false; } var type2 = typeof value; if (type2 == "number" || type2 == "symbol" || type2 == "boolean" || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); } function isKeyable(value) { var type2 = typeof value; return type2 == "string" || type2 == "number" || type2 == "symbol" || type2 == "boolean" ? value !== "__proto__" : value === null; } function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } var stringToPath = memoize(function(string) { string = toString3(string); var result = []; if (reLeadingDot.test(string)) { result.push(""); } string.replace(rePropName, function(match, number, quote, string2) { result.push(quote ? string2.replace(reEscapeChar, "$1") : number || match); }); return result; }); function toKey(value) { if (typeof value == "string" || isSymbol(value)) { return value; } var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result; } function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e2) { } try { return func + ""; } catch (e2) { } } return ""; } function memoize(func, resolver) { if (typeof func != "function" || resolver && typeof resolver != "function") { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache2 = memoized.cache; if (cache2.has(key)) { return cache2.get(key); } var result = func.apply(this, args); memoized.cache = cache2.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache)(); return memoized; } memoize.Cache = MapCache; function eq(value, other) { return value === other || value !== value && other !== other; } var isArray = Array.isArray; function isFunction(value) { var tag = isObject10(value) ? objectToString.call(value) : ""; return tag == funcTag || tag == genTag; } function isObject10(value) { var type2 = typeof value; return !!value && (type2 == "object" || type2 == "function"); } function isObjectLike(value) { return !!value && typeof value == "object"; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; } function toString3(value) { return value == null ? "" : baseToString(value); } function set13(object, path, value) { return object == null ? object : baseSet(object, path, value); } module2.exports = set13; } }); // node_modules/.pnpm/scheduler@0.23.0/node_modules/scheduler/cjs/scheduler.development.js var require_scheduler_development = __commonJS({ "node_modules/.pnpm/scheduler@0.23.0/node_modules/scheduler/cjs/scheduler.development.js"(exports2) { "use strict"; if (true) { (function() { "use strict"; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var enableSchedulerDebugging = false; var enableProfiling = false; var frameYieldMs = 5; function push(heap2, node) { var index2 = heap2.length; heap2.push(node); siftUp(heap2, node, index2); } function peek(heap2) { return heap2.length === 0 ? null : heap2[0]; } function pop(heap2) { if (heap2.length === 0) { return null; } var first = heap2[0]; var last = heap2.pop(); if (last !== first) { heap2[0] = last; siftDown(heap2, last, 0); } return first; } function siftUp(heap2, node, i2) { var index2 = i2; while (index2 > 0) { var parentIndex = index2 - 1 >>> 1; var parent = heap2[parentIndex]; if (compare2(parent, node) > 0) { heap2[parentIndex] = node; heap2[index2] = parent; index2 = parentIndex; } else { return; } } } function siftDown(heap2, node, i2) { var index2 = i2; var length = heap2.length; var halfLength = length >>> 1; while (index2 < halfLength) { var leftIndex = (index2 + 1) * 2 - 1; var left = heap2[leftIndex]; var rightIndex = leftIndex + 1; var right = heap2[rightIndex]; if (compare2(left, node) < 0) { if (rightIndex < length && compare2(right, left) < 0) { heap2[index2] = right; heap2[rightIndex] = node; index2 = rightIndex; } else { heap2[index2] = left; heap2[leftIndex] = node; index2 = leftIndex; } } else if (rightIndex < length && compare2(right, node) < 0) { heap2[index2] = right; heap2[rightIndex] = node; index2 = rightIndex; } else { return; } } } function compare2(a2, b2) { var diff = a2.sortIndex - b2.sortIndex; return diff !== 0 ? diff : a2.id - b2.id; } var ImmediatePriority = 1; var UserBlockingPriority = 2; var NormalPriority = 3; var LowPriority = 4; var IdlePriority = 5; function markTaskErrored(task, ms) { } var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; if (hasPerformanceNow) { var localPerformance = performance; exports2.unstable_now = function() { return localPerformance.now(); }; } else { var localDate = Date; var initialTime = localDate.now(); exports2.unstable_now = function() { return localDate.now() - initialTime; }; } var maxSigned31BitInt = 1073741823; var IMMEDIATE_PRIORITY_TIMEOUT = -1; var USER_BLOCKING_PRIORITY_TIMEOUT = 250; var NORMAL_PRIORITY_TIMEOUT = 5e3; var LOW_PRIORITY_TIMEOUT = 1e4; var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; var taskQueue = []; var timerQueue = []; var taskIdCounter = 1; var currentTask = null; var currentPriorityLevel = NormalPriority; var isPerformingWork = false; var isHostCallbackScheduled = false; var isHostTimeoutScheduled = false; var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; function advanceTimers(currentTime) { var timer = peek(timerQueue); while (timer !== null) { if (timer.callback === null) { pop(timerQueue); } else if (timer.startTime <= currentTime) { pop(timerQueue); timer.sortIndex = timer.expirationTime; push(taskQueue, timer); } else { return; } timer = peek(timerQueue); } } function handleTimeout(currentTime) { isHostTimeoutScheduled = false; advanceTimers(currentTime); if (!isHostCallbackScheduled) { if (peek(taskQueue) !== null) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } } } } function flushWork(hasTimeRemaining, initialTime2) { isHostCallbackScheduled = false; if (isHostTimeoutScheduled) { isHostTimeoutScheduled = false; cancelHostTimeout(); } isPerformingWork = true; var previousPriorityLevel = currentPriorityLevel; try { if (enableProfiling) { try { return workLoop(hasTimeRemaining, initialTime2); } catch (error) { if (currentTask !== null) { var currentTime = exports2.unstable_now(); markTaskErrored(currentTask, currentTime); currentTask.isQueued = false; } throw error; } } else { return workLoop(hasTimeRemaining, initialTime2); } } finally { currentTask = null; currentPriorityLevel = previousPriorityLevel; isPerformingWork = false; } } function workLoop(hasTimeRemaining, initialTime2) { var currentTime = initialTime2; advanceTimers(currentTime); currentTask = peek(taskQueue); while (currentTask !== null && !enableSchedulerDebugging) { if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { break; } var callback = currentTask.callback; if (typeof callback === "function") { currentTask.callback = null; currentPriorityLevel = currentTask.priorityLevel; var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; var continuationCallback = callback(didUserCallbackTimeout); currentTime = exports2.unstable_now(); if (typeof continuationCallback === "function") { currentTask.callback = continuationCallback; } else { if (currentTask === peek(taskQueue)) { pop(taskQueue); } } advanceTimers(currentTime); } else { pop(taskQueue); } currentTask = peek(taskQueue); } if (currentTask !== null) { return true; } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } return false; } } function unstable_runWithPriority(priorityLevel, eventHandler) { switch (priorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: case LowPriority: case IdlePriority: break; default: priorityLevel = NormalPriority; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_next(eventHandler) { var priorityLevel; switch (currentPriorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: priorityLevel = NormalPriority; break; default: priorityLevel = currentPriorityLevel; break; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_wrapCallback(callback) { var parentPriorityLevel = currentPriorityLevel; return function() { var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = parentPriorityLevel; try { return callback.apply(this, arguments); } finally { currentPriorityLevel = previousPriorityLevel; } }; } function unstable_scheduleCallback(priorityLevel, callback, options) { var currentTime = exports2.unstable_now(); var startTime2; if (typeof options === "object" && options !== null) { var delay = options.delay; if (typeof delay === "number" && delay > 0) { startTime2 = currentTime + delay; } else { startTime2 = currentTime; } } else { startTime2 = currentTime; } var timeout; switch (priorityLevel) { case ImmediatePriority: timeout = IMMEDIATE_PRIORITY_TIMEOUT; break; case UserBlockingPriority: timeout = USER_BLOCKING_PRIORITY_TIMEOUT; break; case IdlePriority: timeout = IDLE_PRIORITY_TIMEOUT; break; case LowPriority: timeout = LOW_PRIORITY_TIMEOUT; break; case NormalPriority: default: timeout = NORMAL_PRIORITY_TIMEOUT; break; } var expirationTime = startTime2 + timeout; var newTask = { id: taskIdCounter++, callback, priorityLevel, startTime: startTime2, expirationTime, sortIndex: -1 }; if (startTime2 > currentTime) { newTask.sortIndex = startTime2; push(timerQueue, newTask); if (peek(taskQueue) === null && newTask === peek(timerQueue)) { if (isHostTimeoutScheduled) { cancelHostTimeout(); } else { isHostTimeoutScheduled = true; } requestHostTimeout(handleTimeout, startTime2 - currentTime); } } else { newTask.sortIndex = expirationTime; push(taskQueue, newTask); if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } return newTask; } function unstable_pauseExecution() { } function unstable_continueExecution() { if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } function unstable_getFirstCallbackNode() { return peek(taskQueue); } function unstable_cancelCallback(task) { task.callback = null; } function unstable_getCurrentPriorityLevel() { return currentPriorityLevel; } var isMessageLoopRunning = false; var scheduledHostCallback = null; var taskTimeoutID = -1; var frameInterval = frameYieldMs; var startTime = -1; function shouldYieldToHost() { var timeElapsed = exports2.unstable_now() - startTime; if (timeElapsed < frameInterval) { return false; } return true; } function requestPaint() { } function forceFrameRate(fps) { if (fps < 0 || fps > 125) { console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); return; } if (fps > 0) { frameInterval = Math.floor(1e3 / fps); } else { frameInterval = frameYieldMs; } } var performWorkUntilDeadline = function() { if (scheduledHostCallback !== null) { var currentTime = exports2.unstable_now(); startTime = currentTime; var hasTimeRemaining = true; var hasMoreWork = true; try { hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); } finally { if (hasMoreWork) { schedulePerformWorkUntilDeadline(); } else { isMessageLoopRunning = false; scheduledHostCallback = null; } } } else { isMessageLoopRunning = false; } }; var schedulePerformWorkUntilDeadline; if (typeof localSetImmediate === "function") { schedulePerformWorkUntilDeadline = function() { localSetImmediate(performWorkUntilDeadline); }; } else if (typeof MessageChannel !== "undefined") { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = performWorkUntilDeadline; schedulePerformWorkUntilDeadline = function() { port.postMessage(null); }; } else { schedulePerformWorkUntilDeadline = function() { localSetTimeout(performWorkUntilDeadline, 0); }; } function requestHostCallback(callback) { scheduledHostCallback = callback; if (!isMessageLoopRunning) { isMessageLoopRunning = true; schedulePerformWorkUntilDeadline(); } } function requestHostTimeout(callback, ms) { taskTimeoutID = localSetTimeout(function() { callback(exports2.unstable_now()); }, ms); } function cancelHostTimeout() { localClearTimeout(taskTimeoutID); taskTimeoutID = -1; } var unstable_requestPaint = requestPaint; var unstable_Profiling = null; exports2.unstable_IdlePriority = IdlePriority; exports2.unstable_ImmediatePriority = ImmediatePriority; exports2.unstable_LowPriority = LowPriority; exports2.unstable_NormalPriority = NormalPriority; exports2.unstable_Profiling = unstable_Profiling; exports2.unstable_UserBlockingPriority = UserBlockingPriority; exports2.unstable_cancelCallback = unstable_cancelCallback; exports2.unstable_continueExecution = unstable_continueExecution; exports2.unstable_forceFrameRate = forceFrameRate; exports2.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; exports2.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; exports2.unstable_next = unstable_next; exports2.unstable_pauseExecution = unstable_pauseExecution; exports2.unstable_requestPaint = unstable_requestPaint; exports2.unstable_runWithPriority = unstable_runWithPriority; exports2.unstable_scheduleCallback = unstable_scheduleCallback; exports2.unstable_shouldYield = shouldYieldToHost; exports2.unstable_wrapCallback = unstable_wrapCallback; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } } }); // node_modules/.pnpm/scheduler@0.23.0/node_modules/scheduler/index.js var require_scheduler = __commonJS({ "node_modules/.pnpm/scheduler@0.23.0/node_modules/scheduler/index.js"(exports2, module2) { "use strict"; if (false) { module2.exports = null; } else { module2.exports = require_scheduler_development(); } } }); // node_modules/.pnpm/react-dom@18.2.0_react@18.2.0/node_modules/react-dom/cjs/react-dom.development.js var require_react_dom_development = __commonJS({ "node_modules/.pnpm/react-dom@18.2.0_react@18.2.0/node_modules/react-dom/cjs/react-dom.development.js"(exports2) { "use strict"; if (true) { (function() { "use strict"; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var React84 = require_react(); var Scheduler = require_scheduler(); var ReactSharedInternals = React84.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var suppressWarning = false; function setSuppressWarning(newSuppressWarning) { { suppressWarning = newSuppressWarning; } } function warn(format) { { if (!suppressWarning) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning("warn", format, args); } } } function error(format) { { if (!suppressWarning) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame2.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; var HostRoot = 3; var HostPortal = 4; var HostComponent = 5; var HostText = 6; var Fragment = 7; var Mode = 8; var ContextConsumer = 9; var ContextProvider = 10; var ForwardRef = 11; var Profiler = 12; var SuspenseComponent = 13; var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; var DehydratedFragment = 18; var SuspenseListComponent = 19; var ScopeComponent = 21; var OffscreenComponent = 22; var LegacyHiddenComponent = 23; var CacheComponent = 24; var TracingMarkerComponent = 25; var enableClientRenderFallbackOnTextMismatch = true; var enableNewReconciler = false; var enableLazyContextPropagation = false; var enableLegacyHidden = false; var enableSuspenseAvoidThisFallback = false; var disableCommentsAsDOMContainers = true; var enableCustomElementPropertySupport = false; var warnAboutStringRefs = false; var enableSchedulingProfiler = true; var enableProfilerTimer = true; var enableProfilerCommitHooks = true; var allNativeEvents = new Set(); var registrationNameDependencies = {}; var possibleRegistrationNames = {}; function registerTwoPhaseEvent(registrationName, dependencies2) { registerDirectEvent(registrationName, dependencies2); registerDirectEvent(registrationName + "Capture", dependencies2); } function registerDirectEvent(registrationName, dependencies2) { { if (registrationNameDependencies[registrationName]) { error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName); } } registrationNameDependencies[registrationName] = dependencies2; { var lowerCasedName = registrationName.toLowerCase(); possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === "onDoubleClick") { possibleRegistrationNames.ondblclick = registrationName; } } for (var i2 = 0; i2 < dependencies2.length; i2++) { allNativeEvents.add(dependencies2[i2]); } } var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); var hasOwnProperty2 = Object.prototype.hasOwnProperty; function typeName(value) { { var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; return type2; } } function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e2) { return true; } } } function testStringCoercion(value) { return "" + value; } function checkAttributeStringCoercion(value, attributeName) { { if (willCoercionThrow(value)) { error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value)); return testStringCoercion(value); } } } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function checkPropStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); return testStringCoercion(value); } } } function checkCSSPropertyStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); return testStringCoercion(value); } } } function checkHtmlStringCoercion(value) { { if (willCoercionThrow(value)) { error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function checkFormFieldValueStringCoercion(value) { { if (willCoercionThrow(value)) { error("Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } var RESERVED = 0; var STRING = 1; var BOOLEANISH_STRING = 2; var BOOLEAN = 3; var OVERLOADED_BOOLEAN = 4; var NUMERIC = 5; var POSITIVE_NUMERIC = 6; var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName)) { return true; } if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; { error("Invalid attribute name: `%s`", attributeName); } return false; } function shouldIgnoreAttribute(name2, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null) { return propertyInfo.type === RESERVED; } if (isCustomComponentTag) { return false; } if (name2.length > 2 && (name2[0] === "o" || name2[0] === "O") && (name2[1] === "n" || name2[1] === "N")) { return true; } return false; } function shouldRemoveAttributeWithWarning(name2, value, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null && propertyInfo.type === RESERVED) { return false; } switch (typeof value) { case "function": case "symbol": return true; case "boolean": { if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { return !propertyInfo.acceptsBooleans; } else { var prefix2 = name2.toLowerCase().slice(0, 5); return prefix2 !== "data-" && prefix2 !== "aria-"; } } default: return false; } } function shouldRemoveAttribute(name2, value, propertyInfo, isCustomComponentTag) { if (value === null || typeof value === "undefined") { return true; } if (shouldRemoveAttributeWithWarning(name2, value, propertyInfo, isCustomComponentTag)) { return true; } if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { switch (propertyInfo.type) { case BOOLEAN: return !value; case OVERLOADED_BOOLEAN: return value === false; case NUMERIC: return isNaN(value); case POSITIVE_NUMERIC: return isNaN(value) || value < 1; } } return false; } function getPropertyInfo(name2) { return properties.hasOwnProperty(name2) ? properties[name2] : null; } function PropertyInfoRecord(name2, type2, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { this.acceptsBooleans = type2 === BOOLEANISH_STRING || type2 === BOOLEAN || type2 === OVERLOADED_BOOLEAN; this.attributeName = attributeName; this.attributeNamespace = attributeNamespace; this.mustUseProperty = mustUseProperty; this.propertyName = name2; this.type = type2; this.sanitizeURL = sanitizeURL2; this.removeEmptyString = removeEmptyString; } var properties = {}; var reservedProps = [ "children", "dangerouslySetInnerHTML", "defaultValue", "defaultChecked", "innerHTML", "suppressContentEditableWarning", "suppressHydrationWarning", "style" ]; reservedProps.forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, RESERVED, false, name2, null, false, false); }); [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { var name2 = _ref[0], attributeName = _ref[1]; properties[name2] = new PropertyInfoRecord(name2, STRING, false, attributeName, null, false, false); }); ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, BOOLEANISH_STRING, false, name2.toLowerCase(), null, false, false); }); ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, BOOLEANISH_STRING, false, name2, null, false, false); }); [ "allowFullScreen", "async", "autoFocus", "autoPlay", "controls", "default", "defer", "disabled", "disablePictureInPicture", "disableRemotePlayback", "formNoValidate", "hidden", "loop", "noModule", "noValidate", "open", "playsInline", "readOnly", "required", "reversed", "scoped", "seamless", "itemScope" ].forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, BOOLEAN, false, name2.toLowerCase(), null, false, false); }); [ "checked", "multiple", "muted", "selected" ].forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, BOOLEAN, true, name2, null, false, false); }); [ "capture", "download" ].forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, OVERLOADED_BOOLEAN, false, name2, null, false, false); }); [ "cols", "rows", "size", "span" ].forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, POSITIVE_NUMERIC, false, name2, null, false, false); }); ["rowSpan", "start"].forEach(function(name2) { properties[name2] = new PropertyInfoRecord(name2, NUMERIC, false, name2.toLowerCase(), null, false, false); }); var CAMELIZE = /[\-\:]([a-z])/g; var capitalize = function(token) { return token[1].toUpperCase(); }; [ "accent-height", "alignment-baseline", "arabic-form", "baseline-shift", "cap-height", "clip-path", "clip-rule", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "dominant-baseline", "enable-background", "fill-opacity", "fill-rule", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "glyph-name", "glyph-orientation-horizontal", "glyph-orientation-vertical", "horiz-adv-x", "horiz-origin-x", "image-rendering", "letter-spacing", "lighting-color", "marker-end", "marker-mid", "marker-start", "overline-position", "overline-thickness", "paint-order", "panose-1", "pointer-events", "rendering-intent", "shape-rendering", "stop-color", "stop-opacity", "strikethrough-position", "strikethrough-thickness", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-anchor", "text-decoration", "text-rendering", "underline-position", "underline-thickness", "unicode-bidi", "unicode-range", "units-per-em", "v-alphabetic", "v-hanging", "v-ideographic", "v-mathematical", "vector-effect", "vert-adv-y", "vert-origin-x", "vert-origin-y", "word-spacing", "writing-mode", "xmlns:xlink", "x-height" ].forEach(function(attributeName) { var name2 = attributeName.replace(CAMELIZE, capitalize); properties[name2] = new PropertyInfoRecord(name2, STRING, false, attributeName, null, false, false); }); [ "xlink:actuate", "xlink:arcrole", "xlink:role", "xlink:show", "xlink:title", "xlink:type" ].forEach(function(attributeName) { var name2 = attributeName.replace(CAMELIZE, capitalize); properties[name2] = new PropertyInfoRecord(name2, STRING, false, attributeName, "http://www.w3.org/1999/xlink", false, false); }); [ "xml:base", "xml:lang", "xml:space" ].forEach(function(attributeName) { var name2 = attributeName.replace(CAMELIZE, capitalize); properties[name2] = new PropertyInfoRecord(name2, STRING, false, attributeName, "http://www.w3.org/XML/1998/namespace", false, false); }); ["tabIndex", "crossOrigin"].forEach(function(attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, false, false); }); var xlinkHref = "xlinkHref"; properties[xlinkHref] = new PropertyInfoRecord("xlinkHref", STRING, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false); ["src", "href", "action", "formAction"].forEach(function(attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, true, true); }); var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; var didWarn = false; function sanitizeURL(url) { { if (!didWarn && isJavaScriptProtocol.test(url)) { didWarn = true; error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); } } } function getValueForProperty(node, name2, expected, propertyInfo) { { if (propertyInfo.mustUseProperty) { var propertyName = propertyInfo.propertyName; return node[propertyName]; } else { { checkAttributeStringCoercion(expected, name2); } if (propertyInfo.sanitizeURL) { sanitizeURL("" + expected); } var attributeName = propertyInfo.attributeName; var stringValue = null; if (propertyInfo.type === OVERLOADED_BOOLEAN) { if (node.hasAttribute(attributeName)) { var value = node.getAttribute(attributeName); if (value === "") { return true; } if (shouldRemoveAttribute(name2, expected, propertyInfo, false)) { return value; } if (value === "" + expected) { return expected; } return value; } } else if (node.hasAttribute(attributeName)) { if (shouldRemoveAttribute(name2, expected, propertyInfo, false)) { return node.getAttribute(attributeName); } if (propertyInfo.type === BOOLEAN) { return expected; } stringValue = node.getAttribute(attributeName); } if (shouldRemoveAttribute(name2, expected, propertyInfo, false)) { return stringValue === null ? expected : stringValue; } else if (stringValue === "" + expected) { return expected; } else { return stringValue; } } } } function getValueForAttribute(node, name2, expected, isCustomComponentTag) { { if (!isAttributeNameSafe(name2)) { return; } if (!node.hasAttribute(name2)) { return expected === void 0 ? void 0 : null; } var value = node.getAttribute(name2); { checkAttributeStringCoercion(expected, name2); } if (value === "" + expected) { return expected; } return value; } } function setValueForProperty(node, name2, value, isCustomComponentTag) { var propertyInfo = getPropertyInfo(name2); if (shouldIgnoreAttribute(name2, propertyInfo, isCustomComponentTag)) { return; } if (shouldRemoveAttribute(name2, value, propertyInfo, isCustomComponentTag)) { value = null; } if (isCustomComponentTag || propertyInfo === null) { if (isAttributeNameSafe(name2)) { var _attributeName = name2; if (value === null) { node.removeAttribute(_attributeName); } else { { checkAttributeStringCoercion(value, name2); } node.setAttribute(_attributeName, "" + value); } } return; } var mustUseProperty = propertyInfo.mustUseProperty; if (mustUseProperty) { var propertyName = propertyInfo.propertyName; if (value === null) { var type2 = propertyInfo.type; node[propertyName] = type2 === BOOLEAN ? false : ""; } else { node[propertyName] = value; } return; } var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; if (value === null) { node.removeAttribute(attributeName); } else { var _type = propertyInfo.type; var attributeValue; if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { attributeValue = ""; } else { { { checkAttributeStringCoercion(value, attributeName); } attributeValue = "" + value; } if (propertyInfo.sanitizeURL) { sanitizeURL(attributeValue.toString()); } } if (attributeNamespace) { node.setAttributeNS(attributeNamespace, attributeName, attributeValue); } else { node.setAttribute(attributeName, attributeValue); } } } var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_SCOPE_TYPE = Symbol.for("react.scope"); var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"); var REACT_CACHE_TYPE = Symbol.for("react.cache"); var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === "function") { return maybeIterator; } return null; } var assign = Object.assign; var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() { } disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); } if (disabledDepth < 0) { error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name2, source, ownerFn) { { if (prefix === void 0) { try { throw Error(); } catch (x2) { var match = x2.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ""; } } return "\n" + prefix + name2; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) { return ""; } { var frame = componentFrameCache.get(fn); if (frame !== void 0) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = null; disableLogs(); } try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if (typeof Reflect === "object" && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x2) { control = x2; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x2) { control = x2; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x2) { control = x2; } fn(); } } catch (sample) { if (sample && control && typeof sample.stack === "string") { var sampleLines = sample.stack.split("\n"); var controlLines = control.stack.split("\n"); var s2 = sampleLines.length - 1; var c2 = controlLines.length - 1; while (s2 >= 1 && c2 >= 0 && sampleLines[s2] !== controlLines[c2]) { c2--; } for (; s2 >= 1 && c2 >= 0; s2--, c2--) { if (sampleLines[s2] !== controlLines[c2]) { if (s2 !== 1 || c2 !== 1) { do { s2--; c2--; if (c2 < 0 || sampleLines[s2] !== controlLines[c2]) { var _frame = "\n" + sampleLines[s2].replace(" at new ", " at "); if (fn.displayName && _frame.includes("")) { _frame = _frame.replace("", fn.displayName); } { if (typeof fn === "function") { componentFrameCache.set(fn, _frame); } } return _frame; } } while (s2 >= 1 && c2 >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } var name2 = fn ? fn.displayName || fn.name : ""; var syntheticFrame = name2 ? describeBuiltInComponentFrame(name2) : ""; { if (typeof fn === "function") { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeClassComponentFrame(ctor, source, ownerFn) { { return describeNativeComponentFrame(ctor, true); } } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component7) { var prototype = Component7.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) { if (type2 == null) { return ""; } if (typeof type2 === "function") { { return describeNativeComponentFrame(type2, shouldConstruct(type2)); } } if (typeof type2 === "string") { return describeBuiltInComponentFrame(type2); } switch (type2) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type2.render); case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn); } catch (x2) { } } } } return ""; } function describeFiber(fiber) { var owner = fiber._debugOwner ? fiber._debugOwner.type : null; var source = fiber._debugSource; switch (fiber.tag) { case HostComponent: return describeBuiltInComponentFrame(fiber.type); case LazyComponent: return describeBuiltInComponentFrame("Lazy"); case SuspenseComponent: return describeBuiltInComponentFrame("Suspense"); case SuspenseListComponent: return describeBuiltInComponentFrame("SuspenseList"); case FunctionComponent: case IndeterminateComponent: case SimpleMemoComponent: return describeFunctionComponentFrame(fiber.type); case ForwardRef: return describeFunctionComponentFrame(fiber.type.render); case ClassComponent: return describeClassComponentFrame(fiber.type); default: return ""; } } function getStackByFiberInDevAndProd(workInProgress2) { try { var info = ""; var node = workInProgress2; do { info += describeFiber(node); node = node.return; } while (node); return info; } catch (x2) { return "\nError generating stack: " + x2.message + "\n" + x2.stack; } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ""; return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; } function getContextName(type2) { return type2.displayName || "Context"; } function getComponentNameFromType(type2) { if (type2 == null) { return null; } { if (typeof type2.tag === "number") { error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); } } if (typeof type2 === "function") { return type2.displayName || type2.name || null; } if (typeof type2 === "string") { return type2; } switch (type2) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_CONTEXT_TYPE: var context = type2; return getContextName(context) + ".Consumer"; case REACT_PROVIDER_TYPE: var provider = type2; return getContextName(provider._context) + ".Provider"; case REACT_FORWARD_REF_TYPE: return getWrappedName(type2, type2.render, "ForwardRef"); case REACT_MEMO_TYPE: var outerName = type2.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type2.type) || "Memo"; case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return getComponentNameFromType(init2(payload)); } catch (x2) { return null; } } } } return null; } function getWrappedName$1(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ""; return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); } function getContextName$1(type2) { return type2.displayName || "Context"; } function getComponentNameFromFiber(fiber) { var tag = fiber.tag, type2 = fiber.type; switch (tag) { case CacheComponent: return "Cache"; case ContextConsumer: var context = type2; return getContextName$1(context) + ".Consumer"; case ContextProvider: var provider = type2; return getContextName$1(provider._context) + ".Provider"; case DehydratedFragment: return "DehydratedFragment"; case ForwardRef: return getWrappedName$1(type2, type2.render, "ForwardRef"); case Fragment: return "Fragment"; case HostComponent: return type2; case HostPortal: return "Portal"; case HostRoot: return "Root"; case HostText: return "Text"; case LazyComponent: return getComponentNameFromType(type2); case Mode: if (type2 === REACT_STRICT_MODE_TYPE) { return "StrictMode"; } return "Mode"; case OffscreenComponent: return "Offscreen"; case Profiler: return "Profiler"; case ScopeComponent: return "Scope"; case SuspenseComponent: return "Suspense"; case SuspenseListComponent: return "SuspenseList"; case TracingMarkerComponent: return "TracingMarker"; case ClassComponent: case FunctionComponent: case IncompleteClassComponent: case IndeterminateComponent: case MemoComponent: case SimpleMemoComponent: if (typeof type2 === "function") { return type2.displayName || type2.name || null; } if (typeof type2 === "string") { return type2; } break; } return null; } var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } var owner = current._debugOwner; if (owner !== null && typeof owner !== "undefined") { return getComponentNameFromFiber(owner); } } return null; } function getCurrentFiberStackInDev() { { if (current === null) { return ""; } return getStackByFiberInDevAndProd(current); } } function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; } } function getCurrentFiber() { { return current; } } function setIsRendering(rendering) { { isRendering = rendering; } } function toString3(value) { return "" + value; } function getToStringValue(value) { switch (typeof value) { case "boolean": case "number": case "string": case "undefined": return value; case "object": { checkFormFieldValueStringCoercion(value); } return value; default: return ""; } } var hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true }; function checkControlledValueProps(tagName, props) { { if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); } if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); } } } function isCheckable(elem) { var type2 = elem.type; var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === "input" && (type2 === "checkbox" || type2 === "radio"); } function getTracker(node) { return node._valueTracker; } function detachTracker(node) { node._valueTracker = null; } function getValueFromNode(node) { var value = ""; if (!node) { return value; } if (isCheckable(node)) { value = node.checked ? "true" : "false"; } else { value = node.value; } return value; } function trackValueOnNode(node) { var valueField = isCheckable(node) ? "checked" : "value"; var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); { checkFormFieldValueStringCoercion(node[valueField]); } var currentValue = "" + node[valueField]; if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { return; } var get23 = descriptor.get, set14 = descriptor.set; Object.defineProperty(node, valueField, { configurable: true, get: function() { return get23.call(this); }, set: function(value) { { checkFormFieldValueStringCoercion(value); } currentValue = "" + value; set14.call(this, value); } }); Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable }); var tracker = { getValue: function() { return currentValue; }, setValue: function(value) { { checkFormFieldValueStringCoercion(value); } currentValue = "" + value; }, stopTracking: function() { detachTracker(node); delete node[valueField]; } }; return tracker; } function track(node) { if (getTracker(node)) { return; } node._valueTracker = trackValueOnNode(node); } function updateValueIfChanged(node) { if (!node) { return false; } var tracker = getTracker(node); if (!tracker) { return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(node); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; } function getActiveElement(doc) { doc = doc || (typeof document !== "undefined" ? document : void 0); if (typeof doc === "undefined") { return null; } try { return doc.activeElement || doc.body; } catch (e2) { return doc.body; } } var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function isControlled(props) { var usesChecked = props.type === "checkbox" || props.type === "radio"; return usesChecked ? props.checked != null : props.value != null; } function getHostProps(element, props) { var node = element; var checked = props.checked; var hostProps = assign({}, props, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: checked != null ? checked : node._wrapperState.initialChecked }); return hostProps; } function initWrapperState(element, props) { { checkControlledValueProps("input", props); if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) { error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); didWarnCheckedDefaultChecked = true; } if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) { error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); didWarnValueDefaultValue = true; } } var node = element; var defaultValue = props.defaultValue == null ? "" : props.defaultValue; node._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: getToStringValue(props.value != null ? props.value : defaultValue), controlled: isControlled(props) }; } function updateChecked(element, props) { var node = element; var checked = props.checked; if (checked != null) { setValueForProperty(node, "checked", checked, false); } } function updateWrapper(element, props) { var node = element; { var controlled = isControlled(props); if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); didWarnUncontrolledToControlled = true; } if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); didWarnControlledToUncontrolled = true; } } updateChecked(element, props); var value = getToStringValue(props.value); var type2 = props.type; if (value != null) { if (type2 === "number") { if (value === 0 && node.value === "" || node.value != value) { node.value = toString3(value); } } else if (node.value !== toString3(value)) { node.value = toString3(value); } } else if (type2 === "submit" || type2 === "reset") { node.removeAttribute("value"); return; } { if (props.hasOwnProperty("value")) { setDefaultValue(node, props.type, value); } else if (props.hasOwnProperty("defaultValue")) { setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); } } { if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } } function postMountWrapper(element, props, isHydrating2) { var node = element; if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { var type2 = props.type; var isButton = type2 === "submit" || type2 === "reset"; if (isButton && (props.value === void 0 || props.value === null)) { return; } var initialValue = toString3(node._wrapperState.initialValue); if (!isHydrating2) { { if (initialValue !== node.value) { node.value = initialValue; } } } { node.defaultValue = initialValue; } } var name2 = node.name; if (name2 !== "") { node.name = ""; } { node.defaultChecked = !node.defaultChecked; node.defaultChecked = !!node._wrapperState.initialChecked; } if (name2 !== "") { node.name = name2; } } function restoreControlledState(element, props) { var node = element; updateWrapper(node, props); updateNamedCousins(node, props); } function updateNamedCousins(rootNode, props) { var name2 = props.name; if (props.type === "radio" && name2 != null) { var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } { checkAttributeStringCoercion(name2, "name"); } var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name2) + '][type="radio"]'); for (var i2 = 0; i2 < group.length; i2++) { var otherNode = group[i2]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } var otherProps = getFiberCurrentPropsFromNode(otherNode); if (!otherProps) { throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."); } updateValueIfChanged(otherNode); updateWrapper(otherNode, otherProps); } } } function setDefaultValue(node, type2, value) { if (type2 !== "number" || getActiveElement(node.ownerDocument) !== node) { if (value == null) { node.defaultValue = toString3(node._wrapperState.initialValue); } else if (node.defaultValue !== toString3(value)) { node.defaultValue = toString3(value); } } } var didWarnSelectedSetOnOption = false; var didWarnInvalidChild = false; var didWarnInvalidInnerHTML = false; function validateProps(element, props) { { if (props.value == null) { if (typeof props.children === "object" && props.children !== null) { React84.Children.forEach(props.children, function(child) { if (child == null) { return; } if (typeof child === "string" || typeof child === "number") { return; } if (!didWarnInvalidChild) { didWarnInvalidChild = true; error("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to